Line data Source code
1 : <template>
2 36 : <SidebarTabTemplate :title="$t('sideToolbar.modelLibrary')">
3 : <template #tool-buttons>
4 : <Button
5 : :tooltip="$t('g.refresh')"
6 : tooltip-side="bottom"
7 : variant="muted-textonly"
8 : size="icon"
9 : :aria-label="$t('g.refresh')"
10 : @click="withLoadFailureToast(() => modelStore.refresh())"
11 : >
12 : <i class="icon-[lucide--refresh-cw]" />
13 : </Button>
14 : <Button
15 : v-if="!flags.assetsEnabled"
16 : :tooltip="$t('g.loadAllFolders')"
17 : tooltip-side="bottom"
18 : variant="muted-textonly"
19 : size="icon"
20 : :aria-label="$t('g.loadAllFolders')"
21 : @click="withLoadFailureToast(() => modelStore.loadModels())"
22 : >
23 : <i class="icon-[lucide--cloud-download]" />
24 : </Button>
25 : </template>
26 : <template #header>
27 : <SidebarTopArea>
28 : <SearchInput
29 : ref="searchBoxRef"
30 : v-model:model-value="searchQuery"
31 : :clear-label="$t('g.clear')"
32 : :accessible-label="
33 : $t('g.searchPlaceholder', {
34 : subject: $t('sideToolbar.labels.models')
35 : })
36 : "
37 : :placeholder="
38 : $t('g.searchPlaceholder', {
39 : subject: $t('sideToolbar.labels.models')
40 : })
41 : "
42 : @search="handleSearch"
43 : />
44 : <p
45 : v-if="searchResults.capped"
46 : role="status"
47 : class="mx-2 my-1 text-xs text-muted-foreground"
48 : >
49 : {{
50 : $t('sideToolbar.searchResultsCapped', {
51 : limit: SEARCH_RESULT_LIMIT
52 : })
53 : }}
54 : </p>
55 : </SidebarTopArea>
56 : </template>
57 : <template #body>
58 : <ElectronDownloadItems v-if="isDesktop" />
59 :
60 : <TreeExplorer
61 : v-model:expanded-keys="expandedKeys"
62 : class="model-lib-tree-explorer"
63 : :aria-label="$t('sideToolbar.modelLibrary')"
64 : :root="renderedRoot"
65 : >
66 : <template #preview="{ node }">
67 : <ModelPreview
68 : v-if="node.data && hasPreviewDetails(node.data)"
69 : :model-def="node.data"
70 : />
71 : </template>
72 : </TreeExplorer>
73 : </template>
74 : </SidebarTabTemplate>
75 : </template>
76 :
77 : <script setup lang="ts">
78 : import { computed, onMounted, ref, toRef, watch } from 'vue'
79 : import { useI18n } from 'vue-i18n'
80 :
81 : import SearchInput from '@comfyorg/design-system/search-input/SearchInput'
82 : import SidebarTopArea from '@comfyorg/design-system/navigation/SidebarTopArea'
83 : import TreeExplorer from '@/components/common/TreeExplorer.vue'
84 : import SidebarTabTemplate from '@/components/sidebar/tabs/SidebarTabTemplate.vue'
85 : import ElectronDownloadItems from '@/components/sidebar/tabs/modelLibrary/ElectronDownloadItems.vue'
86 : import ModelPreview from '@/components/sidebar/tabs/modelLibrary/ModelPreview.vue'
87 : import Button from '@comfyorg/design-system/button/Button'
88 : import { startModelLoaderDrag } from '@/composables/node/startModelNodeDragFromAsset'
89 : import { useFeatureFlags } from '@/composables/useFeatureFlags'
90 : import { useTreeExpansion } from '@/composables/useTreeExpansion'
91 : import { useSettingStore } from '@/platform/settings/settingStore'
92 : import { useToast } from '@/components/ui/toast/toastStore'
93 : import { useAssetDownloadStore } from '@/stores/assetDownloadStore'
94 : import type { ComfyModelDef } from '@/stores/modelStore'
95 : import {
96 : ModelFolder,
97 : ResourceState,
98 : getModelPreviewUrl,
99 : useModelStore
100 : } from '@/stores/modelStore'
101 : import { useModelToNodeStore } from '@/stores/modelToNodeStore'
102 : import type { TreeExplorerNode, TreeNode } from '@/types/treeExplorerTypes'
103 : import { isDesktop } from '@/platform/distribution/types'
104 : import { buildTree } from '@/utils/treeUtil'
105 :
106 36 : const modelStore = useModelStore()
107 36 : const modelToNodeStore = useModelToNodeStore()
108 36 : const settingStore = useSettingStore()
109 36 : const toast = useToast()
110 36 : const { t } = useI18n()
111 36 : const { flags } = useFeatureFlags()
112 36 : const assetDownloadStore = useAssetDownloadStore()
113 36 : const searchBoxRef = ref()
114 36 : const searchQuery = ref<string>('')
115 : /**
116 : * The committed query the tree derives from. SearchInput debounces its
117 : * `search` emit, so the full recompute-and-mount cost of a query change runs
118 : * once per typing pause instead of on every keystroke of `searchQuery`.
119 : */
120 36 : const activeSearchQuery = ref<string>('')
121 36 : const expandedKeys = ref<Record<string, boolean>>({})
122 36 : const { toggleNodeOnEvent } = useTreeExpansion(expandedKeys)
123 :
124 : // Search results render expanded and un-virtualized, and the tree's cost is
125 : // O(n^2) in mounted rows, so an unbounded result set hangs the tab on large
126 : // libraries (measured: seconds at 5k models). Cap what renders; refining the
127 : // query is the path to the tail.
128 2355 : const SEARCH_RESULT_LIMIT = 500
129 :
130 36 : const searchResults = computed<{ models: ComfyModelDef[]; capped: boolean }>(
131 : () => {
132 51 : const search = activeSearchQuery.value.toLocaleLowerCase()
133 51 : if (!search) return { models: [], capped: false }
134 14 : const matches: ComfyModelDef[] = []
135 19 : for (const model of modelStore.models) {
136 55 : if (!model.searchable.includes(search)) continue
137 41 : if (matches.length === SEARCH_RESULT_LIMIT) {
138 0 : return { models: matches, capped: true }
139 : }
140 8 : matches.push(model)
141 : }
142 14 : return { models: matches, capped: false }
143 : }
144 : )
145 :
146 36 : const handleSearch = async (query: string) => {
147 6 : autoExpandedSearchKeys.clear()
148 6 : activeSearchQuery.value = query
149 6 : if (!query) {
150 1 : expandedKeys.value = {}
151 1 : return
152 : }
153 : // Load all models to ensure results cover folders not yet opened
154 5 : await modelStore.loadModels()
155 : }
156 :
157 : type ModelOrFolder = ComfyModelDef | ModelFolder
158 :
159 36 : const root = computed<TreeNode<ModelOrFolder>>(() => {
160 111 : const allNodes: ModelOrFolder[] = activeSearchQuery.value
161 : ? searchResults.value.models
162 : : [...modelStore.visibleModelFolders, ...modelStore.models]
163 111 : return buildTree(allNodes, (modelOrFolder: ModelOrFolder) =>
164 : modelOrFolder.key.split('/')
165 : )
166 : })
167 :
168 : /**
169 : * Folder keys already auto-expanded for the current query. Expansion runs
170 : * once per key: the query's initial result set opens on commit, and a
171 : * background reload (e.g. a scan completing mid-search) opens only folders
172 : * newly appearing in the results. A folder the user collapsed keeps its key
173 : * here and stays collapsed, and an unchanged tree costs no expand pass.
174 : */
175 36 : const autoExpandedSearchKeys = new Set<string>()
176 :
177 30 : function expandNewSearchFolders(node: TreeNode<ModelOrFolder>) {
178 30 : if (node.leaf) return
179 30 : if (!autoExpandedSearchKeys.has(node.key)) {
180 9 : autoExpandedSearchKeys.add(node.key)
181 9 : expandedKeys.value[node.key] = true
182 : }
183 30 : for (const child of node.children ?? []) {
184 16 : expandNewSearchFolders(child)
185 : }
186 : }
187 :
188 36 : watch(root, (newRoot) => {
189 75 : if (!activeSearchQuery.value) return
190 14 : expandNewSearchFolders(newRoot)
191 : })
192 :
193 36 : const renderedRoot = computed<TreeExplorerNode<ComfyModelDef>>(() => {
194 110 : const nameFormat = settingStore.get('Comfy.ModelLibrary.NameFormat')
195 110 : const fillNodeInfo = (
196 : node: TreeNode<ModelOrFolder>
197 : ): TreeExplorerNode<ComfyModelDef> => {
198 562 : const children = node.children?.map(fillNodeInfo)
199 562 : const folder = node.data instanceof ModelFolder ? node.data : undefined
200 562 : const model = node.data instanceof ModelFolder ? undefined : node.data
201 :
202 562 : return {
203 : key: node.key,
204 : label: model
205 : ? nameFormat === 'title'
206 : ? model.title
207 : : model.simplified_file_name
208 : : node.label,
209 : leaf: node.leaf,
210 : data: model,
211 : getIcon() {
212 594 : if (model) {
213 116 : return model.image ? 'icon-[lucide--image]' : 'icon-[lucide--file]'
214 : }
215 594 : if (folder) {
216 335 : return folder.state === ResourceState.Loading
217 : ? 'animate-spin motion-reduce:animate-none icon-[lucide--loader-circle]'
218 : : 'icon-[lucide--folder]'
219 : }
220 143 : return 'icon-[lucide--folder]'
221 : },
222 : getIconImage() {
223 594 : return (model && getModelPreviewUrl(model)) || undefined
224 : },
225 : getBadgeText() {
226 : // Return undefined to apply default badge text
227 : // Return empty string to hide badge
228 594 : if (!folder) {
229 259 : return
230 : }
231 594 : return folder.state === ResourceState.Loaded ? undefined : ''
232 : },
233 : children,
234 : draggable: node.leaf,
235 : handleClick(e: MouseEvent) {
236 28 : if (this.leaf && model) {
237 3 : const provider = modelToNodeStore.getNodeProvider(model.directory)
238 3 : if (provider) {
239 3 : startModelLoaderDrag(provider, model.file_name)
240 : }
241 : } else {
242 25 : toggleNodeOnEvent(e, node)
243 : }
244 : }
245 : }
246 : }
247 :
248 110 : return fillNodeInfo(root.value)
249 : })
250 :
251 18 : function hasPreviewDetails(model: ComfyModelDef) {
252 18 : return (
253 : model.has_loaded_metadata &&
254 : Boolean(
255 : model.author ||
256 : model.simplified_file_name != model.title ||
257 : model.description ||
258 : model.usage_hint ||
259 : model.trigger_phrase ||
260 : model.image
261 : )
262 : )
263 : }
264 :
265 36 : const visibleModels = computed(() => {
266 135 : const models: ComfyModelDef[] = []
267 135 : const collect = (node: TreeNode<ModelOrFolder>) => {
268 185 : for (const child of node.children ?? []) {
269 457 : if (child.leaf) {
270 71 : if (child.data && !(child.data instanceof ModelFolder)) {
271 71 : models.push(child.data)
272 : }
273 386 : } else if (expandedKeys.value[child.key]) {
274 50 : collect(child)
275 : }
276 : }
277 : }
278 135 : collect(root.value)
279 135 : return models
280 : })
281 :
282 36 : watch(visibleModels, (models) => {
283 105 : for (const model of models) void model.load()
284 : })
285 :
286 36 : watch(
287 : toRef(expandedKeys, 'value'),
288 : (newExpandedKeys) => {
289 33 : Object.entries(newExpandedKeys).forEach(([key, isExpanded]) => {
290 45 : if (isExpanded) {
291 45 : const folderPath = key.split('/').slice(1).join('/')
292 45 : if (folderPath && !folderPath.includes('/')) {
293 : // Trigger (async) load of model data for this folder
294 35 : void modelStore.getLoadedModelFolder(folderPath)
295 : }
296 : }
297 : })
298 : },
299 : { deep: true }
300 : )
301 :
302 36 : watch(
303 : () => assetDownloadStore.lastCompletedDownload,
304 : (completed) => {
305 0 : if (!completed) return
306 0 : void modelStore.refreshModelFolder(completed.modelType)
307 : }
308 : )
309 :
310 23 : async function withLoadFailureToast(action: () => Promise<unknown>) {
311 23 : try {
312 23 : await action()
313 : } catch (error) {
314 1 : console.error('Model library load failed', error)
315 1 : toast.error(t('g.error'), {
316 : description: t('sideToolbar.modelLibraryLoadFailed'),
317 : duration: 5000
318 : })
319 : }
320 : }
321 :
322 36 : onMounted(async () => {
323 36 : searchBoxRef.value?.focus()
324 : // In asset mode the whole library resolves from one cached walk, so eager
325 : // loading is cheap and keeps search and folder badges complete from the
326 : // start; AutoLoadAll remains the opt-in for the request-per-folder legacy path.
327 36 : if (
328 : flags.assetsEnabled ||
329 : settingStore.get('Comfy.ModelLibrary.AutoLoadAll')
330 : ) {
331 17 : await withLoadFailureToast(() => modelStore.loadModels())
332 : }
333 : })
334 :
335 36 : watch(
336 : () => flags.assetsEnabled,
337 : async (enabled) => {
338 1 : if (enabled) await withLoadFailureToast(() => modelStore.loadModels())
339 : }
340 : )
341 : </script>
|