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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. previous: number[]
  11. points: number[][]
  12. snapshot: DrawSnapshot
  13. constructor(data: Data, id: string, point: number[]) {
  14. super(data)
  15. this.origin = point
  16. this.previous = point
  17. this.points = []
  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 { snapshot } = this
  25. const lp = vec.med(this.previous, vec.toPrecision(point))
  26. this.points.push(vec.sub(lp, this.origin))
  27. this.previous = lp
  28. const page = getPage(data)
  29. const shape = page.shapes[snapshot.id] as DrawShape
  30. getShapeUtils(shape).setProperty(shape, 'points', [...this.points])
  31. }
  32. cancel = (data: Data) => {
  33. const { snapshot } = this
  34. const page = getPage(data)
  35. const shape = page.shapes[snapshot.id] as DrawShape
  36. getShapeUtils(shape).setProperty(shape, 'points', snapshot.points)
  37. }
  38. complete = (data: Data) => {
  39. commands.draw(data, this.snapshot.id, this.points)
  40. }
  41. }
  42. export function getDrawSnapshot(data: Data, shapeId: string) {
  43. const page = getPage(current(data))
  44. const { points, style } = page.shapes[shapeId] as DrawShape
  45. return {
  46. id: shapeId,
  47. points,
  48. strokeWidth: style.strokeWidth,
  49. }
  50. }
  51. export type DrawSnapshot = ReturnType<typeof getDrawSnapshot>