File size: 7,496 Bytes
224165f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
import { devtools } from 'zustand/middleware'

interface EditorState {
  // Current state
  image: File | null
  processedImage: string | null
  mask: string | null
  background: string | null
  isProcessing: boolean
  zoom: number
  tool: 'select' | 'brush' | 'eraser' | 'wand' | null
  
  // History
  history: Array<{
    processedImage: string | null
    mask: string | null
    background: string | null
  }>
  historyIndex: number
  
  // Settings
  brushSize: number
  brushHardness: number
  tolerance: number
  feather: number
  edgeRefinement: number
  
  // Actions
  setImage: (image: File | null) => void
  setProcessedImage: (image: string | null) => void
  setMask: (mask: string | null) => void
  setBackground: (background: string | null) => void
  setIsProcessing: (processing: boolean) => void
  setZoom: (zoom: number) => void
  setTool: (tool: EditorState['tool']) => void
  
  // History actions
  saveToHistory: () => void
  undo: () => void
  redo: () => void
  canUndo: boolean
  canRedo: boolean
  
  // Settings actions
  setBrushSize: (size: number) => void
  setBrushHardness: (hardness: number) => void
  setTolerance: (tolerance: number) => void
  setFeather: (feather: number) => void
  setEdgeRefinement: (refinement: number) => void
  
  // Utils
  reset: () => void
  exportImage: (format: 'png' | 'jpeg' | 'webp', quality?: number) => Promise<Blob>
}

const initialState = {
  image: null,
  processedImage: null,
  mask: null,
  background: null,
  isProcessing: false,
  zoom: 100,
  tool: null,
  history: [],
  historyIndex: -1,
  brushSize: 20,
  brushHardness: 80,
  tolerance: 20,
  feather: 2,
  edgeRefinement: 50,
}

export const useEditorStore = create<EditorState>()(
  devtools(
    immer((set, get) => ({
      ...initialState,
      
      setImage: (image) =>
        set((state) => {
          state.image = image
          if (!image) {
            state.processedImage = null
            state.mask = null
            state.background = null
            state.history = []
            state.historyIndex = -1
          }
        }),
      
      setProcessedImage: (image) =>
        set((state) => {
          state.processedImage = image
        }),
      
      setMask: (mask) =>
        set((state) => {
          state.mask = mask
        }),
      
      setBackground: (background) =>
        set((state) => {
          state.background = background
          get().saveToHistory()
        }),
      
      setIsProcessing: (processing) =>
        set((state) => {
          state.isProcessing = processing
        }),
      
      setZoom: (zoom) =>
        set((state) => {
          state.zoom = Math.max(10, Math.min(500, zoom))
        }),
      
      setTool: (tool) =>
        set((state) => {
          state.tool = tool
        }),
      
      saveToHistory: () =>
        set((state) => {
          const { processedImage, mask, background } = state
          const historyEntry = { processedImage, mask, background }
          
          // Remove any history after current index
          state.history = state.history.slice(0, state.historyIndex + 1)
          
          // Add new entry
          state.history.push(historyEntry)
          state.historyIndex++
          
          // Limit history to 50 entries
          if (state.history.length > 50) {
            state.history.shift()
            state.historyIndex--
          }
        }),
      
      undo: () =>
        set((state) => {
          if (state.historyIndex > 0) {
            state.historyIndex--
            const entry = state.history[state.historyIndex]
            state.processedImage = entry.processedImage
            state.mask = entry.mask
            state.background = entry.background
          }
        }),
      
      redo: () =>
        set((state) => {
          if (state.historyIndex < state.history.length - 1) {
            state.historyIndex++
            const entry = state.history[state.historyIndex]
            state.processedImage = entry.processedImage
            state.mask = entry.mask
            state.background = entry.background
          }
        }),
      
      get canUndo() {
        return get().historyIndex > 0
      },
      
      get canRedo() {
        return get().historyIndex < get().history.length - 1
      },
      
      setBrushSize: (size) =>
        set((state) => {
          state.brushSize = size
        }),
      
      setBrushHardness: (hardness) =>
        set((state) => {
          state.brushHardness = hardness
        }),
      
      setTolerance: (tolerance) =>
        set((state) => {
          state.tolerance = tolerance
        }),
      
      setFeather: (feather) =>
        set((state) => {
          state.feather = feather
        }),
      
      setEdgeRefinement: (refinement) =>
        set((state) => {
          state.edgeRefinement = refinement
        }),
      
      reset: () =>
        set(() => initialState),
      
      exportImage: async (format, quality = 0.95) => {
        const { processedImage, background } = get()
        if (!processedImage) throw new Error('No image to export')
        
        // Create canvas and composite image with background
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        if (!ctx) throw new Error('Failed to create canvas context')
        
        return new Promise<Blob>((resolve, reject) => {
          const img = new Image()
          img.onload = () => {
            canvas.width = img.width
            canvas.height = img.height
            
            // Draw background if present
            if (background) {
              if (background.startsWith('#')) {
                ctx.fillStyle = background
                ctx.fillRect(0, 0, canvas.width, canvas.height)
              } else if (background.startsWith('linear-gradient')) {
                // Handle image backgrounds
                const bgImg = new Image()
                bgImg.onload = () => {
                  ctx.drawImage(bgImg, 0, 0, canvas.width, canvas.height)
                  ctx.drawImage(img, 0, 0)
                  canvas.toBlob(
                    (blob) => {
                      if (blob) resolve(blob)
                      else reject(new Error('Failed to export image'))
                    },
                    `image/${format}`,
                    quality
                  )
                }
                bgImg.src = background
                return
              }
            }
            
            // Draw the processed image
            ctx.drawImage(img, 0, 0)
            
            canvas.toBlob(
              (blob) => {
                if (blob) resolve(blob)
                else reject(new Error('Failed to export image'))
              },
              `image/${format}`,
              quality
            )
          }
          img.onerror = () => reject(new Error('Failed to load image'))
          img.src = processedImage
        })
      },
    }))
  )
) gradient backgrounds
                const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height)
                gradient.addColorStop(0, '#667eea')
                gradient.addColorStop(1, '#764ba2')
                ctx.fillStyle = gradient
                ctx.fillRect(0, 0, canvas.width, canvas.height)
              } else {
                // Handle