Line data Source code
1 : import type {
2 : Bounds as PlacementRect,
3 : RectEdges
4 : } from '@comfyorg/shared-frontend-utils/geometry'
5 :
6 : interface PlacementOffset {
7 : dx: number
8 : dy: number
9 : }
10 :
11 : interface PlacementInput {
12 : existing: readonly PlacementRect[]
13 : viewport: PlacementRect | null
14 : incoming: readonly PlacementRect[]
15 : moveCollisions?: boolean
16 : }
17 :
18 : export const DISCONNECTED_GAP_PX = 600
19 : export const PLACEMENT_GUTTER_PX = 80
20 :
21 0 : function toBounds(rect: PlacementRect): RectEdges {
22 0 : return {
23 : left: rect.x,
24 : top: rect.y,
25 : right: rect.x + rect.width,
26 : bottom: rect.y + rect.height
27 : }
28 : }
29 :
30 0 : function hull(rects: readonly PlacementRect[]): RectEdges {
31 0 : return rects.map(toBounds).reduce((a, b) => ({
32 : left: Math.min(a.left, b.left),
33 : top: Math.min(a.top, b.top),
34 : right: Math.max(a.right, b.right),
35 : bottom: Math.max(a.bottom, b.bottom)
36 : }))
37 : }
38 :
39 0 : function intersects(a: RectEdges, b: RectEdges): boolean {
40 0 : return (
41 : a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom
42 : )
43 : }
44 :
45 0 : function collides(
46 : existing: readonly PlacementRect[],
47 : incoming: readonly PlacementRect[]
48 : ): boolean {
49 0 : const existingBounds = existing.map(toBounds)
50 0 : return incoming.some((rect) => {
51 0 : const bounds = toBounds(rect)
52 0 : return existingBounds.some((other) => intersects(bounds, other))
53 : })
54 : }
55 :
56 : /** Returns a batch translation, or null when its coordinates stay unchanged. */
57 0 : export function placementOffset(input: PlacementInput): PlacementOffset | null {
58 0 : if (input.existing.length === 0 || input.incoming.length === 0) return null
59 0 : const anchor = hull(input.existing)
60 0 : const batch = hull(input.incoming)
61 0 : const offset = {
62 : dx: anchor.right + PLACEMENT_GUTTER_PX - batch.left,
63 : dy: anchor.top - batch.top
64 : }
65 0 : if (input.moveCollisions && collides(input.existing, input.incoming))
66 0 : return offset
67 : const inflated = {
68 : left: anchor.left - DISCONNECTED_GAP_PX,
69 : top: anchor.top - DISCONNECTED_GAP_PX,
70 : right: anchor.right + DISCONNECTED_GAP_PX,
71 : bottom: anchor.bottom + DISCONNECTED_GAP_PX
72 : }
73 0 : if (intersects(inflated, batch)) return null
74 0 : if (input.viewport && intersects(toBounds(input.viewport), batch)) return null
75 0 : return offset
76 : }
|