Line data Source code
1 : import { default as DOMPurify } from 'dompurify'
2 :
3 : import { LGraphCanvas, LiteGraph } from '@/lib/litegraph/src/litegraph'
4 : import type {
5 : IContextMenuValue,
6 : LGraphNode,
7 : IContextMenuOptions,
8 : ContextMenu
9 : } from '@/lib/litegraph/src/litegraph'
10 :
11 : import type { MenuOption, SubMenuOption } from './menuOption'
12 : import type { ContextMenuDivElement } from '@/lib/litegraph/src/types/contextMenu'
13 :
14 : /**
15 : * Hard blacklist - items that should NEVER be included
16 : */
17 2355 : const HARD_BLACKLIST = new Set([
18 : 'Properties', // Never include Properties submenu
19 : 'Colors', // Use singular "Color" instead
20 : 'Shapes', // Use singular "Shape" instead
21 : 'Title',
22 : 'Mode',
23 : 'Properties Panel',
24 : 'Copy (Clipspace)',
25 : // Vue getBypassOption supplies the single state-aware Bypass/Remove Bypass item
26 : 'Bypass',
27 : 'Remove Bypass'
28 : ])
29 :
30 : /**
31 : * Callbacks of built-in LiteGraph node menu items that are superseded by
32 : * the Vue node menu (Minimize Node / Expand Node) or have no working
33 : * Vue-side equivalent. Matched by callback identity so that extensions
34 : * providing their own items with the same labels are not affected.
35 : */
36 2355 : const SUPPRESSED_LITEGRAPH_CALLBACKS = new Set<unknown>([
37 : LGraphCanvas.onMenuResizeNode,
38 : LGraphCanvas.onMenuNodeCollapse
39 : ])
40 :
41 : /**
42 : * Core menu items - items that should appear in the main menu, not under Extensions
43 : * Includes both LiteGraph base menu items and ComfyUI built-in functionality
44 : */
45 2355 : const CORE_MENU_ITEMS = new Set([
46 : // Basic operations
47 : 'Rename',
48 : 'Copy',
49 : 'Duplicate',
50 : 'Clone',
51 : // Node state operations
52 : 'Run Branch',
53 : 'Pin',
54 : 'Unpin',
55 : 'Bypass',
56 : 'Remove Bypass',
57 : 'Mute',
58 : // Structure operations
59 : 'Convert to Subgraph',
60 : 'Frame selection',
61 : 'Frame Nodes',
62 : 'Minimize Node',
63 : 'Expand Node',
64 : // Info and adjustments
65 : 'Node Info',
66 : 'Title',
67 : 'Properties Panel',
68 : 'Adjust Size',
69 : // Visual
70 : 'Color',
71 : 'Colors',
72 : 'Shape',
73 : 'Shapes',
74 : 'Mode',
75 : // Built-in node operations (node-specific)
76 : 'Open Image',
77 : 'Copy Image',
78 : 'Paste Image',
79 : 'Save Image',
80 : 'Show Full Resolution',
81 : 'Show Downscaled Preview',
82 : 'Open in Mask Editor',
83 : 'Edit Subgraph Widgets',
84 : 'Unpack Subgraph',
85 : 'Copy (Clipspace)',
86 : 'Paste (Clipspace)',
87 : // Selection and alignment
88 : 'Align Selected To',
89 : 'Distribute Nodes',
90 : // Deletion
91 : 'Delete',
92 : 'Remove',
93 : // LiteGraph base items
94 : 'Show Advanced',
95 : 'Hide Advanced'
96 : ])
97 :
98 : /**
99 : * Normalize menu item label for duplicate detection
100 : * Handles variations like Colors/Color, Shapes/Shape, Pin/Unpin, Remove/Delete
101 : */
102 31367 : function normalizeLabel(label: string): string {
103 31367 : return label
104 : .toLowerCase()
105 : .replace(/^un/, '') // Remove 'un' prefix (Unpin -> Pin)
106 : .trim()
107 : }
108 :
109 : /**
110 : * Check if a similar menu item already exists in the results
111 : * Returns true if an item with the same normalized label exists
112 : */
113 10934 : function isDuplicateItem(label: string, existingItems: MenuOption[]): boolean {
114 10934 : const normalizedLabel = normalizeLabel(label)
115 :
116 : // Map of equivalent items
117 10934 : const equivalents: Record<string, string[]> = {
118 : color: ['color', 'colors'],
119 : shape: ['shape', 'shapes'],
120 : pin: ['pin', 'unpin'],
121 : delete: ['remove', 'delete'],
122 : duplicate: ['clone', 'duplicate'],
123 : frame: ['frame selection', 'frame nodes']
124 : }
125 :
126 10934 : return existingItems.some((item) => {
127 34616 : if (!item.label) return false
128 :
129 20433 : const existingNormalized = normalizeLabel(item.label)
130 :
131 : // Check direct match
132 34616 : if (existingNormalized === normalizedLabel) return true
133 :
134 : // Check if they're in the same equivalence group
135 34616 : for (const values of Object.values(equivalents)) {
136 122562 : if (
137 : values.includes(normalizedLabel) &&
138 : values.includes(existingNormalized)
139 : ) {
140 0 : return true
141 : }
142 : }
143 :
144 20427 : return false
145 : })
146 : }
147 :
148 : /**
149 : * Check if a menu item is a core menu item (not an extension)
150 : * Core items include LiteGraph base items and ComfyUI built-in functionality
151 : */
152 128491 : function isCoreMenuItem(label: string): boolean {
153 128491 : return CORE_MENU_ITEMS.has(label)
154 : }
155 :
156 : /**
157 : * Filter out duplicate menu items based on label
158 : * Gives precedence to Vue hardcoded options over LiteGraph options
159 : */
160 13532 : function removeDuplicateMenuOptions(options: MenuOption[]): MenuOption[] {
161 : // Group items by label
162 13532 : const itemsByLabel = new Map<string, MenuOption[]>()
163 13532 : const itemsWithoutLabel: MenuOption[] = []
164 :
165 13532 : for (const opt of options) {
166 : // Always keep dividers and category items
167 210148 : if (opt.type === 'divider' || opt.type === 'category') {
168 61096 : itemsWithoutLabel.push(opt)
169 61096 : continue
170 : }
171 :
172 : // Items without labels are kept as-is
173 210148 : if (!opt.label) {
174 0 : itemsWithoutLabel.push(opt)
175 0 : continue
176 : }
177 :
178 : // Group by label
179 180069 : if (!itemsByLabel.has(opt.label)) {
180 144170 : itemsByLabel.set(opt.label, [])
181 : }
182 149052 : itemsByLabel.get(opt.label)!.push(opt)
183 : }
184 :
185 : // Select best item for each label (prefer vue over litegraph)
186 13532 : const result: MenuOption[] = []
187 13532 : const seenLabels = new Set<string>()
188 :
189 13532 : for (const opt of options) {
190 : // Add non-labeled items in original order
191 210148 : if (opt.type === 'divider' || opt.type === 'category' || !opt.label) {
192 61096 : if (itemsWithoutLabel.includes(opt)) {
193 61096 : result.push(opt)
194 61096 : const idx = itemsWithoutLabel.indexOf(opt)
195 61096 : itemsWithoutLabel.splice(idx, 1)
196 : }
197 61096 : continue
198 : }
199 :
200 : // Skip if we already processed this label
201 210148 : if (seenLabels.has(opt.label)) {
202 4882 : continue
203 : }
204 144170 : seenLabels.add(opt.label)
205 :
206 : // Get all items with this label
207 144170 : const duplicates = itemsByLabel.get(opt.label)!
208 :
209 : // If only one item, add it
210 180069 : if (duplicates.length === 1) {
211 139288 : result.push(duplicates[0])
212 139288 : continue
213 : }
214 :
215 : // Multiple items: prefer vue source over litegraph
216 4882 : const vueItem = duplicates.find((item) => item.source === 'vue')
217 104752 : if (vueItem) {
218 4882 : result.push(vueItem)
219 : } else {
220 : // No vue item, just take the first one
221 0 : result.push(duplicates[0])
222 : }
223 : }
224 :
225 13532 : return result
226 : }
227 :
228 : /**
229 : * Order groups for menu items - defines the display order of sections
230 : */
231 2355 : const MENU_ORDER: string[] = [
232 : // Section 0: Media operations (surfaced at the top for media nodes)
233 : 'Open Image',
234 : 'Open in Mask Editor',
235 : 'Copy Image',
236 : 'Paste Image',
237 : 'Save Image',
238 : 'Show Full Resolution',
239 : 'Show Downscaled Preview',
240 : // Section 1: Basic operations
241 : 'Rename',
242 : 'Copy',
243 : 'Duplicate',
244 : // Section 2: Node actions
245 : 'Run Branch',
246 : 'Pin',
247 : 'Unpin',
248 : 'Bypass',
249 : 'Remove Bypass',
250 : 'Mute',
251 : // Section 3: Structure operations
252 : 'Convert to Subgraph',
253 : 'Frame selection',
254 : 'Frame Nodes',
255 : 'Minimize Node',
256 : 'Expand Node',
257 : 'Clone',
258 : // Section 4: Node properties
259 : 'Node Info',
260 : 'Color',
261 : // Section 5: Clipspace operations
262 : 'Copy (Clipspace)',
263 : 'Paste (Clipspace)'
264 : ]
265 :
266 : /**
267 : * Get the order index for a menu item (lower = earlier in menu)
268 : */
269 605266 : function getMenuItemOrder(label: string): number {
270 605266 : const index = MENU_ORDER.indexOf(label)
271 605266 : return index === -1 ? 999 : index
272 : }
273 :
274 : /**
275 : * Build structured menu with core items first, then extensions under a labeled section
276 : * Ensures Delete always appears at the bottom
277 : */
278 13532 : export function buildStructuredMenu(options: MenuOption[]): MenuOption[] {
279 13532 : const deduplicated = removeDuplicateMenuOptions(options)
280 13532 : const coreItemsMap = new Map<string, MenuOption>()
281 13532 : const extensionItems: MenuOption[] = []
282 13532 : let deleteItem: MenuOption | undefined
283 :
284 13532 : for (const option of deduplicated) {
285 205266 : if (option.type === 'divider' || option.type === 'category') continue
286 :
287 : const isDeleteItem = option.label === 'Delete' || option.label === 'Remove'
288 205266 : if (isDeleteItem && !option.hasSubmenu) {
289 15679 : deleteItem = option
290 15679 : continue
291 : }
292 :
293 205266 : if (option.label && isCoreMenuItem(option.label)) {
294 126766 : coreItemsMap.set(option.label, option)
295 : } else {
296 1725 : extensionItems.push(option)
297 : }
298 : }
299 13532 : const orderedCoreItems: MenuOption[] = []
300 13532 : const coreLabels = Array.from(coreItemsMap.keys())
301 13532 : coreLabels.sort((a, b) => getMenuItemOrder(a) - getMenuItemOrder(b))
302 :
303 13532 : const getSectionNumber = (index: number): number => {
304 126766 : if (index <= 6) return 0
305 126766 : if (index <= 9) return 1
306 126766 : if (index <= 15) return 2
307 126765 : if (index <= 21) return 3
308 126763 : if (index <= 23) return 4
309 14701 : return 5
310 : }
311 :
312 13532 : let lastSection = -1
313 13532 : for (const label of coreLabels) {
314 126766 : const item = coreItemsMap.get(label)!
315 : const itemIndex = getMenuItemOrder(label)
316 126766 : const currentSection = getSectionNumber(itemIndex)
317 :
318 126766 : if (lastSection !== -1 && currentSection !== lastSection) {
319 53575 : orderedCoreItems.push({ type: 'divider' })
320 : }
321 :
322 126766 : orderedCoreItems.push(item)
323 126766 : lastSection = currentSection
324 : }
325 :
326 13532 : const result: MenuOption[] = [...orderedCoreItems]
327 :
328 13532 : if (extensionItems.length > 0) {
329 925 : result.push({ type: 'divider' })
330 925 : result.push({
331 : label: 'Extensions',
332 : type: 'category',
333 : disabled: true
334 : })
335 925 : result.push(...extensionItems)
336 : }
337 :
338 13532 : if (deleteItem) {
339 13371 : result.push({ type: 'divider' })
340 13371 : result.push(deleteItem)
341 : }
342 :
343 13532 : return result
344 : }
345 :
346 : /**
347 : * Convert LiteGraph IContextMenuValue items to Vue MenuOption format
348 : * Used to bridge LiteGraph context menus into Vue node menus
349 : * @param items - The LiteGraph menu items to convert
350 : * @param node - The node context (optional)
351 : * @param applyStructuring - Whether to apply menu structuring (core/extensions separation). Defaults to true.
352 : */
353 2444 : export function convertContextMenuToOptions(
354 : items: (IContextMenuValue | null)[],
355 : node?: LGraphNode,
356 : applyStructuring: boolean = true
357 : ): MenuOption[] {
358 2444 : const result: MenuOption[] = []
359 :
360 2444 : for (const item of items) {
361 : // Null items are separators in LiteGraph
362 40902 : if (item === null) {
363 6936 : result.push({ type: 'divider' })
364 6936 : continue
365 : }
366 :
367 : // Skip items without content (shouldn't happen, but be safe)
368 40902 : if (!item.content) {
369 0 : continue
370 : }
371 :
372 : // Skip hard blacklisted items
373 40902 : if (HARD_BLACKLIST.has(item.content)) {
374 18442 : continue
375 : }
376 :
377 : // Skip built-in LiteGraph items that the Vue menu replaces.
378 : // Matched by callback identity, not label, to avoid suppressing
379 : // extension-provided items that happen to share a label.
380 40902 : if (item.callback && SUPPRESSED_LITEGRAPH_CALLBACKS.has(item.callback)) {
381 4590 : continue
382 : }
383 :
384 : // Skip if a similar item already exists in results
385 40902 : if (isDuplicateItem(item.content, result)) {
386 6 : continue
387 : }
388 :
389 10928 : const option: MenuOption = {
390 : label: item.content,
391 : source: 'litegraph'
392 : }
393 :
394 : // Pass through disabled state
395 40902 : if (item.disabled) {
396 3 : option.disabled = true
397 : }
398 :
399 : // Handle submenus
400 40902 : if (item.has_submenu) {
401 : // Static submenu with pre-defined options
402 0 : if (item.submenu?.options) {
403 0 : option.hasSubmenu = true
404 0 : option.submenu = convertSubmenuToOptions(item.submenu.options)
405 : }
406 : // Dynamic submenu - callback creates it on-demand
407 0 : else if (item.callback && !item.disabled) {
408 0 : option.hasSubmenu = true
409 : // Intercept the callback to capture dynamic submenu items
410 0 : const capturedSubmenu = captureDynamicSubmenu(item, node)
411 0 : if (capturedSubmenu) {
412 0 : option.submenu = capturedSubmenu
413 : } else {
414 0 : console.warn(
415 : '[ContextMenuConverter] Failed to capture submenu for:',
416 : item.content
417 : )
418 : }
419 : }
420 10928 : } else if (item.callback && !item.disabled) {
421 10925 : option.action = () => {
422 38 : try {
423 38 : void item.callback?.call(
424 : item as unknown as ContextMenuDivElement,
425 : item.value,
426 : {},
427 : undefined,
428 : undefined,
429 : node
430 : )
431 : } catch (error) {
432 0 : console.error('Error executing context menu callback:', error)
433 : }
434 : }
435 : }
436 :
437 10928 : result.push(option)
438 : }
439 :
440 : // Apply structured menu with core items and extensions section (if requested)
441 2444 : if (applyStructuring) {
442 135 : return buildStructuredMenu(result)
443 : }
444 :
445 2309 : return result
446 : }
447 :
448 : /**
449 : * Capture submenu items from a dynamic submenu callback
450 : * Intercepts ContextMenu constructor to extract items without creating HTML menu
451 : */
452 0 : function captureDynamicSubmenu(
453 : item: IContextMenuValue,
454 : node?: LGraphNode
455 : ): SubMenuOption[] | undefined {
456 0 : let capturedItems: readonly (IContextMenuValue | string | null)[] | undefined
457 0 : let capturedOptions: IContextMenuOptions | undefined
458 :
459 : // Store original ContextMenu constructor
460 0 : const OriginalContextMenu = LiteGraph.ContextMenu
461 :
462 0 : try {
463 : // Mock ContextMenu constructor to capture submenu items and options
464 0 : LiteGraph.ContextMenu = function (
465 : items: readonly (IContextMenuValue | string | null)[],
466 : options?: IContextMenuOptions
467 : ) {
468 : // Capture both items and options
469 0 : capturedItems = items
470 0 : capturedOptions = options
471 : // Return a minimal mock object to prevent errors
472 0 : return {
473 : close: () => {},
474 : root: document.createElement('div')
475 : } as unknown as ContextMenu
476 : } as unknown as typeof ContextMenu
477 :
478 : // Execute the callback to trigger submenu creation
479 0 : try {
480 : // Create a mock MouseEvent for the callback
481 0 : const mockEvent = new MouseEvent('click', {
482 : bubbles: true,
483 : cancelable: true,
484 : clientX: 0,
485 : clientY: 0
486 : })
487 :
488 : // Create a mock parent menu
489 0 : const mockMenu = {
490 : close: () => {},
491 : root: document.createElement('div')
492 : } as unknown as ContextMenu
493 :
494 : // Call the callback which should trigger ContextMenu constructor
495 : // Callback signature varies, but typically: (value, options, event, menu, node)
496 0 : void item.callback?.call(
497 : item as unknown as ContextMenuDivElement,
498 : item.value,
499 : {},
500 : mockEvent,
501 : mockMenu,
502 : node // Pass the node context for callbacks that need it
503 : )
504 : } catch (error) {
505 0 : console.warn(
506 : '[ContextMenuConverter] Error executing callback for:',
507 : item.content,
508 : error
509 : )
510 : }
511 : } finally {
512 : // Always restore original constructor
513 0 : LiteGraph.ContextMenu = OriginalContextMenu
514 : }
515 :
516 : // Convert captured items to Vue submenu format
517 0 : if (capturedItems) {
518 : const converted = convertSubmenuToOptions(capturedItems, capturedOptions)
519 0 : return converted
520 : }
521 :
522 0 : console.warn('[ContextMenuConverter] No items captured for:', item.content)
523 : return undefined
524 : }
525 :
526 : /**
527 : * Convert LiteGraph submenu items to Vue SubMenuOption format
528 : */
529 0 : function convertSubmenuToOptions(
530 : items: readonly (IContextMenuValue | string | null)[],
531 : options?: IContextMenuOptions
532 : ): SubMenuOption[] {
533 0 : const result: SubMenuOption[] = []
534 :
535 0 : for (const item of items) {
536 : // Skip null separators
537 0 : if (item === null) {
538 0 : continue
539 : }
540 :
541 : // Handle string items (simple labels like in Mode/Shapes menus)
542 0 : if (typeof item === 'string') {
543 0 : const subOption: SubMenuOption = {
544 : label: item,
545 : action: () => {
546 0 : try {
547 : // Call the options callback with the string value
548 0 : if (options?.callback) {
549 0 : void options.callback.call(
550 : null,
551 : item,
552 : options,
553 : undefined,
554 : undefined,
555 : options.extra
556 : )
557 : }
558 : } catch (error) {
559 0 : console.error('Error executing string item callback:', error)
560 : }
561 : }
562 : }
563 0 : result.push(subOption)
564 0 : continue
565 : }
566 :
567 : // Handle object items
568 0 : if (!item.content) {
569 0 : continue
570 : }
571 :
572 : // Extract text content from HTML if present
573 : const content = stripHtmlTags(item.content)
574 :
575 0 : const subOption: SubMenuOption = {
576 : label: content,
577 : action: () => {
578 0 : try {
579 0 : void item.callback?.call(
580 : item as unknown as ContextMenuDivElement,
581 : item.value,
582 : {},
583 : undefined,
584 : undefined,
585 : item
586 : )
587 : } catch (error) {
588 0 : console.error('Error executing submenu callback:', error)
589 : }
590 : }
591 : }
592 :
593 : // Pass through disabled state
594 0 : if (item.disabled) {
595 0 : subOption.disabled = true
596 : }
597 :
598 0 : result.push(subOption)
599 : }
600 0 : return result
601 : }
602 :
603 : /**
604 : * Strip HTML tags from content string safely
605 : * LiteGraph menu items often include HTML for styling
606 : */
607 0 : function stripHtmlTags(html: string): string {
608 : // Use DOMPurify to sanitize and strip all HTML tags
609 : const sanitized = DOMPurify.sanitize(html, { ALLOWED_TAGS: [] })
610 : const result = sanitized.trim()
611 0 : return result || html.replace(/<[^>]*>/g, '').trim() || html
612 : }
|