-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
420 lines (363 loc) · 14.5 KB
/
Copy pathmain.js
File metadata and controls
420 lines (363 loc) · 14.5 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { $el } from "../../scripts/ui.js";
function formatTitle(text) {
return `🚀 ${text}`;
}
// Show save workflow dialog using ComfyUI native dialog
async function showSaveWorkflowDialog() {
return new Promise((resolve) => {
const html = '<h3 style="margin: 0 0 15px 0; color: var(--content-fg);">Save API Workflow</h3>' +
'<div style="margin-bottom: 15px;">' +
'<label style="display: block; margin-bottom: 5px; color: var(--content-fg);">Workflow name:</label>' +
'<input type="text" id="workflow-name" placeholder="Enter workflow name" style="width: 100%; padding: 8px; box-sizing: border-box;" required>' +
'</div>' +
'<div>' +
'<label style="display: flex; align-items: center; color: var(--content-fg);">' +
'<input type="checkbox" id="overwrite-checkbox" style="margin-right: 8px;">' +
'Overwrite if exists' +
'</label>' +
'</div>';
// Use existing dialog instance
const dialog = app.ui.dialog;
// Show the dialog with HTML content
dialog.show(html);
// Replace the default buttons with our custom buttons
const modalContent = dialog.element.querySelector('.comfy-modal-content');
const defaultButtons = modalContent.querySelectorAll('button');
defaultButtons.forEach(btn => btn.remove());
// Handle cancel
const handleCancel = () => {
dialog.close();
resolve(null);
};
// Handle save
const handleSave = () => {
const nameInput = dialog.element.querySelector('#workflow-name');
const overwriteCheckbox = dialog.element.querySelector('#overwrite-checkbox');
const name = nameInput.value.trim();
if (!name) {
alert('Please enter a workflow name');
nameInput.focus();
return;
}
dialog.close();
resolve({
name: name,
overwrite: overwriteCheckbox.checked
});
};
// Create our custom button container using $el
const buttonContainer = $el('div', {
style: {
display: 'flex',
gap: '10px',
justifyContent: 'flex-end'
}
}, [
$el('button', {
textContent: 'Cancel',
style: { padding: '8px 16px' },
onclick: handleCancel
}),
$el('button', {
textContent: 'Save',
style: { padding: '8px 16px' },
onclick: handleSave
})
]);
modalContent.appendChild(buttonContainer);
// Get elements from the dialog
const nameInput = dialog.element.querySelector('#workflow-name');
// Focus on name input
setTimeout(() => nameInput?.focus(), 100);
// Handle Enter key in name input
nameInput?.addEventListener('keydown', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
handleSave();
} else if (e.key === 'Escape') {
e.preventDefault();
handleCancel();
}
});
});
}
// Call save API
async function saveWorkflowApi(name, workflow, overwrite) {
const response = await api.fetchApi('/oneapi/v1/save-api-workflow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: name,
workflow: workflow,
overwrite: overwrite
})
});
const responseData = await response.json();
return { response, responseData };
}
// Show result message using ComfyUI native dialog
function showResultMessage(success, message) {
const title = success ? 'Save Successful' : 'Save Failed';
const color = success ? '#28a745' : '#dc3545';
const html = '<h3 style="margin: 0 0 15px 0; color: ' + color + '; text-align: center;">' + title + '</h3>' +
'<p style="margin: 0; text-align: center; color: var(--content-fg);">' + message + '</p>';
const dialog = app.ui.dialog;
// Show the dialog
dialog.show(html);
// Replace the default buttons with our custom button
const modalContent = dialog.element.querySelector('.comfy-modal-content');
const defaultButtons = modalContent.querySelectorAll('button');
defaultButtons.forEach(btn => btn.remove());
// Create our custom button container using $el
const buttonContainer = $el('div', {
style: {
display: 'flex',
justifyContent: 'center'
}
}, [
$el('button', {
textContent: 'OK',
style: { padding: '8px 16px' },
onclick: () => dialog.close(),
$: (btn) => setTimeout(() => btn.focus(), 100)
})
]);
modalContent.appendChild(buttonContainer);
}
// Main function to save workflow as API
async function saveWorkflowAsAPI() {
try {
// Get workflow data
const result = await app.graphToPrompt();
const workflow = result.output;
// Show save dialog
const formValues = await showSaveWorkflowDialog();
if (!formValues) return;
const { name, overwrite } = formValues;
// Call save API
const { response, responseData } = await saveWorkflowApi(name, workflow, overwrite);
// Show result
if (response.ok) {
showResultMessage(true, `Workflow saved as: ${responseData.filename}`);
} else {
showResultMessage(false, responseData.error || 'Unknown error');
}
} catch (error) {
console.error('Error saving workflow:', error);
showResultMessage(false, 'Error occurred while saving workflow: ' + error.message);
}
}
function addCanvasMenuOptions() {
const original_getCanvasMenuOptions = LGraphCanvas.prototype.getCanvasMenuOptions;
LGraphCanvas.prototype.getCanvasMenuOptions = function () {
// get the basic options
const originOptions = original_getCanvasMenuOptions.apply(this, arguments);
const addedOptions = [
{
content: formatTitle("Save Workflow as API"),
callback: saveWorkflowAsAPI
},
null
]
return [...addedOptions, ...originOptions];
// return originOptions;
}
}
function addExtraMenuOptions(nodeType, nodeData, app) {
const nodeTypeClass = nodeType?.comfyClass;
const original_getExtraMenuOptions = nodeType.prototype.getExtraMenuOptions;
nodeType.prototype.getExtraMenuOptions = function (_, options) {
original_getExtraMenuOptions?.apply(this, arguments);
options.splice(0, 0, {
content: formatTitle("Set Node Input"),
callback: async () => {
const selectedNodes = app.canvas.selected_nodes;
const selectedNodeIds = Object.keys(selectedNodes);
if (selectedNodeIds.length > 1) {
alert('Please select only one node');
return;
}
const nodeId = selectedNodeIds[0];
const node = selectedNodes[nodeId];
const fieldNames = node.widgets.map(e => e.name);
// Show field selection dialog
const fieldName = await showFieldSelectionDialog(fieldNames);
if (!fieldName) return;
// Show variable name input dialog
const varName = await showVariableNameDialog(fieldName);
if (!varName) return;
addVar2Node(node, varName, fieldName);
}
})
}
}
// Show field selection dialog
async function showFieldSelectionDialog(fieldNames) {
return new Promise((resolve) => {
const options = fieldNames.map((name, index) =>
'<div style="margin-bottom: 8px;">' +
'<label style="display: flex; align-items: center; color: var(--content-fg); cursor: pointer;">' +
'<input type="radio" name="field-selection" value="' + name + '" style="margin-right: 8px;">' +
name +
'</label>' +
'</div>'
).join('');
const html = '<h3 style="margin: 0 0 15px 0; color: var(--content-fg);">Select Input Field</h3>' +
'<div id="radio-container">' +
options +
'</div>';
const dialog = app.ui.dialog;
// Show the dialog
dialog.show(html);
// Replace the default buttons with our custom buttons
const modalContent = dialog.element.querySelector('.comfy-modal-content');
const defaultButtons = modalContent.querySelectorAll('button');
defaultButtons.forEach(btn => btn.remove());
const handleCancel = () => {
dialog.close();
resolve(null);
};
const handleOK = () => {
const selectedRadio = dialog.element.querySelector('input[name="field-selection"]:checked');
if (!selectedRadio) {
alert('Please select a field');
return;
}
dialog.close();
resolve(selectedRadio.value);
};
// Create our custom button container using $el
const buttonContainer = $el('div', {
style: {
display: 'flex',
gap: '10px',
justifyContent: 'flex-end'
}
}, [
$el('button', {
textContent: 'Cancel',
style: { padding: '8px 16px' },
onclick: handleCancel
}),
$el('button', {
textContent: 'OK',
style: { padding: '8px 16px' },
onclick: handleOK
})
]);
modalContent.appendChild(buttonContainer);
// Auto-select first option and focus on it
setTimeout(() => {
const firstRadio = dialog.element.querySelector('input[name="field-selection"]');
if (firstRadio) {
firstRadio.checked = true;
firstRadio.focus();
}
}, 100);
// 基于 radio 按钮父控件监听键盘事件
const radioContainer = dialog.element.querySelector('#radio-container');
radioContainer?.addEventListener('keydown', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
handleOK();
} else if (e.key === 'Escape') {
e.preventDefault();
handleCancel();
}
});
});
}
// Show variable name input dialog
async function showVariableNameDialog(fieldName) {
return new Promise((resolve) => {
const html = '<h3 style="margin: 0 0 15px 0; color: var(--content-fg);">Set Variable Name for `' + fieldName + '`</h3>' +
'<div>' +
'<input type="text" id="var-name" placeholder="Enter variable name" style="width: 100%; padding: 8px; box-sizing: border-box;" required>' +
'</div>';
const dialog = app.ui.dialog;
// Show the dialog
dialog.show(html);
// Replace the default buttons with our custom buttons
const modalContent = dialog.element.querySelector('.comfy-modal-content');
const defaultButtons = modalContent.querySelectorAll('button');
defaultButtons.forEach(btn => btn.remove());
const handleCancel = () => {
dialog.close();
resolve(null);
};
const handleOK = () => {
const varNameInput = dialog.element.querySelector('#var-name');
const varName = varNameInput.value.trim();
if (!varName) {
alert('Please enter a variable name');
varNameInput?.focus();
return;
}
dialog.close();
resolve(varName);
};
// Create our custom button container using $el
const buttonContainer = $el('div', {
style: {
display: 'flex',
gap: '10px',
justifyContent: 'flex-end'
}
}, [
$el('button', {
textContent: 'Cancel',
style: { padding: '8px 16px' },
onclick: handleCancel
}),
$el('button', {
textContent: 'OK',
style: { padding: '8px 16px' },
onclick: handleOK
})
]);
modalContent.appendChild(buttonContainer);
// Get elements
const varNameInput = dialog.element.querySelector('#var-name');
setTimeout(() => varNameInput?.focus(), 100);
// 基于文本输入框监听键盘事件
varNameInput?.addEventListener('keydown', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
handleOK();
} else if (e.key === 'Escape') {
e.preventDefault();
handleCancel();
}
});
});
}
function addVar2Node(node, varName, fieldName) {
const newPart = '$' + varName + '.' + fieldName;
// Split and remove existing items with the same fieldName
let parts = node.title.split(',').map(item => item.trim());
parts = parts.filter(item => {
// Match $xxx.fieldName
const match = item.match(/^\$[^.]+\.(.+)$/);
// Keep items that are not the current fieldName, or not in $xxx.fieldName format
return !(match && match[1] === fieldName);
});
// Add the new one
parts.push(newPart);
// Rejoin
node.title = parts.filter(Boolean).join(',');
}
app.registerExtension({
name: "ComfyUI-OneAPI-ConvertUIToAPI",
async setup() {
// Custom canvas background right-click menu
addCanvasMenuOptions();
},
async beforeRegisterNodeDef(nodeType, nodeData, app) {
// Custom node right-click menu
addExtraMenuOptions(nodeType, nodeData, app);
},
})