Line data Source code
1 : import { downloadBlob } from '@/base/common/downloadUtil'
2 : import { t } from '@/i18n'
3 : import type { IContextMenuValue } from '@/lib/litegraph/src/types/contextMenu'
4 : import type { LGraphCanvas } from '@/lib/litegraph/src/litegraph'
5 : import { reportError } from '@comfyorg/telemetry/reportError'
6 : import { selectedCanvasNodes } from '@/renderer/core/canvas/litegraph/selectionAdapter'
7 : import { useToast } from '@/components/ui/toast/toastStore'
8 : import { useDialogService } from '@/services/dialogService'
9 : import type { ComfyExtension } from '@/types/comfy'
10 : import { deserialiseAndCreate } from '@/utils/vintageClipboard'
11 : import { getErrorMessage } from '@comfyorg/shared-frontend-utils/errorUtil'
12 :
13 : import { api } from '@/scripts/api'
14 : import { app } from '@/scripts/app'
15 : import { ComfyDialog } from '@/scripts/ui'
16 : import { $el } from '@/scripts/ui/utils'
17 :
18 : // Adds the ability to save and add multiple nodes as a template
19 : // To save:
20 : // Select multiple nodes (ctrl + drag to select a region or ctrl+click individual nodes)
21 : // Right click the canvas
22 : // Save Node Template -> give it a name
23 : //
24 : // To add:
25 : // Right click the canvas
26 : // Node templates -> click the one to add
27 : //
28 : // To delete/rename:
29 : // Right click the canvas
30 : // Node templates -> Manage
31 : //
32 : // To rearrange:
33 : // Open the manage dialog and Drag and drop elements using the "Name:" label as handle
34 :
35 2355 : const id = 'Comfy.NodeTemplates'
36 2355 : const file = 'comfy.templates.json'
37 :
38 : interface NodeTemplate {
39 : name: string
40 : data: string
41 : }
42 :
43 : type TemplatesLoad =
44 : | { ok: true; templates: NodeTemplate[] }
45 : | { ok: false; cause: unknown }
46 :
47 2355 : async function fetchTemplates(): Promise<TemplatesLoad> {
48 2355 : try {
49 2355 : const res = await api.getUserData(file)
50 2344 : if (res.status === 200)
51 320 : return { ok: true, templates: (await res.json()) ?? [] }
52 2024 : if (res.status === 404) return { ok: true, templates: [] }
53 0 : return { ok: false, cause: `${res.status} ${res.statusText}` }
54 : } catch (cause) {
55 0 : return { ok: false, cause }
56 : }
57 : }
58 :
59 2355 : class ManageTemplates extends ComfyDialog {
60 : templates: NodeTemplate[] = []
61 : loading: Promise<boolean>
62 : writes: Promise<void> = Promise.resolve()
63 : draggedEl: HTMLElement | null
64 : saveVisualCue: ReturnType<typeof setTimeout> | null
65 : emptyImg: HTMLImageElement
66 : importInput: HTMLInputElement
67 :
68 : constructor() {
69 2355 : super()
70 2355 : this.loading = this.load()
71 :
72 2355 : this.element.classList.add('comfy-manage-templates')
73 2355 : this.element.dataset.testid = 'manage-node-templates-dialog'
74 2355 : this.draggedEl = null
75 2355 : this.saveVisualCue = null
76 2355 : this.emptyImg = new Image()
77 2355 : this.emptyImg.src =
78 : 'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs='
79 :
80 2355 : this.importInput = $el('input', {
81 : type: 'file',
82 : accept: '.json',
83 : multiple: true,
84 : style: { display: 'none' },
85 : parent: this.element,
86 : onchange: () => this.importAll()
87 : })
88 : }
89 :
90 : override createButtons() {
91 2355 : const btns = super.createButtons()
92 2355 : btns[0].textContent = 'Close'
93 2355 : btns[0].onclick = () => {
94 6 : if (this.saveVisualCue) clearTimeout(this.saveVisualCue)
95 6 : this.close()
96 : }
97 2355 : btns.unshift(
98 : $el('button', {
99 : type: 'button',
100 : textContent: 'Export',
101 : onclick: () => this.exportAll()
102 : })
103 : )
104 2355 : btns.unshift(
105 : $el('button', {
106 : type: 'button',
107 : textContent: 'Import',
108 : onclick: () => {
109 0 : this.importInput.click()
110 : }
111 : })
112 : )
113 2355 : return btns
114 : }
115 :
116 : async load(): Promise<boolean> {
117 2355 : const result = await fetchTemplates()
118 2344 : if (result.ok) {
119 2344 : this.templates = result.templates
120 2344 : return true
121 : }
122 0 : reportError(result.cause, {
123 : surface: 'graph',
124 : errorType: 'failure_loading_node_templates',
125 : tags: {
126 : failure_kind: 'caught_unexpected',
127 : feature_area: 'extensions',
128 : operation: 'load',
129 : outcome: 'recovered'
130 : },
131 : level: 'error'
132 : })
133 0 : return false
134 : }
135 :
136 : store(
137 : update: (templates: NodeTemplate[]) => NodeTemplate[] = (templates) =>
138 : templates
139 : ) {
140 10 : this.writes = this.writes.then(() => this.write(update))
141 10 : return this.writes
142 : }
143 :
144 : async write(update: (templates: NodeTemplate[]) => NodeTemplate[]) {
145 10 : if (!(await this.loading)) {
146 0 : useToast().warning(t('toastMessages.failedToSaveNodeTemplates'), {
147 : description: t('nodeTemplates.notLoaded')
148 : })
149 0 : return
150 : }
151 10 : const next = update(this.templates)
152 10 : const templates = JSON.stringify(next, undefined, 4)
153 10 : try {
154 10 : await api.storeUserData(file, templates, { stringify: false })
155 10 : this.templates = next
156 : } catch (error) {
157 0 : console.error(error)
158 0 : useToast().warning(t('toastMessages.failedToSaveNodeTemplates'), {
159 : description: getErrorMessage(error) ?? t('g.unknownError')
160 : })
161 : }
162 : }
163 :
164 : async importAll() {
165 1 : for (const file of this.importInput.files ?? []) {
166 1 : if (file.type === 'application/json' || file.name.endsWith('.json')) {
167 1 : const reader = new FileReader()
168 1 : reader.onload = async () => {
169 1 : const importFile = JSON.parse(reader.result as string)
170 1 : if (importFile?.templates) {
171 1 : const imported = importFile.templates.filter(
172 : (template: Partial<NodeTemplate> | null) =>
173 : template?.name && template.data
174 : )
175 1 : await this.store((templates) => [...templates, ...imported])
176 : }
177 : }
178 1 : await reader.readAsText(file)
179 : }
180 : }
181 :
182 1 : this.importInput.value = ''
183 :
184 1 : this.close()
185 : }
186 :
187 : exportAll() {
188 0 : if (this.templates.length == 0) {
189 0 : useToast().warning(t('toastMessages.noTemplatesToExport'))
190 0 : return
191 : }
192 :
193 0 : const json = JSON.stringify({ templates: this.templates }, null, 2) // convert the data to a JSON string
194 0 : const blob = new Blob([json], { type: 'application/json' })
195 0 : downloadBlob('node_templates.json', blob)
196 : }
197 :
198 : override show() {
199 : // Show list of template names + delete button
200 7 : super.show(
201 : $el(
202 : 'div',
203 : {},
204 : this.templates.flatMap((t, i) => {
205 6 : let nameInput: HTMLInputElement
206 6 : return [
207 : $el(
208 : 'div',
209 : {
210 : dataset: { id: i.toString() },
211 : className: 'templateManagerRow',
212 : style: {
213 : display: 'grid',
214 : gridTemplateColumns: '1fr auto',
215 : border: '1px dashed transparent',
216 : gap: '5px',
217 : backgroundColor: 'var(--background)'
218 : },
219 : ondragstart: (e: DragEvent) => {
220 0 : const row = e.currentTarget
221 0 : if (!(row instanceof HTMLElement) || !e.dataTransfer) return
222 0 : this.draggedEl = row
223 0 : row.style.opacity = '0.6'
224 0 : row.style.border = '1px dashed yellow'
225 0 : e.dataTransfer.effectAllowed = 'move'
226 0 : e.dataTransfer.setDragImage(this.emptyImg, 0, 0)
227 : },
228 : ondragend: (e: DragEvent) => {
229 0 : const row = e.currentTarget
230 0 : if (!(row instanceof HTMLElement)) return
231 0 : row.style.opacity = '1'
232 0 : row.style.border = '1px dashed transparent'
233 0 : row.removeAttribute('draggable')
234 :
235 : // rearrange the elements
236 0 : this.element
237 : .querySelectorAll<HTMLElement>('.templateManagerRow')
238 : .forEach((el, i) => {
239 0 : const prev_i = Number.parseInt(el.dataset.id ?? '')
240 :
241 0 : if (el == this.draggedEl && prev_i != i) {
242 0 : this.templates.splice(
243 : i,
244 : 0,
245 : this.templates.splice(prev_i, 1)[0]
246 : )
247 : }
248 0 : el.dataset.id = i.toString()
249 : })
250 0 : void this.store()
251 : },
252 : ondragover: (e: DragEvent) => {
253 0 : e.preventDefault()
254 0 : const row = e.currentTarget
255 0 : const draggedEl = this.draggedEl
256 0 : if (
257 : !(row instanceof HTMLElement) ||
258 : !row.parentNode ||
259 : !draggedEl
260 : )
261 0 : return
262 0 : if (row == this.draggedEl) return
263 :
264 0 : const rect = row.getBoundingClientRect()
265 0 : if (e.clientY > rect.top + rect.height / 2) {
266 0 : row.parentNode.insertBefore(draggedEl, row.nextSibling)
267 : } else {
268 0 : row.parentNode.insertBefore(draggedEl, row)
269 : }
270 : }
271 : },
272 : [
273 : $el(
274 : 'label',
275 : {
276 : textContent: 'Name: ',
277 : style: {
278 : cursor: 'grab'
279 : },
280 : onmousedown: (e: MouseEvent) => {
281 : // enable dragging only from the label
282 0 : const label = e.currentTarget
283 0 : if (
284 : e.target instanceof HTMLLabelElement &&
285 : label instanceof HTMLLabelElement &&
286 : label.parentElement
287 : )
288 0 : label.parentElement.draggable = true
289 : }
290 : },
291 : [
292 : $el('input', {
293 : value: t.name,
294 : dataset: { name: t.name },
295 : style: {
296 : transitionProperty: 'background-color',
297 : transitionDuration: '0s'
298 : },
299 : onchange: (e: Event) => {
300 0 : const el = e.target
301 0 : if (!(el instanceof HTMLInputElement)) return
302 0 : if (this.saveVisualCue) clearTimeout(this.saveVisualCue)
303 0 : const row = el.closest<HTMLElement>(
304 : '.templateManagerRow'
305 : )
306 0 : if (!row) return
307 0 : this.templates[Number(row.dataset.id)].name =
308 : el.value.trim() || 'untitled'
309 0 : void this.store()
310 0 : el.style.backgroundColor = 'rgb(40, 95, 40)'
311 0 : el.style.transitionDuration = '0s'
312 0 : this.saveVisualCue = setTimeout(function () {
313 0 : el.style.transitionDuration = '.7s'
314 0 : el.style.backgroundColor = 'var(--input)'
315 : }, 15)
316 : },
317 : onkeypress: (e: KeyboardEvent) => {
318 0 : const el = e.target
319 0 : if (!(el instanceof HTMLInputElement)) return
320 0 : if (this.saveVisualCue) clearTimeout(this.saveVisualCue)
321 0 : el.style.transitionDuration = '0s'
322 0 : el.style.backgroundColor = 'var(--input)'
323 : },
324 : $: (el) => {
325 6 : if (el instanceof HTMLInputElement) nameInput = el
326 : }
327 : })
328 : ]
329 : ),
330 : $el('div', {}, [
331 : $el('button', {
332 : textContent: 'Export',
333 : style: {
334 : fontSize: '12px',
335 : fontWeight: 'normal'
336 : },
337 : onclick: () => {
338 1 : const json = JSON.stringify({ templates: [t] }, null, 2) // convert the data to a JSON string
339 1 : const blob = new Blob([json], {
340 : type: 'application/json'
341 : })
342 1 : const name = (nameInput.value || t.name) + '.json'
343 1 : downloadBlob(name, blob)
344 : }
345 : }),
346 : $el('button', {
347 : textContent: 'Delete',
348 : style: {
349 : fontSize: '12px',
350 : color: 'red',
351 : fontWeight: 'normal'
352 : },
353 : onclick: (e: MouseEvent) => {
354 2 : const target = e.target
355 2 : if (!(target instanceof HTMLElement)) return
356 2 : const item = target.closest<HTMLElement>(
357 : '.templateManagerRow'
358 : )
359 2 : if (!item) return
360 2 : item.remove()
361 2 : this.templates.splice(Number(item.dataset.id), 1)
362 2 : void this.store()
363 : // update the rows index, setTimeout ensures that the list is updated
364 2 : setTimeout(() => {
365 2 : this.element
366 : .querySelectorAll<HTMLElement>('.templateManagerRow')
367 : .forEach((el, i) => {
368 0 : el.dataset.id = i.toString()
369 : })
370 : }, 0)
371 : }
372 : })
373 : ])
374 : ]
375 : )
376 : ]
377 : })
378 : )
379 : )
380 : }
381 : }
382 :
383 2355 : let manager: ManageTemplates | undefined
384 :
385 2387 : function getManager(): ManageTemplates {
386 2387 : manager ??= new ManageTemplates()
387 2387 : return manager
388 : }
389 :
390 2355 : const clipboardAction = async (cb: () => void | Promise<void>) => {
391 : // We use the clipboard functions but dont want to overwrite the current user clipboard
392 : // Restore it after we've run our callback
393 9 : const old = localStorage.getItem('litegrapheditor_clipboard')
394 9 : await cb()
395 9 : if (old === null) localStorage.removeItem('litegrapheditor_clipboard')
396 0 : else localStorage.setItem('litegrapheditor_clipboard', old)
397 : }
398 :
399 2355 : export const nodeTemplatesExtension: ComfyExtension = {
400 : name: id,
401 :
402 : setup() {
403 2355 : getManager()
404 : },
405 :
406 : getCanvasMenuItems(_canvas: LGraphCanvas): (IContextMenuValue | null)[] {
407 32 : const manage = getManager()
408 32 : const items: (IContextMenuValue | null)[] = []
409 :
410 32 : items.push(null)
411 32 : items.push({
412 : content: `Save Selected as Template`,
413 : disabled: !selectedCanvasNodes(app.canvas).length,
414 : callback: async () => {
415 7 : const name = await useDialogService().prompt({
416 : title: t('nodeTemplates.saveAsTemplate'),
417 : message: t('nodeTemplates.enterName'),
418 : defaultValue: ''
419 : })
420 7 : if (!name?.trim()) return
421 :
422 7 : await clipboardAction(async () => {
423 7 : app.canvas.copyToClipboard()
424 7 : const data = localStorage.getItem('litegrapheditor_clipboard')
425 :
426 7 : await manage.store((templates) => [
427 : ...templates,
428 : { name, data: data || '{}' }
429 : ])
430 : })
431 : }
432 : })
433 :
434 32 : const subItems: (IContextMenuValue | null)[] = manage.templates.map(
435 : (template) => {
436 9 : return {
437 : content: template.name,
438 : callback: async () => {
439 2 : await clipboardAction(() => {
440 2 : let data: { reroutes?: unknown }
441 2 : try {
442 2 : data = JSON.parse(template.data)
443 : } catch (error) {
444 0 : console.error('Failed to parse node template data', error)
445 0 : useToast().warning(t('toastMessages.invalidTemplateData'))
446 0 : return
447 : }
448 :
449 2 : if (!data.reroutes) {
450 0 : deserialiseAndCreate(template.data, app.canvas)
451 : } else {
452 2 : localStorage.setItem('litegrapheditor_clipboard', template.data)
453 2 : app.canvas.pasteFromClipboard()
454 : }
455 : })
456 : }
457 : }
458 : }
459 : )
460 :
461 32 : subItems.push(null, {
462 : content: 'Manage',
463 : callback: () => manage.show()
464 : })
465 :
466 32 : items.push({
467 : content: 'Node Templates',
468 : submenu: {
469 : options: subItems
470 : }
471 : })
472 :
473 32 : return items
474 : }
475 : }
|