tldraw/state/commands/stretch.ts

85 lines
2.8 KiB
TypeScript
Raw Normal View History

2021-05-26 19:20:52 +00:00
import Command from "./command"
import history from "../history"
2021-05-27 06:32:55 +00:00
import { StretchType, Data, Edge, Corner } from "types"
import { getCommonBounds, getPage, getSelectedShapes } from "utils/utils"
2021-05-26 19:20:52 +00:00
import { getShapeUtils } from "lib/shape-utils"
2021-05-27 06:32:55 +00:00
import { current } from "immer"
2021-05-26 19:20:52 +00:00
export default function stretchCommand(data: Data, type: StretchType) {
const { currentPageId } = data
2021-05-27 06:32:55 +00:00
const initialShapes = getSelectedShapes(current(data))
const entries = initialShapes.map(
(shape) => [shape.id, getShapeUtils(shape).getBounds(shape)] as const
2021-05-26 19:20:52 +00:00
)
2021-05-27 06:32:55 +00:00
const boundsForShapes = Object.fromEntries(entries)
const commonBounds = getCommonBounds(...entries.map((entry) => entry[1]))
2021-05-26 19:20:52 +00:00
history.execute(
data,
new Command({
2021-05-27 06:32:55 +00:00
name: "stretched",
2021-05-26 19:20:52 +00:00
category: "canvas",
do(data) {
const { shapes } = getPage(data, currentPageId)
switch (type) {
case StretchType.Horizontal: {
2021-05-27 06:32:55 +00:00
for (let id in boundsForShapes) {
const initialShape = initialShapes[id]
const shape = shapes[id]
const oldBounds = boundsForShapes[id]
const newBounds = { ...oldBounds }
newBounds.minX = commonBounds.minX
newBounds.width = commonBounds.width
newBounds.maxX = commonBounds.maxX
getShapeUtils(shape).transform(shape, newBounds, {
type: Corner.TopLeft,
scaleX: newBounds.width / oldBounds.width,
scaleY: 1,
initialShape,
transformOrigin: [0.5, 0.5],
})
}
break
2021-05-26 19:20:52 +00:00
}
case StretchType.Vertical: {
2021-05-27 06:32:55 +00:00
for (let id in boundsForShapes) {
const initialShape = initialShapes[id]
const shape = shapes[id]
const oldBounds = boundsForShapes[id]
const newBounds = { ...oldBounds }
newBounds.minY = commonBounds.minY
newBounds.height = commonBounds.height
newBounds.maxY = commonBounds.maxY
getShapeUtils(shape).transform(shape, newBounds, {
type: Corner.TopLeft,
scaleX: 1,
scaleY: newBounds.height / oldBounds.height,
initialShape,
transformOrigin: [0.5, 0.5],
})
}
2021-05-26 19:20:52 +00:00
}
}
},
undo(data) {
const { shapes } = getPage(data, currentPageId)
2021-05-27 06:32:55 +00:00
for (let id in boundsForShapes) {
2021-05-26 19:20:52 +00:00
const shape = shapes[id]
2021-05-27 06:32:55 +00:00
const initialShape = initialShapes[id]
const initialBounds = boundsForShapes[id]
getShapeUtils(shape).transform(shape, initialBounds, {
type: Corner.BottomRight,
scaleX: 1,
scaleY: 1,
initialShape,
transformOrigin: [0.5, 0.5],
})
2021-05-26 19:20:52 +00:00
}
},
})
)
}