You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

draw-session.ts 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { current } from "immer"
  2. import { Data, DrawShape } from "types"
  3. import BaseSession from "./base-session"
  4. import { getShapeUtils } from "lib/shape-utils"
  5. import { getPage, simplify } from "utils/utils"
  6. import * as vec from "utils/vec"
  7. import commands from "state/commands"
  8. export default class BrushSession extends BaseSession {
  9. origin: number[]
  10. points: number[][]
  11. snapshot: DrawSnapshot
  12. shapeId: string
  13. constructor(data: Data, id: string, point: number[]) {
  14. super(data)
  15. this.shapeId = id
  16. this.origin = point
  17. this.points = [[0, 0]]
  18. this.snapshot = getDrawSnapshot(data, id)
  19. const page = getPage(data)
  20. const shape = page.shapes[id]
  21. getShapeUtils(shape).translateTo(shape, point)
  22. }
  23. update = (data: Data, point: number[]) => {
  24. const { shapeId } = this
  25. this.points.push(vec.sub(point, this.origin))
  26. const page = getPage(data)
  27. const shape = page.shapes[shapeId]
  28. getShapeUtils(shape).setPoints!(shape, [...this.points])
  29. }
  30. cancel = (data: Data) => {
  31. const { shapeId, snapshot } = this
  32. const page = getPage(data)
  33. const shape = page.shapes[shapeId]
  34. getShapeUtils(shape).setPoints!(shape, snapshot.points)
  35. }
  36. complete = (data: Data) => {
  37. commands.points(
  38. data,
  39. this.shapeId,
  40. this.snapshot.points,
  41. simplify(this.points, 1).map(([x, y]) => [
  42. Math.trunc(x * 100) / 100,
  43. Math.trunc(y * 100) / 100,
  44. ])
  45. )
  46. }
  47. }
  48. export function getDrawSnapshot(data: Data, shapeId: string) {
  49. const page = getPage(current(data))
  50. const { points } = page.shapes[shapeId] as DrawShape
  51. return {
  52. points,
  53. }
  54. }
  55. export type DrawSnapshot = ReturnType<typeof getDrawSnapshot>