@rytass/wms-map-react-components 0.1.10 → 0.3.0

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 (122) hide show
  1. package/CHANGELOG.md +181 -0
  2. package/README.md +30 -0
  3. package/components/breadcrumb/breadcrumb-edit-modal.cjs +92 -0
  4. package/components/breadcrumb/breadcrumb-edit-modal.d.cts +9 -0
  5. package/components/breadcrumb/breadcrumb-edit-modal.module.scss.cjs +5 -0
  6. package/components/breadcrumb/breadcrumb.cjs +171 -0
  7. package/components/breadcrumb/breadcrumb.d.cts +11 -0
  8. package/components/breadcrumb/breadcrumb.d.ts +1 -1
  9. package/components/breadcrumb/breadcrumb.module.scss.cjs +5 -0
  10. package/components/canvas/react-flow-canvas.cjs +327 -0
  11. package/components/canvas/react-flow-canvas.d.cts +40 -0
  12. package/components/canvas/react-flow-canvas.d.ts +3 -1
  13. package/components/canvas/react-flow-canvas.js +7 -1
  14. package/components/canvas/react-flow-canvas.module.scss.cjs +5 -0
  15. package/components/modal/wms-map-content.cjs +835 -0
  16. package/components/modal/wms-map-content.d.cts +4 -0
  17. package/components/modal/wms-map-content.d.ts +1 -1
  18. package/components/modal/wms-map-content.js +30 -3
  19. package/components/modal/wms-map-modal-container.cjs +132 -0
  20. package/components/modal/wms-map-modal-container.d.cts +5 -0
  21. package/components/modal/wms-map-modal-container.d.ts +2 -2
  22. package/components/modal/wms-map-modal-container.js +6 -4
  23. package/components/modal/wms-map-modal-container.module.scss.cjs +5 -0
  24. package/components/nodes/base-node.d.cts +12 -0
  25. package/components/nodes/base-node.d.ts +1 -1
  26. package/components/nodes/image-node.cjs +234 -0
  27. package/components/nodes/image-node.d.cts +17 -0
  28. package/components/nodes/image-node.d.ts +1 -1
  29. package/components/nodes/image-node.js +0 -2
  30. package/components/nodes/image-node.module.scss.cjs +5 -0
  31. package/components/nodes/path-node.cjs +554 -0
  32. package/components/nodes/path-node.d.cts +19 -0
  33. package/components/nodes/path-node.d.ts +1 -1
  34. package/components/nodes/path-node.js +6 -5
  35. package/components/nodes/path-node.module.scss.cjs +5 -0
  36. package/components/nodes/rectangle-node.cjs +240 -0
  37. package/components/nodes/rectangle-node.d.cts +11 -0
  38. package/components/nodes/rectangle-node.d.ts +1 -1
  39. package/components/nodes/rectangle-node.js +6 -5
  40. package/components/nodes/rectangle-node.module.scss.cjs +5 -0
  41. package/components/preview/wms-map-preview.cjs +201 -0
  42. package/components/preview/wms-map-preview.d.cts +11 -0
  43. package/components/preview/wms-map-preview.d.ts +11 -0
  44. package/components/preview/wms-map-preview.js +199 -0
  45. package/components/ui/context-menu.cjs +171 -0
  46. package/components/ui/context-menu.d.cts +25 -0
  47. package/components/ui/context-menu.module.scss.cjs +5 -0
  48. package/components/ui/toolbar.cjs +286 -0
  49. package/components/ui/toolbar.d.cts +23 -0
  50. package/components/ui/toolbar.d.ts +1 -1
  51. package/components/ui/toolbar.module.scss.cjs +5 -0
  52. package/components/ui/view-mode-toolbar.cjs +44 -0
  53. package/components/ui/view-mode-toolbar.d.cts +9 -0
  54. package/components/ui/view-mode-toolbar.d.ts +1 -1
  55. package/components/ui/view-mode-toolbar.module.scss.cjs +5 -0
  56. package/constants/index.cjs +54 -0
  57. package/constants/index.d.cts +45 -0
  58. package/constants/index.d.ts +2 -2
  59. package/constants/text-mappings.cjs +46 -0
  60. package/constants/text-mappings.d.cts +181 -0
  61. package/hooks/use-context-menu.cjs +231 -0
  62. package/hooks/use-context-menu.d.cts +37 -0
  63. package/hooks/use-context-menu.d.ts +1 -1
  64. package/hooks/use-direct-state-history.cjs +217 -0
  65. package/hooks/use-direct-state-history.d.cts +58 -0
  66. package/hooks/use-direct-state-history.d.ts +2 -2
  67. package/hooks/use-fit-view-when-ready.cjs +74 -0
  68. package/hooks/use-fit-view-when-ready.d.cts +18 -0
  69. package/hooks/use-fit-view-when-ready.d.ts +18 -0
  70. package/hooks/use-fit-view-when-ready.js +72 -0
  71. package/hooks/use-pen-drawing.cjs +366 -0
  72. package/hooks/use-pen-drawing.d.cts +30 -0
  73. package/hooks/use-pen-drawing.d.ts +1 -1
  74. package/hooks/use-rectangle-drawing.cjs +139 -0
  75. package/hooks/use-rectangle-drawing.d.cts +19 -0
  76. package/hooks/use-rectangle-drawing.d.ts +1 -1
  77. package/hooks/use-text-editing.cjs +156 -0
  78. package/hooks/use-text-editing.d.cts +19 -0
  79. package/icons/index.cjs +233 -0
  80. package/icons/index.d.cts +16 -0
  81. package/index.cjs +28 -0
  82. package/index.d.cts +6 -0
  83. package/index.d.ts +6 -5
  84. package/index.js +1 -0
  85. package/package.json +68 -3
  86. package/types/callback.types.d.cts +7 -0
  87. package/types/callback.types.d.ts +1 -1
  88. package/types/canvas.types.d.cts +35 -0
  89. package/types/canvas.types.d.ts +1 -1
  90. package/types/component-props.types.d.cts +76 -0
  91. package/types/component-props.types.d.ts +33 -2
  92. package/types/history.types.d.cts +24 -0
  93. package/types/history.types.d.ts +2 -2
  94. package/types/index.d.cts +5 -0
  95. package/types/index.d.ts +5 -5
  96. package/types/react-flow.types.d.cts +30 -0
  97. package/typings.cjs +44 -0
  98. package/typings.d.cts +136 -0
  99. package/utils/api-data-transform.cjs +221 -0
  100. package/utils/api-data-transform.d.cts +33 -0
  101. package/utils/api-data-transform.d.ts +1 -1
  102. package/utils/color-utils.cjs +58 -0
  103. package/utils/color-utils.d.cts +17 -0
  104. package/utils/debug-logger.cjs +45 -0
  105. package/utils/debug-logger.d.cts +33 -0
  106. package/utils/fit-trigger.cjs +41 -0
  107. package/utils/fit-trigger.d.cts +37 -0
  108. package/utils/fit-trigger.d.ts +37 -0
  109. package/utils/fit-trigger.js +36 -0
  110. package/utils/map-data-transform.cjs +360 -0
  111. package/utils/map-data-transform.d.cts +18 -0
  112. package/utils/map-data-transform.d.ts +1 -1
  113. package/utils/node-operations.cjs +88 -0
  114. package/utils/node-operations.d.cts +26 -0
  115. package/utils/node-utils.cjs +40 -0
  116. package/utils/node-utils.d.cts +10 -0
  117. package/utils/preview-highlight.cjs +38 -0
  118. package/utils/preview-highlight.d.cts +12 -0
  119. package/utils/preview-highlight.d.ts +12 -0
  120. package/utils/preview-highlight.js +34 -0
  121. package/index.cjs.css +0 -1
  122. package/index.cjs.js +0 -5128
@@ -0,0 +1,58 @@
1
+ import { EditMode } from '../typings.cjs';
2
+ import { FlowNode, FlowEdge } from '../types/react-flow.types.cjs';
3
+ interface HistoryState {
4
+ nodes: FlowNode[];
5
+ edges: FlowEdge[];
6
+ editMode: EditMode;
7
+ operation: string;
8
+ timestamp: number;
9
+ }
10
+ interface UseDirectStateHistoryOptions {
11
+ maxHistorySize?: number;
12
+ debugMode?: boolean;
13
+ }
14
+ interface HistorySummary {
15
+ canUndo: boolean;
16
+ canRedo: boolean;
17
+ historyLength: number;
18
+ currentIndex: number;
19
+ currentOperation?: string;
20
+ operations?: Array<{
21
+ index: number;
22
+ operation: string;
23
+ nodes: number;
24
+ edges: number;
25
+ isCurrent: boolean;
26
+ }>;
27
+ }
28
+ interface UseDirectStateHistoryReturn {
29
+ saveState: (nodes: FlowNode[], edges: FlowEdge[], operation: string, editMode: EditMode) => void;
30
+ undo: () => {
31
+ nodes: FlowNode[];
32
+ edges: FlowEdge[];
33
+ editMode: EditMode;
34
+ } | null;
35
+ redo: () => {
36
+ nodes: FlowNode[];
37
+ edges: FlowEdge[];
38
+ editMode: EditMode;
39
+ } | null;
40
+ canUndo: boolean;
41
+ canRedo: boolean;
42
+ initializeHistory: (initialNodes: FlowNode[], initialEdges: FlowEdge[], editMode: EditMode) => void;
43
+ clearHistory: () => void;
44
+ getHistorySummary: () => HistorySummary;
45
+ history?: HistoryState[];
46
+ currentIndex?: number;
47
+ }
48
+ /**
49
+ * 直接狀態歷史系統
50
+ *
51
+ * 核心概念:
52
+ * - 直接記錄 nodes 和 edges 的完整狀態
53
+ * - 每個用戶操作後保存一份狀態快照
54
+ * - undo/redo 就是直接設置 nodes 和 edges
55
+ * - 簡單、直接、可靠
56
+ */
57
+ export declare const useDirectStateHistory: ({ maxHistorySize, debugMode, }?: UseDirectStateHistoryOptions) => UseDirectStateHistoryReturn;
58
+ export {};
@@ -1,5 +1,5 @@
1
- import { EditMode } from '../typings';
2
- import { FlowNode, FlowEdge } from '../types/react-flow.types';
1
+ import { EditMode } from '../typings.js';
2
+ import { FlowNode, FlowEdge } from '../types/react-flow.types.js';
3
3
  interface HistoryState {
4
4
  nodes: FlowNode[];
5
5
  edges: FlowEdge[];
@@ -0,0 +1,74 @@
1
+ "use client";
2
+ 'use strict';
3
+
4
+ var React = require('react');
5
+ var react = require('@xyflow/react');
6
+
7
+ /** 等待節點量測完成的 rAF 重試上限(約 2 秒);超過即放棄,避免無限輪詢。 */ const MAX_READY_FRAMES = 120;
8
+ const isMeasured = (width, height)=>(width ?? 0) > 0 && (height ?? 0) > 0;
9
+ /**
10
+ * 在 requestToken 變動時,等節點全部量測完成後直接設定 viewport 框住節點。
11
+ *
12
+ * 不使用 React Flow 的 `fitView`:它只會在下一次 `setNodes` 或 `updateNodeInternals` 時才執行,
13
+ * 換入新節點集合時若未觸發這兩者會永遠不 fit。這裡改為自行輪詢 store,就緒後直接呼叫 panZoom。
14
+ * 只有 requestToken 變動時才會 fit,之後使用者的手動縮放或平移不會被覆寫。
15
+ */ const useFitViewWhenReady = (options)=>{
16
+ const store = react.useStoreApi();
17
+ const latestRef = React.useRef(options);
18
+ React.useEffect(()=>{
19
+ latestRef.current = options;
20
+ });
21
+ const { requestToken } = options;
22
+ React.useEffect(()=>{
23
+ if (requestToken === 0) {
24
+ return undefined;
25
+ }
26
+ let frame = null;
27
+ let attempts = 0;
28
+ const tryFit = ()=>{
29
+ frame = null;
30
+ const { nodeIds, focusIds, padding } = latestRef.current;
31
+ if (nodeIds.length === 0) {
32
+ return;
33
+ }
34
+ const { nodeLookup, width, height, panZoom, minZoom, maxZoom, nodeOrigin } = store.getState();
35
+ const ready = width > 0 && height > 0 && panZoom !== null && nodeLookup.size === nodeIds.length && nodeIds.every((id)=>{
36
+ const node = nodeLookup.get(id);
37
+ return node !== undefined && isMeasured(node.measured.width, node.measured.height);
38
+ });
39
+ if (!ready) {
40
+ attempts += 1;
41
+ if (attempts < MAX_READY_FRAMES) {
42
+ frame = requestAnimationFrame(tryFit);
43
+ }
44
+ return;
45
+ }
46
+ const focused = focusIds?.filter((id)=>nodeLookup.has(id)) ?? [];
47
+ const targetIds = focused.length > 0 ? focused : nodeIds;
48
+ const bounds = react.getNodesBounds([
49
+ ...targetIds
50
+ ], {
51
+ nodeLookup,
52
+ nodeOrigin
53
+ });
54
+ if (bounds.width <= 0 || bounds.height <= 0) {
55
+ return;
56
+ }
57
+ const viewport = react.getViewportForBounds(bounds, width, height, minZoom, maxZoom, padding);
58
+ void panZoom?.setViewport(viewport, {
59
+ duration: 0
60
+ });
61
+ };
62
+ frame = requestAnimationFrame(tryFit);
63
+ return ()=>{
64
+ if (frame !== null) {
65
+ cancelAnimationFrame(frame);
66
+ }
67
+ };
68
+ }, [
69
+ requestToken,
70
+ store
71
+ ]);
72
+ };
73
+
74
+ exports.useFitViewWhenReady = useFitViewWhenReady;
@@ -0,0 +1,18 @@
1
+ export interface FitViewWhenReadyOptions {
2
+ /** 每次要求 fit 時遞增;0 代表尚未要求,不會 fit。 */
3
+ requestToken: number;
4
+ /** 目前節點集合的全部 id;全部節點量測完成後才會 fit。 */
5
+ nodeIds: readonly string[];
6
+ /** 要框住的節點 id(例如 highlightIds);未提供或皆不存在時框住全部節點。 */
7
+ focusIds?: readonly string[];
8
+ /** 比例 padding,語意與 React Flow `fitView` 相同(0.1 = 10%)。 */
9
+ padding: number;
10
+ }
11
+ /**
12
+ * 在 requestToken 變動時,等節點全部量測完成後直接設定 viewport 框住節點。
13
+ *
14
+ * 不使用 React Flow 的 `fitView`:它只會在下一次 `setNodes` 或 `updateNodeInternals` 時才執行,
15
+ * 換入新節點集合時若未觸發這兩者會永遠不 fit。這裡改為自行輪詢 store,就緒後直接呼叫 panZoom。
16
+ * 只有 requestToken 變動時才會 fit,之後使用者的手動縮放或平移不會被覆寫。
17
+ */
18
+ export declare const useFitViewWhenReady: (options: FitViewWhenReadyOptions) => void;
@@ -0,0 +1,18 @@
1
+ export interface FitViewWhenReadyOptions {
2
+ /** 每次要求 fit 時遞增;0 代表尚未要求,不會 fit。 */
3
+ requestToken: number;
4
+ /** 目前節點集合的全部 id;全部節點量測完成後才會 fit。 */
5
+ nodeIds: readonly string[];
6
+ /** 要框住的節點 id(例如 highlightIds);未提供或皆不存在時框住全部節點。 */
7
+ focusIds?: readonly string[];
8
+ /** 比例 padding,語意與 React Flow `fitView` 相同(0.1 = 10%)。 */
9
+ padding: number;
10
+ }
11
+ /**
12
+ * 在 requestToken 變動時,等節點全部量測完成後直接設定 viewport 框住節點。
13
+ *
14
+ * 不使用 React Flow 的 `fitView`:它只會在下一次 `setNodes` 或 `updateNodeInternals` 時才執行,
15
+ * 換入新節點集合時若未觸發這兩者會永遠不 fit。這裡改為自行輪詢 store,就緒後直接呼叫 panZoom。
16
+ * 只有 requestToken 變動時才會 fit,之後使用者的手動縮放或平移不會被覆寫。
17
+ */
18
+ export declare const useFitViewWhenReady: (options: FitViewWhenReadyOptions) => void;
@@ -0,0 +1,72 @@
1
+ "use client";
2
+ import { useRef, useEffect } from 'react';
3
+ import { useStoreApi, getNodesBounds, getViewportForBounds } from '@xyflow/react';
4
+
5
+ /** 等待節點量測完成的 rAF 重試上限(約 2 秒);超過即放棄,避免無限輪詢。 */ const MAX_READY_FRAMES = 120;
6
+ const isMeasured = (width, height)=>(width ?? 0) > 0 && (height ?? 0) > 0;
7
+ /**
8
+ * 在 requestToken 變動時,等節點全部量測完成後直接設定 viewport 框住節點。
9
+ *
10
+ * 不使用 React Flow 的 `fitView`:它只會在下一次 `setNodes` 或 `updateNodeInternals` 時才執行,
11
+ * 換入新節點集合時若未觸發這兩者會永遠不 fit。這裡改為自行輪詢 store,就緒後直接呼叫 panZoom。
12
+ * 只有 requestToken 變動時才會 fit,之後使用者的手動縮放或平移不會被覆寫。
13
+ */ const useFitViewWhenReady = (options)=>{
14
+ const store = useStoreApi();
15
+ const latestRef = useRef(options);
16
+ useEffect(()=>{
17
+ latestRef.current = options;
18
+ });
19
+ const { requestToken } = options;
20
+ useEffect(()=>{
21
+ if (requestToken === 0) {
22
+ return undefined;
23
+ }
24
+ let frame = null;
25
+ let attempts = 0;
26
+ const tryFit = ()=>{
27
+ frame = null;
28
+ const { nodeIds, focusIds, padding } = latestRef.current;
29
+ if (nodeIds.length === 0) {
30
+ return;
31
+ }
32
+ const { nodeLookup, width, height, panZoom, minZoom, maxZoom, nodeOrigin } = store.getState();
33
+ const ready = width > 0 && height > 0 && panZoom !== null && nodeLookup.size === nodeIds.length && nodeIds.every((id)=>{
34
+ const node = nodeLookup.get(id);
35
+ return node !== undefined && isMeasured(node.measured.width, node.measured.height);
36
+ });
37
+ if (!ready) {
38
+ attempts += 1;
39
+ if (attempts < MAX_READY_FRAMES) {
40
+ frame = requestAnimationFrame(tryFit);
41
+ }
42
+ return;
43
+ }
44
+ const focused = focusIds?.filter((id)=>nodeLookup.has(id)) ?? [];
45
+ const targetIds = focused.length > 0 ? focused : nodeIds;
46
+ const bounds = getNodesBounds([
47
+ ...targetIds
48
+ ], {
49
+ nodeLookup,
50
+ nodeOrigin
51
+ });
52
+ if (bounds.width <= 0 || bounds.height <= 0) {
53
+ return;
54
+ }
55
+ const viewport = getViewportForBounds(bounds, width, height, minZoom, maxZoom, padding);
56
+ void panZoom?.setViewport(viewport, {
57
+ duration: 0
58
+ });
59
+ };
60
+ frame = requestAnimationFrame(tryFit);
61
+ return ()=>{
62
+ if (frame !== null) {
63
+ cancelAnimationFrame(frame);
64
+ }
65
+ };
66
+ }, [
67
+ requestToken,
68
+ store
69
+ ]);
70
+ };
71
+
72
+ export { useFitViewWhenReady };
@@ -0,0 +1,366 @@
1
+ "use client";
2
+ 'use strict';
3
+
4
+ var React = require('react');
5
+ var react = require('@xyflow/react');
6
+ var typings = require('../typings.cjs');
7
+
8
+ // Utility function to constrain point to straight lines (horizontal, vertical, 45-degree)
9
+ const constrainToStraightLine = (currentPoint, previousPoint)=>{
10
+ const dx = currentPoint.x - previousPoint.x;
11
+ const dy = currentPoint.y - previousPoint.y;
12
+ // Calculate angle in degrees
13
+ const angle = Math.atan2(dy, dx) * (180 / Math.PI);
14
+ // Normalize angle to 0-360 range
15
+ const normalizedAngle = (angle % 360 + 360) % 360;
16
+ // Snap to nearest cardinal/diagonal direction (every 45 degrees)
17
+ const snapAngle = Math.round(normalizedAngle / 45) * 45;
18
+ // Calculate distance from previous point
19
+ const distance = Math.sqrt(dx * dx + dy * dy);
20
+ // Convert back to radians and calculate constrained position
21
+ const constrainedAngle = snapAngle * Math.PI / 180;
22
+ return {
23
+ x: previousPoint.x + Math.cos(constrainedAngle) * distance,
24
+ y: previousPoint.y + Math.sin(constrainedAngle) * distance
25
+ };
26
+ };
27
+ const usePenDrawing = ({ editMode, drawingMode, onCreatePath })=>{
28
+ const { screenToFlowPosition } = react.useReactFlow();
29
+ const containerRef = React.useRef(null);
30
+ const previousModeRef = React.useRef(drawingMode);
31
+ const previousEditModeRef = React.useRef(editMode);
32
+ const [drawingState, setDrawingState] = React.useState({
33
+ isDrawing: false,
34
+ points: [],
35
+ screenPoints: [],
36
+ currentMousePos: null,
37
+ lastClickTime: 0,
38
+ isShiftPressed: false
39
+ });
40
+ const handleClick = React.useCallback((event)=>{
41
+ if (drawingMode !== typings.DrawingMode.PEN || editMode !== typings.EditMode.LAYER) return;
42
+ // IMMEDIATELY stop event propagation to prevent React Flow pane click
43
+ event.stopPropagation();
44
+ event.preventDefault();
45
+ event.stopImmediatePropagation();
46
+ // Debug log for shift key behavior
47
+ if (event.shiftKey) {
48
+ console.log('🖱️ Pen tool click with Shift key pressed - event stopped', {
49
+ isDrawing: drawingState.isDrawing,
50
+ pointsCount: drawingState.points.length,
51
+ lastClickTime: drawingState.lastClickTime,
52
+ currentTime: Date.now()
53
+ });
54
+ }
55
+ const currentTime = Date.now();
56
+ const wrapper = containerRef.current;
57
+ if (!wrapper) return;
58
+ const rect = wrapper.getBoundingClientRect();
59
+ const screenX = event.clientX - rect.left;
60
+ const screenY = event.clientY - rect.top;
61
+ const basePosition = screenToFlowPosition({
62
+ x: event.clientX,
63
+ y: event.clientY
64
+ });
65
+ const baseScreenPos = {
66
+ x: screenX,
67
+ y: screenY
68
+ };
69
+ // Apply straight line constraint if Shift is pressed and we have a previous point
70
+ const { position, constrainedScreenPos } = (()=>{
71
+ if (!event.shiftKey || drawingState.points.length === 0) {
72
+ return {
73
+ position: basePosition,
74
+ constrainedScreenPos: baseScreenPos
75
+ };
76
+ }
77
+ const previousPoint = drawingState.points[drawingState.points.length - 1];
78
+ const constrainedPosition = constrainToStraightLine(basePosition, previousPoint);
79
+ // Also constrain the screen position for consistent preview
80
+ const constrainedScreen = drawingState.screenPoints.length > 0 ? (()=>{
81
+ const previousScreenPoint = drawingState.screenPoints[drawingState.screenPoints.length - 1];
82
+ return constrainToStraightLine(baseScreenPos, previousScreenPoint);
83
+ })() : baseScreenPos;
84
+ return {
85
+ position: constrainedPosition,
86
+ constrainedScreenPos: constrainedScreen
87
+ };
88
+ })();
89
+ // Check for double-click (within 300ms)
90
+ const isDoubleClick = currentTime - drawingState.lastClickTime < 300;
91
+ // Check if clicking on the first point to close the path (only if we have at least 3 points)
92
+ // IMPORTANT: Use original screen position, not constrained position, to avoid accidental closing when using Shift
93
+ const isClickingFirstPoint = (()=>{
94
+ if (!drawingState.isDrawing || drawingState.points.length < 3) {
95
+ return false;
96
+ }
97
+ const firstPoint = drawingState.screenPoints[0];
98
+ const distance = Math.sqrt(Math.pow(screenX - firstPoint.x, 2) + Math.pow(screenY - firstPoint.y, 2));
99
+ // Consider it a click on the first point if within 10 pixels
100
+ return distance <= 10;
101
+ })();
102
+ if (isClickingFirstPoint) {
103
+ console.log('🔵 Pen tool: Closing path by clicking first point', {
104
+ shiftKey: event.shiftKey,
105
+ pointsCount: drawingState.points.length
106
+ });
107
+ // Close the path by adding the first point at the end
108
+ const closedPath = [
109
+ ...drawingState.points,
110
+ drawingState.points[0]
111
+ ];
112
+ onCreatePath(closedPath);
113
+ // Reset drawing state
114
+ setDrawingState({
115
+ isDrawing: false,
116
+ points: [],
117
+ screenPoints: [],
118
+ currentMousePos: null,
119
+ lastClickTime: 0,
120
+ isShiftPressed: false
121
+ });
122
+ } else if (isDoubleClick && drawingState.isDrawing) {
123
+ console.log('🔵 Pen tool: Completing path by double-click', {
124
+ shiftKey: event.shiftKey,
125
+ pointsCount: drawingState.points.length,
126
+ timeDiff: currentTime - drawingState.lastClickTime
127
+ });
128
+ // Complete and close the path if we have at least 3 points
129
+ if (drawingState.points.length >= 3) {
130
+ // Close the path by adding the first point at the end
131
+ const closedPath = [
132
+ ...drawingState.points,
133
+ drawingState.points[0]
134
+ ];
135
+ onCreatePath(closedPath);
136
+ } else if (drawingState.points.length >= 2) {
137
+ // If only 2 points, create an open path
138
+ onCreatePath(drawingState.points);
139
+ }
140
+ // Reset drawing state
141
+ setDrawingState({
142
+ isDrawing: false,
143
+ points: [],
144
+ screenPoints: [],
145
+ currentMousePos: null,
146
+ lastClickTime: 0,
147
+ isShiftPressed: false
148
+ });
149
+ } else {
150
+ // Regular click - add point
151
+ setDrawingState((prev)=>({
152
+ ...prev,
153
+ isDrawing: true,
154
+ points: [
155
+ ...prev.points,
156
+ position
157
+ ],
158
+ screenPoints: [
159
+ ...prev.screenPoints,
160
+ constrainedScreenPos
161
+ ],
162
+ lastClickTime: currentTime,
163
+ isShiftPressed: event.shiftKey
164
+ }));
165
+ }
166
+ }, [
167
+ drawingMode,
168
+ editMode,
169
+ screenToFlowPosition,
170
+ drawingState.lastClickTime,
171
+ drawingState.isDrawing,
172
+ drawingState.points,
173
+ drawingState.screenPoints,
174
+ onCreatePath
175
+ ]);
176
+ const handleMouseMove = React.useCallback((event)=>{
177
+ if (drawingMode !== typings.DrawingMode.PEN || editMode !== typings.EditMode.LAYER) return;
178
+ const wrapper = containerRef.current;
179
+ if (!wrapper) return;
180
+ const rect = wrapper.getBoundingClientRect();
181
+ const baseScreenX = event.clientX - rect.left;
182
+ const baseScreenY = event.clientY - rect.top;
183
+ // Apply constraint to mouse position if Shift is pressed and we're drawing
184
+ const { screenX, screenY } = (()=>{
185
+ if (!event.shiftKey || drawingState.screenPoints.length === 0) {
186
+ return {
187
+ screenX: baseScreenX,
188
+ screenY: baseScreenY
189
+ };
190
+ }
191
+ const previousScreenPoint = drawingState.screenPoints[drawingState.screenPoints.length - 1];
192
+ const constrainedPos = constrainToStraightLine({
193
+ x: baseScreenX,
194
+ y: baseScreenY
195
+ }, previousScreenPoint);
196
+ return {
197
+ screenX: constrainedPos.x,
198
+ screenY: constrainedPos.y
199
+ };
200
+ })();
201
+ setDrawingState((prev)=>({
202
+ ...prev,
203
+ currentMousePos: {
204
+ x: screenX,
205
+ y: screenY
206
+ },
207
+ isShiftPressed: event.shiftKey
208
+ }));
209
+ }, [
210
+ drawingMode,
211
+ editMode,
212
+ drawingState.screenPoints
213
+ ]);
214
+ const handleKeyDown = React.useCallback((event)=>{
215
+ if (drawingMode !== typings.DrawingMode.PEN || editMode !== typings.EditMode.LAYER || !drawingState.isDrawing) return;
216
+ // Escape key cancels current path
217
+ if (event.key === 'Escape') {
218
+ setDrawingState({
219
+ isDrawing: false,
220
+ points: [],
221
+ screenPoints: [],
222
+ currentMousePos: null,
223
+ lastClickTime: 0,
224
+ isShiftPressed: false
225
+ });
226
+ }
227
+ // Enter key completes and closes the path
228
+ if (event.key === 'Enter' && drawingState.points.length >= 2) {
229
+ if (drawingState.points.length >= 3) {
230
+ // Close the path by adding the first point at the end
231
+ const closedPath = [
232
+ ...drawingState.points,
233
+ drawingState.points[0]
234
+ ];
235
+ onCreatePath(closedPath);
236
+ } else {
237
+ // If only 2 points, create an open path
238
+ onCreatePath(drawingState.points);
239
+ }
240
+ setDrawingState({
241
+ isDrawing: false,
242
+ points: [],
243
+ screenPoints: [],
244
+ currentMousePos: null,
245
+ lastClickTime: 0,
246
+ isShiftPressed: false
247
+ });
248
+ }
249
+ }, [
250
+ drawingMode,
251
+ editMode,
252
+ drawingState.isDrawing,
253
+ drawingState.points,
254
+ onCreatePath
255
+ ]);
256
+ // Force complete current path (for auto-close on pane click)
257
+ const forceComplete = React.useCallback(()=>{
258
+ console.log('🔴 forceComplete called', {
259
+ isDrawing: drawingState.isDrawing,
260
+ pointsLength: drawingState.points.length,
261
+ willClose: drawingState.points.length >= 3
262
+ });
263
+ if (!drawingState.isDrawing || drawingState.points.length < 2) return;
264
+ // Auto-close the path if we have 3+ points, otherwise create open path
265
+ if (drawingState.points.length >= 3) {
266
+ console.log('🔴 Force completing with closed path');
267
+ const closedPath = [
268
+ ...drawingState.points,
269
+ drawingState.points[0]
270
+ ];
271
+ onCreatePath(closedPath);
272
+ } else {
273
+ console.log('🔴 Force completing with open path');
274
+ onCreatePath(drawingState.points);
275
+ }
276
+ // Reset drawing state
277
+ setDrawingState({
278
+ isDrawing: false,
279
+ points: [],
280
+ screenPoints: [],
281
+ currentMousePos: null,
282
+ lastClickTime: 0,
283
+ isShiftPressed: false
284
+ });
285
+ }, [
286
+ drawingState.isDrawing,
287
+ drawingState.points,
288
+ onCreatePath
289
+ ]);
290
+ // Reset drawing state when switching away from pen mode or LAYER mode
291
+ React.useEffect(()=>{
292
+ const modeChanged = previousModeRef.current !== drawingMode;
293
+ const editModeChanged = previousEditModeRef.current !== editMode;
294
+ if (modeChanged || editModeChanged) {
295
+ setDrawingState((prev)=>{
296
+ // Should we force complete before resetting?
297
+ const shouldForceComplete = // Switching away from PEN mode
298
+ (previousModeRef.current === typings.DrawingMode.PEN && drawingMode !== typings.DrawingMode.PEN || // Switching away from LAYER mode
299
+ previousEditModeRef.current === typings.EditMode.LAYER && editMode !== typings.EditMode.LAYER) && prev.isDrawing && prev.points.length >= 2;
300
+ if (shouldForceComplete) {
301
+ // Force complete the current path before switching
302
+ if (prev.points.length >= 3) {
303
+ const closedPath = [
304
+ ...prev.points,
305
+ prev.points[0]
306
+ ];
307
+ onCreatePath(closedPath);
308
+ } else {
309
+ onCreatePath(prev.points);
310
+ }
311
+ }
312
+ // Reset drawing state
313
+ return {
314
+ isDrawing: false,
315
+ points: [],
316
+ screenPoints: [],
317
+ currentMousePos: null,
318
+ lastClickTime: 0,
319
+ isShiftPressed: false
320
+ };
321
+ });
322
+ // Update refs
323
+ previousModeRef.current = drawingMode;
324
+ previousEditModeRef.current = editMode;
325
+ }
326
+ }, [
327
+ drawingMode,
328
+ editMode,
329
+ onCreatePath
330
+ ]);
331
+ // Event listeners setup
332
+ React.useEffect(()=>{
333
+ const wrapper = containerRef.current;
334
+ if (!wrapper) return;
335
+ // Use capture phase to intercept clicks before React Flow processes them
336
+ wrapper.addEventListener('click', handleClick, true);
337
+ document.addEventListener('mousemove', handleMouseMove);
338
+ document.addEventListener('keydown', handleKeyDown);
339
+ return ()=>{
340
+ wrapper.removeEventListener('click', handleClick, true);
341
+ document.removeEventListener('mousemove', handleMouseMove);
342
+ document.removeEventListener('keydown', handleKeyDown);
343
+ };
344
+ }, [
345
+ handleClick,
346
+ handleMouseMove,
347
+ handleKeyDown
348
+ ]);
349
+ // Calculate preview path including current mouse position
350
+ const previewPath = drawingState.isDrawing && drawingState.screenPoints.length > 0 ? drawingState.currentMousePos ? [
351
+ ...drawingState.screenPoints,
352
+ drawingState.currentMousePos
353
+ ] : drawingState.screenPoints : null;
354
+ return {
355
+ containerRef,
356
+ isDrawing: drawingState.isDrawing,
357
+ previewPath,
358
+ currentPoints: drawingState.screenPoints,
359
+ // 提供起始點資訊,用於顯示閉合提示
360
+ firstPoint: drawingState.screenPoints.length > 0 ? drawingState.screenPoints[0] : null,
361
+ canClose: drawingState.isDrawing && drawingState.screenPoints.length >= 3,
362
+ forceComplete
363
+ };
364
+ };
365
+
366
+ exports.usePenDrawing = usePenDrawing;
@@ -0,0 +1,30 @@
1
+ import React from 'react';
2
+ import { EditMode, DrawingMode } from '../typings.cjs';
3
+ interface UsePenDrawingProps {
4
+ editMode: EditMode;
5
+ drawingMode: DrawingMode;
6
+ onCreatePath: (points: {
7
+ x: number;
8
+ y: number;
9
+ }[]) => void;
10
+ }
11
+ interface UsePenDrawingReturn {
12
+ containerRef: React.RefObject<HTMLDivElement | null>;
13
+ isDrawing: boolean;
14
+ previewPath: {
15
+ x: number;
16
+ y: number;
17
+ }[] | null;
18
+ currentPoints: {
19
+ x: number;
20
+ y: number;
21
+ }[];
22
+ firstPoint: {
23
+ x: number;
24
+ y: number;
25
+ } | null;
26
+ canClose: boolean;
27
+ forceComplete: () => void;
28
+ }
29
+ export declare const usePenDrawing: ({ editMode, drawingMode, onCreatePath }: UsePenDrawingProps) => UsePenDrawingReturn;
30
+ export {};
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
- import { EditMode, DrawingMode } from '../typings';
2
+ import { EditMode, DrawingMode } from '../typings.js';
3
3
  interface UsePenDrawingProps {
4
4
  editMode: EditMode;
5
5
  drawingMode: DrawingMode;