tldraw/lib/code/index.ts

65 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-05-14 22:56:41 +00:00
import { Shape } from "types"
2021-05-20 09:49:40 +00:00
import { getShapeUtils } from "lib/shape-utils"
2021-05-17 10:01:11 +00:00
import * as vec from "utils/vec"
import Vector from "./vector"
import { vectorToPoint } from "utils/utils"
2021-05-14 22:56:41 +00:00
2021-05-15 13:02:13 +00:00
export const codeShapes = new Set<CodeShape<Shape>>([])
2021-05-17 10:01:11 +00:00
type WithVectors<T extends Shape> = {
[key in keyof T]: number[] extends T[key] ? Vector : T[key]
}
2021-05-15 13:02:13 +00:00
/**
* A base class for code shapes. Note that creating a shape adds it to the
* shape map, while deleting it removes it from the collected shapes set
*/
2021-05-14 22:56:41 +00:00
export default class CodeShape<T extends Shape> {
private _shape: T
constructor(props: T) {
this._shape = props
2021-05-15 13:02:13 +00:00
codeShapes.add(this)
2021-05-14 22:56:41 +00:00
}
destroy() {
2021-05-15 13:02:13 +00:00
codeShapes.delete(this)
2021-05-14 22:56:41 +00:00
}
2021-05-17 10:01:11 +00:00
moveTo(point: Vector) {
this.shape.point = vectorToPoint(point)
2021-05-14 22:56:41 +00:00
}
2021-05-17 10:01:11 +00:00
translate(delta: Vector) {
this.shape.point = vec.add(this._shape.point, vectorToPoint(delta))
2021-05-14 22:56:41 +00:00
}
rotate(rotation: number) {
this.shape.rotation = rotation
}
scale(scale: number) {
return getShapeUtils(this.shape).scale(this.shape, scale)
}
getBounds() {
return getShapeUtils(this.shape).getBounds(this.shape)
}
2021-05-17 10:01:11 +00:00
hitTest(point: Vector) {
return getShapeUtils(this.shape).hitTest(this.shape, vectorToPoint(point))
2021-05-14 22:56:41 +00:00
}
get shape() {
return this._shape
}
get point() {
return [...this.shape.point]
}
get rotation() {
return this.shape.rotation
}
}