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.

handle-session.ts 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { Data, Shape } from 'types'
  2. import vec from 'utils/vec'
  3. import BaseSession from './base-session'
  4. import commands from 'state/commands'
  5. import tld from 'utils/tld'
  6. import { getShapeUtils } from 'state/shape-utils'
  7. import { deepClone } from 'utils'
  8. export default class HandleSession extends BaseSession {
  9. delta = [0, 0]
  10. origin: number[]
  11. shiftKey: boolean
  12. initialShape: Shape
  13. handleId: string
  14. isCreating: boolean
  15. constructor(
  16. data: Data,
  17. shapeId: string,
  18. handleId: string,
  19. point: number[],
  20. isCreating: boolean
  21. ) {
  22. super(data)
  23. this.origin = point
  24. this.handleId = handleId
  25. this.initialShape = deepClone(tld.getShape(data, shapeId))
  26. this.isCreating = isCreating
  27. }
  28. update(
  29. data: Data,
  30. point: number[],
  31. shiftKey: boolean,
  32. altKey: boolean,
  33. metaKey: boolean
  34. ): void {
  35. const shape = tld.getPage(data).shapes[this.initialShape.id]
  36. this.shiftKey = shiftKey
  37. const delta = vec.vec(this.origin, point)
  38. const handles = this.initialShape.handles
  39. getShapeUtils(shape).onHandleChange(
  40. shape,
  41. {
  42. [this.handleId]: {
  43. ...handles[this.handleId],
  44. point: vec.round(vec.add(handles[this.handleId].point, delta)), // vec.rot(delta, shape.rotation)),
  45. },
  46. },
  47. { delta, shiftKey, altKey, metaKey }
  48. )
  49. }
  50. cancel(data: Data): void {
  51. if (this.isCreating) {
  52. tld.deleteShapes(data, [this.initialShape])
  53. } else {
  54. tld.getPage(data).shapes[this.initialShape.id] = this.initialShape
  55. }
  56. }
  57. complete(data: Data): void {
  58. const before = this.initialShape
  59. const after = deepClone(tld.getShape(data, before.id))
  60. if (this.isCreating) {
  61. commands.createShapes(data, [after])
  62. } else {
  63. commands.mutate(data, [before], [after])
  64. }
  65. }
  66. }
  67. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  68. export function getHandleSnapshot(data: Data, shapeId: string) {
  69. return deepClone(tld.getShape(data, shapeId))
  70. }
  71. export type HandleSnapshot = ReturnType<typeof getHandleSnapshot>