tldraw/lib/code/index.ts

72 lines
1.5 KiB
TypeScript
Raw Normal View History

2021-06-02 15:05:44 +00:00
import { Shape } from 'types'
2021-05-25 09:09:51 +00:00
import shapeUtilityMap, {
createShape,
getShapeUtils,
ShapeUtility,
2021-06-02 15:05:44 +00:00
} from 'lib/shape-utils'
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>>([])
/**
* 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
2021-05-25 09:09:51 +00:00
private utils: ShapeUtility<T>
2021-05-14 22:56:41 +00:00
constructor(props: T) {
2021-06-04 16:14:01 +00:00
this._shape = createShape(props.type, props) as T
2021-05-25 09:09:51 +00:00
this.utils = getShapeUtils<T>(this._shape)
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) {
2021-06-02 15:05:44 +00:00
this.utils.setProperty(this._shape, 'point', vectorToPoint(point))
return this
2021-05-14 22:56:41 +00:00
}
2021-05-17 10:01:11 +00:00
translate(delta: Vector) {
2021-06-02 15:05:44 +00:00
this.utils.setProperty(
this._shape,
2021-06-02 15:05:44 +00:00
'point',
vec.add(this._shape.point, vectorToPoint(delta))
)
return this
2021-05-14 22:56:41 +00:00
}
rotate(rotation: number) {
2021-06-02 15:05:44 +00:00
this.utils.setProperty(this._shape, 'rotation', rotation)
return this
2021-05-14 22:56:41 +00:00
}
getBounds() {
this.utils.getBounds(this.shape)
return this
2021-05-14 22:56:41 +00:00
}
2021-05-17 10:01:11 +00:00
hitTest(point: Vector) {
this.utils.hitTest(this.shape, vectorToPoint(point))
return this
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
}
}