LCOV - code coverage report
Current view: top level - packages/layer-editor/src/tools - transformTool.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 14.2 % 190 27
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { SetTransformCommand } from '#/commands/setTransform'
       2              : import { filterTopmost, findNode, flattenTree } from '#/document'
       3              : import { CommandGroup, Dirty } from '#/history'
       4              : import type { Command } from '#/history'
       5              : import type { SceneNode, Transform } from '#/node'
       6              : import type { Point2D as Vec2 } from '@comfyorg/shared-frontend-utils/geometry'
       7              : import { getNodeKind } from '#/nodeKind'
       8              : import { applySnap, buildSnapTargets } from '#/snapping'
       9              : import type { Guide, SnapTargets } from '#/snapping'
      10              : import { defaultControl } from '#/tool'
      11              : import type { Overlay, Tool, ToolContext, ToolControl, ToolDef } from '#/tool'
      12              : import { addTransformBox } from './overlayBox'
      13              : import {
      14              :   alignedTo,
      15              :   angleTo,
      16              :   applyMove,
      17              :   applyResize,
      18              :   applyRotate,
      19              :   center,
      20              :   groupResize,
      21              :   groupScale,
      22              :   hitHandle,
      23              :   insideBox,
      24              :   rotateAround,
      25              :   scaleAround,
      26              :   scaleAroundFrame,
      27              :   unionBounds
      28              : } from './transformMath'
      29              : import type { HandleId } from './transformMath'
      30              : 
      31            2 : const TRANSFORMABLE_KINDS = new Set(['raster', 'text', 'vector'])
      32              : 
      33              : interface TransformSession {
      34              :   ids: string[]
      35              :   before: Map<string, Transform>
      36              :   gizmo: Transform
      37              : }
      38              : 
      39              : type Drag =
      40              :   | { mode: 'idle' }
      41              :   | {
      42              :       mode: 'move'
      43              :       start: Vec2
      44              :       gizmoBase: Transform
      45              :       bases: Map<string, Transform>
      46              :     }
      47              :   | {
      48              :       mode: 'resize'
      49              :       handle: HandleId
      50              :       gizmoBase: Transform
      51              :       bases: Map<string, Transform>
      52              :     }
      53              :   | {
      54              :       mode: 'rotate'
      55              :       gizmoBase: Transform
      56              :       grab: number
      57              :       bases: Map<string, Transform>
      58              :     }
      59              : 
      60              : export interface TransformToolApi {
      61              :   apply(): boolean
      62              :   cancel(): boolean
      63              :   isDirty(): boolean
      64              : }
      65              : 
      66            0 : function sameTransform(a: Transform, b: Transform): boolean {
      67            0 :   return (
      68              :     a.x === b.x &&
      69              :     a.y === b.y &&
      70              :     a.w === b.w &&
      71              :     a.h === b.h &&
      72              :     a.rotation === b.rotation
      73              :   )
      74              : }
      75              : 
      76            0 : function sameIds(a: string[], b: string[]): boolean {
      77            0 :   return a.length === b.length && a.every((x, i) => x === b[i])
      78              : }
      79              : 
      80           20 : export function canTransformNode(node: SceneNode | null): node is SceneNode {
      81           20 :   return !!node && TRANSFORMABLE_KINDS.has(node.kind) && !node.locks.position
      82              : }
      83              : 
      84           14 : function computeGizmo(targets: SceneNode[]): Transform {
      85           14 :   return targets.length === 1
      86              :     ? { ...targets[0].transform }
      87              :     : unionBounds(targets.map((n) => n.transform))
      88              : }
      89              : 
      90            2 : class TransformTool implements Tool, TransformToolApi {
      91              :   readonly control: ToolControl
      92              :   private session: TransformSession | null = null
      93              :   private drag: Drag = { mode: 'idle' }
      94              :   private snapGuides: Guide[] = []
      95              : 
      96              :   constructor(
      97            2 :     readonly id: string,
      98            2 :     private readonly ctx: ToolContext
      99              :   ) {
     100            2 :     this.control = {
     101              :       ...defaultControl(),
     102              :       cursor: 'default',
     103              :       abortMask: Dirty.STRUCTURE
     104              :     }
     105              :   }
     106              : 
     107              :   private tol(): number {
     108            0 :     return 8 / Math.max(1e-3, this.ctx.zoom())
     109              :   }
     110              : 
     111              :   private snapContext(excludeIds: Set<string>): {
     112              :     targets: SnapTargets
     113              :     rects: Transform[]
     114              :   } {
     115            0 :     const doc = this.ctx.document()
     116            0 :     const rects = flattenTree(doc.root)
     117              :       .filter(
     118              :         (n) =>
     119              :           n.visible && TRANSFORMABLE_KINDS.has(n.kind) && !excludeIds.has(n.id)
     120              :       )
     121              :       .map((n) => unionBounds([n.transform]))
     122            0 :     const grid = this.ctx.snapGrid()
     123            0 :     const guides = doc.guides ?? []
     124              :     const targets = buildSnapTargets(
     125              :       rects,
     126              :       { w: doc.width, h: doc.height },
     127              :       {
     128              :         gridX: grid > 0 ? grid : undefined,
     129              :         gridY: grid > 0 ? grid : undefined,
     130              :         guideXs: guides.filter((g) => g.axis === 'x').map((g) => g.pos),
     131              :         guideYs: guides.filter((g) => g.axis === 'y').map((g) => g.pos)
     132              :       }
     133              :     )
     134            0 :     return { targets, rects }
     135              :   }
     136              : 
     137              :   private snapMove(
     138              :     gizmo: Transform,
     139              :     excludeIds: Set<string>
     140              :   ): { dx: number; dy: number } {
     141            0 :     const doc = this.ctx.document()
     142            0 :     const aabb = unionBounds([gizmo])
     143            0 :     const thr = this.tol()
     144            0 :     const { targets, rects } = this.snapContext(excludeIds)
     145            0 :     const res = applySnap('move', aabb, targets, {
     146              :       thrX: thr,
     147              :       thrY: thr,
     148              :       minWH: 1,
     149              :       boundsW: doc.width,
     150              :       boundsH: doc.height,
     151              :       clamp: false,
     152              :       eqRects: rects
     153              :     })
     154            0 :     this.snapGuides = res.guides
     155            0 :     return { dx: res.rect.x - aabb.x, dy: res.rect.y - aabb.y }
     156              :   }
     157              : 
     158              :   private snapResize(
     159              :     next: Transform,
     160              :     handle: HandleId,
     161              :     excludeIds: Set<string>
     162              :   ): Transform {
     163            0 :     if (handle === 'rotate' || Math.abs(next.rotation) > 1e-6) return next
     164            0 :     const doc = this.ctx.document()
     165            0 :     const thr = this.tol()
     166              :     const aabb = unionBounds([next])
     167            0 :     const res = applySnap(handle, aabb, this.snapContext(excludeIds).targets, {
     168              :       thrX: thr,
     169              :       thrY: thr,
     170              :       minWH: 1,
     171              :       boundsW: doc.width,
     172              :       boundsH: doc.height,
     173              :       clamp: false
     174              :     })
     175            0 :     this.snapGuides = res.guides
     176            0 :     return {
     177              :       ...next,
     178              :       x: res.rect.x,
     179              :       y: res.rect.y,
     180              :       w: res.rect.w,
     181              :       h: res.rect.h
     182              :     }
     183              :   }
     184              : 
     185              :   private eligibleTargets(): SceneNode[] {
     186           24 :     const root = this.ctx.document().root
     187           24 :     return filterTopmost(root, this.ctx.selectedNodeIds())
     188              :       .map((id) => findNode(root, id)?.node ?? null)
     189              :       .filter((n): n is SceneNode => canTransformNode(n))
     190              :   }
     191              : 
     192              :   private sessionNodes(): SceneNode[] {
     193            0 :     if (!this.session) return []
     194            0 :     const root = this.ctx.document().root
     195            0 :     return this.session.ids
     196              :       .map((id) => findNode(root, id)?.node ?? null)
     197              :       .filter((n): n is SceneNode => !!n)
     198              :   }
     199              : 
     200              :   private ensureSession(): SceneNode[] | null {
     201            2 :     const targets = this.eligibleTargets()
     202            2 :     if (!targets.length) {
     203            2 :       if (this.session) this.apply()
     204            2 :       return null
     205              :     }
     206            0 :     const ids = targets.map((n) => n.id)
     207            2 :     if (this.session && !sameIds(this.session.ids, ids)) this.apply()
     208            0 :     if (!this.session) {
     209            0 :       const before = new Map<string, Transform>()
     210            0 :       for (const n of targets) before.set(n.id, { ...n.transform })
     211            0 :       this.session = { ids, before, gizmo: computeGizmo(targets) }
     212              :     }
     213            0 :     return targets
     214              :   }
     215              : 
     216              :   onActivate(): void {
     217            2 :     this.ensureSession()
     218              :   }
     219              : 
     220              :   onDeactivate(): void {
     221            0 :     if (this.isDirty()) this.apply()
     222            0 :     else this.session = null
     223              :   }
     224              : 
     225              :   onButtonPress(_e: PointerEvent, pt: Vec2): void {
     226            0 :     const targets = this.ensureSession()
     227            0 :     const s = this.session
     228            0 :     if (!targets || !s) return
     229            0 :     const bases = new Map<string, Transform>()
     230            0 :     for (const n of this.sessionNodes()) bases.set(n.id, { ...n.transform })
     231            0 :     const gizmoBase = { ...s.gizmo }
     232            0 :     const h = hitHandle(s.gizmo, pt, this.tol())
     233            0 :     if (h === 'rotate') {
     234            0 :       this.drag = {
     235              :         mode: 'rotate',
     236              :         gizmoBase,
     237              :         grab: angleTo(s.gizmo, pt),
     238              :         bases
     239              :       }
     240            0 :       return
     241              :     }
     242            0 :     if (h) {
     243            0 :       this.drag = { mode: 'resize', handle: h, gizmoBase, bases }
     244            0 :       return
     245              :     }
     246            0 :     if (insideBox(s.gizmo, pt)) {
     247            0 :       this.drag = { mode: 'move', start: pt, gizmoBase, bases }
     248            0 :       return
     249              :     }
     250            0 :     this.apply()
     251              :   }
     252              : 
     253              :   private setTransform(id: string, t: Transform): void {
     254            0 :     const node = findNode(this.ctx.document().root, id)?.node
     255            0 :     if (node) node.transform = t
     256              :   }
     257              : 
     258              :   onMotion(e: PointerEvent, pt: Vec2): void {
     259            0 :     const s = this.session
     260            0 :     const d = this.drag
     261            0 :     if (!s || d.mode === 'idle') return
     262            0 :     const single = d.bases.size === 1
     263            0 :     this.snapGuides = []
     264            0 :     if (d.mode === 'move') {
     265            0 :       let dx = pt.x - d.start.x
     266            0 :       let dy = pt.y - d.start.y
     267            0 :       if (!e.altKey) {
     268            0 :         const adj = this.snapMove(
     269              :           applyMove(d.gizmoBase, dx, dy),
     270              :           new Set(d.bases.keys())
     271              :         )
     272            0 :         dx += adj.dx
     273            0 :         dy += adj.dy
     274              :       }
     275            0 :       s.gizmo = applyMove(d.gizmoBase, dx, dy)
     276            0 :       for (const [id, base] of d.bases)
     277            0 :         this.setTransform(id, applyMove(base, dx, dy))
     278            0 :     } else if (d.mode === 'resize') {
     279            0 :       if (single) {
     280            0 :         let next = applyResize(d.gizmoBase, d.handle, pt, 1, e.shiftKey)
     281            0 :         if (!e.altKey && !e.shiftKey) {
     282            0 :           next = this.snapResize(next, d.handle, new Set(d.bases.keys()))
     283              :         }
     284            0 :         s.gizmo = next
     285            0 :         for (const [id] of d.bases) this.setTransform(id, next)
     286              :       } else {
     287            0 :         const frame = d.gizmoBase.rotation
     288              :         const nonUniform =
     289              :           !e.shiftKey &&
     290              :           [...d.bases.values()].every((b) => alignedTo(b.rotation, frame))
     291            0 :         if (nonUniform) {
     292            0 :           const { gizmo, anchor, sx, sy } = groupScale(
     293              :             d.gizmoBase,
     294              :             d.handle,
     295              :             pt,
     296              :             1
     297              :           )
     298            0 :           s.gizmo = gizmo
     299            0 :           for (const [id, base] of d.bases)
     300            0 :             this.setTransform(id, scaleAroundFrame(base, anchor, frame, sx, sy))
     301              :         } else {
     302            0 :           const { gizmo, anchor, scale } = groupResize(
     303              :             d.gizmoBase,
     304              :             d.handle,
     305              :             pt,
     306              :             1
     307              :           )
     308            0 :           s.gizmo = gizmo
     309            0 :           for (const [id, base] of d.bases)
     310            0 :             this.setTransform(id, scaleAround(base, anchor, scale))
     311              :         }
     312              :       }
     313              :     } else {
     314            0 :       const next = applyRotate(
     315              :         d.gizmoBase,
     316              :         d.gizmoBase.rotation,
     317              :         d.grab,
     318              :         pt,
     319              :         e.shiftKey ? Math.PI / 12 : 0
     320              :       )
     321            0 :       const theta = next.rotation - d.gizmoBase.rotation
     322            0 :       const pivot = center(d.gizmoBase)
     323            0 :       s.gizmo = next
     324            0 :       for (const [id, base] of d.bases)
     325            0 :         this.setTransform(id, rotateAround(base, pivot, theta))
     326              :     }
     327            0 :     this.ctx.requestRender()
     328              :   }
     329              : 
     330              :   onButtonRelease(): void {
     331            0 :     this.drag = { mode: 'idle' }
     332            0 :     this.snapGuides = []
     333            0 :     this.ctx.requestRender()
     334              :   }
     335              : 
     336              :   onHover(): void {
     337            0 :     this.ensureSession()
     338              :   }
     339              : 
     340              :   cursorFor(pt: Vec2): string {
     341            0 :     const gizmo = this.currentGizmo()
     342            0 :     if (!gizmo) return 'default'
     343            0 :     if (hitHandle(gizmo, pt, this.tol())) return 'pointer'
     344            0 :     if (insideBox(gizmo, pt)) return 'move'
     345            0 :     return 'default'
     346              :   }
     347              : 
     348              :   private currentGizmo(): Transform | null {
     349            0 :     if (this.session) return this.session.gizmo
     350            0 :     const targets = this.eligibleTargets()
     351            0 :     return targets.length ? computeGizmo(targets) : null
     352              :   }
     353              : 
     354              :   drawOverlay(overlay: Overlay): void {
     355           22 :     const targets = this.session ? this.sessionNodes() : this.eligibleTargets()
     356           22 :     if (!targets.length) return
     357           22 :     const gizmo = this.session?.gizmo ?? computeGizmo(targets)
     358           22 :     if (targets.length > 1) {
     359            0 :       for (const n of targets) {
     360            0 :         const b = n.transform
     361            0 :         if (b.w > 0 && b.h > 0) addTransformBox(overlay, b, false)
     362              :       }
     363              :     }
     364           14 :     addTransformBox(overlay, gizmo, true)
     365           14 :     const doc = this.ctx.document()
     366           14 :     const tick = 4 / Math.max(1e-3, this.ctx.zoom())
     367           22 :     for (const g of this.snapGuides) {
     368            0 :       if (g.kind === 'gap' && g.spans && g.cross != null) {
     369            0 :         for (const [a, b] of g.spans) {
     370            0 :           if (g.axis === 'x') {
     371            0 :             overlay.add({
     372              :               type: 'line',
     373              :               a: { x: a, y: g.cross },
     374              :               b: { x: b, y: g.cross }
     375              :             })
     376            0 :             overlay.add({
     377              :               type: 'line',
     378              :               a: { x: a, y: g.cross - tick },
     379              :               b: { x: a, y: g.cross + tick }
     380              :             })
     381            0 :             overlay.add({
     382              :               type: 'line',
     383              :               a: { x: b, y: g.cross - tick },
     384              :               b: { x: b, y: g.cross + tick }
     385              :             })
     386              :           } else {
     387            0 :             overlay.add({
     388              :               type: 'line',
     389              :               a: { x: g.cross, y: a },
     390              :               b: { x: g.cross, y: b }
     391              :             })
     392            0 :             overlay.add({
     393              :               type: 'line',
     394              :               a: { x: g.cross - tick, y: a },
     395              :               b: { x: g.cross + tick, y: a }
     396              :             })
     397            0 :             overlay.add({
     398              :               type: 'line',
     399              :               a: { x: g.cross - tick, y: b },
     400              :               b: { x: g.cross + tick, y: b }
     401              :             })
     402              :           }
     403              :         }
     404            0 :         continue
     405              :       }
     406            0 :       if (g.axis === 'x') {
     407            0 :         overlay.add({
     408              :           type: 'line',
     409              :           a: { x: g.pos, y: 0 },
     410              :           b: { x: g.pos, y: doc.height }
     411              :         })
     412              :       } else {
     413            0 :         overlay.add({
     414              :           type: 'line',
     415              :           a: { x: 0, y: g.pos },
     416              :           b: { x: doc.width, y: g.pos }
     417              :         })
     418              :       }
     419              :     }
     420              :   }
     421              : 
     422              :   isDirty(): boolean {
     423            0 :     const s = this.session
     424            0 :     if (!s) return false
     425            0 :     for (const [id, before] of s.before) {
     426            0 :       const node = findNode(this.ctx.document().root, id)?.node
     427            0 :       if (node && !sameTransform(before, node.transform)) return true
     428              :     }
     429            0 :     return false
     430              :   }
     431              : 
     432              :   private buildCommands(s: TransformSession): Command[] {
     433            0 :     const cmds: Command[] = []
     434            0 :     for (const [id, before] of s.before) {
     435            0 :       const node = findNode(this.ctx.document().root, id)?.node
     436            0 :       if (!node || sameTransform(before, node.transform)) continue
     437            0 :       cmds.push(
     438              :         new SetTransformCommand('transform', node, before, {
     439              :           ...node.transform
     440              :         })
     441              :       )
     442            0 :       const extra =
     443              :         getNodeKind(node.kind).onTransformCommitted?.(node, before, {
     444              :           content: this.ctx.content
     445              :         }) ?? null
     446            0 :       if (extra) cmds.push(extra)
     447              :     }
     448            0 :     return cmds
     449              :   }
     450              : 
     451              :   apply(): boolean {
     452            0 :     const s = this.session
     453            0 :     this.session = null
     454            0 :     this.drag = { mode: 'idle' }
     455            0 :     this.snapGuides = []
     456            0 :     if (!s) return false
     457            0 :     const cmds = this.buildCommands(s)
     458            0 :     if (!cmds.length) return false
     459            0 :     if (cmds.length === 1) {
     460            0 :       this.ctx.history.push(cmds[0])
     461              :     } else {
     462            0 :       const group = new CommandGroup('transform')
     463            0 :       group.children.push(...cmds)
     464            0 :       this.ctx.history.push(group)
     465              :     }
     466            0 :     this.ctx.requestRender()
     467            0 :     return true
     468              :   }
     469              : 
     470              :   cancel(): boolean {
     471            0 :     const s = this.session
     472            0 :     this.session = null
     473            0 :     this.drag = { mode: 'idle' }
     474            0 :     this.snapGuides = []
     475            0 :     if (!s) return false
     476            0 :     let changed = false
     477            0 :     for (const [id, before] of s.before) {
     478            0 :       const node = findNode(this.ctx.document().root, id)?.node
     479            0 :       if (node && !sameTransform(before, node.transform)) {
     480            0 :         node.transform = { ...before }
     481            0 :         changed = true
     482              :       }
     483              :     }
     484            0 :     if (changed) this.ctx.requestRender()
     485            0 :     return changed
     486              :   }
     487              : }
     488              : 
     489            0 : export function isTransformTool(
     490              :   tool: Tool | null
     491              : ): tool is Tool & TransformToolApi {
     492            0 :   return !!tool && tool.id === 'transform'
     493              : }
     494              : 
     495            2 : export function makeTransformToolDef(): ToolDef {
     496            2 :   return {
     497              :     id: 'transform',
     498              :     create: (ctx) => new TransformTool('transform', ctx)
     499              :   }
     500              : }
        

Generated by: LCOV version 2.0-1