Line data Source code
1 : import type { UploadImageResponse } from '@comfyorg/ingest-types'
2 :
3 : import { writeImageWidgetValue } from '@/renderer/extensions/maskEditor/composables/imageWidgetAdapter'
4 : import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
5 : import { useMaskEditorDataStore } from '@/renderer/extensions/maskEditor/stores/maskEditorDataStore'
6 : import { useMaskEditorStore } from '@comfyorg/mask-editor/maskEditorStore'
7 : import { useNodeOutputStore } from '@/stores/nodeOutputStore'
8 : import type {
9 : EditorOutputData,
10 : EditorOutputLayer,
11 : ImageRef
12 : } from '@/renderer/extensions/maskEditor/stores/maskEditorDataStore'
13 : import { api } from '@/scripts/api'
14 : import { useApp } from '@/scripts/appInstance'
15 : import { createImageOutput } from '@comfyorg/mask-editor/imageOutput'
16 : import { imageLayerFilenamesByTimestamp } from './layerFilenames'
17 : import { isResultItemType } from '@/utils/typeGuardUtil'
18 :
19 31 : export function useMaskEditorSaver() {
20 31 : const dataStore = useMaskEditorDataStore()
21 31 : const editorStore = useMaskEditorStore()
22 31 : const nodeOutputStore = useNodeOutputStore()
23 :
24 31 : const save = async (): Promise<void> => {
25 8 : const sourceNode = dataStore.sourceNode
26 8 : if (!sourceNode || !dataStore.inputData) {
27 0 : throw new Error('No source node or input data')
28 : }
29 :
30 8 : try {
31 8 : const outputData = await prepareOutputData()
32 8 : dataStore.outputData = outputData
33 :
34 8 : await updateNodePreview(sourceNode, outputData)
35 :
36 8 : await uploadAllLayers(outputData)
37 :
38 6 : updateNodeWithServerReferences(sourceNode, outputData)
39 :
40 6 : useApp().canvas.setDirty(true)
41 : } catch (error) {
42 2 : console.error('[MaskEditorSaver] Save failed:', error)
43 2 : throw error
44 : }
45 : }
46 :
47 8 : async function prepareOutputData(): Promise<EditorOutputData> {
48 8 : const maskCanvas = editorStore.maskCanvas
49 8 : const paintCanvas = editorStore.rgbCanvas
50 8 : const imgCanvas = editorStore.imgCanvas
51 :
52 8 : if (!maskCanvas || !paintCanvas || !imgCanvas) {
53 0 : throw new Error('Canvas not initialized')
54 : }
55 :
56 : const timestamp = Date.now()
57 8 : const filenames = imageLayerFilenamesByTimestamp(timestamp)
58 :
59 8 : const layers = await createImageOutput({
60 : imgCanvas,
61 : maskCanvas,
62 : paintCanvas
63 : })
64 :
65 8 : return {
66 : maskedImage: {
67 : ...layers.maskedImage,
68 : ref: createFileRef(filenames.maskedImage)
69 : },
70 : paintLayer: { ...layers.paintLayer, ref: createFileRef(filenames.paint) },
71 : paintedImage: {
72 : ...layers.paintedImage,
73 : ref: createFileRef(filenames.paintedImage)
74 : },
75 : paintedMaskedImage: {
76 : ...layers.paintedMaskedImage,
77 : ref: createFileRef(filenames.paintedMaskedImage)
78 : }
79 : }
80 : }
81 :
82 8 : async function uploadAllLayers(outputData: EditorOutputData): Promise<void> {
83 8 : const actualMaskedRef = await uploadLayer(outputData.maskedImage)
84 6 : const actualPaintRef = await uploadLayer(outputData.paintLayer)
85 6 : const actualPaintedRef = await uploadLayer(outputData.paintedImage)
86 6 : const actualPaintedMaskedRef = await uploadLayer(
87 : outputData.paintedMaskedImage
88 : )
89 :
90 6 : outputData.maskedImage.ref = actualMaskedRef
91 6 : outputData.paintLayer.ref = actualPaintRef
92 6 : outputData.paintedImage.ref = actualPaintedRef
93 6 : outputData.paintedMaskedImage.ref = actualPaintedMaskedRef
94 : }
95 :
96 26 : async function uploadLayer(layer: EditorOutputLayer): Promise<ImageRef> {
97 26 : const formData = new FormData()
98 26 : formData.append('image', layer.blob, layer.ref.filename)
99 26 : formData.append('type', 'input')
100 :
101 26 : const response = await api.fetchApi('/upload/image', {
102 : method: 'POST',
103 : body: formData
104 : })
105 :
106 26 : if (!response.ok) {
107 2 : const body = await response.text().catch(() => '')
108 2 : throw new Error(
109 : `Failed to upload ${layer.ref.filename} (${response.status}${body ? `: ${body}` : ''})`
110 : )
111 : }
112 :
113 24 : let data: UploadImageResponse
114 24 : try {
115 24 : data = await response.json()
116 : } catch (error) {
117 0 : throw new Error(
118 : `Invalid upload response for ${layer.ref.filename}: ${
119 : error instanceof Error ? error.message : String(error)
120 : }`,
121 : { cause: error }
122 : )
123 : }
124 :
125 24 : if (!data.name) {
126 0 : throw new Error(
127 : `Upload response missing 'name' for ${layer.ref.filename}`
128 : )
129 : }
130 :
131 26 : return {
132 : filename: data.name,
133 : subfolder: data.subfolder || '',
134 : type: data.type || 'input'
135 : }
136 : }
137 :
138 8 : async function updateNodePreview(
139 : node: LGraphNode,
140 : outputData: EditorOutputData
141 : ): Promise<void> {
142 : const canvas = outputData.paintedMaskedImage.canvas
143 : const dataUrl = canvas.toDataURL('image/png')
144 :
145 : const mainImg = await loadImageFromUrl(dataUrl)
146 8 : node.imgs = [mainImg]
147 :
148 8 : useApp().canvas.setDirty(true)
149 : }
150 :
151 6 : function updateNodeWithServerReferences(
152 : node: LGraphNode,
153 : outputData: EditorOutputData
154 : ): void {
155 6 : if (!node.graph) return
156 :
157 6 : const mainRef = outputData.paintedMaskedImage.ref
158 :
159 6 : writeImageWidgetValue(
160 : node,
161 : mainRef.filename + (mainRef.type ? ` [${mainRef.type}]` : '')
162 : )
163 :
164 6 : node.imgs = undefined
165 6 : nodeOutputStore.replaceNodeOutputImages(node, [
166 : {
167 : filename: mainRef.filename,
168 : subfolder: mainRef.subfolder,
169 : type: isResultItemType(mainRef.type) ? mainRef.type : 'input'
170 : }
171 : ])
172 6 : node.graph.setDirtyCanvas(true)
173 : }
174 :
175 8 : function loadImageFromUrl(url: string): Promise<HTMLImageElement> {
176 8 : return new Promise((resolve, reject) => {
177 8 : const img = new Image()
178 8 : img.crossOrigin = 'anonymous'
179 :
180 8 : img.onload = () => resolve(img)
181 8 : img.onerror = (error) => {
182 0 : console.error('[MaskEditorSaver] Failed to load image:', url, error)
183 0 : reject(new Error(`Failed to load image: ${url}`))
184 : }
185 :
186 8 : img.src = url
187 : })
188 : }
189 :
190 32 : function createFileRef(filename: string): ImageRef {
191 32 : return {
192 : filename,
193 : subfolder: 'clipspace',
194 : type: 'input'
195 : }
196 : }
197 :
198 31 : return {
199 : save
200 : }
201 : }
|