tldraw/lib/shapes/rectangle.tsx

95 lines
1.8 KiB
TypeScript
Raw Normal View History

2021-05-12 21:11:17 +00:00
import { v4 as uuid } from "uuid"
import * as vec from "utils/vec"
2021-05-13 18:22:16 +00:00
import { RectangleShape, ShapeType } from "types"
2021-05-14 12:44:23 +00:00
import { createShape } from "./index"
2021-05-13 18:22:16 +00:00
import { boundsContained, boundsCollide } from "utils/bounds"
2021-05-12 21:11:17 +00:00
2021-05-13 18:22:16 +00:00
const rectangle = createShape<RectangleShape>({
2021-05-14 12:44:23 +00:00
boundsCache: new WeakMap([]),
2021-05-13 18:22:16 +00:00
create(props) {
2021-05-12 21:11:17 +00:00
return {
id: uuid(),
type: ShapeType.Rectangle,
2021-05-15 13:02:13 +00:00
isGenerated: false,
2021-05-12 21:11:17 +00:00
name: "Rectangle",
parentId: "page0",
childIndex: 0,
point: [0, 0],
size: [1, 1],
rotation: 0,
style: {},
...props,
}
},
render({ id, size }) {
return <rect id={id} width={size[0]} height={size[1]} />
},
getBounds(shape) {
2021-05-14 12:44:23 +00:00
if (this.boundsCache.has(shape)) {
return this.boundsCache.get(shape)
2021-05-12 22:08:53 +00:00
}
2021-05-12 21:11:17 +00:00
const {
point: [x, y],
size: [width, height],
} = shape
2021-05-12 22:08:53 +00:00
const bounds = {
2021-05-12 21:11:17 +00:00
minX: x,
maxX: x + width,
minY: y,
maxY: y + height,
width,
height,
}
2021-05-12 22:08:53 +00:00
2021-05-14 12:44:23 +00:00
this.boundsCache.set(shape, bounds)
2021-05-12 22:08:53 +00:00
return bounds
2021-05-12 21:11:17 +00:00
},
hitTest(shape) {
return true
},
2021-05-13 18:22:16 +00:00
hitTestBounds(shape, brushBounds) {
const shapeBounds = this.getBounds(shape)
return (
boundsContained(shapeBounds, brushBounds) ||
boundsCollide(shapeBounds, brushBounds)
)
},
2021-05-12 21:11:17 +00:00
rotate(shape) {
return shape
},
2021-05-13 06:44:52 +00:00
translate(shape, delta) {
shape.point = vec.add(shape.point, delta)
2021-05-12 21:11:17 +00:00
return shape
},
2021-05-13 18:22:16 +00:00
scale(shape, scale) {
2021-05-12 21:11:17 +00:00
return shape
},
2021-05-13 18:22:16 +00:00
stretch(shape, scaleX, scaleY) {
2021-05-14 12:44:23 +00:00
shape.size = vec.mulV(shape.size, [scaleX, scaleY])
return shape
},
transform(shape, bounds) {
shape.point = [bounds.minX, bounds.minY]
shape.size = [bounds.width, bounds.height]
2021-05-12 21:11:17 +00:00
return shape
},
2021-05-15 13:02:13 +00:00
canTransform: true,
2021-05-13 18:22:16 +00:00
})
2021-05-12 21:11:17 +00:00
2021-05-13 18:22:16 +00:00
export default rectangle