Line data Source code
1 : import { useResizeObserver } from '@vueuse/core'
2 : import type { Ref } from 'vue'
3 : import { computed, ref, watch } from 'vue'
4 :
5 : import { useLiveGraphNode } from '@/composables/useLiveGraphNode'
6 : import { locateWidgetNode } from '@/composables/widgetHistoryScope'
7 : import type { LocatedWidget } from '@/composables/widgetHistoryScope'
8 : import { resolveWidgetInputSource } from '@/composables/widgetInputSource'
9 : import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
10 : import { LiteGraph } from '@/lib/litegraph/src/litegraph'
11 : import type { Bounds } from '@comfyorg/shared-frontend-utils/geometry'
12 : import { useNodeOutputStore } from '@/stores/nodeOutputStore'
13 : import type { NodeId } from '@comfyorg/graph-model/nodeId'
14 :
15 : type ResizeDirection =
16 : | 'top'
17 : | 'bottom'
18 : | 'left'
19 : | 'right'
20 : | 'nw'
21 : | 'ne'
22 : | 'sw'
23 : | 'se'
24 :
25 : interface ResizeHandle {
26 : direction: ResizeDirection
27 : class: string
28 : style: {
29 : left: string
30 : top: string
31 : width?: string
32 : height?: string
33 : }
34 : }
35 :
36 49 : const HANDLE_SIZE = 8
37 49 : const CORNER_HIT_SIZE = 16
38 49 : const CORNER_DOT_CLASS =
39 : "after:pointer-events-none after:absolute after:left-1/2 after:top-1/2 after:size-[9px] after:-translate-x-1/2 after:-translate-y-1/2 after:rounded-full after:bg-white/80 after:content-['']"
40 : /** Minimum crop width/height in source image pixel space. */
41 49 : const MIN_CROP_SIZE = 16
42 49 : const CROP_BOX_BORDER = 1
43 :
44 : /**
45 : * Next `isLoading` when `imageUrl` transitions. `null` means do not change
46 : * `isLoading` (e.g. same URL).
47 : */
48 52 : export function imageCropLoadingAfterUrlChange(
49 : url: string | null,
50 : previous: string | null | undefined
51 : ): boolean | null {
52 52 : if (url == null) return false
53 30 : if (url !== previous) return true
54 0 : return null
55 : }
56 :
57 49 : export const ASPECT_RATIOS = {
58 : '1:1': 1,
59 : '3:4': 3 / 4,
60 : '4:3': 4 / 3,
61 : '16:9': 16 / 9,
62 : '9:16': 9 / 16,
63 : custom: null
64 : } as const
65 :
66 : interface UseImageCropOptions {
67 : widget: LocatedWidget
68 : imageEl: Ref<HTMLImageElement | null>
69 : containerEl: Ref<HTMLDivElement | null>
70 : modelValue: Ref<Bounds>
71 : onEditEnd?: () => void
72 : }
73 :
74 51 : function imageInputSlot(node: LGraphNode): number {
75 51 : if (node.isSubgraphNode()) return 0
76 :
77 51 : const slot = node.inputs.findIndex((input) =>
78 : LiteGraph.isValidConnection('IMAGE', input.type)
79 : )
80 51 : return slot === -1 ? 0 : slot
81 : }
82 :
83 49 : export function useImageCrop(nodeId: NodeId, options: UseImageCropOptions) {
84 49 : const { widget, imageEl, containerEl, modelValue, onEditEnd } = options
85 49 : const nodeOutputStore = useNodeOutputStore()
86 :
87 49 : const node = useLiveGraphNode(() => {
88 49 : const location = locateWidgetNode(widget, nodeId)
89 49 : return location?.graph.getNodeById(location.nodeId)
90 : })
91 :
92 49 : const imageUrl = ref<string | null>(null)
93 49 : const isLoading = ref(false)
94 :
95 49 : const naturalWidth = ref(0)
96 49 : const naturalHeight = ref(0)
97 49 : const displayedWidth = ref(0)
98 49 : const displayedHeight = ref(0)
99 49 : const scaleFactor = ref(1)
100 49 : const imageOffsetX = ref(0)
101 49 : const imageOffsetY = ref(0)
102 :
103 49 : const cropX = computed({
104 : get: () => modelValue.value.x,
105 : set: (v: number) => {
106 16 : modelValue.value.x = v
107 : }
108 : })
109 :
110 49 : const cropY = computed({
111 : get: () => modelValue.value.y,
112 : set: (v: number) => {
113 15 : modelValue.value.y = v
114 : }
115 : })
116 :
117 49 : const cropWidth = computed({
118 : get: () => modelValue.value.width || 512,
119 : set: (v: number) => {
120 13 : modelValue.value.width = v
121 : }
122 : })
123 :
124 49 : const cropHeight = computed({
125 : get: () => modelValue.value.height || 512,
126 : set: (v: number) => {
127 14 : modelValue.value.height = v
128 : }
129 : })
130 :
131 49 : const isDragging = ref(false)
132 49 : const dragStartX = ref(0)
133 49 : const dragStartY = ref(0)
134 49 : const dragStartCropX = ref(0)
135 49 : const dragStartCropY = ref(0)
136 :
137 49 : const isResizing = ref(false)
138 49 : const resizeDirection = ref<ResizeDirection | null>(null)
139 49 : const resizeStartX = ref(0)
140 49 : const resizeStartY = ref(0)
141 49 : const resizeStartCropX = ref(0)
142 49 : const resizeStartCropY = ref(0)
143 49 : const resizeStartCropWidth = ref(0)
144 49 : const resizeStartCropHeight = ref(0)
145 :
146 49 : const lockedRatio = ref<number | null>(null)
147 :
148 49 : const selectedRatio = computed({
149 : get: () => {
150 65 : if (lockedRatio.value == null) return 'custom'
151 12 : const entry = Object.entries(ASPECT_RATIOS).find(
152 : ([, v]) => v === lockedRatio.value
153 : )
154 65 : return entry ? entry[0] : 'custom'
155 : },
156 : set: (key: string) => {
157 5 : if (key === 'custom') {
158 1 : lockedRatio.value = null
159 1 : return
160 : }
161 5 : lockedRatio.value =
162 : ASPECT_RATIOS[key as keyof typeof ASPECT_RATIOS] ?? null
163 5 : applyLockedRatio()
164 5 : onEditEnd?.()
165 : }
166 : })
167 :
168 49 : const isLockEnabled = computed({
169 : get: () => lockedRatio.value != null,
170 : set: (locked: boolean) => {
171 11 : if (locked && lockedRatio.value == null) {
172 8 : lockedRatio.value = cropWidth.value / cropHeight.value
173 : }
174 11 : if (!locked) {
175 3 : lockedRatio.value = null
176 : }
177 : }
178 : })
179 :
180 4 : function applyLockedRatio() {
181 4 : if (lockedRatio.value == null) return
182 :
183 4 : const ratio = lockedRatio.value
184 4 : const w = cropWidth.value
185 4 : let newHeight = Math.round(w / ratio)
186 :
187 4 : if (cropY.value + newHeight > naturalHeight.value) {
188 2 : newHeight = naturalHeight.value - cropY.value
189 2 : const newWidth = Math.round(newHeight * ratio)
190 2 : cropWidth.value = Math.max(MIN_CROP_SIZE, newWidth)
191 : }
192 :
193 4 : cropHeight.value = Math.max(MIN_CROP_SIZE, newHeight)
194 : }
195 :
196 49 : useResizeObserver(containerEl, () => {
197 78 : if (imageEl.value && imageUrl.value) {
198 56 : updateDisplayedDimensions()
199 : }
200 : })
201 :
202 49 : const inputImageUrl = computed<string | null>(() => {
203 51 : const cropNode = node.value
204 51 : if (!cropNode) return null
205 :
206 51 : const sourceNode = resolveWidgetInputSource(
207 : cropNode,
208 : imageInputSlot(cropNode),
209 : nodeId
210 : )
211 51 : if (!sourceNode) return null
212 :
213 51 : return nodeOutputStore.getNodeImageUrls(sourceNode)?.[0] ?? null
214 : })
215 :
216 49 : watch(
217 : inputImageUrl,
218 : (url) => {
219 51 : imageUrl.value = url
220 : },
221 : { immediate: true }
222 : )
223 :
224 49 : watch(
225 : imageUrl,
226 : (url, previous) => {
227 52 : const next = imageCropLoadingAfterUrlChange(url, previous)
228 52 : if (next !== null) {
229 52 : isLoading.value = next
230 : }
231 : },
232 : { immediate: true }
233 : )
234 :
235 49 : const updateDisplayedDimensions = () => {
236 85 : if (!imageEl.value || !containerEl.value) return
237 :
238 85 : const img = imageEl.value
239 85 : const container = containerEl.value
240 :
241 85 : naturalWidth.value = img.naturalWidth
242 85 : naturalHeight.value = img.naturalHeight
243 :
244 85 : if (naturalWidth.value <= 0 || naturalHeight.value <= 0) {
245 27 : scaleFactor.value = 1
246 27 : return
247 : }
248 :
249 58 : const containerWidth = container.clientWidth
250 58 : const containerHeight = container.clientHeight
251 :
252 58 : const imageAspect = naturalWidth.value / naturalHeight.value
253 : const containerAspect = containerWidth / containerHeight
254 :
255 84 : if (imageAspect > containerAspect) {
256 0 : displayedWidth.value = containerWidth
257 0 : displayedHeight.value = containerWidth / imageAspect
258 0 : imageOffsetX.value = 0
259 0 : imageOffsetY.value = (containerHeight - displayedHeight.value) / 2
260 : } else {
261 58 : displayedHeight.value = containerHeight
262 58 : displayedWidth.value = containerHeight * imageAspect
263 58 : imageOffsetX.value = (containerWidth - displayedWidth.value) / 2
264 58 : imageOffsetY.value = 0
265 : }
266 :
267 85 : if (naturalWidth.value <= 0 || displayedWidth.value <= 0) {
268 0 : scaleFactor.value = 1
269 : } else {
270 58 : scaleFactor.value = displayedWidth.value / naturalWidth.value
271 : }
272 : }
273 :
274 49 : const getEffectiveScale = (): number => {
275 19 : const container = containerEl.value
276 :
277 19 : if (!container || naturalWidth.value <= 0 || displayedWidth.value <= 0) {
278 0 : return 1
279 : }
280 :
281 19 : const rect = container.getBoundingClientRect()
282 19 : const clientWidth = container.clientWidth
283 :
284 19 : if (!clientWidth || !rect.width) return 1
285 :
286 : const renderedDisplayedWidth =
287 : (displayedWidth.value / clientWidth) * rect.width
288 :
289 19 : return renderedDisplayedWidth / naturalWidth.value
290 : }
291 :
292 49 : const cropBoxStyle = computed(() => ({
293 : left: `${imageOffsetX.value + cropX.value * scaleFactor.value - CROP_BOX_BORDER}px`,
294 : top: `${imageOffsetY.value + cropY.value * scaleFactor.value - CROP_BOX_BORDER}px`,
295 : width: `${cropWidth.value * scaleFactor.value}px`,
296 : height: `${cropHeight.value * scaleFactor.value}px`
297 : }))
298 :
299 49 : const CORNER_DIRECTIONS = new Set<ResizeDirection>(['nw', 'ne', 'sw', 'se'])
300 :
301 49 : const allResizeHandles = computed<ResizeHandle[]>(() => {
302 99 : const x = imageOffsetX.value + cropX.value * scaleFactor.value
303 99 : const y = imageOffsetY.value + cropY.value * scaleFactor.value
304 99 : const w = cropWidth.value * scaleFactor.value
305 99 : const h = cropHeight.value * scaleFactor.value
306 99 : const borderMid = CROP_BOX_BORDER / 2
307 :
308 99 : return [
309 : {
310 : direction: 'top',
311 : class: 'h-2 cursor-ns-resize',
312 : style: {
313 : left: `${x + HANDLE_SIZE}px`,
314 : top: `${y - HANDLE_SIZE / 2}px`,
315 : width: `${Math.max(0, w - HANDLE_SIZE * 2)}px`
316 : }
317 : },
318 : {
319 : direction: 'bottom',
320 : class: 'h-2 cursor-ns-resize',
321 : style: {
322 : left: `${x + HANDLE_SIZE}px`,
323 : top: `${y + h - HANDLE_SIZE / 2}px`,
324 : width: `${Math.max(0, w - HANDLE_SIZE * 2)}px`
325 : }
326 : },
327 : {
328 : direction: 'left',
329 : class: 'w-2 cursor-ew-resize',
330 : style: {
331 : left: `${x - HANDLE_SIZE / 2}px`,
332 : top: `${y + HANDLE_SIZE}px`,
333 : height: `${Math.max(0, h - HANDLE_SIZE * 2)}px`
334 : }
335 : },
336 : {
337 : direction: 'right',
338 : class: 'w-2 cursor-ew-resize',
339 : style: {
340 : left: `${x + w - HANDLE_SIZE / 2}px`,
341 : top: `${y + HANDLE_SIZE}px`,
342 : height: `${Math.max(0, h - HANDLE_SIZE * 2)}px`
343 : }
344 : },
345 : {
346 : direction: 'nw',
347 : class: `cursor-nwse-resize ${CORNER_DOT_CLASS}`,
348 : style: {
349 : left: `${x - borderMid - CORNER_HIT_SIZE / 2}px`,
350 : top: `${y - borderMid - CORNER_HIT_SIZE / 2}px`,
351 : width: `${CORNER_HIT_SIZE}px`,
352 : height: `${CORNER_HIT_SIZE}px`
353 : }
354 : },
355 : {
356 : direction: 'ne',
357 : class: `cursor-nesw-resize ${CORNER_DOT_CLASS}`,
358 : style: {
359 : left: `${x + w + borderMid - CORNER_HIT_SIZE / 2}px`,
360 : top: `${y - borderMid - CORNER_HIT_SIZE / 2}px`,
361 : width: `${CORNER_HIT_SIZE}px`,
362 : height: `${CORNER_HIT_SIZE}px`
363 : }
364 : },
365 : {
366 : direction: 'sw',
367 : class: `cursor-nesw-resize ${CORNER_DOT_CLASS}`,
368 : style: {
369 : left: `${x - borderMid - CORNER_HIT_SIZE / 2}px`,
370 : top: `${y + h + borderMid - CORNER_HIT_SIZE / 2}px`,
371 : width: `${CORNER_HIT_SIZE}px`,
372 : height: `${CORNER_HIT_SIZE}px`
373 : }
374 : },
375 : {
376 : direction: 'se',
377 : class: `cursor-nwse-resize ${CORNER_DOT_CLASS}`,
378 : style: {
379 : left: `${x + w + borderMid - CORNER_HIT_SIZE / 2}px`,
380 : top: `${y + h + borderMid - CORNER_HIT_SIZE / 2}px`,
381 : width: `${CORNER_HIT_SIZE}px`,
382 : height: `${CORNER_HIT_SIZE}px`
383 : }
384 : }
385 : ]
386 : })
387 :
388 49 : const resizeHandles = computed<ResizeHandle[]>(() => {
389 109 : if (!isLockEnabled.value) return allResizeHandles.value
390 14 : return allResizeHandles.value.filter((h) =>
391 : CORNER_DIRECTIONS.has(h.direction)
392 : )
393 : })
394 :
395 49 : const handleImageLoad = () => {
396 29 : isLoading.value = false
397 29 : updateDisplayedDimensions()
398 : }
399 :
400 49 : const handleImageError = () => {
401 1 : isLoading.value = false
402 1 : imageUrl.value = null
403 : }
404 :
405 49 : const capturePointer = (e: PointerEvent) => {
406 18 : if (e.target instanceof HTMLElement) e.target.setPointerCapture(e.pointerId)
407 : }
408 :
409 49 : const releasePointer = (e: PointerEvent) => {
410 18 : if (e.target instanceof HTMLElement)
411 18 : e.target.releasePointerCapture(e.pointerId)
412 : }
413 :
414 49 : const handleDragStart = (e: PointerEvent) => {
415 4 : if (!imageUrl.value) return
416 :
417 4 : isDragging.value = true
418 4 : dragStartX.value = e.clientX
419 4 : dragStartY.value = e.clientY
420 4 : dragStartCropX.value = cropX.value
421 4 : dragStartCropY.value = cropY.value
422 4 : capturePointer(e)
423 : }
424 :
425 49 : const handleDragMove = (e: PointerEvent) => {
426 5 : if (!isDragging.value) return
427 :
428 5 : const effectiveScale = getEffectiveScale()
429 5 : if (effectiveScale === 0) return
430 :
431 5 : const deltaX = (e.clientX - dragStartX.value) / effectiveScale
432 5 : const deltaY = (e.clientY - dragStartY.value) / effectiveScale
433 :
434 5 : const maxX = naturalWidth.value - cropWidth.value
435 5 : const maxY = naturalHeight.value - cropHeight.value
436 :
437 5 : cropX.value = Math.round(
438 : Math.max(0, Math.min(maxX, dragStartCropX.value + deltaX))
439 : )
440 5 : cropY.value = Math.round(
441 : Math.max(0, Math.min(maxY, dragStartCropY.value + deltaY))
442 : )
443 : }
444 :
445 49 : const handleDragEnd = (e: PointerEvent) => {
446 4 : if (!isDragging.value) return
447 :
448 4 : isDragging.value = false
449 4 : releasePointer(e)
450 4 : onEditEnd?.()
451 : }
452 :
453 49 : const handleResizeStart = (e: PointerEvent, direction: ResizeDirection) => {
454 14 : if (!imageUrl.value) return
455 :
456 14 : e.stopPropagation()
457 14 : isResizing.value = true
458 14 : resizeDirection.value = direction
459 :
460 14 : resizeStartX.value = e.clientX
461 14 : resizeStartY.value = e.clientY
462 14 : resizeStartCropX.value = cropX.value
463 14 : resizeStartCropY.value = cropY.value
464 14 : resizeStartCropWidth.value = cropWidth.value
465 14 : resizeStartCropHeight.value = cropHeight.value
466 14 : capturePointer(e)
467 : }
468 :
469 49 : const handleResizeMove = (e: PointerEvent) => {
470 14 : if (!isResizing.value || !resizeDirection.value) return
471 :
472 14 : const effectiveScale = getEffectiveScale()
473 14 : if (effectiveScale === 0) return
474 :
475 14 : const dir = resizeDirection.value
476 14 : const deltaX = (e.clientX - resizeStartX.value) / effectiveScale
477 14 : const deltaY = (e.clientY - resizeStartY.value) / effectiveScale
478 :
479 14 : const ratioValue = isLockEnabled.value ? lockedRatio.value : null
480 :
481 14 : if (ratioValue != null && CORNER_DIRECTIONS.has(dir)) {
482 5 : handleConstrainedResize(dir, deltaX, deltaY, ratioValue)
483 5 : return
484 : }
485 :
486 14 : const affectsLeft = dir === 'left' || dir === 'nw' || dir === 'sw'
487 14 : const affectsRight = dir === 'right' || dir === 'ne' || dir === 'se'
488 14 : const affectsTop = dir === 'top' || dir === 'nw' || dir === 'ne'
489 14 : const affectsBottom = dir === 'bottom' || dir === 'sw' || dir === 'se'
490 :
491 14 : let newX = resizeStartCropX.value
492 14 : let newY = resizeStartCropY.value
493 14 : let newWidth = resizeStartCropWidth.value
494 14 : let newHeight = resizeStartCropHeight.value
495 :
496 14 : if (affectsLeft) {
497 2 : const maxDeltaX = resizeStartCropWidth.value - MIN_CROP_SIZE
498 2 : const minDeltaX = -resizeStartCropX.value
499 2 : const clampedDeltaX = Math.max(minDeltaX, Math.min(maxDeltaX, deltaX))
500 2 : newX = resizeStartCropX.value + clampedDeltaX
501 2 : newWidth = resizeStartCropWidth.value - clampedDeltaX
502 7 : } else if (affectsRight) {
503 4 : const maxWidth = naturalWidth.value - resizeStartCropX.value
504 4 : newWidth = Math.max(
505 : MIN_CROP_SIZE,
506 : Math.min(maxWidth, resizeStartCropWidth.value + deltaX)
507 : )
508 : }
509 :
510 9 : if (affectsTop) {
511 2 : const maxDeltaY = resizeStartCropHeight.value - MIN_CROP_SIZE
512 2 : const minDeltaY = -resizeStartCropY.value
513 2 : const clampedDeltaY = Math.max(minDeltaY, Math.min(maxDeltaY, deltaY))
514 2 : newY = resizeStartCropY.value + clampedDeltaY
515 2 : newHeight = resizeStartCropHeight.value - clampedDeltaY
516 7 : } else if (affectsBottom) {
517 3 : const maxHeight = naturalHeight.value - resizeStartCropY.value
518 3 : newHeight = Math.max(
519 : MIN_CROP_SIZE,
520 : Math.min(maxHeight, resizeStartCropHeight.value + deltaY)
521 : )
522 : }
523 :
524 14 : if (affectsLeft || affectsRight) {
525 6 : cropX.value = Math.round(newX)
526 6 : cropWidth.value = Math.round(newWidth)
527 : }
528 14 : if (affectsTop || affectsBottom) {
529 5 : cropY.value = Math.round(newY)
530 5 : cropHeight.value = Math.round(newHeight)
531 : }
532 : }
533 :
534 5 : function handleConstrainedResize(
535 : dir: ResizeDirection,
536 : deltaX: number,
537 : deltaY: number,
538 : ratio: number
539 : ) {
540 5 : const affectsLeft = dir === 'nw' || dir === 'sw'
541 5 : const affectsTop = dir === 'nw' || dir === 'ne'
542 :
543 5 : const sx = affectsLeft ? -1 : 1
544 5 : const sy = affectsTop ? -1 : 1
545 :
546 5 : const invRatio = 1 / ratio
547 : const dot = deltaX * sx + deltaY * sy * invRatio
548 : const lenSq = 1 + invRatio * invRatio
549 : const widthDelta = dot / lenSq
550 :
551 5 : let newWidth = Math.round(resizeStartCropWidth.value + widthDelta)
552 5 : let newHeight = Math.round(newWidth / ratio)
553 :
554 5 : if (newWidth < MIN_CROP_SIZE) {
555 1 : newWidth = MIN_CROP_SIZE
556 1 : newHeight = Math.round(newWidth / ratio)
557 : }
558 5 : if (newHeight < MIN_CROP_SIZE) {
559 0 : newHeight = MIN_CROP_SIZE
560 0 : newWidth = Math.round(newHeight * ratio)
561 : }
562 :
563 5 : let newX = resizeStartCropX.value
564 5 : let newY = resizeStartCropY.value
565 :
566 5 : if (affectsLeft) {
567 2 : newX = resizeStartCropX.value + resizeStartCropWidth.value - newWidth
568 : }
569 5 : if (affectsTop) {
570 2 : newY = resizeStartCropY.value + resizeStartCropHeight.value - newHeight
571 : }
572 :
573 5 : if (newX < 0) {
574 1 : newWidth += newX
575 1 : newX = 0
576 1 : newHeight = Math.round(newWidth / ratio)
577 : }
578 5 : if (newY < 0) {
579 1 : newHeight += newY
580 1 : newY = 0
581 1 : newWidth = Math.round(newHeight * ratio)
582 : }
583 5 : if (newX + newWidth > naturalWidth.value) {
584 1 : newWidth = naturalWidth.value - newX
585 1 : newHeight = Math.round(newWidth / ratio)
586 : }
587 5 : if (newY + newHeight > naturalHeight.value) {
588 0 : newHeight = naturalHeight.value - newY
589 0 : newWidth = Math.round(newHeight * ratio)
590 : }
591 :
592 5 : cropX.value = Math.round(newX)
593 5 : cropY.value = Math.round(newY)
594 5 : cropWidth.value = Math.max(MIN_CROP_SIZE, newWidth)
595 5 : cropHeight.value = Math.max(MIN_CROP_SIZE, newHeight)
596 : }
597 :
598 49 : const handleResizeEnd = (e: PointerEvent) => {
599 14 : if (!isResizing.value) return
600 :
601 14 : isResizing.value = false
602 14 : resizeDirection.value = null
603 14 : releasePointer(e)
604 14 : onEditEnd?.()
605 : }
606 :
607 49 : return {
608 : imageUrl,
609 : isLoading,
610 :
611 : cropX,
612 : cropY,
613 : cropWidth,
614 : cropHeight,
615 :
616 : selectedRatio,
617 : isLockEnabled,
618 :
619 : cropBoxStyle,
620 : resizeHandles,
621 :
622 : handleImageLoad,
623 : handleImageError,
624 : handleDragStart,
625 : handleDragMove,
626 : handleDragEnd,
627 : handleResizeStart,
628 : handleResizeMove,
629 : handleResizeEnd
630 : }
631 : }
|