Line data Source code
1 : import { toLightThemeNodeColor } from '@/renderer/extensions/vueNodes/utils/nodeStyleUtils'
2 : import { computed } from 'vue'
3 : import type { ComputedRef } from 'vue'
4 :
5 : import { useNodePricing } from '@/composables/node/useNodePricing'
6 : import { t } from '@/i18n'
7 : import type {
8 : LGraph,
9 : LGraphNode,
10 : SubgraphNode
11 : } from '@/lib/litegraph/src/litegraph'
12 : import { registerBadgeRowsProvider } from '@/lib/litegraph/src/nodeBadgeDraw'
13 : import { useSettingStore } from '@/platform/settings/settingStore'
14 : import { useLinkStore } from '@/stores/linkStore'
15 : import { graphScopeOf } from '@comfyorg/graph-model/graphScopeId'
16 : import { useNodeDefStore } from '@/stores/nodeDefStore'
17 : import { useWidgetValueStore } from '@/stores/widgetValueStore'
18 : import { useThemeStore } from '@/platform/theme/themeStore'
19 : import { CORE_PART_ORDER } from '@/types/badgeData'
20 : import type { BadgeData, CoreBadgePart } from '@/types/badgeData'
21 : import type { NodeId } from '@comfyorg/graph-model/nodeId'
22 : import { NodeBadgeMode } from '@/types/nodeSource'
23 : import { widgetId } from '@comfyorg/graph-model/widgetId'
24 : import { mapUniqueNodes } from '@/utils/graphTraversalUtil'
25 : import type { UUID } from '@/utils/uuid'
26 :
27 : /** The badge-relevant projection of a node's definition. */
28 : interface NodeDefBadgeSources {
29 : isCoreNode: boolean
30 : lifecycleText: string
31 : sourceText: string
32 : }
33 :
34 : /** How a node participates in credits pricing, decided by the gatherer. */
35 : type PricingBadgeSources =
36 : | { kind: 'none' }
37 : | { kind: 'api-node'; label: string }
38 : | { kind: 'subgraph'; apiNodeCount: number; singleLabel: string }
39 :
40 : /**
41 : * The domain state a node's badges are computed from. Plain data so
42 : * {@link computeBadges} stays pure — {@link nodeBadges}' computed
43 : * gathers these from the live stores.
44 : */
45 : export interface BadgeSources {
46 : nodeId: NodeId
47 : nodeDef: NodeDefBadgeSources | null
48 : badgeModes: {
49 : id: NodeBadgeMode
50 : lifecycle: NodeBadgeMode
51 : source: NodeBadgeMode
52 : }
53 : colors: { fgColor: string; bgColor: string; creditsBgColor: string }
54 : pricing: PricingBadgeSources
55 : }
56 :
57 60225 : function badgeTextVisible(
58 : nodeDef: NodeDefBadgeSources | null,
59 : badgeMode: NodeBadgeMode
60 : ): boolean {
61 60225 : return !(
62 : badgeMode === NodeBadgeMode.None ||
63 : (nodeDef?.isCoreNode && badgeMode === NodeBadgeMode.HideBuiltIn)
64 : )
65 : }
66 :
67 : /** Projects a node's core and credits badge rows from their sources. */
68 20075 : export function computeBadges(sources: BadgeSources): BadgeData[] {
69 20075 : const { nodeId, nodeDef, badgeModes, colors, pricing } = sources
70 20075 : const corePartsByPart: Record<CoreBadgePart, [NodeBadgeMode, string]> = {
71 : id: [badgeModes.id, `#${nodeId}`],
72 : lifecycle: [badgeModes.lifecycle, nodeDef?.lifecycleText ?? ''],
73 : source: [badgeModes.source, nodeDef?.sourceText ?? '']
74 : }
75 : const coreParts = CORE_PART_ORDER.map(
76 : (part): [CoreBadgePart, NodeBadgeMode, string] => [
77 : part,
78 : ...corePartsByPart[part]
79 : ]
80 : )
81 20075 : const rows: BadgeData[] = coreParts
82 : .filter(
83 : ([, mode, text]) => badgeTextVisible(nodeDef, mode) && text.length > 0
84 : )
85 : .map(([part, , text]) => ({
86 : kind: 'core',
87 : part,
88 : text,
89 : fgColor: colors.fgColor,
90 : bgColor: colors.bgColor
91 : }))
92 :
93 20075 : const creditsText = computeCreditsText(pricing)
94 20075 : if (creditsText) {
95 70 : rows.push({
96 : kind: 'credits',
97 : text: creditsText,
98 : fgColor: colors.fgColor,
99 : bgColor: colors.creditsBgColor
100 : })
101 : }
102 20075 : return rows
103 : }
104 :
105 20075 : function computeCreditsText(pricing: PricingBadgeSources): string {
106 20075 : switch (pricing.kind) {
107 : case 'none':
108 19541 : return ''
109 : case 'api-node':
110 98 : return pricing.label
111 : case 'subgraph':
112 436 : if (pricing.apiNodeCount > 1) {
113 0 : return t('nodeBadge.partnerNodesCount', {
114 : count: pricing.apiNodeCount
115 : })
116 : }
117 436 : return pricing.apiNodeCount === 1 ? pricing.singleLabel : ''
118 : }
119 : }
120 :
121 2356 : const CREDITS_BASE_BG_COLOR = '#8D6932'
122 :
123 : /**
124 : * Reads the pricing-relevant store state so the calling computed re-runs
125 : * when a price revision, priced widget value, or priced input connection
126 : * changes.
127 : */
128 103 : function touchPricingSources(graphId: UUID, node: LGraphNode): void {
129 103 : const pricing = useNodePricing()
130 103 : const nodeId = node.id
131 103 : void pricing.getNodeRevisionRef(nodeId).value
132 :
133 103 : if (!node.type || !pricing.hasDynamicPricing(node.type)) return
134 70 : const widgetStore = useWidgetValueStore()
135 70 : for (const name of pricing.getRelevantWidgetNames(node.type)) {
136 235 : void widgetStore.getWidget(widgetId(graphId, nodeId, name))?.value
137 : }
138 70 : const linkStore = useLinkStore()
139 70 : const inputNames = pricing.getInputNames(node.type)
140 70 : const groupPrefixes = pricing.getInputGroupPrefixes(node.type)
141 70 : const graph = node.graph
142 103 : const graphScope = graph ? graphScopeOf(graph) : undefined
143 103 : node.inputs.forEach((input, index) => {
144 : const relevant =
145 : (input.name && inputNames.includes(input.name)) ||
146 : groupPrefixes.some((prefix) => input.name.startsWith(prefix + '.'))
147 350 : if (relevant && graphScope) {
148 60 : void linkStore.isInputSlotConnected(graphScope, nodeId, index)
149 : }
150 : })
151 : }
152 :
153 : /** Promoted widget values on the wrapper override the inner node's own. */
154 5 : function collectPromotedOverrides(
155 : wrapper: SubgraphNode,
156 : innerNode: LGraphNode
157 : ): ReadonlyMap<string, unknown> {
158 5 : const overrides = new Map<string, unknown>()
159 5 : for (const input of wrapper.inputs) {
160 3 : if (!input.widgetId) continue
161 3 : for (const linkId of input._subgraphSlot?.linkIds ?? []) {
162 3 : const link = wrapper.subgraph.getLink(linkId)
163 3 : if (link?.target_id !== innerNode.id) continue
164 3 : const widgetName = innerNode.inputs[link.target_slot]?.widget?.name
165 3 : if (!widgetName) continue
166 3 : overrides.set(
167 : widgetName,
168 : useWidgetValueStore().getWidget(input.widgetId)?.value
169 : )
170 : }
171 : }
172 5 : return overrides
173 : }
174 :
175 : /**
176 : * Aggregates the inner api nodes' credits for a wrapper, tracking their
177 : * pricing revisions so inner price changes recompute the wrapper.
178 : */
179 436 : function gatherSubgraphCredits(wrapper: SubgraphNode): PricingBadgeSources {
180 436 : const pricing = useNodePricing()
181 436 : const apiLeaves = mapUniqueNodes(wrapper.subgraph, (node) =>
182 : !node.isSubgraphNode() && node.constructor.nodeData?.api_node
183 : ? node
184 : : undefined
185 : )
186 436 : for (const leaf of apiLeaves) {
187 5 : const graphId = leaf.graph?.rootGraph.id
188 5 : if (graphId !== undefined) touchPricingSources(graphId, leaf)
189 : }
190 :
191 436 : if (apiLeaves.length !== 1) {
192 431 : return { kind: 'subgraph', apiNodeCount: apiLeaves.length, singleLabel: '' }
193 : }
194 5 : const leaf = apiLeaves[0]
195 : const singleLabel = pricing.getNodeDisplayPrice(
196 : leaf,
197 : collectPromotedOverrides(wrapper, leaf)
198 : )
199 5 : return { kind: 'subgraph', apiNodeCount: 1, singleLabel }
200 : }
201 :
202 20058 : function gatherPricing(node: LGraphNode): PricingBadgeSources {
203 20058 : if (node.isSubgraphNode()) return gatherSubgraphCredits(node)
204 20058 : if (!node.constructor.nodeData?.api_node) return { kind: 'none' }
205 20058 : const graphId = node.graph?.rootGraph.id
206 20058 : if (graphId !== undefined) touchPricingSources(graphId, node)
207 98 : return { kind: 'api-node', label: useNodePricing().getNodeDisplayPrice(node) }
208 : }
209 :
210 20075 : function gatherSources(node: LGraphNode): BadgeSources {
211 20075 : const settingStore = useSettingStore()
212 20075 : const themeStore = useThemeStore()
213 20075 : const palette = themeStore.activeTheme
214 20075 : const def = useNodeDefStore().fromLGraphNode(node)
215 20075 : const showApiPricing = settingStore.get('Comfy.NodeBadge.ShowApiPricing')
216 :
217 20075 : return {
218 : nodeId: node.id,
219 : nodeDef: def
220 : ? {
221 : isCoreNode: def.isCoreNode,
222 : lifecycleText: def.nodeLifeCycleBadgeText,
223 : sourceText: def.nodeSource.badgeText
224 : }
225 : : null,
226 : badgeModes: {
227 : id: settingStore.get('Comfy.NodeBadge.NodeIdBadgeMode'),
228 : lifecycle: settingStore.get('Comfy.NodeBadge.NodeLifeCycleBadgeMode'),
229 : source: settingStore.get('Comfy.NodeBadge.NodeSourceBadgeMode')
230 : },
231 : colors: {
232 : fgColor: palette.canvas.badgeForegroundColor,
233 : bgColor: palette.canvas.badgeBackgroundColor,
234 : creditsBgColor:
235 : themeStore.colorScheme === 'light'
236 : ? toLightThemeNodeColor(CREDITS_BASE_BG_COLOR)
237 : : CREDITS_BASE_BG_COLOR
238 : },
239 : pricing: showApiPricing ? gatherPricing(node) : { kind: 'none' }
240 : }
241 : }
242 :
243 2356 : const badgeComputeds = new WeakMap<LGraphNode, ComputedRef<BadgeData[]>>()
244 :
245 : /**
246 : * A node's derived badge rows, memoized per node instance and recomputed
247 : * when a source changes. Entries die with their nodes; there is no
248 : * registration or teardown.
249 : */
250 74395 : export function nodeBadges(node: LGraphNode): readonly BadgeData[] {
251 74395 : let rows = badgeComputeds.get(node)
252 74395 : if (!rows) {
253 : // Instantiate source stores outside the computed: a store's first
254 : // instantiation mutates pinia.state and would invalidate it.
255 19743 : useSettingStore()
256 19743 : useNodeDefStore()
257 19743 : useThemeStore()
258 19743 : useWidgetValueStore()
259 19743 : useLinkStore()
260 19743 : rows = computed(() => {
261 20075 : return computeBadges(gatherSources(node))
262 : })
263 19743 : badgeComputeds.set(node, rows)
264 : }
265 74395 : return rows.value
266 : }
267 :
268 : interface CreditsBadgeEntry {
269 : nodeId: NodeId
270 : price: string
271 : title: string
272 : }
273 :
274 2356 : const creditsComputeds = new WeakMap<LGraph, ComputedRef<CreditsBadgeEntry[]>>()
275 :
276 : /**
277 : * The credits rows of every unique non-wrapper node under a root graph,
278 : * memoized per graph instance like {@link nodeBadges}.
279 : */
280 80 : export function graphCreditsBadges(
281 : rootGraph: LGraph
282 : ): readonly CreditsBadgeEntry[] {
283 80 : let entries = creditsComputeds.get(rootGraph)
284 80 : if (!entries) {
285 63 : entries = computed(() =>
286 : mapUniqueNodes(rootGraph, (node) => {
287 501 : if (node.isSubgraphNode()) return
288 497 : const priceRow = nodeBadges(node).find((row) => row.kind === 'credits')
289 497 : if (!priceRow) return
290 0 : return { nodeId: node.id, price: priceRow.text, title: node.title }
291 : })
292 : )
293 63 : creditsComputeds.set(rootGraph, entries)
294 : }
295 80 : return entries.value
296 : }
297 :
298 : /** Installs {@link nodeBadges} as the legacy canvas's badge row source. */
299 2355 : export function installNodeBadges(): () => void {
300 2355 : return registerBadgeRowsProvider(nodeBadges)
301 : }
|