Line data Source code
1 : import { defineStore } from 'pinia'
2 : import { computed, ref, watch } from 'vue'
3 :
4 : import { st } from '@/i18n'
5 : import type { IBaseWidget } from '@comfyorg/graph-model/widgets'
6 : import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
7 : import { useApp } from '@/scripts/appInstance'
8 : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
9 : import { isNodeLocatorId } from '@comfyorg/graph-model/nodeIdentification'
10 : import type { NodeLocatorId } from '@comfyorg/graph-model/nodeIdentification'
11 : import { parseNodeId } from '@comfyorg/graph-model/nodeId'
12 : import { getNodeByLocatorId } from '@/utils/graphTraversalUtil'
13 : import { resolveNodeDisplayName } from '@/utils/nodeTitleUtil'
14 : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
15 :
16 : /**
17 : * Unique identifier for a favorited widget.
18 : * Combines node locator ID and widget name to locate a widget in the graph.
19 : */
20 : interface FavoritedWidgetId {
21 : /** The node locator ID in the graph */
22 : nodeLocatorId: NodeLocatorId
23 : /** The widget name on the node */
24 : widgetName: string
25 : }
26 :
27 : /**
28 : * A favorited widget with its resolved runtime instance.
29 : * The widget instance may be null if the node or widget no longer exists.
30 : */
31 : interface FavoritedWidget extends FavoritedWidgetId {
32 : /** The resolved node instance (null if node was deleted) */
33 : node: LGraphNode | null
34 : /** The resolved widget instance (null if widget no longer exists) */
35 : widget: IBaseWidget | null
36 : /** Display label for the favorited item */
37 : label: string
38 : }
39 :
40 : export interface ValidFavoritedWidget extends FavoritedWidget {
41 : node: LGraphNode
42 : widget: IBaseWidget
43 : }
44 :
45 : /**
46 : * Storage format for persisted favorited widgets.
47 : * Stored in workflow.extra.favoritedWidgets.
48 : */
49 : interface FavoritedWidgetStorage {
50 : /** Array of favorited widget identifiers */
51 : favorites: FavoritedWidgetId[]
52 : }
53 :
54 : /**
55 : * Store for managing favorited/starred widgets.
56 : *
57 : * Favorited widgets can be accessed and edited from the properties panel
58 : * without needing to select the corresponding node. This store manages:
59 : * - Persisting favorited widget IDs per workflow
60 : * - Resolving widget IDs to actual widget instances
61 : * - Handling cases where nodes/widgets are deleted
62 : *
63 : * Design decisions:
64 : * - Scope: Per-workflow (not global user preference)
65 : * - Identifier: node locator ID + widget.name
66 : * - Persistence: Stored in workflow.extra.favoritedWidgets (serialized with workflow)
67 : * - Future: Can be extended for Linear Mode
68 : */
69 2356 : export const useFavoritedWidgetsStore = defineStore('favoritedWidgets', () => {
70 175 : const workflowStore = useWorkflowStore()
71 175 : const canvasStore = useCanvasStore()
72 :
73 : /** In-memory array of favorited widget IDs, ordered for display */
74 175 : const favoritedIds = ref<string[]>([])
75 :
76 : // TODO(ADR-SUBGRAPH-PROMOTION-0009): key favorites by the host-scoped WidgetId instead of
77 : // (nodeLocatorId, widgetName). That drops the isShownOnParents/favoriteNode
78 : // indirection for promoted widgets. Deferred: needs a one-time migration of
79 : // the persisted workflow.extra.favoritedWidgets format.
80 : /**
81 : * Generate a unique string key for a favorited widget ID.
82 : */
83 646 : function getFavoriteKey(id: FavoritedWidgetId): string {
84 646 : return JSON.stringify([id.nodeLocatorId, id.widgetName])
85 : }
86 :
87 : /**
88 : * Parse a favorite key back into a FavoritedWidgetId.
89 : */
90 3 : function parseFavoriteKey(key: string): FavoritedWidgetId | null {
91 3 : try {
92 3 : const [nodeLocatorId, widgetName] = JSON.parse(key) as [string, string]
93 3 : if (!isNodeLocatorId(nodeLocatorId) || !widgetName) return null
94 3 : return { nodeLocatorId, widgetName }
95 : } catch {
96 0 : const separatorIndex = key.indexOf(':')
97 0 : if (separatorIndex === -1) return null
98 0 : const nodeLocatorId = key.slice(0, separatorIndex)
99 0 : const widgetName = key.slice(separatorIndex + 1)
100 0 : if (!isNodeLocatorId(nodeLocatorId) || !widgetName) return null
101 0 : return { nodeLocatorId, widgetName }
102 : }
103 : }
104 :
105 0 : function normalizeFavoritedId(
106 : id: FavoritedWidgetId | { nodeId?: unknown; widgetName?: unknown } | null
107 : ): FavoritedWidgetId | null {
108 0 : if (!id || !id.widgetName) return null
109 :
110 0 : if ('nodeLocatorId' in id && id.nodeLocatorId) {
111 0 : if (!isNodeLocatorId(id.nodeLocatorId)) return null
112 0 : return {
113 : nodeLocatorId: id.nodeLocatorId,
114 : widgetName: id.widgetName
115 : }
116 : }
117 :
118 0 : if ('nodeId' in id && id.nodeId !== undefined) {
119 0 : const parsedNodeId = parseNodeId(id.nodeId)
120 0 : if (!parsedNodeId) return null
121 0 : return {
122 : nodeLocatorId: workflowStore.nodeIdToNodeLocatorId(parsedNodeId),
123 : widgetName: String(id.widgetName)
124 : }
125 : }
126 :
127 0 : return null
128 : }
129 :
130 646 : function createFavoriteId(
131 : node: LGraphNode,
132 : widgetName: string
133 : ): FavoritedWidgetId {
134 646 : return {
135 : nodeLocatorId: workflowStore.nodeToNodeLocatorId(node),
136 : widgetName
137 : }
138 : }
139 :
140 : /**
141 : * Load favorited widgets from the current workflow's extra data.
142 : */
143 203 : function loadFromWorkflow() {
144 203 : const graph = useApp().rootGraphOrUndefined
145 203 : if (!graph) return
146 :
147 203 : try {
148 203 : const storedData = graph.extra.favoritedWidgets as
149 : | FavoritedWidgetStorage
150 : | undefined
151 :
152 203 : if (storedData?.favorites) {
153 0 : const normalized = storedData.favorites
154 : .map((fav) => normalizeFavoritedId(fav))
155 : .filter((fav): fav is FavoritedWidgetId => fav !== null)
156 0 : favoritedIds.value = normalized.map(getFavoriteKey)
157 : } else {
158 203 : favoritedIds.value = []
159 : }
160 : } catch (error) {
161 0 : console.error('Failed to load favorited widgets from workflow:', error)
162 0 : favoritedIds.value = []
163 : }
164 : }
165 :
166 : /**
167 : * Save favorited widgets to the current workflow's extra data.
168 : * Marks the workflow as modified.
169 : */
170 2 : function saveToWorkflow() {
171 2 : const graph = useApp().rootGraphOrUndefined
172 2 : if (!graph) return
173 :
174 2 : try {
175 : const favorites: FavoritedWidgetId[] = favoritedIds.value
176 : .map(parseFavoriteKey)
177 : .filter((id): id is FavoritedWidgetId => id !== null)
178 :
179 2 : const data: FavoritedWidgetStorage = { favorites }
180 :
181 2 : graph.extra.favoritedWidgets = data
182 :
183 : // Mark the workflow as modified
184 2 : canvasStore.canvas?.setDirty(true, true)
185 : } catch (error) {
186 0 : console.error('Failed to save favorited widgets to workflow:', error)
187 : }
188 : }
189 :
190 : /**
191 : * Resolve a favorited widget ID to its actual widget instance.
192 : * Returns null if the node or widget no longer exists.
193 : */
194 1 : function resolveWidget(id: FavoritedWidgetId): FavoritedWidget {
195 1 : const graph = useApp().rootGraphOrUndefined
196 1 : if (!graph) {
197 0 : return { ...id, node: null, widget: null, label: id.widgetName }
198 : }
199 :
200 1 : const node = getNodeByLocatorId(graph, id.nodeLocatorId)
201 1 : if (!node) {
202 0 : return {
203 : ...id,
204 : node: null,
205 : widget: null,
206 : label: `${id.widgetName} (node deleted)`
207 : }
208 : }
209 :
210 1 : const widget = node.widgets?.find((w) => w.name === id.widgetName)
211 1 : if (!widget) {
212 0 : return {
213 : ...id,
214 : node,
215 : widget: null,
216 : label: `${id.widgetName} (widget not found)`
217 : }
218 : }
219 :
220 1 : const fallbackNodeTitle = st('rightSidePanel.fallbackNodeTitle', 'Node')
221 1 : const nodeTitle = resolveNodeDisplayName(node, {
222 : emptyLabel: fallbackNodeTitle,
223 : untitledLabel: fallbackNodeTitle
224 : })
225 1 : const widgetLabel = widget.label || widget.name
226 1 : return {
227 : ...id,
228 : node,
229 : widget,
230 : label: `${nodeTitle} / ${widgetLabel}`
231 : }
232 : }
233 :
234 : /**
235 : * Get all favorited widgets with their resolved instances.
236 : * Widgets that no longer exist will have null node/widget properties.
237 : */
238 175 : const favoritedWidgets = computed((): FavoritedWidget[] => {
239 151 : return favoritedIds.value
240 : .map(parseFavoriteKey)
241 : .filter((id): id is FavoritedWidgetId => id !== null)
242 : .map(resolveWidget)
243 : })
244 :
245 : /**
246 : * Get only the valid favorited widgets (where both node and widget exist).
247 : */
248 175 : const validFavoritedWidgets = computed((): ValidFavoritedWidget[] => {
249 151 : return favoritedWidgets.value.filter(
250 : (fw) => fw.node !== null && fw.widget !== null
251 : ) as ValidFavoritedWidget[]
252 : })
253 :
254 : /**
255 : * Check if a widget is favorited.
256 : */
257 644 : function isFavorited(node: LGraphNode, widgetName: string): boolean {
258 644 : return favoritedIds.value.includes(
259 : getFavoriteKey(createFavoriteId(node, widgetName))
260 : )
261 : }
262 :
263 : /**
264 : * Add a widget to favorites.
265 : */
266 2 : function addFavorite(node: LGraphNode, widgetName: string) {
267 2 : const key = getFavoriteKey(createFavoriteId(node, widgetName))
268 2 : if (favoritedIds.value.includes(key)) return
269 :
270 2 : favoritedIds.value.push(key)
271 2 : saveToWorkflow()
272 : }
273 :
274 : /**
275 : * Remove a widget from favorites.
276 : */
277 0 : function removeFavorite(node: LGraphNode, widgetName: string) {
278 0 : const key = getFavoriteKey(createFavoriteId(node, widgetName))
279 0 : const index = favoritedIds.value.indexOf(key)
280 0 : if (index === -1) return
281 :
282 0 : favoritedIds.value.splice(index, 1)
283 0 : saveToWorkflow()
284 : }
285 :
286 : /**
287 : * Toggle a widget's favorite status.
288 : */
289 2 : function toggleFavorite(node: LGraphNode, widgetName: string) {
290 2 : if (isFavorited(node, widgetName)) {
291 0 : removeFavorite(node, widgetName)
292 : } else {
293 2 : addFavorite(node, widgetName)
294 : }
295 : }
296 :
297 : /**
298 : * Clear all favorites for the current workflow.
299 : */
300 0 : function clearFavorites() {
301 0 : favoritedIds.value = []
302 0 : saveToWorkflow()
303 : }
304 :
305 : /**
306 : * Remove invalid favorites (where node or widget no longer exists).
307 : * Useful for cleanup after loading a workflow.
308 : */
309 0 : function pruneInvalidFavorites() {
310 0 : const validKeys = validFavoritedWidgets.value.map((fw) =>
311 : getFavoriteKey({
312 : nodeLocatorId: fw.nodeLocatorId,
313 : widgetName: fw.widgetName
314 : })
315 : )
316 0 : const validSet = new Set(validKeys)
317 :
318 0 : const filteredIds = favoritedIds.value.filter((key) => validSet.has(key))
319 :
320 0 : if (filteredIds.length !== favoritedIds.value.length) {
321 0 : favoritedIds.value = filteredIds
322 0 : saveToWorkflow()
323 : }
324 : }
325 :
326 : /**
327 : * Reorder favorites based on the provided array of widgets.
328 : * Used when dragging and dropping favorites to reorder them.
329 : */
330 0 : function reorderFavorites(reorderedWidgets: ValidFavoritedWidget[]) {
331 0 : favoritedIds.value = reorderedWidgets.map((fw) =>
332 : getFavoriteKey({
333 : nodeLocatorId: fw.nodeLocatorId,
334 : widgetName: fw.widgetName
335 : })
336 : )
337 0 : saveToWorkflow()
338 : }
339 :
340 : // Watch for workflow changes and reload favorites from workflow.extra
341 175 : watch(
342 : () => workflowStore.activeWorkflow?.path,
343 : () => {
344 203 : loadFromWorkflow()
345 : },
346 : { immediate: true }
347 : )
348 :
349 175 : return {
350 : // State
351 : favoritedWidgets,
352 : validFavoritedWidgets,
353 :
354 : // Actions
355 : isFavorited,
356 : addFavorite,
357 : removeFavorite,
358 : toggleFavorite,
359 : clearFavorites,
360 : pruneInvalidFavorites,
361 : reorderFavorites
362 : }
363 : })
|