tldraw/state/sessions/direction-session.ts

70 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-06-29 12:00:59 +00:00
import { Data, Shape } from 'types'
import vec from 'utils/vec'
import BaseSession from './base-session'
import commands from 'state/commands'
2021-06-29 12:00:59 +00:00
import tld from 'utils/tld'
import { deepClone } from 'utils'
import { getShapeUtils } from 'state/shape-utils'
2021-05-15 15:20:21 +00:00
export default class DirectionSession extends BaseSession {
delta = [0, 0]
origin: number[]
snapshot: DirectionSnapshot
constructor(data: Data, point: number[]) {
super(data)
this.origin = point
this.snapshot = getDirectionSnapshot(data)
}
2021-06-21 21:35:28 +00:00
update(data: Data, point: number[]): void {
2021-06-29 12:00:59 +00:00
const page = tld.getPage(data)
2021-06-29 12:00:59 +00:00
this.snapshot.forEach((initialShape) => {
const shape = page.shapes[initialShape.id]
2021-05-15 15:20:21 +00:00
2021-06-29 12:00:59 +00:00
if ('direction' in shape) {
getShapeUtils(shape).setProperty(
shape,
'direction',
vec.uni(vec.vec(shape.point, point))
)
}
})
2021-05-15 15:20:21 +00:00
}
2021-06-21 21:35:28 +00:00
cancel(data: Data): void {
2021-06-29 12:00:59 +00:00
const page = tld.getPage(data)
this.snapshot.forEach((initialShape) => {
const shape = page.shapes[initialShape.id]
2021-05-15 15:20:21 +00:00
2021-06-29 12:00:59 +00:00
if ('direction' in shape && 'direction' in initialShape) {
getShapeUtils(shape).setProperty(
shape,
'direction',
initialShape.direction
)
}
})
2021-05-15 15:20:21 +00:00
}
2021-06-21 21:35:28 +00:00
complete(data: Data): void {
2021-06-29 12:00:59 +00:00
commands.mutate(
data,
this.snapshot,
getDirectionSnapshot(data),
'change_direction'
)
2021-05-15 15:20:21 +00:00
}
}
2021-06-29 12:00:59 +00:00
export function getDirectionSnapshot(data: Data): Shape[] {
return tld
.getSelectedShapes(data)
.filter((shape) => 'direction' in shape)
.map((shape) => deepClone(shape))
2021-05-15 15:20:21 +00:00
}
export type DirectionSnapshot = ReturnType<typeof getDirectionSnapshot>