Line data Source code
1 : import type {
2 : Bounds,
3 : CompactSize
4 : } from '@comfyorg/shared-frontend-utils/geometry'
5 : import type {
6 : CompositorLayerEntry,
7 : CompositorBackgroundEntry,
8 : CompositorLayerState
9 : } from './compositorTypes'
10 : export type { CompositorLayerState } from './compositorTypes'
11 : import { LAYER_MODES } from '#/mode'
12 : import type { BlendFn } from '#/mode'
13 : import type { FillData, SceneNode, Transform } from '#/node'
14 :
15 2 : const HEX_COLOR_RE = /^#[0-9a-fA-F]{6}$/
16 :
17 2 : const DEFAULT_BACKGROUND_ENTRY: CompositorBackgroundEntry = {
18 : color: '#ffffff',
19 : opacity: 1,
20 : visible: false
21 : }
22 :
23 2 : const LAYER_STATE_VERSION = 1
24 :
25 : export interface CompositorBBox extends Bounds {
26 : name?: string | null
27 : rotation?: number
28 : visible?: boolean
29 : opacity?: number
30 : blend?: string
31 : flipH?: boolean
32 : flipV?: boolean
33 : }
34 :
35 : interface CompositorLayerStateInit {
36 : canvas?: CompactSize
37 : background?: CompositorBackgroundEntry
38 : order?: number[]
39 : layers: Array<Partial<CompositorLayerEntry> | null>
40 : }
41 :
42 : interface CompositorLayerOps {
43 : setCanvasSize(w: number, h: number): void
44 : setLayerOrder(ids: string[]): void
45 : setBackgroundColor(hex: string): void
46 : setBackgroundOpacity(value: number): void
47 : setBackgroundVisible(visible: boolean): void
48 : renameLayer(id: string, name: string): void
49 : toggleVisible(id: string): void
50 : setOpacity(id: string, value: number): void
51 : setBlendMode(id: string, blend: BlendFn): void
52 : flipLayer(id: string, axis: 'h' | 'v'): void
53 : setLayerPosition(id: string, x?: number, y?: number): void
54 : setLayerDimensions(id: string, w?: number, h?: number): void
55 : setLayerRotationDeg(id: string, deg: number): void
56 : }
57 :
58 0 : function isFiniteNumber(value: unknown): value is number {
59 0 : return typeof value === 'number' && Number.isFinite(value)
60 : }
61 :
62 0 : function isBlendFn(value: unknown): value is BlendFn {
63 0 : return typeof value === 'string' && Object.hasOwn(LAYER_MODES, value)
64 : }
65 :
66 0 : function parseTransform(value: unknown): Transform | null {
67 0 : if (typeof value !== 'object' || value === null) return null
68 0 : const { x, y, w, h, rotation } = value as Record<string, unknown>
69 0 : if (
70 : !isFiniteNumber(x) ||
71 : !isFiniteNumber(y) ||
72 : !isFiniteNumber(w) ||
73 : !isFiniteNumber(h) ||
74 : !isFiniteNumber(rotation)
75 : )
76 0 : return null
77 0 : return { x, y, w, h, rotation }
78 : }
79 :
80 0 : function parseFlip(value: unknown): boolean | null {
81 0 : if (value === undefined) return false
82 0 : return typeof value === 'boolean' ? value : null
83 : }
84 :
85 0 : function parseEntry(value: unknown): CompositorLayerEntry | null {
86 0 : if (typeof value !== 'object' || value === null) return null
87 0 : const { name, visible, opacity, blend, transform, flipH, flipV } =
88 : value as Record<string, unknown>
89 0 : const parsedTransform = parseTransform(transform)
90 0 : const parsedFlipH = parseFlip(flipH)
91 0 : const parsedFlipV = parseFlip(flipV)
92 0 : if (
93 : typeof name !== 'string' ||
94 : typeof visible !== 'boolean' ||
95 : !isFiniteNumber(opacity) ||
96 : !isBlendFn(blend) ||
97 : !parsedTransform ||
98 : parsedFlipH === null ||
99 : parsedFlipV === null
100 : )
101 0 : return null
102 0 : return {
103 : name,
104 : visible,
105 : opacity,
106 : blend,
107 : transform: parsedTransform,
108 : flipH: parsedFlipH,
109 : flipV: parsedFlipV
110 : }
111 : }
112 :
113 0 : function backgroundEntry(node: FillData): CompositorBackgroundEntry {
114 0 : return {
115 : color:
116 : node.fill.type === 'solid'
117 : ? node.fill.color
118 : : DEFAULT_BACKGROUND_ENTRY.color,
119 : opacity: node.opacity,
120 : visible: node.visible
121 : }
122 : }
123 :
124 0 : export function extractLayerState(
125 : canvas: CompactSize,
126 : layers: readonly SceneNode[],
127 : layerFlips: (id: string) => { h: boolean; v: boolean },
128 : inputs?: string[],
129 : inputOrder?: readonly string[]
130 : ): CompositorLayerState {
131 0 : const background = layers.find(
132 : (node): node is FillData => node.kind === 'fill'
133 : )
134 0 : const imageNodes = layers.filter((node) => node.kind !== 'fill')
135 0 : const orderIds = inputOrder ?? imageNodes.map((node) => node.id)
136 0 : const inputIndex = new Map(orderIds.map((id, index) => [id, index]))
137 0 : const entries: Array<CompositorLayerEntry | null> = orderIds.map(() => null)
138 0 : const order: number[] = []
139 0 : for (const node of imageNodes) {
140 0 : const index = inputIndex.get(node.id)
141 0 : if (index === undefined) continue
142 0 : const flips = layerFlips(node.id)
143 0 : entries[index] = {
144 : name: node.name,
145 : visible: node.visible,
146 : opacity: node.opacity,
147 : blend: node.mode.blend,
148 : transform: { ...node.transform },
149 : flipH: flips.h,
150 : flipV: flips.v
151 : }
152 0 : order.push(index)
153 : }
154 0 : const identityOrder =
155 : order.length === entries.length &&
156 : order.every((value, index) => value === index)
157 0 : return {
158 : version: LAYER_STATE_VERSION,
159 : canvas: { w: canvas.w, h: canvas.h },
160 : ...(inputs ? { inputs } : {}),
161 : ...(background ? { background: backgroundEntry(background) } : {}),
162 : ...(identityOrder ? {} : { order }),
163 : layers: entries
164 : }
165 : }
166 :
167 0 : function parseCanvasSize(value: unknown): CompactSize | undefined {
168 0 : if (typeof value !== 'object' || value === null) return undefined
169 0 : const { w, h } = value as Record<string, unknown>
170 0 : return isFiniteNumber(w) && isFiniteNumber(h) ? { w, h } : undefined
171 : }
172 :
173 0 : function parseBackground(
174 : value: unknown
175 : ): CompositorBackgroundEntry | undefined {
176 0 : if (typeof value !== 'object' || value === null) return undefined
177 0 : const { color, opacity, visible } = value as Record<string, unknown>
178 0 : return {
179 : color:
180 : typeof color === 'string' && HEX_COLOR_RE.test(color)
181 : ? color
182 : : DEFAULT_BACKGROUND_ENTRY.color,
183 : opacity: isFiniteNumber(opacity)
184 : ? Math.max(0, Math.min(1, opacity))
185 : : DEFAULT_BACKGROUND_ENTRY.opacity,
186 : visible:
187 : typeof visible === 'boolean' ? visible : DEFAULT_BACKGROUND_ENTRY.visible
188 : }
189 : }
190 :
191 0 : function parseOrder(value: unknown, layerCount: number): number[] | undefined {
192 0 : if (!Array.isArray(value) || value.length !== layerCount || layerCount === 0)
193 0 : return undefined
194 0 : const items: unknown[] = value
195 0 : if (
196 : !items.every(
197 : (item): item is number =>
198 : typeof item === 'number' &&
199 : Number.isInteger(item) &&
200 : item >= 0 &&
201 : item < layerCount
202 : )
203 : )
204 0 : return undefined
205 0 : return new Set(items).size === layerCount ? [...items] : undefined
206 : }
207 :
208 0 : function parseInputs(value: unknown): string[] | undefined {
209 0 : if (!Array.isArray(value)) return undefined
210 0 : const items: unknown[] = value
211 0 : return items.every((item): item is string => typeof item === 'string')
212 : ? [...items]
213 : : undefined
214 : }
215 :
216 0 : function parseJson(json: string): unknown {
217 0 : try {
218 0 : return JSON.parse(json)
219 : } catch {
220 0 : return null
221 : }
222 : }
223 :
224 0 : export function parseLayerState(value: unknown): CompositorLayerState | null {
225 0 : const raw = typeof value === 'string' ? parseJson(value) : value
226 0 : if (typeof raw !== 'object' || raw === null) return null
227 0 : if (Object.keys(raw).length === 0) return null
228 :
229 0 : const { version, canvas, layers, inputs, background, order } = raw as Record<
230 : string,
231 : unknown
232 : >
233 0 : if (version !== undefined && version !== LAYER_STATE_VERSION) return null
234 0 : const canvasSize = parseCanvasSize(canvas)
235 0 : const parsedInputs = parseInputs(inputs)
236 0 : const parsedBackground = parseBackground(background)
237 0 : const parsedLayers = Array.isArray(layers) ? layers.map(parseEntry) : []
238 0 : const parsedOrder = parseOrder(order, parsedLayers.length)
239 :
240 0 : return {
241 : version: LAYER_STATE_VERSION,
242 : ...(canvasSize ? { canvas: canvasSize } : {}),
243 : ...(parsedInputs ? { inputs: parsedInputs } : {}),
244 : ...(parsedBackground ? { background: parsedBackground } : {}),
245 : ...(parsedOrder ? { order: parsedOrder } : {}),
246 : layers: parsedLayers
247 : }
248 : }
249 :
250 0 : export function layerStateInputsMatch(
251 : saved: readonly string[] | undefined,
252 : current: readonly string[] | undefined
253 : ): boolean {
254 0 : if (!saved || !current) return false
255 0 : return (
256 : saved.length === current.length &&
257 : saved.every((value, index) => value === current[index])
258 : )
259 : }
260 :
261 0 : function bboxLayerState(
262 : bboxes: ReadonlyArray<CompositorBBox | null> | undefined,
263 : canvas?: CompactSize
264 : ): CompositorLayerStateInit | null {
265 0 : if (!bboxes?.some((bbox) => bbox !== null)) return null
266 0 : const canvasSize = parseCanvasSize(canvas)
267 0 : return {
268 : ...(canvasSize ? { canvas: canvasSize } : {}),
269 : layers: bboxes.map((bbox) =>
270 : bbox
271 : ? {
272 : ...(typeof bbox.name === 'string' && bbox.name
273 : ? { name: bbox.name }
274 : : {}),
275 : ...(typeof bbox.visible === 'boolean'
276 : ? { visible: bbox.visible }
277 : : {}),
278 : ...(isFiniteNumber(bbox.opacity) ? { opacity: bbox.opacity } : {}),
279 : ...(isBlendFn(bbox.blend) ? { blend: bbox.blend } : {}),
280 : ...(bbox.flipH === true ? { flipH: true } : {}),
281 : ...(bbox.flipV === true ? { flipV: true } : {}),
282 : transform: {
283 : x: bbox.x,
284 : y: bbox.y,
285 : w: bbox.width,
286 : h: bbox.height,
287 : rotation: isFiniteNumber(bbox.rotation) ? bbox.rotation : 0
288 : }
289 : }
290 : : null
291 : )
292 : }
293 : }
294 :
295 0 : export function resolveInitialLayerState(
296 : savedState: CompositorLayerState | null,
297 : currentInputs: readonly string[] | undefined,
298 : bboxes: ReadonlyArray<CompositorBBox | null> | undefined,
299 : canvas?: CompactSize
300 : ): CompositorLayerStateInit | null {
301 0 : if (savedState && layerStateInputsMatch(savedState.inputs, currentInputs))
302 0 : return savedState
303 0 : return bboxLayerState(bboxes, canvas)
304 : }
305 :
306 0 : export function applyLayerState(
307 : state: CompositorLayerStateInit,
308 : layers: ReadonlyArray<{ id: string; visible: boolean }>,
309 : ops: CompositorLayerOps
310 : ): void {
311 0 : if (state.canvas) ops.setCanvasSize(state.canvas.w, state.canvas.h)
312 :
313 0 : const background = state.background ?? DEFAULT_BACKGROUND_ENTRY
314 0 : ops.setBackgroundColor(background.color)
315 0 : ops.setBackgroundOpacity(background.opacity)
316 0 : ops.setBackgroundVisible(background.visible)
317 :
318 0 : if (state.layers.length !== layers.length) return
319 0 : const count = layers.length
320 0 : for (let i = 0; i < count; i++) {
321 0 : const entry = state.layers[i]
322 0 : if (!entry) continue
323 0 : const { id, visible } = layers[i]
324 0 : if (entry.name !== undefined) ops.renameLayer(id, entry.name)
325 0 : if (entry.visible !== undefined && visible !== entry.visible)
326 0 : ops.toggleVisible(id)
327 0 : if (entry.opacity !== undefined) ops.setOpacity(id, entry.opacity)
328 0 : if (entry.blend !== undefined) ops.setBlendMode(id, entry.blend)
329 0 : if (entry.flipH) ops.flipLayer(id, 'h')
330 0 : if (entry.flipV) ops.flipLayer(id, 'v')
331 0 : if (entry.transform) {
332 0 : ops.setLayerPosition(id, entry.transform.x, entry.transform.y)
333 0 : ops.setLayerDimensions(id, entry.transform.w, entry.transform.h)
334 0 : ops.setLayerRotationDeg(id, (entry.transform.rotation * 180) / Math.PI)
335 : }
336 : }
337 :
338 0 : if (state.order) {
339 0 : const ids = state.order
340 : .map((index) => layers.at(index)?.id)
341 : .filter((id): id is string => id !== undefined)
342 0 : if (ids.length > 0) ops.setLayerOrder(ids)
343 : }
344 : }
|