Skip to content

AI-native design editor. Open-source Figma alternative.

fix(hit): fix hit area when parent rotation (#195)

jongwong5f30ae39b73e
diff --git a/packages/core/src/canvas/coordinate.ts b/packages/core/src/canvas/coordinate.ts
new file mode 100644
index 000000000..fef1622c4
--- /dev/null
+++ b/packages/core/src/canvas/coordinate.ts
@@ -0,0 +1,199 @@
+import Matrix, { type Mat3 } from '@open-pencil/core/canvas/matrix'
+
+import type { SceneGraph, SceneNode, Vector } from '@open-pencil/core'
+
+export function getWorldMatrix(node: SceneNode, graph: SceneGraph): Mat3 {
+ const chain: SceneNode[] = []
+ let current: SceneNode | undefined = node
+
+ while (current) {
+ chain.unshift(current)
+ if (!current.parentId) break
+ current = graph.getNode(current.parentId)
+ }
+
+ let matrix = Matrix.identity()
+
+ for (const n of chain) {
+ const local = getNodeLocalMatrix(n)
+ matrix = Matrix.multiply(matrix, local)
+ }
+
+ return matrix
+}
+
+export function getAbsolutePosition(node: SceneNode, graph: SceneGraph): Vector {
+ const matrix = getWorldMatrix(node, graph)
+ const p = Matrix.mapPoints(matrix, [0, 0])
+
+ return {
+ x: p[0],
+ y: p[1]
+ }
+}
+export function getAbsoluteRotation(node: SceneNode, graph: SceneGraph): number {
+ const matrix = getWorldMatrix(node, graph)
+ const a = matrix[0]
+ const b = matrix[1]
+ const angle = Math.atan2(b, a)
+ let deg = (angle * 180) / Math.PI
+ deg = (deg + 360) % 360
+
+ return deg
+}
+
+export function getAbsolutePositionFull(node: SceneNode, graph: SceneGraph) {
+ const matrix = getWorldMatrix(node, graph)
+
+ const origin = Matrix.mapPoints(matrix, [0, 0])
+ const x = origin[0]
+ const y = origin[1]
+
+ const pts = Matrix.mapPoints(matrix, [
+ 0,
+ 0,
+ node.width,
+ 0,
+ node.width,
+ node.height,
+ 0,
+ node.height
+ ])
+
+ const [x1, y1, x2, y2, x3, y3, x4, y4] = pts
+
+ const minX = Math.min(x1, x2, x3, x4)
+ const maxX = Math.max(x1, x2, x3, x4)
+ const minY = Math.min(y1, y2, y3, y4)
+ const maxY = Math.max(y1, y2, y3, y4)
+
+ const width = maxX - minX
+ const height = maxY - minY
+
+ let angle = Math.atan2(matrix[3], matrix[0])
+
+ const det = matrix[0] * matrix[4] - matrix[1] * matrix[3]
+ if (det < 0) {
+ angle = -angle
+ }
+
+ const rotation = angle * (180 / Math.PI)
+
+ const center = Matrix.mapPoints(matrix, [node.width / 2, node.height / 2])
+
+ const centerX = center[0]
+ const centerY = center[1]
+
+ return {
+ x,
+ y,
+
+ // AABB
+ boundX: minX,
+ boundY: minY,
+ width,
+ height,
+
+ rotation,
+
+ centerX,
+ centerY
+ }
+}
+export function getNodeLocalMatrix(n: SceneNode) {
+ const rad = (n.rotation * Math.PI) / 180
+
+ const cx = n.width / 2
+ const cy = n.height / 2
+
+ const sx = n.flipX ? -1 : 1
+ const sy = n.flipY ? -1 : 1
+
+ let m = Matrix.identity()
+
+ // local translation (relative to parent)
+ m = Matrix.multiply(m, Matrix.translated(n.x, n.y))
+
+ // pivot to center
+ m = Matrix.multiply(m, Matrix.translated(cx, cy))
+
+ if (n.flipX || n.flipY) {
+ m = Matrix.multiply(m, Matrix.scaled(sx, sy))
+ }
+
+ // rotate around center
+ if (n.rotation) {
+ m = Matrix.multiply(m, Matrix.rotated(rad, 0, 0))
+ }
+
+ // pivot back
+ m = Matrix.multiply(m, Matrix.translated(-cx, -cy))
+
+ return m
+}
+export function getNodeWorldBounds(node: SceneNode) {
+ const m = getNodeLocalMatrix(node)
+
+ const points = Matrix.mapPoints(m, [0, 0, node.width, 0, node.width, node.height, 0, node.height])
+
+ let minX = Infinity
+ let minY = Infinity
+ let maxX = -Infinity
+ let maxY = -Infinity
+
+ for (let i = 0; i < points.length; i += 2) {
+ const x = points[i]
+ const y = points[i + 1]
+
+ minX = Math.min(minX, x)
+ minY = Math.min(minY, y)
+ maxX = Math.max(maxX, x)
+ maxY = Math.max(maxY, y)
+ }
+
+ return {
+ x: minX,
+ y: minY,
+ width: maxX - minX,
+ height: maxY - minY
+ }
+}
+
+export function getWorldHandles(node: SceneNode, graph: SceneGraph) {
+ const matrix = getWorldMatrix(node, graph)
+
+ const w = node.width
+ const h = node.height
+
+ const localPts = [
+ 0,
+ 0, // nw
+ w / 2,
+ 0, // n
+ w,
+ 0, // ne
+ w,
+ h / 2, // e
+ w,
+ h, // se
+ w / 2,
+ h, // s
+ 0,
+ h, // sw
+ 0,
+ h / 2 // w
+ ]
+
+ const pts = Matrix.mapPoints(matrix, localPts)
+
+ return {
+ nw: { x: pts[0], y: pts[1] },
+ n: { x: pts[2], y: pts[3] },
+ ne: { x: pts[4], y: pts[5] },
+ e: { x: pts[6], y: pts[7] },
+ se: { x: pts[8], y: pts[9] },
+ s: { x: pts[10], y: pts[11] },
+ sw: { x: pts[12], y: pts[13] },
+ w: { x: pts[14], y: pts[15] }
+ }
+}
diff --git a/packages/core/src/canvas/matrix.ts b/packages/core/src/canvas/matrix.ts
new file mode 100644
index 000000000..118aa5ba2
--- /dev/null
+++ b/packages/core/src/canvas/matrix.ts
@@ -0,0 +1,116 @@
+import type { Vector } from '@open-pencil/core'
+
+export type Mat3 = number[]
+
+const identity = (): Mat3 => [1, 0, 0, 0, 1, 0, 0, 0, 1]
+
+const multiply2 = (m1: Mat3, m2: Mat3): Mat3 => {
+ // row-major general 3x3 multiply: out = m1 * m2
+ return [
+ m1[0] * m2[0] + m1[1] * m2[3] + m1[2] * m2[6],
+ m1[0] * m2[1] + m1[1] * m2[4] + m1[2] * m2[7],
+ m1[0] * m2[2] + m1[1] * m2[5] + m1[2] * m2[8],
+
+ m1[3] * m2[0] + m1[4] * m2[3] + m1[5] * m2[6],
+ m1[3] * m2[1] + m1[4] * m2[4] + m1[5] * m2[7],
+ m1[3] * m2[2] + m1[4] * m2[5] + m1[5] * m2[8],
+
+ m1[6] * m2[0] + m1[7] * m2[3] + m1[8] * m2[6],
+ m1[6] * m2[1] + m1[7] * m2[4] + m1[8] * m2[7],
+ m1[6] * m2[2] + m1[7] * m2[5] + m1[8] * m2[8]
+ ]
+}
+
+const multiply = (...ms: Mat3[]): Mat3 => {
+ if (ms.length === 0) return identity()
+ let out = ms[0].slice() as Mat3
+ for (let i = 1; i < ms.length; i++) out = multiply2(out, ms[i])
+ return out
+}
+
+const translated = (dx: number, dy: number): Mat3 => [1, 0, dx, 0, 1, dy, 0, 0, 1]
+
+const rotated = (radians: number, px = 0, py = 0): Mat3 => {
+ const s = Math.sin(radians)
+ const c = Math.cos(radians)
+ // exactly like ck.Matrix.rotated
+ return [
+ c,
+ -s,
+ s * py + (1 - c) * px,
+
+ s,
+ c,
+ -s * px + (1 - c) * py,
+
+ 0,
+ 0,
+ 1
+ ]
+}
+
+const scaled = (sx: number, sy: number, px = 0, py = 0): Mat3 => {
+ // match ck.Matrix.scaled
+ return [
+ sx,
+ 0,
+ px - sx * px,
+
+ 0,
+ sy,
+ py - sy * py,
+
+ 0,
+ 0,
+ 1
+ ]
+}
+
+const invert = (m: Mat3): Mat3 | null => {
+ // match ck.Matrix.invert (Sarrus)
+ const det =
+ m[0] * m[4] * m[8] +
+ m[1] * m[5] * m[6] +
+ m[2] * m[3] * m[7] -
+ m[2] * m[4] * m[6] -
+ m[1] * m[3] * m[8] -
+ m[0] * m[5] * m[7]
+ if (!det) return null
+
+ return [
+ (m[4] * m[8] - m[5] * m[7]) / det,
+ (m[2] * m[7] - m[1] * m[8]) / det,
+ (m[1] * m[5] - m[2] * m[4]) / det,
+
+ (m[5] * m[6] - m[3] * m[8]) / det,
+ (m[0] * m[8] - m[2] * m[6]) / det,
+ (m[2] * m[3] - m[0] * m[5]) / det,
+
+ (m[3] * m[7] - m[4] * m[6]) / det,
+ (m[1] * m[6] - m[0] * m[7]) / det,
+ (m[0] * m[4] - m[1] * m[3]) / det
+ ]
+}
+
+const mapPoints = (matrix: Mat3, ptArr: number[]): number[] => {
+ if (ptArr.length % 2) throw new Error('mapPoints requires even length [x,y,...].')
+ const out = ptArr.slice()
+ for (let i = 0; i < out.length; i += 2) {
+ const x = out[i]
+ const y = out[i + 1]
+ const denom = matrix[6] * x + matrix[7] * y + matrix[8]
+ const xTrans = matrix[0] * x + matrix[1] * y + matrix[2]
+ const yTrans = matrix[3] * x + matrix[4] * y + matrix[5]
+ out[i] = xTrans / denom
+ out[i + 1] = yTrans / denom
+ }
+ return out
+}
+
+const mapPoint = (m: Mat3, p: Vector): Vector => {
+ const arr = mapPoints(m, [p.x, p.y])
+ return { x: arr[0], y: arr[1] }
+}
+
+const Matrix = { identity, multiply, translated, rotated, scaled, invert, mapPoints, mapPoint }
+export default Matrix
diff --git a/packages/core/src/canvas/overlays.ts b/packages/core/src/canvas/overlays.ts
index 58b80afdf..51a273d3f 100644
--- a/packages/core/src/canvas/overlays.ts
+++ b/packages/core/src/canvas/overlays.ts
@@ -1,25 +1,28 @@
+import { getWorldMatrix } from '@open-pencil/core/canvas/coordinate'
+
+import Matrix from '../canvas/matrix'
import {
+ FLASH_ATTACK_MS,
+ FLASH_COLOR,
+ FLASH_HOLD_MS,
+ FLASH_OVERSHOOT,
+ FLASH_RELEASE_MS,
HANDLE_HALF_SIZE,
+ LAYOUT_INDICATOR_STROKE,
MARQUEE_FILL_ALPHA,
SELECTION_DASH_ALPHA,
- LAYOUT_INDICATOR_STROKE,
- TEXT_SELECTION_COLOR,
TEXT_CARET_COLOR,
TEXT_CARET_WIDTH,
- FLASH_COLOR,
- FLASH_ATTACK_MS,
- FLASH_HOLD_MS,
- FLASH_RELEASE_MS,
- FLASH_OVERSHOOT
+ TEXT_SELECTION_COLOR
} from '../constants'
import { rotatedCorners } from '../geometry'
import { drawNodeHighlightRect } from './highlight-rect'
-import type { SceneNode, SceneGraph } from '../scene-graph'
-import type { SnapGuide } from '../scene-graph/snap'
+import type { SceneGraph, SceneNode } from '../scene-graph'
import type { TextEditor } from '../text/editor'
import type { Rect, Vector } from '../types'
-import type { SkiaRenderer, RenderOverlays } from './renderer'
+import type { RenderOverlays, SkiaRenderer } from './renderer'
+import type { SnapGuide } from '@open-pencil/core'
import type { Canvas } from 'canvaskit-wasm'
function getNodeTransformChain(graph: SceneGraph, node: SceneNode): SceneNode[] {
@@ -120,11 +123,11 @@ export function drawSelection(
const useComponentColor = r.isComponentType(node.type)
r.selectionPaint.setColor(useComponentColor ? r.compColor() : r.selColor())
- r.selectionPaint.setStrokeWidth(1)
+ r.selectionPaint.setStrokeWidth(1 / r.zoom)
- const rotation =
+ const _rotation =
overlays.rotationPreview?.nodeId === id ? overlays.rotationPreview.angle : node.rotation
- r.drawNodeSelection(canvas, node, rotation, graph)
+ r.drawNodeSelection(canvas, node, _rotation, graph)
r.drawSelectionLabels(canvas, graph, selectedIds, overlays)
r.selectionPaint.setColor(r.selColor())
@@ -165,18 +168,20 @@ function withNodeBounds(
graph: SceneGraph,
draw: (x1: number, y1: number, x2: number, y2: number) => void
): void {
- const abs = graph.getAbsolutePosition(node.id)
- const cx = (abs.x + node.width / 2) * r.zoom + r.panX
- const cy = (abs.y + node.height / 2) * r.zoom + r.panY
- const hw = (node.width / 2) * r.zoom
- const hh = (node.height / 2) * r.zoom
+ const worldMatrix = getWorldMatrix(
+ {
+ ...node,
+ rotation
+ },
+ graph
+ )
canvas.save()
- if (rotation !== 0) {
- canvas.rotate(rotation, cx, cy)
- }
+ canvas.translate(r.panX, r.panY)
+ canvas.scale(r.zoom, r.zoom)
+ canvas.concat(worldMatrix)
+ draw(0, 0, node.width, node.height)
- draw(cx - hw, cy - hh, cx + hw, cy + hh)
canvas.restore()
}
@@ -190,17 +195,24 @@ export function drawNodeSelection(
withNodeBounds(r, canvas, node, rotation, graph, (x1, y1, x2, y2) => {
canvas.drawRect(r.ck.LTRBRect(x1, y1, x2, y2), r.selectionPaint)
- r.drawHandle(canvas, x1, y1)
- r.drawHandle(canvas, x2, y1)
- r.drawHandle(canvas, x1, y2)
- r.drawHandle(canvas, x2, y2)
+ const drawHandle = (x: number, y: number) => {
+ r.drawHandle(canvas, x, y)
+ }
+
+ // corners
+ drawHandle(x1, y1)
+ drawHandle(x2, y1)
+ drawHandle(x1, y2)
+ drawHandle(x2, y2)
+ // center
const mx = (x1 + x2) / 2
const my = (y1 + y2) / 2
- r.drawHandle(canvas, mx, y1)
- r.drawHandle(canvas, mx, y2)
- r.drawHandle(canvas, x1, my)
- r.drawHandle(canvas, x2, my)
+
+ drawHandle(mx, y1)
+ drawHandle(mx, y2)
+ drawHandle(x1, my)
+ drawHandle(x2, my)
})
}
@@ -214,29 +226,41 @@ export function drawParentFrameOutlines(
for (const id of selectedIds) {
const node = graph.getNode(id)
if (!node?.parentId) continue
- const nodeParent = graph.getNode(node.parentId)
- if (!nodeParent || nodeParent.type === 'CANVAS') continue
- if (drawn.has(node.parentId) || selectedIds.has(node.parentId)) continue
- const parent = nodeParent
+ const parent = graph.getNode(node.parentId)
+ if (!parent || parent.type === 'CANVAS') continue
+ if (drawn.has(parent.id) || selectedIds.has(parent.id)) continue
const grandparent = parent.parentId ? graph.getNode(parent.parentId) : null
if (!grandparent || grandparent.type === 'CANVAS') continue
- drawn.add(node.parentId)
+ drawn.add(parent.id)
- const abs = graph.getAbsolutePosition(parent.id)
- const x = abs.x * r.zoom + r.panX
- const y = abs.y * r.zoom + r.panY
- const w = parent.width * r.zoom
- const h = parent.height * r.zoom
+ const world = getWorldMatrix(parent, graph)
- canvas.save()
- if (parent.rotation !== 0) {
- canvas.rotate(parent.rotation, x + w / 2, y + h / 2)
- }
- canvas.drawRect(r.ck.LTRBRect(x, y, x + w, y + h), r.parentOutlinePaint)
- canvas.restore()
+ const view = Matrix.multiply(Matrix.translated(r.panX, r.panY), Matrix.scaled(r.zoom, r.zoom))
+
+ const m = Matrix.multiply(view, world)
+
+ const pts = Matrix.mapPoints(m, [
+ 0,
+ 0,
+ parent.width,
+ 0,
+ parent.width,
+ parent.height,
+ 0,
+ parent.height
+ ])
+
+ const path = new r.ck.Path()
+ path.moveTo(pts[0], pts[1])
+ path.lineTo(pts[2], pts[3])
+ path.lineTo(pts[4], pts[5])
+ path.lineTo(pts[6], pts[7])
+ path.close()
+
+ canvas.drawPath(path, r.parentOutlinePaint)
}
}
@@ -316,10 +340,10 @@ export { drawSelectionLabels } from './selection-labels'
export function drawHandle(r: SkiaRenderer, canvas: Canvas, x: number, y: number): void {
r.auxFill.setColor(r.ck.WHITE)
const rect = r.ck.LTRBRect(
- x - HANDLE_HALF_SIZE,
- y - HANDLE_HALF_SIZE,
- x + HANDLE_HALF_SIZE,
- y + HANDLE_HALF_SIZE
+ x - HANDLE_HALF_SIZE / r.zoom,
+ y - HANDLE_HALF_SIZE / r.zoom,
+ x + HANDLE_HALF_SIZE / r.zoom,
+ y + HANDLE_HALF_SIZE / r.zoom
)
canvas.drawRect(rect, r.auxFill)
canvas.drawRect(rect, r.selectionPaint)
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index 558ec637d..489abb6c4 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -835,7 +835,7 @@ export class SkiaRenderer {
const pageNode = graph.getNode(this.pageId ?? graph.rootId)
if (pageNode) {
for (const childId of pageNode.childIds) {
- this.renderNode(canvas, graph, childId, overlays, 0, 0)
+ this.renderNode(canvas, graph, childId, overlays)
}
}
p.endPhase('render:volatile')
@@ -921,7 +921,7 @@ export class SkiaRenderer {
const recCanvas = recorder.beginRecording(bounds)
if (pageNode) {
for (const childId of pageNode.childIds) {
- this.renderNode(recCanvas, graph, childId, {}, 0, 0)
+ this.renderNode(recCanvas, graph, childId, {})
}
}
this.scenePicture = recorder.finishRecordingAsPicture()
@@ -1201,15 +1201,8 @@ export class SkiaRenderer {
drawComponentLabelsFn(this, canvas, graph)
}
- renderNode(
- canvas: Canvas,
- graph: SceneGraph,
- nodeId: string,
- overlays: RenderOverlays,
- parentAbsX = 0,
- parentAbsY = 0
- ): void {
- renderNodeFn(this, canvas, graph, nodeId, overlays, parentAbsX, parentAbsY)
+ renderNode(canvas: Canvas, graph: SceneGraph, nodeId: string, overlays: RenderOverlays): void {
+ renderNodeFn(this, canvas, graph, nodeId, overlays)
}
renderSection(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index 80f2646db..95fe6990f 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -80,9 +80,7 @@ function renderChildren(
canvas: Canvas,
graph: SceneGraph,
node: SceneNode,
- overlays: RenderOverlays,
- absX: number,
- absY: number
+ overlays: RenderOverlays
): void {
const isClippableContainer =
node.type === 'FRAME' || node.type === 'COMPONENT' || node.type === 'INSTANCE'
@@ -101,12 +99,12 @@ function renderChildren(
canvas.clipRect(r.ck.LTRBRect(0, 0, node.width, node.height), r.ck.ClipOp.Intersect, true)
}
for (const childId of node.childIds) {
- r.renderNode(canvas, graph, childId, overlays, absX, absY)
+ r.renderNode(canvas, graph, childId, overlays)
}
canvas.restore()
} else {
for (const childId of node.childIds) {
- r.renderNode(canvas, graph, childId, overlays, absX, absY)
+ r.renderNode(canvas, graph, childId, overlays)
}
}
}
@@ -154,7 +152,7 @@ export function renderNode(
applyNodeTransforms(r, canvas, node, nodeId, overlays)
renderNodeContent(r, canvas, graph, node, nodeId, overlays)
- renderChildren(r, canvas, graph, node, overlays, absX, absY)
+ renderChildren(r, canvas, graph, node, overlays)
if (layerBlur) {
canvas.restore()
diff --git a/packages/core/src/canvas/selection-labels.ts b/packages/core/src/canvas/selection-labels.ts
index bf98f87dc..5a590fd92 100644
--- a/packages/core/src/canvas/selection-labels.ts
+++ b/packages/core/src/canvas/selection-labels.ts
@@ -1,3 +1,4 @@
+import { getAbsolutePosition, getWorldMatrix } from '../canvas/coordinate'
import {
LABEL_OFFSET_Y,
SIZE_PILL_PADDING_X,
@@ -6,7 +7,7 @@ import {
SIZE_PILL_RADIUS,
SIZE_PILL_TEXT_OFFSET_Y
} from '../constants'
-import { degToRad, rotatePoint, rotatedCorners } from '../geometry'
+import { rotatedCorners } from '../geometry'
import type { SceneNode, SceneGraph } from '../scene-graph'
import type { SkiaRenderer, RenderOverlays } from './renderer'
@@ -33,7 +34,7 @@ function accumulateSelectionBounds(
const node = graph.getNode(id)
if (!node) continue
nodes.push(node)
- const abs = graph.getAbsolutePosition(id)
+ const abs = getAbsolutePosition(node, graph)
const rotation = getOverlayRotation(node, overlays)
if (rotation !== 0) {
const corners = rotatedCorners(abs.x, abs.y, node.width, node.height, rotation)
@@ -66,32 +67,30 @@ function drawSingleFrameTitle(
const isTopLevel = !parentNode || parentNode.type === 'CANVAS' || parentNode.type === 'SECTION'
if (node.type !== 'FRAME' || !isTopLevel) return
- const abs = graph.getAbsolutePosition(node.id)
- const rotation = getOverlayRotation(node, overlays)
- const anchor =
- rotation === 0
- ? { x: abs.x, y: abs.y }
- : rotatePoint(
- abs.x,
- abs.y,
- abs.x + node.width / 2,
- abs.y + node.height / 2,
- degToRad(rotation)
- )
- const labelX = anchor.x * r.zoom + r.panX
- const labelY = anchor.y * r.zoom + r.panY - LABEL_OFFSET_Y
+ const overlayRotation = getOverlayRotation(node, overlays) // degrees
+
+ const world = getWorldMatrix({ ...node, rotation: overlayRotation }, graph)
+
+ // World -> screen (pan + zoom)
+ const view = r.ck.Matrix.multiply(
+ r.ck.Matrix.translated(r.panX, r.panY),
+ r.ck.Matrix.scaled(r.zoom, r.zoom)
+ )
+
+ const m = r.ck.Matrix.multiply(view, world)
r.auxFill.setColor(r.selColor())
+
canvas.save()
- canvas.translate(labelX, labelY)
- if (rotation !== 0) {
- canvas.rotate(rotation, 0, LABEL_OFFSET_Y)
- }
- canvas.drawText(node.name, 0, 0, r.auxFill, labelFont)
+ canvas.concat(m)
+
+ // After concat(m), local (0,0) is node's top-left in screen space (after rotation etc.)
+ canvas.drawText(node.name, 0, -LABEL_OFFSET_Y, r.auxFill, labelFont)
+
canvas.restore()
}
-function drawSingleSelectionSize(
+export function drawSingleSelectionSize(
r: SkiaRenderer,
canvas: Canvas,
graph: SceneGraph,
@@ -103,41 +102,56 @@ function drawSingleSelectionSize(
const glyphIds = sizeFont.getGlyphIDs(sizeText)
const widths = sizeFont.getGlyphWidths(glyphIds)
let textWidth = 0
- for (const width of widths) textWidth += width
+ for (const w of widths) textWidth += w
+
const pillW = textWidth + SIZE_PILL_PADDING_X * 2
const pillH = SIZE_PILL_HEIGHT
const pillColor = r.isComponentType(node.type) ? r.compColor() : r.selColor()
- const abs = graph.getAbsolutePosition(node.id)
- const rotation = getOverlayRotation(node, overlays)
- const cx = (abs.x + node.width / 2) * r.zoom + r.panX
- const cy = (abs.y + node.height / 2) * r.zoom + r.panY
- const localY = (node.height * r.zoom) / 2 + SIZE_PILL_PADDING_Y
+ const overlayRotation = getOverlayRotation(node, overlays)
+ const world = getWorldMatrix({ ...node, rotation: overlayRotation }, graph)
+ const view = r.ck.Matrix.multiply(
+ r.ck.Matrix.translated(r.panX, r.panY),
+ r.ck.Matrix.scaled(r.zoom, r.zoom)
+ )
+
+ // Local -> screen matrix.
+ const m = r.ck.Matrix.multiply(view, world)
+
+ // Node center in local space.
+ const localCX = node.width / 2
+ const localCY = node.height / 2
+
+ // Pill placement in local space (below the node, centered).
+ const localX = -pillW / 2
+ const localY = localCY + SIZE_PILL_PADDING_Y
canvas.save()
- canvas.translate(cx, cy)
- if (rotation !== 0) {
- canvas.rotate(rotation, 0, 0)
- }
+ canvas.concat(m)
+ // Move origin to node center (still in local space).
+ canvas.translate(localCX, localCY)
+
+ // Pill background.
r.auxFill.setColor(pillColor)
const rrect = r.ck.RRectXY(
- r.ck.LTRBRect(-pillW / 2, localY, pillW / 2, localY + pillH),
+ r.ck.LTRBRect(localX, localY, localX + pillW, localY + pillH),
SIZE_PILL_RADIUS,
SIZE_PILL_RADIUS
)
canvas.drawRRect(rrect, r.auxFill)
+ // Text.
r.auxFill.setColor(r.ck.WHITE)
canvas.drawText(
sizeText,
- -pillW / 2 + SIZE_PILL_PADDING_X,
+ localX + SIZE_PILL_PADDING_X,
localY + SIZE_PILL_TEXT_OFFSET_Y,
r.auxFill,
sizeFont
)
+
canvas.restore()
}
-
function drawMultiSelectionSize(
r: SkiaRenderer,
canvas: Canvas,
@@ -192,7 +206,6 @@ export function drawSelectionLabels(
const labelFont = r.labelFont
const sizeFont = r.sizeFont
if (!labelFont || !sizeFont) return
-
const activeOverlays = overlays ?? {}
const { nodes, minX, minY, maxX, maxY } = accumulateSelectionBounds(
graph,
diff --git a/packages/core/src/editor/selection.ts b/packages/core/src/editor/selection.ts
index ea59d342a..b445bbd31 100644
--- a/packages/core/src/editor/selection.ts
+++ b/packages/core/src/editor/selection.ts
@@ -101,6 +101,8 @@ export function createSelectionActions(ctx: EditorContext) {
}
function hitTestAtPoint(cx: number, cy: number, deep = false): SceneNode | null {
+ const renderer = ctx.getRenderer()
+ if (!renderer) return null
const scopeId = ctx.state.enteredContainerId
if (scopeId) {
const scopeNode = ctx.graph.getNode(scopeId)
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 0279efed9..806e0e94e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -402,3 +402,5 @@ export {
getStockPhotoProviders
} from './tools/stock-photo'
export type { StockPhotoProvider, StockPhotoResult } from './tools/stock-photo'
+
+export { getAbsoluteRotation, getWorldHandles, getAbsolutePosition } from './canvas/coordinate'
diff --git a/packages/core/src/scene-graph/hit-test.ts b/packages/core/src/scene-graph/hit-test.ts
index 3f4456248..bd1d45ad0 100644
--- a/packages/core/src/scene-graph/hit-test.ts
+++ b/packages/core/src/scene-graph/hit-test.ts
@@ -1,4 +1,6 @@
-import { degToRad } from '../geometry'
+import Matrix from '@open-pencil/core/canvas/matrix'
+
+import { getWorldMatrix } from '../canvas/coordinate'
import type { SceneGraph, SceneNode, NodeType } from './'
@@ -17,21 +19,13 @@ function hasVisibleFillOrStroke(node: SceneNode): boolean {
return node.fills.some((f) => f.visible) || node.strokes.some((s) => s.visible)
}
-function containsPoint(px: number, py: number, ax: number, ay: number, node: SceneNode): boolean {
- if (node.rotation === 0) {
- return px >= ax && px <= ax + node.width && py >= ay && py <= ay + node.height
- }
+function containsPoint(px: number, py: number, node: SceneNode, graph: SceneGraph): boolean {
+ const m = getWorldMatrix(node, graph)
- const cx = ax + node.width / 2
- const cy = ay + node.height / 2
- const dx = px - cx
- const dy = py - cy
- const rad = degToRad(-node.rotation)
- const cos = Math.cos(rad)
- const sin = Math.sin(rad)
- const localX = dx * cos - dy * sin + node.width / 2
- const localY = dx * sin + dy * cos + node.height / 2
+ const inv = Matrix.invert(m)
+ if (!inv) return false
+ const [localX, localY] = Matrix.mapPoints(inv, [px, py])
return localX >= 0 && localX <= node.width && localY >= 0 && localY <= node.height
}
@@ -41,35 +35,37 @@ function hitTestOpaqueContainer(
py: number,
child: SceneNode,
childId: string,
- ax: number,
- ay: number,
deep: boolean
): SceneNode | null {
- if (!containsPoint(px, py, ax, ay, child)) return null
- const childHit = hitTestChildren(graph, px, py, childId, ax, ay, deep)
+ if (!containsPoint(px, py, child, graph)) return null
+ const childHit = hitTestChildren(graph, px, py, childId, deep)
if (childHit) return child
if (hasVisibleFillOrStroke(child)) return child
return null
}
-
function hitTestTransparentContainer(
graph: SceneGraph,
px: number,
py: number,
child: SceneNode,
childId: string,
- ax: number,
- ay: number,
deep: boolean
): SceneNode | null {
- const childHit = hitTestChildren(graph, px, py, childId, ax, ay, deep)
+ if (child.type === 'GROUP') {
+ if (!containsPoint(px, py, child, graph)) return null
+
+ if (deep) return hitTestChildren(graph, px, py, childId, deep) ?? child
+
+ return child
+ }
+
+ const childHit = hitTestChildren(graph, px, py, childId, deep)
if (childHit) {
- if (!deep && child.type === 'GROUP') return child
if (child.locked) return child
return childHit
}
- if (child.type === 'GROUP') return null
- if (containsPoint(px, py, ax, ay, child) && hasVisibleFillOrStroke(child)) return child
+
+ if (containsPoint(px, py, child, graph) && hasVisibleFillOrStroke(child)) return child
return null
}
@@ -78,39 +74,34 @@ function hitTestChildren(
px: number,
py: number,
parentId: string,
- offsetX: number,
- offsetY: number,
deep = false
): SceneNode | null {
const parent = graph.nodes.get(parentId)
if (!parent) return null
if (parent.clipsContent) {
- if (!containsPoint(px, py, offsetX, offsetY, parent)) return null
+ if (!containsPoint(px, py, parent, graph)) return null
}
for (let i = parent.childIds.length - 1; i >= 0; i--) {
const childId = parent.childIds[i]
const child = graph.nodes.get(childId)
if (!child || !child.visible) continue
-
- const ax = offsetX + child.x
- const ay = offsetY + child.y
-
if (CONTAINER_TYPES.has(child.type)) {
if (OPAQUE_CONTAINER_TYPES.has(child.type) && !deep) {
- const hit = hitTestOpaqueContainer(graph, px, py, child, childId, ax, ay, deep)
+ const hit = hitTestOpaqueContainer(graph, px, py, child, childId, deep)
if (hit) return hit
continue
}
- const hit = hitTestTransparentContainer(graph, px, py, child, childId, ax, ay, deep)
+ const hit = hitTestTransparentContainer(graph, px, py, child, childId, deep)
if (hit) return hit
continue
}
- if (containsPoint(px, py, ax, ay, child)) return child
+ if (containsPoint(px, py, child, graph)) return child
}
+
return null
}
@@ -121,7 +112,7 @@ export function hitTest(
scopeId?: string
): SceneNode | null {
const scope = scopeId ?? graph.rootId
- return hitTestChildren(graph, px, py, scope, 0, 0, false)
+ return hitTestChildren(graph, px, py, scope, false)
}
export function hitTestDeep(
@@ -131,7 +122,7 @@ export function hitTestDeep(
scopeId?: string
): SceneNode | null {
const scope = scopeId ?? graph.rootId
- return hitTestChildren(graph, px, py, scope, 0, 0, true)
+ return hitTestChildren(graph, px, py, scope, true)
}
function hitTestFrameChildren(
diff --git a/packages/core/src/scene-graph/index.ts b/packages/core/src/scene-graph/index.ts
index 247087834..03e79301f 100644
--- a/packages/core/src/scene-graph/index.ts
+++ b/packages/core/src/scene-graph/index.ts
@@ -17,6 +17,8 @@ import {
} from './instances'
export type { GUID, Color } from '../types'
+import { getAbsolutePosition } from '@open-pencil/core/canvas/coordinate'
+
import type { Matrix, Vector, Color, Rect } from '../types'
import type { Emitter } from 'nanoevents'
@@ -753,15 +755,9 @@ export class SceneGraph {
const cached = this.absPosCache.get(id)
if (cached) return cached
- let ax = 0
- let ay = 0
- let current = this.nodes.get(id)
- while (current && current.id !== this.rootId && current.type !== 'CANVAS') {
- ax += current.x
- ay += current.y
- current = current.parentId ? this.nodes.get(current.parentId) : undefined
- }
- const result = { x: ax, y: ay }
+ const node = this.getNode(id)
+
+ const result = getAbsolutePosition(node!, this)
this.absPosCache.set(id, result)
return result
}
diff --git a/packages/vue/src/Canvas/useCanvasInput.ts b/packages/vue/src/Canvas/useCanvasInput.ts
index bfad47b0c..3d982bf97 100644
--- a/packages/vue/src/Canvas/useCanvasInput.ts
+++ b/packages/vue/src/Canvas/useCanvasInput.ts
@@ -8,8 +8,9 @@ import {
DEFAULT_TEXT_HEIGHT,
degToRad
} from '@open-pencil/core'
+import { getAbsolutePositionFull } from '@open-pencil/core/canvas/coordinate'
import { handleDrawMove, handleDrawUp } from '@open-pencil/vue/shared/input/draw'
-import { hitTestCornerRotation } from '@open-pencil/vue/shared/input/geometry'
+import { hitTestCornerRotationByMatrix } from '@open-pencil/vue/shared/input/geometry'
import { handleMoveMove, handleMoveUp } from '@open-pencil/vue/shared/input/move'
import { setupPanZoom } from '@open-pencil/vue/shared/input/pan-zoom'
import { applyResize } from '@open-pencil/vue/shared/input/resize'
@@ -120,6 +121,9 @@ export function useCanvasInput(
function hitTestInScope(cx: number, cy: number, deep: boolean): SceneNode | null {
const scopeId = editor.state.enteredContainerId
+
+ const renderer = editor.renderer
+ if (!renderer) return null
if (scopeId) {
if (!editor.graph.getNode(scopeId)) {
editor.state.enteredContainerId = null
@@ -192,37 +196,27 @@ export function useCanvasInput(
return true
}
- function tryStartRotation(sx: number, sy: number): boolean {
+ function tryStartRotation(cx: number, cy: number): boolean {
if (editor.state.selectedIds.size !== 1) return false
const id = [...editor.state.selectedIds][0]
const node = editor.graph.getNode(id)
if (!node || node.locked) return false
- const abs = editor.graph.getAbsolutePosition(id)
- if (
- !hitTestCornerRotation(
- sx,
- sy,
- abs.x,
- abs.y,
- node.width,
- node.height,
- editor.state.zoom,
- editor.state.panX,
- editor.state.panY,
- node.rotation
- )
- )
+
+ if (editor.state.selectedIds.size > 1) {
return false
+ }
+ const abs = getAbsolutePositionFull(node, editor.graph)
- const screenCx = (abs.x + node.width / 2) * editor.state.zoom + editor.state.panX
- const screenCy = (abs.y + node.height / 2) * editor.state.zoom + editor.state.panY
- const startAngle = Math.atan2(sy - screenCy, sx - screenCx) * (180 / Math.PI)
+ if (!hitTestCornerRotationByMatrix(cx, cy, node, editor.graph, editor.renderer?.zoom!)) {
+ return false
+ }
+ const startAngle = Math.atan2(cy - abs.centerY, cx - abs.centerX) * (180 / Math.PI)
drag.value = {
type: 'rotate',
nodeId: id,
- centerX: screenCx,
- centerY: screenCy,
- startAngle,
+ centerX: abs.centerX,
+ centerY: abs.centerY,
+ startAngle: startAngle,
origRotation: node.rotation
}
return true
@@ -238,7 +232,11 @@ export function useCanvasInput(
function handleRotateMove(d: DragRotate, sx: number, sy: number, shiftKey: boolean) {
const currentAngle = Math.atan2(sy - d.centerY, sx - d.centerX) * (180 / Math.PI)
- let rotation = d.origRotation + (currentAngle - d.startAngle)
+
+ let delta = currentAngle - d.startAngle
+
+ delta = ((((delta + 180) % 360) + 360) % 360) - 180
+ let rotation = d.origRotation + delta
if (shiftKey) {
rotation = Math.round(rotation / ROTATION_SNAP_DEGREES) * ROTATION_SNAP_DEGREES
@@ -376,18 +374,7 @@ export function useCanvasInput(
}
if (tool === 'SELECT') {
- handleSelectDown(
- e,
- sx,
- sy,
- cx,
- cy,
- editor,
- hitFns,
- tryStartRotation,
- handleTextEditClick,
- setDrag
- )
+ handleSelectDown(e, cx, cy, editor, hitFns, tryStartRotation, handleTextEditClick, setDrag)
return
}
@@ -514,8 +501,8 @@ export function useCanvasInput(
}
if (!drag.value && editor.state.activeTool === 'SELECT') {
- const { sx, sy, cx, cy } = getCoords(e)
- cursorOverride.value = updateHoverCursor(sx, sy, cx, cy, editor, hitFns)
+ const { cx, cy } = getCoords(e)
+ cursorOverride.value = updateHoverCursor(cx, cy, editor, hitFns)
}
if (!drag.value) return
@@ -526,10 +513,10 @@ export function useCanvasInput(
return
}
- const { cx, cy, sx, sy } = getCoords(e)
+ const { cx, cy } = getCoords(e)
if (d.type === 'rotate') {
- handleRotateMove(d, sx, sy, e.shiftKey)
+ handleRotateMove(d, cx, cy, e.shiftKey)
return
}
if (d.type === 'move') {
@@ -811,7 +798,6 @@ export function useCanvasInput(
})
setupPanZoom(canvasRef, editor, drag, onMouseDown, onMouseMove, onMouseUp)
-
return {
drag,
cursorOverride
diff --git a/packages/vue/src/shared/assets/resize-cursor.svg b/packages/vue/src/shared/assets/resize-cursor.svg
new file mode 100644
index 000000000..8d8dfae7e
--- /dev/null
+++ b/packages/vue/src/shared/assets/resize-cursor.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 1024 1024">
+ <path d="M781.33 239.94 781.33 381.12 600.77 381.12 600.77 381.12 238.68 381.12 239.94 242.00 58.93 422.94 239.94 603.94 239.94 462.75 758.89 462.75 783.77 462.75 783.77 604.80 964.77 423.80Z" fill="black" stroke="white" stroke-width="33.33"/>
+</svg>
+
diff --git a/packages/vue/src/shared/input/geometry.ts b/packages/vue/src/shared/input/geometry.ts
index 688ac2ddf..502ba8ab5 100644
--- a/packages/vue/src/shared/input/geometry.ts
+++ b/packages/vue/src/shared/input/geometry.ts
@@ -1,20 +1,15 @@
-import { CORNER_ROTATE_ZONE, HANDLE_HIT_RADIUS } from '@open-pencil/core'
-
+import {
+ CORNER_ROTATE_ZONE,
+ getAbsoluteRotation,
+ getWorldHandles,
+ HANDLE_HIT_RADIUS
+} from '@open-pencil/core'
+
+import resizeCursorSvg from '../assets/resize-cursor.svg?raw'
import rotateCursorSvg from '../assets/rotate-cursor.svg?raw'
import type { CornerPosition, HandlePosition } from './types'
-import type { Vector } from '@open-pencil/core'
-
-export const HANDLE_CURSORS: Record<HandlePosition, string> = {
- nw: 'nwse-resize',
- n: 'ns-resize',
- ne: 'nesw-resize',
- e: 'ew-resize',
- se: 'nwse-resize',
- s: 'ns-resize',
- sw: 'nesw-resize',
- w: 'ew-resize'
-}
+import type { Vector, SceneGraph, SceneNode } from '@open-pencil/core'
export function getScreenRect(
absX: number,
@@ -77,67 +72,106 @@ export function unrotate(
}
}
-export function hitTestHandle(
- sx: number,
- sy: number,
- absX: number,
- absY: number,
- w: number,
- h: number,
- zoom: number,
- panX: number,
- panY: number,
- rotation = 0
-): HandlePosition | null {
- const { x1, y1, x2, y2 } = getScreenRect(absX, absY, w, h, zoom, panX, panY)
- const cx = (x1 + x2) / 2
- const cy = (y1 + y2) / 2
- const ur = unrotate(sx, sy, cx, cy, rotation)
-
- const handles = getHandlePositions(absX, absY, w, h, zoom, panX, panY)
- for (const [pos, pt] of Object.entries(handles)) {
- if (Math.abs(ur.sx - pt.x) < HANDLE_HIT_RADIUS && Math.abs(ur.sy - pt.y) < HANDLE_HIT_RADIUS) {
- return pos as HandlePosition
+function getCursorAngleFromHandle(handle: HandlePosition, rotation: number): number {
+ const map: Record<HandlePosition, [number, number]> = {
+ nw: [1, 1],
+ ne: [-1, 1],
+ se: [-1, -1],
+ sw: [1, -1],
+
+ n: [0, 1],
+ e: [1, 0],
+ s: [0, -1],
+ w: [-1, 0]
+ }
+
+ const [bx, by] = map[handle]
+
+ const baseAngle = (Math.atan2(by, bx) * 180) / Math.PI
+
+ const angle = baseAngle - rotation
+
+ return (angle + 360) % 360
+}
+
+export function getHitHandleByMatrix(
+ cx: number,
+ cy: number,
+ node: SceneNode,
+ graph: SceneGraph,
+ zoom = 1
+): {
+ handle: HandlePosition
+ rotation: number
+} | null {
+ const handles = getWorldHandles(node, graph)
+
+ const CORNER_R = HANDLE_HIT_RADIUS / zoom
+
+ const rotation = getAbsoluteRotation(node, graph)
+ for (const key in handles) {
+ const handleKey = key as HandlePosition
+ const p = handles[handleKey]
+
+ if (!p) continue
+
+ const dx = cx - p.x
+ const dy = cy - p.y
+
+ if (dx * dx + dy * dy <= CORNER_R * CORNER_R) {
+ const angle = getCursorAngleFromHandle(handleKey, rotation)
+
+ return {
+ handle: handleKey,
+ rotation: angle
+ }
}
}
+
return null
}
-
-export function hitTestCornerRotation(
- sx: number,
- sy: number,
- absX: number,
- absY: number,
- w: number,
- h: number,
- zoom: number,
- panX: number,
- panY: number,
- rotation = 0
+export function hitTestCornerRotationByMatrix(
+ cx: number,
+ cy: number,
+ node: SceneNode,
+ graph: SceneGraph,
+ zoom: number = 1
): CornerPosition | null {
- const { x1, y1, x2, y2 } = getScreenRect(absX, absY, w, h, zoom, panX, panY)
- const cx = (x1 + x2) / 2
- const cy = (y1 + y2) / 2
- const ur = unrotate(sx, sy, cx, cy, rotation)
-
- const corners: Array<{ pos: CornerPosition; x: number; y: number }> = [
- { pos: 'nw', x: x1, y: y1 },
- { pos: 'ne', x: x2, y: y1 },
- { pos: 'se', x: x2, y: y2 },
- { pos: 'sw', x: x1, y: y2 }
+ const handles = getWorldHandles(node, graph)
+
+ const HANDLE_R = HANDLE_HIT_RADIUS / zoom
+ const ROTATE_R = CORNER_ROTATE_ZONE / zoom
+
+ const corners: Array<{ key: CornerPosition; p: { x: number; y: number } }> = [
+ { key: 'nw', p: handles.nw },
+ { key: 'ne', p: handles.ne },
+ { key: 'se', p: handles.se },
+ { key: 'sw', p: handles.sw }
]
- for (const { pos, x, y } of corners) {
- const dx = Math.abs(ur.sx - x)
- const dy = Math.abs(ur.sy - y)
- if (
- dx <= CORNER_ROTATE_ZONE &&
- dy <= CORNER_ROTATE_ZONE &&
- (dx > HANDLE_HIT_RADIUS || dy > HANDLE_HIT_RADIUS)
- ) {
- return pos
+ for (const { key, p } of corners) {
+ const dx = cx - p.x
+ const dy = cy - p.y
+ const d = Math.hypot(dx, dy)
+
+ if (d > HANDLE_R && d <= ROTATE_R) {
+ switch (key) {
+ case 'nw':
+ if (dx < 0 && dy < 0) return key
+ break
+ case 'ne':
+ if (dx > 0 && dy < 0) return key
+ break
+ case 'se':
+ if (dx > 0 && dy > 0) return key
+ break
+ case 'sw':
+ if (dx < 0 && dy > 0) return key
+ break
+ }
}
}
+
return null
}
@@ -166,5 +200,17 @@ export function buildRotationCursor(angleDeg: number): string {
}
export function cornerRotationCursor(corner: CornerPosition, nodeRotation = 0): string {
- return buildRotationCursor(CORNER_BASE_ANGLES[corner] + nodeRotation)
+ return buildRotationCursor(CORNER_BASE_ANGLES[corner] - nodeRotation)
+}
+
+export function buildResizeCursor(angleDeg: number): string {
+ const normalized = ((Math.round(angleDeg) % 360) + 360) % 360
+
+ let svg = resizeCursorSvg
+ .replace(
+ '<path',
+ `<g transform='translate(512 512) rotate(${normalized}) translate(-512 -512)'><path`
+ )
+ .replace('</svg>', '</g></svg>')
+ return `url("data:image/svg+xml,${encodeURIComponent(svg)}") 12 12, auto`
}
diff --git a/packages/vue/src/shared/input/resize.ts b/packages/vue/src/shared/input/resize.ts
index 5f0c4bbcb..74b51af68 100644
--- a/packages/vue/src/shared/input/resize.ts
+++ b/packages/vue/src/shared/input/resize.ts
@@ -1,6 +1,5 @@
import { cloneVectorNetwork } from '@open-pencil/core'
-
-import { hitTestHandle } from './geometry'
+import { getHitHandleByMatrix } from '@open-pencil/vue/shared/input/geometry'
import type { DragResize, HandlePosition } from './types'
import type { Rect, SceneNode } from '@open-pencil/core'
@@ -45,26 +44,32 @@ export function applyResize(
) {
const { handle, origRect } = d
let { x, y, width, height } = origRect
+
const dx = cx - d.startX
const dy = cy - d.startY
+ const origX = origRect.x
+ const origY = origRect.y
+ const origW = origRect.width
+ const origH = origRect.height
+
const moveLeft = handle.includes('w')
const moveRight = handle.includes('e')
const moveTop = handle === 'nw' || handle === 'n' || handle === 'ne'
const moveBottom = handle === 'sw' || handle === 's' || handle === 'se'
- if (moveRight) width = origRect.width + dx
+ if (moveRight) width = origW + dx
if (moveLeft) {
- x = origRect.x + dx
- width = origRect.width - dx
+ x = origX + dx
+ width = origW - dx
}
- if (moveBottom) height = origRect.height + dy
+ if (moveBottom) height = origH + dy
if (moveTop) {
- y = origRect.y + dy
- height = origRect.height - dy
+ y = origY + dy
+ height = origH - dy
}
- if (constrain && origRect.width > 0 && origRect.height > 0) {
+ if (constrain && origW > 0 && origH > 0) {
;({ x, y, width, height } = constrainToAspectRatio(handle, origRect, width, height, dx, dy))
}
@@ -79,25 +84,23 @@ export function applyResize(
const newW = Math.round(Math.max(1, width))
const newH = Math.round(Math.max(1, height))
+ const newX = Math.round(x)
+ const newY = Math.round(y)
+
const changes: Partial<SceneNode> = {
- x: Math.round(x),
- y: Math.round(y),
+ x: newX,
+ y: newY,
width: newW,
height: newH
}
- // Scale vectorNetwork vertices + tangents proportionally
- if (d.origVectorNetwork && origRect.width > 0 && origRect.height > 0) {
- const sx = newW / origRect.width
- const sy = newH / origRect.height
+ if (d.origVectorNetwork && origW > 0 && origH > 0) {
+ const sx = newW / origW
+ const sy = newH / origH
if (sx !== 1 || sy !== 1) {
const vn = d.origVectorNetwork
changes.vectorNetwork = {
- vertices: vn.vertices.map((v) => ({
- ...v,
- x: v.x * sx,
- y: v.y * sy
- })),
+ vertices: vn.vertices.map((v) => ({ ...v, x: v.x * sx, y: v.y * sy })),
segments: vn.segments.map((s) => ({
...s,
tangentStart: { x: s.tangentStart.x * sx, y: s.tangentStart.y * sy },
@@ -110,34 +113,15 @@ export function applyResize(
editor.updateNode(d.nodeId, changes)
}
-
-export function tryStartResize(
- sx: number,
- sy: number,
- cx: number,
- cy: number,
- editor: Editor
-): DragResize | null {
+export function tryStartResize(cx: number, cy: number, editor: Editor): DragResize | null {
for (const id of editor.state.selectedIds) {
const node = editor.graph.getNode(id)
if (!node || node.locked) continue
- const abs = editor.graph.getAbsolutePosition(id)
- const handle = hitTestHandle(
- sx,
- sy,
- abs.x,
- abs.y,
- node.width,
- node.height,
- editor.state.zoom,
- editor.state.panX,
- editor.state.panY,
- node.rotation
- )
- if (handle) {
+ const handleResult = getHitHandleByMatrix(cx, cy, node, editor.graph, editor?.renderer?.zoom)
+ if (handleResult?.handle) {
return {
type: 'resize',
- handle,
+ handle: handleResult?.handle,
startX: cx,
startY: cy,
origRect: { x: node.x, y: node.y, width: node.width, height: node.height },
diff --git a/packages/vue/src/shared/input/select.ts b/packages/vue/src/shared/input/select.ts
index 7e43b1258..24c2b8c75 100644
--- a/packages/vue/src/shared/input/select.ts
+++ b/packages/vue/src/shared/input/select.ts
@@ -1,14 +1,21 @@
import {
- HANDLE_CURSORS,
- hitTestHandle,
- hitTestCornerRotation,
- cornerRotationCursor
+ getAbsoluteRotation,
+ SceneNode,
+ Vector,
+ VectorSegment,
+ VectorVertex
+} from '@open-pencil/core'
+
+import {
+ cornerRotationCursor,
+ getHitHandleByMatrix,
+ hitTestCornerRotationByMatrix,
+ buildResizeCursor
} from './geometry'
import { duplicateAndDrag, detectAutoLayoutParent } from './move'
import { tryStartResize } from './resize'
import type { DragEditHandle, DragEditNode, DragState } from './types'
-import type { SceneNode, Vector, VectorSegment, VectorVertex } from '@open-pencil/core'
import type { Editor } from '@open-pencil/core/editor'
type NodeEditState = {
@@ -348,13 +355,11 @@ export function handleNodeEditMove(
export function handleSelectDown(
e: MouseEvent,
- sx: number,
- sy: number,
cx: number,
cy: number,
editor: Editor,
fns: HitTestFns,
- tryStartRotation: (sx: number, sy: number) => boolean,
+ tryStartRotation: (cx: number, cy: number) => boolean,
handleTextEditClick: (cx: number, cy: number, shiftKey: boolean) => boolean,
setDrag: (d: DragState) => void
) {
@@ -368,14 +373,14 @@ export function handleSelectDown(
if (editor.state.editingTextId) editor.commitTextEdit()
- const resizeDrag = tryStartResize(sx, sy, cx, cy, editor)
+ if (tryStartRotation(cx, cy)) return
+
+ const resizeDrag = tryStartResize(cx, cy, editor)
if (resizeDrag) {
setDrag(resizeDrag)
return
}
- if (tryStartRotation(sx, sy)) return
-
const hit = resolveHit(cx, cy, editor, fns)
if (!hit) {
if (!editor.state.enteredContainerId) {
@@ -405,7 +410,6 @@ export function handleSelectDown(
setDrag(result.drag)
return
}
-
setDrag({
type: 'move',
startX: cx,
@@ -418,8 +422,6 @@ export function handleSelectDown(
}
export function updateHoverCursor(
- sx: number,
- sy: number,
cx: number,
cy: number,
editor: Editor,
@@ -435,21 +437,10 @@ export function updateHoverCursor(
for (const id of editor.state.selectedIds) {
const node = editor.graph.getNode(id)
if (!node) continue
- const abs = editor.graph.getAbsolutePosition(id)
- const handle = hitTestHandle(
- sx,
- sy,
- abs.x,
- abs.y,
- node.width,
- node.height,
- editor.state.zoom,
- editor.state.panX,
- editor.state.panY,
- node.rotation
- )
- if (handle) {
- cursor = HANDLE_CURSORS[handle]
+
+ const handHit = getHitHandleByMatrix(cx, cy, node, editor.graph, editor?.renderer?.zoom!)
+ if (handHit?.handle) {
+ cursor = buildResizeCursor(handHit?.rotation)
break
}
}
@@ -458,21 +449,16 @@ export function updateHoverCursor(
const id = [...editor.state.selectedIds][0]
const node = editor.graph.getNode(id)
if (node) {
- const abs = editor.graph.getAbsolutePosition(id)
- const corner = hitTestCornerRotation(
- sx,
- sy,
- abs.x,
- abs.y,
- node.width,
- node.height,
- editor.state.zoom,
- editor.state.panX,
- editor.state.panY,
- node.rotation
+ const corner = hitTestCornerRotationByMatrix(
+ cx,
+ cy,
+ node,
+ editor.graph,
+ editor?.renderer?.zoom!
)
if (corner) {
- cursor = cornerRotationCursor(corner, node.rotation)
+ const abRotation = getAbsoluteRotation(node, editor.graph)
+ cursor = cornerRotationCursor(corner, abRotation)
}
}
}
diff --git a/src/composables/use-keyboard.ts b/src/composables/use-keyboard.ts
index f306cfa05..913b66746 100644
--- a/src/composables/use-keyboard.ts
+++ b/src/composables/use-keyboard.ts
@@ -252,7 +252,9 @@ export function useKeyboard() {
// Mod
whenever(mod('backslash'), toggleUI)
whenever(mod('keyj'), toggleAI)
- whenever(mod('keyw'), () => { if (activeTabRef.value) closeTab(activeTabRef.value.id) })
+ whenever(mod('keyw'), () => {
+ if (activeTabRef.value) closeTab(activeTabRef.value.id)
+ })
whenever(mod('keyn'), () => createTab())
whenever(mod('keyt'), () => createTab())
whenever(mod('keyz'), () => runCommand('edit.undo'))
diff --git a/tests/e2e/app-menu.spec.ts b/tests/e2e/app-menu.spec.ts
index 61e770c29..a32e6e88e 100644
--- a/tests/e2e/app-menu.spec.ts
+++ b/tests/e2e/app-menu.spec.ts
@@ -93,9 +93,7 @@ test('Undo via Edit menu works', async () => {
await page.locator('[role="menu"] [role="menuitem"]', { hasText: 'Undo' }).click()
await canvas.waitForRender()
- const afterUndo = await page.evaluate(
- () => window.__OPEN_PENCIL_STORE__!.state.selectedIds.size
- )
+ const afterUndo = await page.evaluate(() => window.__OPEN_PENCIL_STORE__!.state.selectedIds.size)
expect(afterUndo).toBe(0)
})
diff --git a/tests/engine/hit-test-scope.test.ts b/tests/engine/hit-test-scope.test.ts
index 3d854f1ac..f4fc0ae3b 100644
--- a/tests/engine/hit-test-scope.test.ts
+++ b/tests/engine/hit-test-scope.test.ts
@@ -43,7 +43,7 @@ describe('hitTest — group behavior', () => {
test('hitTest with scope=group returns child', () => {
const { graph, group } = setup()
- const hit = graph.hitTest(10, 10, group.id)
+ const hit = graph.hitTest(110, 110, group.id)
expect(hit).not.toBeNull()
expect(hit!.name).toBe('Rect')
})
@@ -91,21 +91,21 @@ describe('hitTest — nested groups', () => {
test('click from page scope returns GroupA', () => {
const { graph, page } = setup()
- const hit = graph.hitTest(160, 160, page)
+ const hit = graph.hitTest(100, 100, page)
expect(hit).not.toBeNull()
expect(hit!.name).toBe('GroupA')
})
test('click with scope=GroupA returns GroupB', () => {
const { graph, groupA } = setup()
- const hit = graph.hitTest(60, 60, groupA.id)
+ const hit = graph.hitTest(150, 150, groupA.id)
expect(hit).not.toBeNull()
expect(hit!.name).toBe('GroupB')
})
test('click with scope=GroupB returns DeepRect', () => {
const { graph, groupB } = setup()
- const hit = graph.hitTest(10, 10, groupB.id)
+ const hit = graph.hitTest(160, 160, groupB.id)
expect(hit).not.toBeNull()
expect(hit!.name).toBe('DeepRect')
})
@@ -253,7 +253,7 @@ describe('hitTest — frame with children', () => {
height: 40
})
- const hit = graph.hitTest(20, 20, frame.id)
+ const hit = graph.hitTest(70, 70, frame.id)
expect(hit).not.toBeNull()
expect(hit!.id).toBe(child.id)
})
@@ -277,11 +277,13 @@ describe('hitTest — frame with children', () => {
height: 40
})
- const hitInside = graph.hitTest(100, 60, frame.id)
+ // point that is inside rotated frame bounds and child bounds
+ const hitInside = graph.hitTest(193, 111, frame.id)
expect(hitInside).not.toBeNull()
expect(hitInside!.id).toBe(child.id)
- const hitOutside = graph.hitTest(10, 10, frame.id)
+ // point that would be inside if frame were not rotated
+ const hitOutside = graph.hitTest(160, 130, frame.id)
expect(hitOutside).toBeNull()
})
})
@@ -374,7 +376,7 @@ describe('hitTest — opaque containers (COMPONENT/INSTANCE)', () => {
height: 20
})
- const hit = graph.hitTestDeep(5, 5, inst.id)
+ const hit = graph.hitTestDeep(55, 55, inst.id)
expect(hit).not.toBeNull()
expect(hit!.id).toBe(child.id)
})
@@ -402,12 +404,15 @@ describe('hitTest — absolute position and scope offset', () => {
const abs = graph.getAbsolutePosition(frame.id)
expect(abs.x).toBe(200)
expect(abs.y).toBe(300)
+ const abs2 = graph.getAbsolutePosition(child.id)
+ expect(abs2.x).toBe(250)
+ expect(abs2.y).toBe(360)
- const hit = graph.hitTest(50, 60, frame.id)
+ const hit = graph.hitTest(250, 360, frame.id)
expect(hit).not.toBeNull()
expect(hit!.id).toBe(child.id)
- const missHit = graph.hitTest(250, 360, frame.id)
+ const missHit = graph.hitTest(50, 60, frame.id)
expect(missHit).toBeNull()
})
})
diff --git a/tests/engine/scene-graph.test.ts b/tests/engine/scene-graph.test.ts
index 5429ce278..9c9753bd0 100644
--- a/tests/engine/scene-graph.test.ts
+++ b/tests/engine/scene-graph.test.ts
@@ -30,11 +30,17 @@ describe('SceneGraph', () => {
test('reparent into frame', () => {
const graph = new SceneGraph()
- const frame = graph.createNode('FRAME', pageId(graph), { name: 'F', x: 50, y: 50, width: 400, height: 400 }).id
+ const frame = graph.createNode('FRAME', pageId(graph), {
+ name: 'F',
+ x: 50,
+ y: 50,
+ width: 400,
+ height: 400
+ }).id
const r = rect(graph, 'R', 100, 100)
graph.reparentNode(r, frame)
const children = graph.getChildren(frame)
- expect(children.map(c => c.id)).toContain(r)
+ expect(children.map((c) => c.id)).toContain(r)
})
test('children order', () => {
@@ -42,7 +48,7 @@ describe('SceneGraph', () => {
rect(graph, 'A')
rect(graph, 'B')
rect(graph, 'C')
- const names = graph.getChildren(pageId(graph)).map(n => n.name)
+ const names = graph.getChildren(pageId(graph)).map((n) => n.name)
expect(names).toEqual(['A', 'B', 'C'])
})
@@ -69,7 +75,11 @@ describe('SceneGraph', () => {
test('create instance clones children with componentId mapping', () => {
const graph = new SceneGraph()
- const comp = graph.createNode('COMPONENT', pageId(graph), { name: 'Btn', width: 100, height: 40 })
+ const comp = graph.createNode('COMPONENT', pageId(graph), {
+ name: 'Btn',
+ width: 100,
+ height: 40
+ })
const child = graph.createNode('RECTANGLE', comp.id, { name: 'BG', width: 100, height: 40 })
const instance = graph.createInstance(comp.id, pageId(graph))!
expect(instance.type).toBe('INSTANCE')
@@ -82,7 +92,11 @@ describe('SceneGraph', () => {
test('syncInstances propagates changes from component to instance', () => {
const graph = new SceneGraph()
- const comp = graph.createNode('COMPONENT', pageId(graph), { name: 'Card', width: 200, height: 100 })
+ const comp = graph.createNode('COMPONENT', pageId(graph), {
+ name: 'Card',
+ width: 200,
+ height: 100
+ })
const label = graph.createNode('TEXT', comp.id, { name: 'Title', text: 'Hello', fontSize: 14 })
const instance = graph.createInstance(comp.id, pageId(graph))!
const instLabel = graph.getChildren(instance.id)[0]
@@ -97,7 +111,11 @@ describe('SceneGraph', () => {
test('syncInstances preserves overrides', () => {
const graph = new SceneGraph()
- const comp = graph.createNode('COMPONENT', pageId(graph), { name: 'Card', width: 200, height: 100 })
+ const comp = graph.createNode('COMPONENT', pageId(graph), {
+ name: 'Card',
+ width: 200,
+ height: 100
+ })
graph.createNode('TEXT', comp.id, { name: 'Title', text: 'Default', fontSize: 14 })
const instance = graph.createInstance(comp.id, pageId(graph))!
const instLabel = graph.getChildren(instance.id)[0]
@@ -117,7 +135,11 @@ describe('SceneGraph', () => {
test('syncInstances adds new children from component', () => {
const graph = new SceneGraph()
- const comp = graph.createNode('COMPONENT', pageId(graph), { name: 'Card', width: 200, height: 100 })
+ const comp = graph.createNode('COMPONENT', pageId(graph), {
+ name: 'Card',
+ width: 200,
+ height: 100
+ })
graph.createNode('RECTANGLE', comp.id, { name: 'BG' })
const instance = graph.createInstance(comp.id, pageId(graph))!
expect(graph.getChildren(instance.id)).toHaveLength(1)
@@ -133,7 +155,11 @@ describe('SceneGraph', () => {
test('detachInstance breaks link', () => {
const graph = new SceneGraph()
- const comp = graph.createNode('COMPONENT', pageId(graph), { name: 'Btn', width: 100, height: 40 })
+ const comp = graph.createNode('COMPONENT', pageId(graph), {
+ name: 'Btn',
+ width: 100,
+ height: 40
+ })
graph.createNode('RECTANGLE', comp.id, { name: 'BG' })
const instance = graph.createInstance(comp.id, pageId(graph))!
expect(instance.type).toBe('INSTANCE')
@@ -344,7 +370,11 @@ describe('hitTest', () => {
const graph = new SceneGraph()
graph.createNode('FRAME', pageId(graph), {
name: 'Empty Frame',
- x: 0, y: 0, width: 200, height: 200, fills: [],
+ x: 0,
+ y: 0,
+ width: 200,
+ height: 200,
+ fills: []
})
expect(graph.hitTest(100, 100, pageId(graph))).toBeNull()
})
@@ -353,8 +383,19 @@ describe('hitTest', () => {
const graph = new SceneGraph()
const frame = graph.createNode('FRAME', pageId(graph), {
name: 'Filled Frame',
- x: 0, y: 0, width: 200, height: 200,
- fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true, blendMode: 'NORMAL' }],
+ x: 0,
+ y: 0,
+ width: 200,
+ height: 200,
+ fills: [
+ {
+ type: 'SOLID',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ blendMode: 'NORMAL'
+ }
+ ]
})
expect(graph.hitTest(100, 100, pageId(graph))?.id).toBe(frame.id)
})
@@ -362,25 +403,42 @@ describe('hitTest', () => {
test('group returns group on hit, not child (Figma-style)', () => {
const graph = new SceneGraph()
const groupId = graph.createNode('GROUP', pageId(graph), {
- name: 'Group', x: 0, y: 0, width: 200, height: 200,
+ name: 'Group',
+ x: 0,
+ y: 0,
+ width: 200,
+ height: 200
}).id
graph.createNode('RECTANGLE', groupId, {
- name: 'Child', x: 10, y: 10, width: 30, height: 30,
+ name: 'Child',
+ x: 10,
+ y: 10,
+ width: 30,
+ height: 30
})
// Hit returns group (single click selects group, dblclick enters)
expect(graph.hitTest(20, 20, pageId(graph))?.id).toBe(groupId)
// Miss in group's empty area
- expect(graph.hitTest(150, 150, pageId(graph))).toBeNull()
+ expect(graph.hitTest(201, 200, pageId(graph))).toBeNull()
})
test('clipsContent prevents hits outside parent bounds', () => {
const graph = new SceneGraph()
const frame = graph.createNode('FRAME', pageId(graph), {
- name: 'Clip Frame', x: 0, y: 0, width: 100, height: 100,
- clipsContent: true, fills: [],
+ name: 'Clip Frame',
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 100,
+ clipsContent: true,
+ fills: []
})
const childId = graph.createNode('RECTANGLE', frame.id, {
- name: 'Overflow Child', x: 50, y: 50, width: 200, height: 200,
+ name: 'Overflow Child',
+ x: 50,
+ y: 50,
+ width: 200,
+ height: 200
}).id
// Inside both frame and child — hit
expect(graph.hitTest(75, 75, pageId(graph))?.id).toBe(childId)
@@ -391,10 +449,19 @@ describe('hitTest', () => {
test('instance without fills is click-through in empty area', () => {
const graph = new SceneGraph()
const compId = graph.createNode('COMPONENT', pageId(graph), {
- name: 'Comp', x: 0, y: 0, width: 200, height: 200, fills: [],
+ name: 'Comp',
+ x: 0,
+ y: 0,
+ width: 200,
+ height: 200,
+ fills: []
}).id
graph.createNode('RECTANGLE', compId, {
- name: 'Inner', x: 10, y: 10, width: 30, height: 30,
+ name: 'Inner',
+ x: 10,
+ y: 10,
+ width: 30,
+ height: 30
})
const instId = graph.createInstance(compId, pageId(graph), { x: 300, y: 0 }).id
// Hit on instance's child area — returns instance (opaque container)