tldraw/state/sessions/direction-session.ts

64 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-05-15 15:20:21 +00:00
import { Data, LineShape, RayShape } from "types"
import * as vec from "utils/vec"
import BaseSession from "./base-session"
import commands from "state/commands"
import { current } from "immer"
import { getPage } from "utils/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)
}
update(data: Data, point: number[]) {
const { shapes } = this.snapshot
const page = getPage(data)
2021-05-15 15:20:21 +00:00
for (let { id } of shapes) {
const shape = page.shapes[id] as RayShape | LineShape
2021-05-15 15:20:21 +00:00
shape.direction = vec.uni(vec.vec(shape.point, point))
}
}
cancel(data: Data) {
const page = getPage(data, this.snapshot.currentPageId)
2021-05-15 15:20:21 +00:00
for (let { id, direction } of this.snapshot.shapes) {
const shape = page.shapes[id] as RayShape | LineShape
2021-05-15 15:20:21 +00:00
shape.direction = direction
}
}
complete(data: Data) {
2021-05-17 21:27:18 +00:00
commands.direct(data, this.snapshot, getDirectionSnapshot(data))
2021-05-15 15:20:21 +00:00
}
}
export function getDirectionSnapshot(data: Data) {
const { shapes } = getPage(current(data))
2021-05-15 15:20:21 +00:00
let snapshapes: { id: string; direction: number[] }[] = []
data.selectedIds.forEach((id) => {
const shape = shapes[id]
if ("direction" in shape) {
snapshapes.push({ id: shape.id, direction: shape.direction })
}
})
return {
currentPageId: data.currentPageId,
2021-05-15 15:20:21 +00:00
shapes: snapshapes,
}
}
export type DirectionSnapshot = ReturnType<typeof getDirectionSnapshot>