Line data Source code
1 : import { defineStore } from 'pinia'
2 : import { computed, ref, shallowRef, watch } from 'vue'
3 :
4 : import { i18n, st } from '@/i18n'
5 : import { isCloud } from '@/platform/distribution/types'
6 : import { api } from '@/scripts/api'
7 : import type {
8 : NavGroupData,
9 : NavItemData
10 : } from '@comfyorg/design-system/lib/navigation/types'
11 : import { generateCategoryId, getCategoryIcon } from '@/utils/categoryUtil'
12 : import { normalizeI18nKey } from '@/utils/formatUtil'
13 :
14 : import { zLogoIndex } from '@comfyorg/api-client/templateSchema'
15 : import type { LogoIndex } from '@comfyorg/api-client/templateSchema'
16 : import type {
17 : TemplateGroup,
18 : TemplateInfo,
19 : WorkflowTemplates
20 : } from '@comfyorg/api-client/templateTypes'
21 :
22 : // Enhanced template interface for easier filtering
23 : interface EnhancedTemplate extends TemplateInfo {
24 : sourceModule: string
25 : category?: string
26 : categoryType?: string
27 : categoryGroup?: string // 'GENERATION TYPE' or 'CLOSED SOURCE MODELS'
28 : isEssential?: boolean
29 : isPartnerNode?: boolean // Computed from OpenSource === false
30 : searchableText?: string
31 : }
32 :
33 2356 : export const useWorkflowTemplatesStore = defineStore(
34 : 'workflowTemplates',
35 : () => {
36 2355 : const activeTemplateLoad = shallowRef<{
37 : id: string
38 : controller: AbortController
39 : phase: 'preparing' | 'loading'
40 : } | null>(null)
41 2355 : const loadingTemplateId = computed(
42 : () => activeTemplateLoad.value?.id ?? null
43 : )
44 :
45 10 : function startTemplateLoad(id: string) {
46 10 : if (activeTemplateLoad.value?.phase === 'loading') return
47 10 : activeTemplateLoad.value?.controller.abort()
48 10 : const controller = new AbortController()
49 10 : activeTemplateLoad.value = { id, controller, phase: 'preparing' }
50 10 : return controller
51 : }
52 :
53 9 : function startTemplateGraphLoad(controller: AbortController) {
54 9 : const load = activeTemplateLoad.value
55 9 : if (load?.controller !== controller) return false
56 9 : activeTemplateLoad.value = { ...load, phase: 'loading' }
57 9 : return true
58 : }
59 :
60 10 : function finishTemplateLoad(controller: AbortController) {
61 10 : if (activeTemplateLoad.value?.controller === controller)
62 10 : activeTemplateLoad.value = null
63 : }
64 :
65 16 : function cancelTemplateLoad(controller: AbortController | undefined) {
66 16 : const load = activeTemplateLoad.value
67 16 : if (load?.controller !== controller || load?.phase !== 'preparing') return
68 0 : load.controller.abort()
69 0 : activeTemplateLoad.value = null
70 : }
71 2355 : const customTemplates = shallowRef<{ [moduleName: string]: string[] }>({})
72 2355 : const coreTemplates = shallowRef<WorkflowTemplates[]>([])
73 2355 : const englishTemplates = shallowRef<WorkflowTemplates[]>([])
74 2355 : const logoIndex = shallowRef<LogoIndex>({})
75 2355 : const isLoaded = ref(false)
76 2355 : const knownTemplateNames = ref(new Set<string>())
77 :
78 2355 : const getTemplateByName = (name: string): EnhancedTemplate | undefined => {
79 0 : return enhancedTemplates.value.find((template) => template.name === name)
80 : }
81 :
82 : // Store filter mappings for dynamic categories
83 : type FilterData = {
84 : category?: string
85 : categoryGroup?: string
86 : }
87 :
88 2355 : const categoryFilters = ref(new Map<string, FilterData>())
89 :
90 : /**
91 : * Add localization fields to a template.
92 : */
93 2355 : const addLocalizedFieldsToTemplate = (
94 : template: TemplateInfo,
95 : categoryTitle: string
96 : ) => ({
97 : ...template,
98 : localizedTitle: st(
99 : `templateWorkflows.template.${normalizeI18nKey(categoryTitle)}.${normalizeI18nKey(template.name)}`,
100 : template.title ?? template.name
101 : ),
102 : localizedDescription: st(
103 : `templateWorkflows.templateDescription.${normalizeI18nKey(categoryTitle)}.${normalizeI18nKey(template.name)}`,
104 : template.description
105 : )
106 : })
107 :
108 : /**
109 : * Add localization fields to all templates in a list of templates.
110 : */
111 2355 : const localizeTemplateList = (
112 : templates: TemplateInfo[],
113 : categoryTitle: string
114 : ) =>
115 : templates.map((template) =>
116 : addLocalizedFieldsToTemplate(template, categoryTitle)
117 : )
118 :
119 : /**
120 : * Add localization fields to a template category and all its constituent templates.
121 : */
122 2355 : const localizeTemplateCategory = (templateCategory: WorkflowTemplates) => ({
123 : ...templateCategory,
124 : localizedTitle: st(
125 : `templateWorkflows.category.${normalizeI18nKey(templateCategory.title)}`,
126 : templateCategory.title
127 : ),
128 : templates: localizeTemplateList(
129 : templateCategory.templates,
130 : templateCategory.title
131 : )
132 : })
133 :
134 : // Create an "All" category that combines all templates
135 2355 : const createAllCategory = () => {
136 : // First, get core templates with source module added
137 0 : const coreTemplatesWithSourceModule = coreTemplates.value.flatMap(
138 : (category) =>
139 : // For each template in each category, add the sourceModule and pass through any localized fields
140 : category.templates.map((template) => {
141 : // Get localized template with its original category title for i18n lookup
142 : const localizedTemplate = addLocalizedFieldsToTemplate(
143 : template,
144 : category.title
145 : )
146 0 : return {
147 : ...localizedTemplate,
148 : sourceModule: category.moduleName
149 : }
150 : })
151 : )
152 :
153 : // Now handle custom templates
154 0 : const customTemplatesWithSourceModule = Object.entries(
155 : customTemplates.value
156 : ).flatMap(([moduleName, templates]) =>
157 : templates.map((name) => ({
158 : name,
159 : mediaType: 'image',
160 : mediaSubtype: 'jpg',
161 : description: name,
162 : sourceModule: moduleName
163 : }))
164 : )
165 :
166 0 : return {
167 : moduleName: 'all',
168 : title: 'All',
169 : localizedTitle: st('templateWorkflows.category.All', 'All Templates'),
170 : templates: [
171 : ...coreTemplatesWithSourceModule,
172 : ...customTemplatesWithSourceModule
173 : ]
174 : }
175 : }
176 :
177 : /**
178 : * Original grouped templates for backward compatibility
179 : */
180 2355 : const groupedTemplates = computed<TemplateGroup[]>(() => {
181 : // Get regular categories
182 0 : const allTemplates = [
183 : ...coreTemplates.value.map(localizeTemplateCategory),
184 : ...Object.entries(customTemplates.value).map(
185 : ([moduleName, templates]) => ({
186 : moduleName,
187 : title: moduleName,
188 : localizedTitle: st(
189 : `templateWorkflows.category.${normalizeI18nKey(moduleName)}`,
190 : moduleName
191 : ),
192 : templates: templates.map((name) => ({
193 : name,
194 : mediaType: 'image',
195 : mediaSubtype: 'jpg',
196 : description: name
197 : }))
198 : })
199 : )
200 : ]
201 :
202 : // Group templates by their main category
203 : const groupedByCategory = [
204 : {
205 : label: st(
206 : 'templateWorkflows.category.ComfyUI Examples',
207 : 'ComfyUI Examples'
208 : ),
209 : modules: [
210 : createAllCategory(),
211 : ...allTemplates.filter((t) => t.moduleName === 'default')
212 : ]
213 : },
214 : ...(Object.keys(customTemplates.value).length > 0
215 : ? [
216 : {
217 : label: st(
218 : 'templateWorkflows.category.Custom Nodes',
219 : 'Custom Nodes'
220 : ),
221 : modules: allTemplates.filter((t) => t.moduleName !== 'default')
222 : }
223 : ]
224 : : [])
225 : ]
226 :
227 0 : return groupedByCategory
228 : })
229 :
230 : /**
231 : * Enhanced templates with proper categorization for filtering
232 : */
233 2355 : const enhancedTemplates = computed<EnhancedTemplate[]>(() => {
234 116 : const allTemplates: EnhancedTemplate[] = []
235 :
236 : // Process core templates
237 116 : coreTemplates.value.forEach((category) => {
238 298 : category.templates.forEach((template) => {
239 14114 : const enhancedTemplate: EnhancedTemplate = {
240 : ...template,
241 : sourceModule: category.moduleName,
242 : category: category.title,
243 : categoryType: category.type,
244 : categoryGroup: category.category,
245 : isEssential: category.isEssential,
246 : isPartnerNode: template.openSource === false,
247 : searchableText: [
248 : template.title || template.name,
249 : template.description || '',
250 : category.title,
251 : ...(template.tags || []),
252 : ...(template.models || [])
253 : ].join(' ')
254 : }
255 :
256 14114 : allTemplates.push(enhancedTemplate)
257 : })
258 : })
259 :
260 : // Process custom templates
261 116 : Object.entries(customTemplates.value).forEach(
262 : ([moduleName, templates]) => {
263 0 : templates.forEach((name) => {
264 0 : const enhancedTemplate: EnhancedTemplate = {
265 : name,
266 : title: name,
267 : description: name,
268 : mediaType: 'image',
269 : mediaSubtype: 'jpg',
270 : sourceModule: moduleName,
271 : category: 'Extensions',
272 : categoryType: 'extension',
273 : searchableText: `${name} ${moduleName} extension`
274 : }
275 0 : allTemplates.push(enhancedTemplate)
276 : })
277 : }
278 : )
279 :
280 : // TODO: Temporary filtering of custom node templates on local installations
281 : // Future: Add UX that allows local users to opt-in to templates with custom nodes,
282 : // potentially conditional on whether they have those specific custom nodes installed.
283 : // This would provide better template discovery while respecting local user workflows.
284 : const filteredTemplates = isCloud
285 : ? allTemplates
286 : : allTemplates.filter(
287 : (template) => !template.requiresCustomNodes?.length
288 : )
289 :
290 : return filteredTemplates
291 : })
292 :
293 : /**
294 : * Filter templates by category ID using stored filter mappings
295 : */
296 2355 : const filterTemplatesByCategory = (categoryId: string) => {
297 123 : if (categoryId === 'all') {
298 113 : return enhancedTemplates.value
299 : }
300 :
301 27 : if (categoryId.startsWith('basics-')) {
302 : // Filter for templates from categories marked as essential
303 0 : return enhancedTemplates.value.filter(
304 : (t) =>
305 : t.isEssential &&
306 : t.category?.toLowerCase().replace(/\s+/g, '-') ===
307 : categoryId.replace('basics-', '')
308 : )
309 : }
310 :
311 10 : if (categoryId === 'popular') {
312 10 : return enhancedTemplates.value
313 : }
314 :
315 0 : if (categoryId === 'partner-nodes') {
316 : // Filter for templates where OpenSource === false
317 0 : return enhancedTemplates.value.filter((t) => t.isPartnerNode)
318 : }
319 :
320 : // Handle extension-specific filters
321 0 : if (categoryId.startsWith('extension-')) {
322 0 : const moduleName = categoryId.replace('extension-', '')
323 0 : return enhancedTemplates.value.filter(
324 : (t) => t.sourceModule === moduleName
325 : )
326 : }
327 :
328 : // Look up the filter from our stored mappings
329 0 : const filter = categoryFilters.value.get(categoryId)
330 0 : if (!filter) {
331 0 : return enhancedTemplates.value
332 : }
333 :
334 : // Apply the filter
335 0 : return enhancedTemplates.value.filter((template) => {
336 0 : if (filter.category && template.category !== filter.category) {
337 0 : return false
338 : }
339 0 : if (
340 : filter.categoryGroup &&
341 : template.categoryGroup !== filter.categoryGroup
342 : ) {
343 0 : return false
344 : }
345 0 : return true
346 : })
347 : }
348 :
349 : /**
350 : * New navigation structure dynamically built from JSON categories
351 : */
352 2355 : const navGroupedTemplates = computed<(NavItemData | NavGroupData)[]>(() => {
353 22 : if (!isLoaded.value) return []
354 :
355 22 : const items: (NavItemData | NavGroupData)[] = []
356 :
357 : // Clear and rebuild filter mappings
358 22 : categoryFilters.value.clear()
359 :
360 : // 1. All Templates - always first
361 22 : items.push({
362 : id: 'all',
363 : label: st('templateWorkflows.category.All', 'All Templates'),
364 : icon: getCategoryIcon('all')
365 : })
366 :
367 : // 1.5. Popular categories
368 :
369 22 : items.push({
370 : id: 'popular',
371 : label: st('templateWorkflows.category.Popular', 'Popular'),
372 : icon: 'icon-[lucide--flame]'
373 : })
374 :
375 : // 2. Basics (isEssential categories) - always beneath All Templates if they exist
376 22 : const essentialCats = coreTemplates.value.filter(
377 : (cat) => cat.isEssential && cat.templates.length > 0
378 : )
379 :
380 22 : if (essentialCats.length > 0) {
381 11 : essentialCats.forEach((essentialCat) => {
382 33 : const categoryIcon = essentialCat.icon
383 33 : const categoryTitle = essentialCat.title
384 33 : const categoryId = generateCategoryId('basics', essentialCat.title)
385 33 : items.push({
386 : id: categoryId,
387 : label: st(
388 : `templateWorkflows.category.${normalizeI18nKey(categoryTitle)}`,
389 : categoryTitle
390 : ),
391 : icon:
392 : categoryIcon ||
393 : getCategoryIcon(essentialCat.type || 'getting-started')
394 : })
395 : })
396 : }
397 :
398 : // 3. Group categories from JSON dynamically
399 22 : const categoryGroups = new Map<
400 : string,
401 : { title: string; items: NavItemData[] }
402 : >()
403 :
404 : // Process all categories from JSON
405 22 : coreTemplates.value.forEach((category) => {
406 : // Skip essential categories as they're handled as Basics
407 143 : if (category.isEssential) return
408 :
409 110 : const categoryGroup = category.category
410 110 : const categoryIcon = category.icon
411 :
412 110 : if (categoryGroup) {
413 99 : if (!categoryGroups.has(categoryGroup)) {
414 11 : categoryGroups.set(categoryGroup, {
415 : title: categoryGroup,
416 : items: []
417 : })
418 : }
419 :
420 99 : const group = categoryGroups.get(categoryGroup)!
421 :
422 : // Generate unique ID for this category
423 99 : const categoryId = generateCategoryId(categoryGroup, category.title)
424 :
425 : // Store the filter mapping
426 99 : categoryFilters.value.set(categoryId, {
427 : category: category.title,
428 : categoryGroup: categoryGroup
429 : })
430 :
431 99 : group.items.push({
432 : id: categoryId,
433 : label: st(
434 : `templateWorkflows.category.${normalizeI18nKey(category.title)}`,
435 : category.title
436 : ),
437 : icon: categoryIcon || getCategoryIcon(category.type || 'default')
438 : })
439 : }
440 : })
441 :
442 : // Add grouped categories
443 22 : categoryGroups.forEach((group, groupName) => {
444 11 : if (group.items.length > 0) {
445 11 : items.push({
446 : title: st(
447 : `templateWorkflows.category.${normalizeI18nKey(groupName)}`,
448 : groupName
449 : .split(' ')
450 : .map(
451 : (word) =>
452 : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
453 : )
454 : .join(' ')
455 : ),
456 : items: group.items
457 : })
458 : }
459 : })
460 :
461 : // 3.5. Partner Nodes - virtual category for OpenSource === false templates
462 : const partnerNodeCount = enhancedTemplates.value.filter(
463 : (t) => t.isPartnerNode
464 : ).length
465 :
466 22 : if (partnerNodeCount > 0) {
467 13 : items.push({
468 : id: 'partner-nodes',
469 : label: st(
470 : 'templateWorkflows.category.Partner Nodes',
471 : 'Partner Nodes'
472 : ),
473 : icon: 'icon-[lucide--handshake]'
474 : })
475 : }
476 :
477 : // 4. Extensions - always last
478 : const extensionCounts = enhancedTemplates.value.filter(
479 : (t) => t.sourceModule !== 'default'
480 : ).length
481 :
482 22 : if (extensionCounts > 0) {
483 : // Get unique extension modules
484 : const extensionModules = Array.from(
485 : new Set(
486 : enhancedTemplates.value
487 : .filter((t) => t.sourceModule !== 'default')
488 : .map((t) => t.sourceModule)
489 : )
490 : ).sort()
491 :
492 0 : const extensionItems: NavItemData[] = extensionModules.map(
493 : (moduleName) => ({
494 : id: `extension-${moduleName}`,
495 : label: st(
496 : `templateWorkflows.category.${normalizeI18nKey(moduleName)}`,
497 : moduleName
498 : ),
499 : icon: getCategoryIcon('extensions')
500 : })
501 : )
502 :
503 0 : items.push({
504 : title: st('templateWorkflows.category.Extensions', 'Extensions'),
505 : items: extensionItems,
506 : collapsible: true
507 : })
508 : }
509 :
510 22 : return items
511 : })
512 :
513 49 : async function fetchCoreTemplates() {
514 49 : const locale = i18n.global.locale.value
515 49 : const [coreResult, englishResult, logoIndexResult] = await Promise.all([
516 : api.getCoreWorkflowTemplates(locale),
517 : isCloud && locale !== 'en'
518 : ? api.getCoreWorkflowTemplates('en')
519 : : Promise.resolve([]),
520 : fetchLogoIndex()
521 : ])
522 :
523 46 : coreTemplates.value = coreResult
524 46 : englishTemplates.value = englishResult
525 46 : logoIndex.value = logoIndexResult
526 :
527 46 : const coreNames = coreTemplates.value.flatMap((category) =>
528 : category.templates.map((template) => template.name)
529 : )
530 46 : const customNames = Object.values(customTemplates.value).flat()
531 46 : knownTemplateNames.value = new Set([...coreNames, ...customNames])
532 : }
533 :
534 52 : async function loadWorkflowTemplates() {
535 52 : try {
536 52 : if (!isLoaded.value) {
537 50 : customTemplates.value = await api.getWorkflowTemplates()
538 49 : await fetchCoreTemplates()
539 46 : isLoaded.value = true
540 : }
541 : } catch (error) {
542 0 : console.error('Error fetching workflow templates:', error)
543 : }
544 : }
545 :
546 2355 : watch(
547 : () => i18n.global.locale.value,
548 : async () => {
549 8 : if (!isLoaded.value) return
550 0 : try {
551 0 : await fetchCoreTemplates()
552 : } catch (error) {
553 0 : console.error('Error reloading templates for new locale:', error)
554 : }
555 : }
556 : )
557 :
558 49 : async function fetchLogoIndex(): Promise<LogoIndex> {
559 49 : try {
560 49 : const response = await fetch(api.fileURL('/templates/index_logo.json'))
561 : const contentType = response.headers.get('content-type')
562 49 : if (!contentType?.includes('application/json')) return {}
563 48 : const data = await response.json()
564 46 : const result = zLogoIndex.safeParse(data)
565 49 : return result.success ? result.data : {}
566 : } catch {
567 0 : return {}
568 : }
569 : }
570 :
571 132 : function getLogoUrl(provider: string): string {
572 132 : const logoPath = logoIndex.value[provider]
573 132 : if (!logoPath) return ''
574 :
575 : // Validate path to prevent directory traversal and ensure safe file extensions
576 : const safePathPattern = /^[a-z0-9_\-./]+\.(png|jpg|jpeg|svg|webp)$/i
577 132 : if (
578 : !safePathPattern.test(logoPath) ||
579 : logoPath.includes('..') ||
580 : logoPath.startsWith('/')
581 : ) {
582 0 : return ''
583 : }
584 :
585 132 : return api.fileURL(`/templates/${logoPath}`)
586 : }
587 :
588 0 : function getEnglishMetadata(templateName: string): {
589 : tags?: string[]
590 : category?: string
591 : useCase?: string
592 : models?: string[]
593 : license?: string
594 : } | null {
595 0 : if (englishTemplates.value.length === 0) {
596 0 : return null
597 : }
598 :
599 0 : for (const category of englishTemplates.value) {
600 0 : const template = category.templates.find((t) => t.name === templateName)
601 0 : if (template) {
602 0 : return {
603 : tags: template.tags,
604 : category: category.title,
605 : useCase: template.useCase,
606 : models: template.models,
607 : license: template.license
608 : }
609 : }
610 : }
611 :
612 0 : return null
613 : }
614 :
615 2355 : return {
616 : groupedTemplates,
617 : navGroupedTemplates,
618 : enhancedTemplates,
619 : filterTemplatesByCategory,
620 : isLoaded,
621 : loadWorkflowTemplates,
622 : loadingTemplateId,
623 : startTemplateLoad,
624 : startTemplateGraphLoad,
625 : finishTemplateLoad,
626 : cancelTemplateLoad,
627 : knownTemplateNames,
628 : getTemplateByName,
629 : getEnglishMetadata,
630 : getLogoUrl
631 : }
632 : }
633 : )
|