Line data Source code
1 : import { toValue } from 'vue'
2 : import type { MaybeRefOrGetter, Ref } from 'vue'
3 : import type { UploadImageResponse } from '@comfyorg/ingest-types'
4 :
5 : import { useErrorHandling } from '@/composables/useErrorHandling'
6 : import { useToast } from '@/components/ui/toast/toastStore'
7 : import { t } from '@/i18n'
8 : import { resolveWidgetValueAsset } from '@/platform/assets/utils/resolveWidgetValueAsset'
9 : import type { ResultItem } from '@comfyorg/api-client/executionTypes'
10 : import { ServerFeatureFlag } from '@/platform/remoteConfig/serverFeatureFlag'
11 : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
12 : import type { FormDropdownItem } from '@/renderer/extensions/vueNodes/widgets/components/form/dropdown/types'
13 : import type { ResultItemType } from '@comfyorg/api-client/resultItemTypeSchema'
14 : import { api } from '@/scripts/api'
15 : import { useAssetsStore } from '@/stores/assetsStore'
16 : import { useNodeOutputStore } from '@/stores/nodeOutputStore'
17 : import type { NodeLocatorId } from '@comfyorg/graph-model/nodeIdentification'
18 : import type { SimplifiedWidget } from '@/types/simplifiedWidget'
19 : import { isHdrImageFilename } from '@/utils/hdrFormatUtil'
20 : import { parseImageWidgetValue } from '@/utils/imageUtil'
21 : import { isExtensionlessVideo } from '@/utils/mediaUploadUtil'
22 : import { isResultItemType } from '@/utils/typeGuardUtil'
23 :
24 847 : const BYTES_PER_MB = 1024 * 1024
25 : interface UploadResponse extends UploadImageResponse {
26 : asset?: { preview_id?: string }
27 : }
28 :
29 0 : function buildUploadErrorMessage(resp: Response) {
30 0 : if (resp.status === 413) {
31 0 : const maxUploadSize = api.getServerFeature<number>(
32 : ServerFeatureFlag.MAX_UPLOAD_SIZE
33 : )
34 0 : return typeof maxUploadSize === 'number' && maxUploadSize > 0
35 : ? t('g.uploadFileTooLargeWithLimit', {
36 : limit: Math.round(maxUploadSize / BYTES_PER_MB)
37 : })
38 : : t('g.uploadFileTooLarge')
39 : }
40 :
41 0 : return t('g.uploadFailed', {
42 : reason: resp.statusText || `HTTP ${resp.status}`
43 : })
44 : }
45 :
46 16 : function toUploadedPath({ subfolder, name }: UploadResponse) {
47 16 : return subfolder ? `${subfolder}/${name}` : name
48 : }
49 :
50 16 : function addMissingOptionValues(
51 : widget: SimplifiedWidget<string | undefined>,
52 : paths: (string | undefined)[]
53 : ) {
54 16 : const values = widget.options?.values
55 16 : if (!Array.isArray(values)) return
56 16 : for (const path of paths) if (!values.includes(path)) values.push(path)
57 : }
58 :
59 : interface UseWidgetSelectActionsOptions {
60 : modelValue: Ref<string | undefined>
61 : dropdownItems: MaybeRefOrGetter<readonly FormDropdownItem[]>
62 : widget: MaybeRefOrGetter<SimplifiedWidget<string | undefined>>
63 : uploadFolder: MaybeRefOrGetter<ResultItemType | undefined>
64 : uploadSubfolder: MaybeRefOrGetter<string | undefined>
65 : locatorId?: MaybeRefOrGetter<NodeLocatorId | undefined>
66 : }
67 :
68 197 : export function useWidgetSelectActions(options: UseWidgetSelectActionsOptions) {
69 197 : const { modelValue, dropdownItems } = options
70 197 : const toast = useToast()
71 197 : const { wrapWithErrorHandlingAsync } = useErrorHandling()
72 :
73 2 : function setPreviewImage(image: ResultItem) {
74 2 : const locatorId = toValue(options.locatorId)
75 2 : if (locatorId)
76 2 : useNodeOutputStore().nodeOutputs[locatorId] = { images: [image] }
77 : }
78 :
79 197 : const showHdrPreviewIfApplicable = wrapWithErrorHandlingAsync(
80 : async (widgetValue: string | undefined) => {
81 199 : if (!widgetValue) return
82 167 : const { filename, subfolder, type } = parseImageWidgetValue(widgetValue)
83 167 : if (!isHdrImageFilename(filename)) return
84 :
85 0 : const asset = await resolveWidgetValueAsset(widgetValue)
86 199 : if (!asset?.preview_id || modelValue.value !== widgetValue) return
87 :
88 199 : setPreviewImage({
89 : filename,
90 : preview_id: asset.preview_id,
91 : subfolder,
92 : type: isResultItemType(type) ? type : undefined
93 : })
94 : }
95 : )
96 :
97 197 : void showHdrPreviewIfApplicable(modelValue.value)
98 :
99 2 : function updateSelectedItems(selectedItems: Set<string>) {
100 2 : const id =
101 : selectedItems.size > 0 ? selectedItems.values().next().value : undefined
102 2 : const name =
103 : id == null
104 : ? undefined
105 : : toValue(dropdownItems).find((item) => item.id === id)?.name
106 :
107 2 : modelValue.value = name
108 2 : void showHdrPreviewIfApplicable(name)
109 2 : useWorkflowStore().activeWorkflow?.changeTracker.captureCanvasState()
110 : }
111 :
112 16 : async function uploadFile(
113 : file: File,
114 : isPasted: boolean = false,
115 : formFields: Partial<{ type: ResultItemType }> = {}
116 : ) {
117 16 : const body = new FormData()
118 16 : body.append('image', file)
119 16 : if (isPasted) body.append('subfolder', 'pasted')
120 : else {
121 16 : const subfolder = toValue(options.uploadSubfolder)
122 16 : if (subfolder) body.append('subfolder', subfolder)
123 : }
124 16 : if (formFields.type) body.append('type', formFields.type)
125 :
126 16 : const resp = await api.fetchApi('/upload/image', {
127 : method: 'POST',
128 : body
129 : })
130 :
131 16 : if (resp.status !== 200) {
132 0 : toast.warning(buildUploadErrorMessage(resp))
133 0 : return null
134 : }
135 :
136 16 : const data: UploadResponse = await resp.json()
137 :
138 16 : if (formFields.type === 'input' || (!formFields.type && !isPasted)) {
139 16 : await useAssetsStore().inputAssets.invalidate()
140 : }
141 :
142 16 : return data
143 : }
144 :
145 16 : async function uploadFiles(files: File[]): Promise<UploadResponse[]> {
146 16 : const folder = toValue(options.uploadFolder) ?? 'input'
147 16 : const uploadPromises = files.map((file) =>
148 : uploadFile(file, false, { type: folder })
149 : )
150 16 : return (await Promise.all(uploadPromises)).filter((data) => !!data)
151 : }
152 :
153 16 : function showUploadPreview(upload: UploadResponse) {
154 16 : if (!upload.asset?.preview_id) return
155 16 : setPreviewImage({
156 : filename: upload.name,
157 : preview_id: upload.asset.preview_id,
158 : subfolder: upload.subfolder,
159 : type: isResultItemType(upload.type) ? upload.type : undefined
160 : })
161 : }
162 :
163 : const handleFilesUpdate = wrapWithErrorHandlingAsync(
164 : async (files: File[]) => {
165 17 : if (files.length === 0) return
166 17 : if (files.some(isExtensionlessVideo)) {
167 1 : toast.warning(t('g.videoFilenameExtensionRequired'))
168 1 : return
169 : }
170 :
171 16 : const uploadedResponses = await uploadFiles(files)
172 16 : const uploadedPaths = uploadedResponses.map(toUploadedPath)
173 :
174 17 : if (uploadedPaths.length === 0) {
175 0 : toast.warning(t('toastMessages.fileUploadFailed'))
176 0 : return
177 : }
178 :
179 16 : const widget = toValue(options.widget)
180 16 : addMissingOptionValues(widget, uploadedPaths)
181 16 : modelValue.value = uploadedPaths[0]
182 17 : widget.callback?.(uploadedPaths[0])
183 17 : showUploadPreview(uploadedResponses[0])
184 :
185 17 : useWorkflowStore().activeWorkflow?.changeTracker.captureCanvasState()
186 : }
187 : )
188 :
189 197 : return {
190 : updateSelectedItems,
191 : handleFilesUpdate
192 : }
193 : }
|