File size: 8,432 Bytes
044eef3
 
 
 
 
 
 
 
 
 
 
 
 
dadd5bd
044eef3
 
 
 
 
dadd5bd
044eef3
 
 
 
 
 
 
 
 
 
 
 
dadd5bd
 
 
 
 
044eef3
 
 
 
 
65493c3
dadd5bd
 
 
65493c3
dadd5bd
 
 
 
 
 
 
 
 
 
044eef3
65493c3
dadd5bd
044eef3
 
65493c3
dadd5bd
 
044eef3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dadd5bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
044eef3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dadd5bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
044eef3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dadd5bd
 
 
 
 
044eef3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dadd5bd
 
044eef3
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import { useState, useRef, useCallback } from 'react';
import { CanvasObject, CanvasSize, CanvasBgColor } from '../types/canvas.types';
import { generateId, getNextZIndex } from '../utils/canvas.utils';

// Distributed Omit type for union types
type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;

const MAX_HISTORY_SIZE = 50;

export function useCanvasState() {
  const [objects, setObjectsState] = useState<CanvasObject[]>([]);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [canvasSize, setCanvasSize] = useState<CanvasSize>('1200x675');
  const [bgColor, setBgColor] = useState<CanvasBgColor>('seriousLight');

  // History management - store complete state snapshots
  const history = useRef<CanvasObject[][]>([[]]);  // Start with empty canvas
  const historyIndex = useRef<number>(0);
  const isApplyingHistory = useRef<boolean>(false);
  const skipHistoryRecording = useRef<boolean>(false); // Flag to skip history for text editing

  // Set objects with history tracking
  const setObjects = useCallback((newObjects: CanvasObject[]) => {
    setObjectsState(newObjects);

    // Don't record history during undo/redo operations
    if (isApplyingHistory.current) {
      return;
    }

    // Use setTimeout to ensure state has been updated before recording
    setTimeout(() => {
      // Check skip flag inside setTimeout to catch updates
      if (skipHistoryRecording.current) {
        return;
      }

      // Remove any future history if we're not at the end
      if (historyIndex.current < history.current.length - 1) {
        history.current = history.current.slice(0, historyIndex.current + 1);
      }

      // Deep clone and normalize state (remove isEditing flag for comparison)
      const normalizeState = (state: CanvasObject[]) => {
        return state.map((obj: CanvasObject) => {
          if (obj.type === 'text') {
            const { isEditing, ...rest } = obj as any;
            return rest;
          }
          return obj;
        });
      };

      const normalizedNewState = normalizeState(newObjects);
      const normalizedCurrentState = history.current[historyIndex.current]
        ? normalizeState(history.current[historyIndex.current])
        : [];

      // Only add to history if state actually changed (ignoring isEditing)
      const stateChanged = JSON.stringify(normalizedCurrentState) !== JSON.stringify(normalizedNewState);

      if (stateChanged) {
        // Store the normalized state (without isEditing)
        const stateCopy = JSON.parse(JSON.stringify(normalizedNewState));

        history.current.push(stateCopy);
        historyIndex.current++;

        // Limit history size
        if (history.current.length > MAX_HISTORY_SIZE) {
          history.current.shift();
          historyIndex.current--;
        }
      }
    }, 0);
  }, []);

  // Undo function
  const undo = useCallback(() => {
    if (historyIndex.current > 0) {
      isApplyingHistory.current = true;
      historyIndex.current--;
      const previousState = JSON.parse(JSON.stringify(history.current[historyIndex.current]));

      // Recalculate text dimensions for text objects to fix clipping issues
      const recalculatedState = previousState.map((obj: CanvasObject) => {
        if (obj.type === 'text' && obj.text) {
          try {
            const Konva = require('konva').default;
            const tempText = new Konva.Text({
              text: obj.text,
              fontSize: obj.fontSize,
              fontFamily: obj.fontFamily,
              fontStyle: `${obj.bold ? 'bold' : 'normal'} ${obj.italic ? 'italic' : ''}`
            });

            const newWidth = Math.max(100, tempText.width() + 20);
            const newHeight = Math.max(40, tempText.height() + 10);

            tempText.destroy();

            // Always recalculate to ensure proper fit
            return { ...obj, width: newWidth, height: newHeight, isEditing: false };
          } catch (error) {
            console.error('Error recalculating text dimensions:', error);
            return obj;
          }
        }
        return obj;
      });

      setObjectsState(recalculatedState);
      setSelectedIds([]); // Deselect when undoing

      // Reset flag after state update
      setTimeout(() => {
        isApplyingHistory.current = false;
      }, 0);
    }
  }, []);

  // Redo function
  const redo = useCallback(() => {
    if (historyIndex.current < history.current.length - 1) {
      isApplyingHistory.current = true;
      historyIndex.current++;
      const nextState = JSON.parse(JSON.stringify(history.current[historyIndex.current]));

      // Recalculate text dimensions for text objects to fix clipping issues
      const recalculatedState = nextState.map((obj: CanvasObject) => {
        if (obj.type === 'text' && obj.text) {
          try {
            const Konva = require('konva').default;
            const tempText = new Konva.Text({
              text: obj.text,
              fontSize: obj.fontSize,
              fontFamily: obj.fontFamily,
              fontStyle: `${obj.bold ? 'bold' : 'normal'} ${obj.italic ? 'italic' : ''}`
            });

            const newWidth = Math.max(100, tempText.width() + 20);
            const newHeight = Math.max(40, tempText.height() + 10);

            tempText.destroy();

            // Always recalculate to ensure proper fit
            return { ...obj, width: newWidth, height: newHeight, isEditing: false };
          } catch (error) {
            console.error('Error recalculating text dimensions:', error);
            return obj;
          }
        }
        return obj;
      });

      setObjectsState(recalculatedState);
      setSelectedIds([]); // Deselect when redoing

      // Reset flag after state update
      setTimeout(() => {
        isApplyingHistory.current = false;
      }, 0);
    }
  }, []);

  // Add object to canvas
  const addObject = (obj: DistributiveOmit<CanvasObject, 'id' | 'zIndex'>) => {
    const newObject: CanvasObject = {
      ...obj,
      id: generateId(),
      zIndex: getNextZIndex(objects)
    } as CanvasObject;

    setObjects([...objects, newObject]);
    setSelectedIds([newObject.id]);
  };

  // Delete selected objects
  const deleteSelected = () => {
    if (selectedIds.length > 0) {
      setObjects(objects.filter(obj => !selectedIds.includes(obj.id)));
      setSelectedIds([]);
    }
  };

  // Update selected objects
  const updateSelected = (updates: Partial<CanvasObject>) => {
    if (selectedIds.length > 0) {
      setObjects(objects.map(obj =>
        selectedIds.includes(obj.id) ? { ...obj, ...updates } as CanvasObject : obj
      ));
    }
  };

  // Bring to front
  const bringToFront = (id: string) => {
    const maxZ = getNextZIndex(objects);
    setObjects(objects.map(obj =>
      obj.id === id ? { ...obj, zIndex: maxZ } : obj
    ));
  };

  // Send to back
  const sendToBack = (id: string) => {
    const minZ = Math.min(...objects.map(obj => obj.zIndex));
    setObjects(objects.map(obj =>
      obj.id === id ? { ...obj, zIndex: minZ - 1 } : obj
    ));
  };

  // Move forward
  const moveForward = (id: string) => {
    const obj = objects.find(o => o.id === id);
    if (!obj) return;

    const objectsAbove = objects.filter(o => o.zIndex > obj.zIndex);
    if (objectsAbove.length === 0) return;

    const nextZ = Math.min(...objectsAbove.map(o => o.zIndex));
    setObjects(objects.map(o =>
      o.id === id ? { ...o, zIndex: nextZ + 0.5 } : o
    ));
  };

  // Move backward
  const moveBackward = (id: string) => {
    const obj = objects.find(o => o.id === id);
    if (!obj) return;

    const objectsBelow = objects.filter(o => o.zIndex < obj.zIndex);
    if (objectsBelow.length === 0) return;

    const prevZ = Math.max(...objectsBelow.map(o => o.zIndex));
    setObjects(objects.map(o =>
      o.id === id ? { ...o, zIndex: prevZ - 0.5 } : o
    ));
  };

  // Enable/disable history recording (for text editing)
  const setSkipHistoryRecording = useCallback((skip: boolean) => {
    skipHistoryRecording.current = skip;
  }, []);

  return {
    objects,
    selectedIds,
    canvasSize,
    bgColor,
    setObjects,
    setSelectedIds,
    setCanvasSize,
    setBgColor,
    addObject,
    deleteSelected,
    updateSelected,
    bringToFront,
    sendToBack,
    moveForward,
    moveBackward,
    undo,
    redo,
    setSkipHistoryRecording
  };
}