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.

state.ts 53KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822
  1. import { createSelectorHook, createState } from '@state-designer/react'
  2. import { updateFromCode } from './code/generate'
  3. import { createShape, getShapeUtils } from './shape-utils'
  4. import vec from 'utils/vec'
  5. import inputs from './inputs'
  6. import history from './history'
  7. import storage from './storage'
  8. import clipboard from './clipboard'
  9. import * as Sessions from './sessions'
  10. import commands from './commands'
  11. import {
  12. getChildren,
  13. getCommonBounds,
  14. getCurrent,
  15. getCurrentCamera,
  16. getPage,
  17. getSelectedBounds,
  18. getSelectedShapes,
  19. getShape,
  20. screenToWorld,
  21. setZoomCSS,
  22. rotateBounds,
  23. getBoundsCenter,
  24. getDocumentBranch,
  25. getCameraZoom,
  26. getSelectedIds,
  27. setSelectedIds,
  28. getPageState,
  29. setToArray,
  30. } from 'utils/utils'
  31. import {
  32. Data,
  33. PointerInfo,
  34. Shape,
  35. ShapeType,
  36. Corner,
  37. Edge,
  38. CodeControl,
  39. MoveType,
  40. ShapeStyles,
  41. DistributeType,
  42. AlignType,
  43. StretchType,
  44. DashStyle,
  45. SizeStyle,
  46. ColorStyle,
  47. } from 'types'
  48. import session from './session'
  49. import { pointInBounds } from 'utils/hitTests'
  50. const initialData: Data = {
  51. isReadOnly: false,
  52. settings: {
  53. fontSize: 13,
  54. isDarkMode: false,
  55. isCodeOpen: false,
  56. isStyleOpen: false,
  57. isToolLocked: false,
  58. isPenLocked: false,
  59. nudgeDistanceLarge: 10,
  60. nudgeDistanceSmall: 1,
  61. },
  62. currentStyle: {
  63. size: SizeStyle.Medium,
  64. color: ColorStyle.Black,
  65. dash: DashStyle.Solid,
  66. isFilled: false,
  67. },
  68. activeTool: 'select',
  69. brush: undefined,
  70. boundsRotation: 0,
  71. pointedId: null,
  72. hoveredId: null,
  73. editingId: null,
  74. currentPageId: 'page1',
  75. currentParentId: 'page1',
  76. currentCodeFileId: 'file0',
  77. codeControls: {},
  78. document: {
  79. id: '0001',
  80. name: 'My Document',
  81. pages: {
  82. page1: {
  83. id: 'page1',
  84. type: 'page',
  85. name: 'Page 1',
  86. childIndex: 0,
  87. shapes: {},
  88. },
  89. },
  90. code: {
  91. file0: {
  92. id: 'file0',
  93. name: 'index.ts',
  94. code: ``,
  95. },
  96. },
  97. },
  98. pageStates: {
  99. page1: {
  100. id: 'page1',
  101. selectedIds: new Set([]),
  102. camera: {
  103. point: [0, 0],
  104. zoom: 1,
  105. },
  106. },
  107. },
  108. }
  109. const state = createState({
  110. data: initialData,
  111. on: {
  112. UNMOUNTED: { to: 'loading' },
  113. },
  114. initial: 'loading',
  115. states: {
  116. loading: {
  117. on: {
  118. MOUNTED: {
  119. do: 'restoreSavedData',
  120. to: 'ready',
  121. },
  122. },
  123. },
  124. ready: {
  125. onEnter: {
  126. wait: 0.01,
  127. if: 'hasSelection',
  128. do: 'zoomCameraToSelectionActual',
  129. else: ['zoomCameraToActual'],
  130. },
  131. on: {
  132. COPIED: { if: 'hasSelection', do: 'copyToClipboard' },
  133. PASTED: { do: 'pasteFromClipboard' },
  134. PASTED_SHAPES_FROM_CLIPBOARD: 'pasteShapesFromClipboard',
  135. LOADED_FONTS: 'resetShapes',
  136. TOGGLED_SHAPE_LOCK: { if: 'hasSelection', do: 'lockSelection' },
  137. TOGGLED_SHAPE_HIDE: { if: 'hasSelection', do: 'hideSelection' },
  138. TOGGLED_SHAPE_ASPECT_LOCK: {
  139. if: 'hasSelection',
  140. do: 'aspectLockSelection',
  141. },
  142. TOGGLED_CODE_PANEL_OPEN: 'toggleCodePanel',
  143. TOGGLED_STYLE_PANEL_OPEN: 'toggleStylePanel',
  144. POINTED_CANVAS: ['closeStylePanel', 'clearCurrentParentId'],
  145. CHANGED_STYLE: ['updateStyles', 'applyStylesToSelection'],
  146. USED_PEN_DEVICE: 'enablePenLock',
  147. DISABLED_PEN_LOCK: 'disablePenLock',
  148. CLEARED_PAGE: {
  149. if: 'hasSelection',
  150. do: 'deleteSelection',
  151. else: ['selectAll', 'deleteSelection'],
  152. },
  153. SELECTED_ALL: { to: 'selecting', do: 'selectAll' },
  154. CHANGED_PAGE: 'changePage',
  155. CREATED_PAGE: ['clearSelectedIds', 'createPage'],
  156. DELETED_PAGE: { unless: 'hasOnlyOnePage', do: 'deletePage' },
  157. LOADED_FROM_FILE: ['loadDocumentFromJson', 'resetHistory'],
  158. PANNED_CAMERA: 'panCamera',
  159. SELECTED_SELECT_TOOL: { to: 'selecting' },
  160. SELECTED_DRAW_TOOL: { unless: 'isReadOnly', to: 'draw' },
  161. SELECTED_ARROW_TOOL: { unless: 'isReadOnly', to: 'arrow' },
  162. SELECTED_DOT_TOOL: { unless: 'isReadOnly', to: 'dot' },
  163. SELECTED_ELLIPSE_TOOL: { unless: 'isReadOnly', to: 'ellipse' },
  164. SELECTED_RAY_TOOL: { unless: 'isReadOnly', to: 'ray' },
  165. SELECTED_LINE_TOOL: { unless: 'isReadOnly', to: 'line' },
  166. SELECTED_POLYLINE_TOOL: { unless: 'isReadOnly', to: 'polyline' },
  167. SELECTED_RECTANGLE_TOOL: { unless: 'isReadOnly', to: 'rectangle' },
  168. SELECTED_TEXT_TOOL: { unless: 'isReadOnly', to: 'text' },
  169. },
  170. initial: 'selecting',
  171. states: {
  172. selecting: {
  173. onEnter: ['setActiveToolSelect', 'clearInputs'],
  174. on: {
  175. UNDO: 'undo',
  176. REDO: 'redo',
  177. SAVED: 'forceSave',
  178. LOADED_FROM_FILE_STSTEM: 'loadFromFileSystem',
  179. SAVED_TO_FILESYSTEM: 'saveToFileSystem',
  180. SAVED_AS_TO_FILESYSTEM: 'saveAsToFileSystem',
  181. SAVED_CODE: 'saveCode',
  182. DELETED: 'deleteSelection',
  183. INCREASED_CODE_FONT_SIZE: 'increaseCodeFontSize',
  184. DECREASED_CODE_FONT_SIZE: 'decreaseCodeFontSize',
  185. CHANGED_CODE_CONTROL: 'updateControls',
  186. GENERATED_FROM_CODE: ['setCodeControls', 'setGeneratedShapes'],
  187. TOGGLED_TOOL_LOCK: 'toggleToolLock',
  188. MOVED_TO_PAGE: {
  189. if: 'hasSelection',
  190. do: ['moveSelectionToPage', 'zoomCameraToSelectionActual'],
  191. },
  192. MOVED: { if: 'hasSelection', do: 'moveSelection' },
  193. DUPLICATED: { if: 'hasSelection', do: 'duplicateSelection' },
  194. ROTATED_CCW: { if: 'hasSelection', do: 'rotateSelectionCcw' },
  195. ALIGNED: { if: 'hasMultipleSelection', do: 'alignSelection' },
  196. STRETCHED: { if: 'hasMultipleSelection', do: 'stretchSelection' },
  197. DISTRIBUTED: {
  198. if: 'hasMultipleSelection',
  199. do: 'distributeSelection',
  200. },
  201. GROUPED: { if: 'hasMultipleSelection', do: 'groupSelection' },
  202. UNGROUPED: {
  203. if: ['hasSelection', 'selectionIncludesGroups'],
  204. do: 'ungroupSelection',
  205. },
  206. NUDGED: { do: 'nudgeSelection' },
  207. ZOOMED_CAMERA: {
  208. do: 'zoomCamera',
  209. },
  210. ZOOMED_TO_ACTUAL: {
  211. if: 'hasSelection',
  212. do: 'zoomCameraToSelectionActual',
  213. else: 'zoomCameraToActual',
  214. },
  215. ZOOMED_TO_SELECTION: {
  216. if: 'hasSelection',
  217. do: 'zoomCameraToSelection',
  218. },
  219. ZOOMED_TO_FIT: ['zoomCameraToFit', 'zoomCameraToActual'],
  220. ZOOMED_IN: 'zoomIn',
  221. ZOOMED_OUT: 'zoomOut',
  222. RESET_CAMERA: 'resetCamera',
  223. COPIED_TO_SVG: 'copyToSvg',
  224. },
  225. initial: 'notPointing',
  226. states: {
  227. notPointing: {
  228. on: {
  229. CANCELLED: 'clearSelectedIds',
  230. STARTED_PINCHING: { to: 'pinching' },
  231. POINTED_CANVAS: { to: 'brushSelecting' },
  232. POINTED_BOUNDS: [
  233. {
  234. if: 'isPressingMetaKey',
  235. to: 'brushSelecting',
  236. },
  237. { to: 'pointingBounds' },
  238. ],
  239. POINTED_BOUNDS_HANDLE: {
  240. if: 'isPointingRotationHandle',
  241. to: 'rotatingSelection',
  242. else: { to: 'transformingSelection' },
  243. },
  244. STARTED_EDITING_SHAPE: {
  245. get: 'firstSelectedShape',
  246. if: ['hasSingleSelection', 'canEditSelectedShape'],
  247. do: 'setEditingId',
  248. to: 'editingShape',
  249. },
  250. DOUBLE_POINTED_BOUNDS_HANDLE: {
  251. if: 'hasSingleSelection',
  252. do: 'resetShapeBounds',
  253. },
  254. POINTED_HANDLE: { to: 'translatingHandles' },
  255. MOVED_OVER_SHAPE: {
  256. if: 'pointHitsShape',
  257. then: {
  258. unless: 'shapeIsHovered',
  259. do: 'setHoveredId',
  260. },
  261. else: {
  262. if: 'shapeIsHovered',
  263. do: 'clearHoveredId',
  264. },
  265. },
  266. UNHOVERED_SHAPE: 'clearHoveredId',
  267. DOUBLE_POINTED_SHAPE: [
  268. 'setPointedId',
  269. {
  270. if: 'isPointedShapeSelected',
  271. then: {
  272. get: 'firstSelectedShape',
  273. if: 'canEditSelectedShape',
  274. do: 'setEditingId',
  275. to: 'editingShape',
  276. },
  277. },
  278. {
  279. unless: 'isPressingShiftKey',
  280. do: [
  281. 'setDrilledPointedId',
  282. 'clearSelectedIds',
  283. 'pushPointedIdToSelectedIds',
  284. ],
  285. to: 'pointingBounds',
  286. },
  287. ],
  288. POINTED_SHAPE: [
  289. {
  290. if: 'isPressingMetaKey',
  291. to: 'brushSelecting',
  292. },
  293. 'setPointedId',
  294. {
  295. if: 'pointInSelectionBounds',
  296. to: 'pointingBounds',
  297. },
  298. {
  299. unless: 'isPointedShapeSelected',
  300. then: {
  301. if: 'isPressingShiftKey',
  302. do: ['pushPointedIdToSelectedIds', 'clearPointedId'],
  303. else: ['clearSelectedIds', 'pushPointedIdToSelectedIds'],
  304. },
  305. },
  306. {
  307. to: 'pointingBounds',
  308. },
  309. ],
  310. RIGHT_POINTED: [
  311. {
  312. if: 'isPointingCanvas',
  313. do: 'clearSelectedIds',
  314. else: {
  315. if: 'isPointingShape',
  316. then: [
  317. 'setPointedId',
  318. {
  319. unless: 'isPointedShapeSelected',
  320. do: [
  321. 'clearSelectedIds',
  322. 'pushPointedIdToSelectedIds',
  323. ],
  324. },
  325. ],
  326. },
  327. },
  328. ],
  329. },
  330. },
  331. pointingBounds: {
  332. on: {
  333. STOPPED_POINTING_BOUNDS: [],
  334. STOPPED_POINTING: [
  335. {
  336. if: 'isPointingBounds',
  337. do: 'clearSelectedIds',
  338. },
  339. {
  340. if: 'isPressingShiftKey',
  341. then: [
  342. {
  343. if: 'isPointedShapeSelected',
  344. do: 'pullPointedIdFromSelectedIds',
  345. },
  346. ],
  347. else: {
  348. unless: 'isPointingBounds',
  349. do: ['clearSelectedIds', 'pushPointedIdToSelectedIds'],
  350. },
  351. },
  352. { to: 'notPointing' },
  353. ],
  354. MOVED_POINTER: {
  355. unless: 'isReadOnly',
  356. if: 'distanceImpliesDrag',
  357. to: 'translatingSelection',
  358. },
  359. },
  360. },
  361. rotatingSelection: {
  362. onEnter: 'startRotateSession',
  363. onExit: ['completeSession', 'clearBoundsRotation'],
  364. on: {
  365. MOVED_POINTER: 'updateRotateSession',
  366. PANNED_CAMERA: 'updateRotateSession',
  367. PRESSED_SHIFT_KEY: 'keyUpdateRotateSession',
  368. RELEASED_SHIFT_KEY: 'keyUpdateRotateSession',
  369. STOPPED_POINTING: { to: 'selecting' },
  370. CANCELLED: { do: 'cancelSession', to: 'selecting' },
  371. },
  372. },
  373. transformingSelection: {
  374. onEnter: 'startTransformSession',
  375. onExit: 'completeSession',
  376. on: {
  377. // MOVED_POINTER: 'updateTransformSession', using hacks.fastTransform
  378. PANNED_CAMERA: 'updateTransformSession',
  379. PRESSED_SHIFT_KEY: 'keyUpdateTransformSession',
  380. RELEASED_SHIFT_KEY: 'keyUpdateTransformSession',
  381. STOPPED_POINTING: { to: 'selecting' },
  382. CANCELLED: { do: 'cancelSession', to: 'selecting' },
  383. },
  384. },
  385. translatingSelection: {
  386. onEnter: 'startTranslateSession',
  387. onExit: 'completeSession',
  388. on: {
  389. STARTED_PINCHING: { to: 'pinching' },
  390. MOVED_POINTER: 'updateTranslateSession',
  391. PANNED_CAMERA: 'updateTranslateSession',
  392. PRESSED_SHIFT_KEY: 'keyUpdateTranslateSession',
  393. RELEASED_SHIFT_KEY: 'keyUpdateTranslateSession',
  394. PRESSED_ALT_KEY: 'keyUpdateTranslateSession',
  395. RELEASED_ALT_KEY: 'keyUpdateTranslateSession',
  396. STOPPED_POINTING: { to: 'selecting' },
  397. CANCELLED: { do: 'cancelSession', to: 'selecting' },
  398. },
  399. },
  400. translatingHandles: {
  401. onEnter: 'startHandleSession',
  402. onExit: 'completeSession',
  403. on: {
  404. MOVED_POINTER: 'updateHandleSession',
  405. PANNED_CAMERA: 'updateHandleSession',
  406. PRESSED_SHIFT_KEY: 'keyUpdateHandleSession',
  407. RELEASED_SHIFT_KEY: 'keyUpdateHandleSession',
  408. STOPPED_POINTING: { to: 'selecting' },
  409. DOUBLE_POINTED_HANDLE: {
  410. do: ['cancelSession', 'doublePointHandle'],
  411. to: 'selecting',
  412. },
  413. CANCELLED: { do: 'cancelSession', to: 'selecting' },
  414. },
  415. },
  416. brushSelecting: {
  417. onExit: 'completeSession',
  418. onEnter: [
  419. {
  420. unless: ['isPressingMetaKey', 'isPressingShiftKey'],
  421. do: 'clearSelectedIds',
  422. },
  423. 'clearBoundsRotation',
  424. 'startBrushSession',
  425. ],
  426. on: {
  427. // MOVED_POINTER: 'updateBrushSession', using hacks.fastBrushSelect
  428. PANNED_CAMERA: 'updateBrushSession',
  429. STOPPED_POINTING: { to: 'selecting' },
  430. STARTED_PINCHING: { to: 'pinching' },
  431. CANCELLED: { do: 'cancelSession', to: 'selecting' },
  432. },
  433. },
  434. },
  435. },
  436. editingShape: {
  437. onEnter: 'startEditSession',
  438. onExit: ['completeSession', 'clearEditingId'],
  439. on: {
  440. EDITED_SHAPE: { do: 'updateEditSession' },
  441. BLURRED_EDITING_SHAPE: { to: 'selecting' },
  442. CANCELLED: [
  443. {
  444. get: 'editingShape',
  445. if: 'shouldDeleteShape',
  446. do: 'breakSession',
  447. else: 'cancelSession',
  448. },
  449. { to: 'selecting' },
  450. ],
  451. },
  452. },
  453. pinching: {
  454. on: {
  455. // PINCHED: { do: 'pinchCamera' }, using hacks.fastPinchCamera
  456. },
  457. initial: 'selectPinching',
  458. onExit: { secretlyDo: 'updateZoomCSS' },
  459. states: {
  460. selectPinching: {
  461. on: {
  462. STOPPED_PINCHING: { to: 'selecting' },
  463. },
  464. },
  465. toolPinching: {
  466. on: {
  467. STOPPED_PINCHING: { to: 'usingTool.previous' },
  468. },
  469. },
  470. },
  471. },
  472. usingTool: {
  473. initial: 'draw',
  474. onEnter: 'clearSelectedIds',
  475. on: {
  476. STARTED_PINCHING: {
  477. do: 'breakSession',
  478. to: 'pinching.toolPinching',
  479. },
  480. TOGGLED_TOOL_LOCK: 'toggleToolLock',
  481. },
  482. states: {
  483. draw: {
  484. onEnter: 'setActiveToolDraw',
  485. initial: 'creating',
  486. states: {
  487. creating: {
  488. on: {
  489. CANCELLED: { to: 'selecting' },
  490. POINTED_SHAPE: {
  491. get: 'newDraw',
  492. do: 'createShape',
  493. to: 'draw.editing',
  494. },
  495. POINTED_CANVAS: {
  496. get: 'newDraw',
  497. do: 'createShape',
  498. to: 'draw.editing',
  499. },
  500. UNDO: 'undo',
  501. REDO: 'redo',
  502. SAVED: 'forceSave',
  503. LOADED_FROM_FILE_STSTEM: 'loadFromFileSystem',
  504. SAVED_TO_FILESYSTEM: 'saveToFileSystem',
  505. SAVED_AS_TO_FILESYSTEM: 'saveAsToFileSystem',
  506. },
  507. },
  508. editing: {
  509. onEnter: 'startDrawSession',
  510. onExit: 'completeSession',
  511. on: {
  512. CANCELLED: {
  513. do: 'breakSession',
  514. to: 'selecting',
  515. },
  516. STOPPED_POINTING: {
  517. do: 'completeSession',
  518. to: 'draw.creating',
  519. },
  520. PRESSED_SHIFT: 'keyUpdateDrawSession',
  521. RELEASED_SHIFT: 'keyUpdateDrawSession',
  522. // MOVED_POINTER: 'updateDrawSession',
  523. PANNED_CAMERA: 'updateDrawSession',
  524. },
  525. },
  526. },
  527. },
  528. dot: {
  529. onEnter: 'setActiveToolDot',
  530. initial: 'creating',
  531. states: {
  532. creating: {
  533. on: {
  534. CANCELLED: { to: 'selecting' },
  535. POINTED_SHAPE: {
  536. get: 'newDot',
  537. do: 'createShape',
  538. to: 'dot.editing',
  539. },
  540. POINTED_CANVAS: {
  541. get: 'newDot',
  542. do: 'createShape',
  543. to: 'dot.editing',
  544. },
  545. },
  546. },
  547. editing: {
  548. on: {
  549. STOPPED_POINTING: [
  550. 'completeSession',
  551. {
  552. if: 'isToolLocked',
  553. to: 'dot.creating',
  554. else: { to: 'selecting' },
  555. },
  556. ],
  557. CANCELLED: {
  558. do: 'breakSession',
  559. to: 'selecting',
  560. },
  561. },
  562. initial: 'inactive',
  563. states: {
  564. inactive: {
  565. on: {
  566. MOVED_POINTER: {
  567. if: 'distanceImpliesDrag',
  568. to: 'dot.editing.active',
  569. },
  570. },
  571. },
  572. active: {
  573. onExit: 'completeSession',
  574. onEnter: 'startTranslateSession',
  575. on: {
  576. MOVED_POINTER: 'updateTranslateSession',
  577. PANNED_CAMERA: 'updateTranslateSession',
  578. },
  579. },
  580. },
  581. },
  582. },
  583. },
  584. arrow: {
  585. onEnter: 'setActiveToolArrow',
  586. initial: 'creating',
  587. states: {
  588. creating: {
  589. on: {
  590. CANCELLED: { to: 'selecting' },
  591. POINTED_SHAPE: {
  592. get: 'newArrow',
  593. do: 'createShape',
  594. to: 'arrow.editing',
  595. },
  596. POINTED_CANVAS: {
  597. get: 'newArrow',
  598. do: 'createShape',
  599. to: 'arrow.editing',
  600. },
  601. UNDO: { do: 'undo' },
  602. REDO: { do: 'redo' },
  603. },
  604. },
  605. editing: {
  606. onExit: 'completeSession',
  607. onEnter: 'startArrowSession',
  608. on: {
  609. STOPPED_POINTING: [
  610. 'completeSession',
  611. {
  612. if: 'isToolLocked',
  613. to: 'arrow.creating',
  614. else: { to: 'selecting' },
  615. },
  616. ],
  617. CANCELLED: {
  618. do: 'breakSession',
  619. if: 'isToolLocked',
  620. to: 'arrow.creating',
  621. else: { to: 'selecting' },
  622. },
  623. PRESSED_SHIFT: 'keyUpdateArrowSession',
  624. RELEASED_SHIFT: 'keyUpdateArrowSession',
  625. MOVED_POINTER: 'updateArrowSession',
  626. PANNED_CAMERA: 'updateArrowSession',
  627. },
  628. },
  629. },
  630. },
  631. ellipse: {
  632. onEnter: 'setActiveToolEllipse',
  633. initial: 'creating',
  634. states: {
  635. creating: {
  636. on: {
  637. CANCELLED: { to: 'selecting' },
  638. POINTED_CANVAS: {
  639. to: 'ellipse.editing',
  640. },
  641. },
  642. },
  643. editing: {
  644. on: {
  645. STOPPED_POINTING: { to: 'selecting' },
  646. CANCELLED: { to: 'selecting' },
  647. MOVED_POINTER: {
  648. if: 'distanceImpliesDrag',
  649. then: {
  650. get: 'newEllipse',
  651. do: 'createShape',
  652. to: 'drawingShape.bounds',
  653. },
  654. },
  655. },
  656. },
  657. },
  658. },
  659. rectangle: {
  660. onEnter: 'setActiveToolRectangle',
  661. initial: 'creating',
  662. states: {
  663. creating: {
  664. on: {
  665. CANCELLED: { to: 'selecting' },
  666. POINTED_SHAPE: {
  667. to: 'rectangle.editing',
  668. },
  669. POINTED_CANVAS: {
  670. to: 'rectangle.editing',
  671. },
  672. },
  673. },
  674. editing: {
  675. on: {
  676. STOPPED_POINTING: { to: 'selecting' },
  677. CANCELLED: { to: 'selecting' },
  678. MOVED_POINTER: {
  679. if: 'distanceImpliesDrag',
  680. then: {
  681. get: 'newRectangle',
  682. do: 'createShape',
  683. to: 'drawingShape.bounds',
  684. },
  685. },
  686. },
  687. },
  688. },
  689. },
  690. text: {
  691. onEnter: 'setActiveToolText',
  692. initial: 'creating',
  693. states: {
  694. creating: {
  695. on: {
  696. CANCELLED: { to: 'selecting' },
  697. POINTED_SHAPE: [
  698. {
  699. get: 'newText',
  700. do: 'createShape',
  701. },
  702. {
  703. get: 'firstSelectedShape',
  704. if: 'canEditSelectedShape',
  705. do: 'setEditingId',
  706. to: 'editingShape',
  707. },
  708. ],
  709. POINTED_CANVAS: [
  710. {
  711. get: 'newText',
  712. do: 'createShape',
  713. to: 'editingShape',
  714. },
  715. ],
  716. },
  717. },
  718. },
  719. },
  720. ray: {
  721. onEnter: 'setActiveToolRay',
  722. initial: 'creating',
  723. states: {
  724. creating: {
  725. on: {
  726. CANCELLED: { to: 'selecting' },
  727. POINTED_SHAPE: {
  728. get: 'newRay',
  729. do: 'createShape',
  730. to: 'ray.editing',
  731. },
  732. POINTED_CANVAS: {
  733. get: 'newRay',
  734. do: 'createShape',
  735. to: 'ray.editing',
  736. },
  737. },
  738. },
  739. editing: {
  740. on: {
  741. STOPPED_POINTING: { to: 'selecting' },
  742. CANCELLED: { to: 'selecting' },
  743. MOVED_POINTER: {
  744. if: 'distanceImpliesDrag',
  745. to: 'drawingShape.direction',
  746. },
  747. },
  748. },
  749. },
  750. },
  751. line: {
  752. onEnter: 'setActiveToolLine',
  753. initial: 'creating',
  754. states: {
  755. creating: {
  756. on: {
  757. CANCELLED: { to: 'selecting' },
  758. POINTED_SHAPE: {
  759. get: 'newLine',
  760. do: 'createShape',
  761. to: 'line.editing',
  762. },
  763. POINTED_CANVAS: {
  764. get: 'newLine',
  765. do: 'createShape',
  766. to: 'line.editing',
  767. },
  768. },
  769. },
  770. editing: {
  771. on: {
  772. STOPPED_POINTING: { to: 'selecting' },
  773. CANCELLED: { to: 'selecting' },
  774. MOVED_POINTER: {
  775. if: 'distanceImpliesDrag',
  776. to: 'drawingShape.direction',
  777. },
  778. },
  779. },
  780. },
  781. },
  782. polyline: {
  783. onEnter: 'setActiveToolPolyline',
  784. },
  785. },
  786. },
  787. drawingShape: {
  788. onExit: 'completeSession',
  789. on: {
  790. STOPPED_POINTING: [
  791. 'completeSession',
  792. {
  793. if: 'isToolLocked',
  794. to: 'usingTool.previous',
  795. else: { to: 'selecting' },
  796. },
  797. ],
  798. CANCELLED: {
  799. do: 'breakSession',
  800. to: 'selecting',
  801. },
  802. },
  803. initial: 'drawingShapeBounds',
  804. states: {
  805. bounds: {
  806. onEnter: 'startDrawTransformSession',
  807. on: {
  808. MOVED_POINTER: 'updateTransformSession',
  809. PANNED_CAMERA: 'updateTransformSession',
  810. },
  811. },
  812. direction: {
  813. onEnter: 'startDirectionSession',
  814. onExit: 'completeSession',
  815. on: {
  816. MOVED_POINTER: 'updateDirectionSession',
  817. PANNED_CAMERA: 'updateDirectionSession',
  818. },
  819. },
  820. },
  821. },
  822. },
  823. },
  824. },
  825. results: {
  826. newDot() {
  827. return ShapeType.Dot
  828. },
  829. newRay() {
  830. return ShapeType.Ray
  831. },
  832. newLine() {
  833. return ShapeType.Line
  834. },
  835. newText() {
  836. return ShapeType.Text
  837. },
  838. newDraw() {
  839. return ShapeType.Draw
  840. },
  841. newArrow() {
  842. return ShapeType.Arrow
  843. },
  844. newEllipse() {
  845. return ShapeType.Ellipse
  846. },
  847. newRectangle() {
  848. return ShapeType.Rectangle
  849. },
  850. firstSelectedShape(data) {
  851. return getSelectedShapes(data)[0]
  852. },
  853. editingShape(data) {
  854. return getShape(data, data.editingId)
  855. },
  856. },
  857. conditions: {
  858. shouldDeleteShape(data, payload, shape: Shape) {
  859. return getShapeUtils(shape).shouldDelete(shape)
  860. },
  861. isPointingCanvas(data, payload: PointerInfo) {
  862. return payload.target === 'canvas'
  863. },
  864. isPointingBounds(data, payload: PointerInfo) {
  865. return getSelectedIds(data).size > 0 && payload.target === 'bounds'
  866. },
  867. isPointingShape(data, payload: PointerInfo) {
  868. return (
  869. payload.target &&
  870. payload.target !== 'canvas' &&
  871. payload.target !== 'bounds'
  872. )
  873. },
  874. isReadOnly(data) {
  875. return data.isReadOnly
  876. },
  877. canEditSelectedShape(data, payload, result: Shape) {
  878. return getShapeUtils(result).canEdit && !result.isLocked
  879. },
  880. distanceImpliesDrag(data, payload: PointerInfo) {
  881. return vec.dist2(payload.origin, payload.point) > 8
  882. },
  883. hasPointedTarget(data, payload: PointerInfo) {
  884. return payload.target !== undefined
  885. },
  886. isPointedShapeSelected(data) {
  887. return getSelectedIds(data).has(data.pointedId)
  888. },
  889. isPressingShiftKey(data, payload: PointerInfo) {
  890. return payload.shiftKey
  891. },
  892. isPressingMetaKey(data, payload: PointerInfo) {
  893. return payload.metaKey
  894. },
  895. shapeIsHovered(data, payload: { target: string }) {
  896. return data.hoveredId === payload.target
  897. },
  898. pointInSelectionBounds(data, payload: PointerInfo) {
  899. const bounds = getSelectionBounds(data)
  900. if (!bounds) return false
  901. return pointInBounds(screenToWorld(payload.point, data), bounds)
  902. },
  903. pointHitsShape(data, payload: PointerInfo) {
  904. const shape = getShape(data, payload.target)
  905. return getShapeUtils(shape).hitTest(
  906. shape,
  907. screenToWorld(payload.point, data)
  908. )
  909. },
  910. isPointingRotationHandle(
  911. data,
  912. payload: { target: Edge | Corner | 'rotate' }
  913. ) {
  914. return payload.target === 'rotate'
  915. },
  916. hasSelection(data) {
  917. return getSelectedIds(data).size > 0
  918. },
  919. hasSingleSelection(data) {
  920. return getSelectedIds(data).size === 1
  921. },
  922. hasMultipleSelection(data) {
  923. return getSelectedIds(data).size > 1
  924. },
  925. isToolLocked(data) {
  926. return data.settings.isToolLocked
  927. },
  928. isPenLocked(data) {
  929. return data.settings.isPenLocked
  930. },
  931. hasOnlyOnePage(data) {
  932. return Object.keys(data.document.pages).length === 1
  933. },
  934. selectionIncludesGroups(data) {
  935. return getSelectedShapes(data).some(
  936. (shape) => shape.type === ShapeType.Group
  937. )
  938. },
  939. },
  940. actions: {
  941. /* ---------------------- Pages --------------------- */
  942. changePage(data, payload: { id: string }) {
  943. commands.changePage(data, payload.id)
  944. },
  945. createPage(data) {
  946. commands.createPage(data, true)
  947. },
  948. deletePage(data, payload: { id: string }) {
  949. commands.deletePage(data, payload.id)
  950. },
  951. /* --------------------- Shapes --------------------- */
  952. resetShapes(data) {
  953. const page = getPage(data)
  954. Object.values(page.shapes).forEach((shape) => {
  955. page.shapes[shape.id] = { ...shape }
  956. })
  957. },
  958. createShape(data, payload, type: ShapeType) {
  959. const shape = createShape(type, {
  960. parentId: data.currentPageId,
  961. point: vec.round(screenToWorld(payload.point, data)),
  962. style: getCurrent(data.currentStyle),
  963. })
  964. const siblings = getChildren(data, shape.parentId)
  965. const childIndex = siblings.length
  966. ? siblings[siblings.length - 1].childIndex + 1
  967. : 1
  968. data.editingId = shape.id
  969. getShapeUtils(shape).setProperty(shape, 'childIndex', childIndex)
  970. getPage(data).shapes[shape.id] = shape
  971. setSelectedIds(data, [shape.id])
  972. },
  973. /* -------------------- Sessions -------------------- */
  974. // Shared
  975. breakSession(data) {
  976. session.current?.cancel(data)
  977. session.clear()
  978. history.disable()
  979. commands.deleteSelected(data)
  980. history.enable()
  981. },
  982. cancelSession(data) {
  983. session.current?.cancel(data)
  984. session.clear()
  985. },
  986. completeSession(data) {
  987. session.current?.complete(data)
  988. session.clear()
  989. },
  990. // Editing
  991. startEditSession(data) {
  992. session.current = new Sessions.EditSession(data)
  993. },
  994. updateEditSession(data, payload: { change: Partial<Shape> }) {
  995. session.current.update(data, payload.change)
  996. },
  997. // Brushing
  998. startBrushSession(data, payload: PointerInfo) {
  999. session.current = new Sessions.BrushSession(
  1000. data,
  1001. screenToWorld(payload.point, data)
  1002. )
  1003. },
  1004. updateBrushSession(data, payload: PointerInfo) {
  1005. session.current.update(data, screenToWorld(payload.point, data))
  1006. },
  1007. // Rotating
  1008. startRotateSession(data, payload: PointerInfo) {
  1009. session.current = new Sessions.RotateSession(
  1010. data,
  1011. screenToWorld(payload.point, data)
  1012. )
  1013. },
  1014. keyUpdateRotateSession(data, payload: PointerInfo) {
  1015. session.current.update(
  1016. data,
  1017. screenToWorld(inputs.pointer.point, data),
  1018. payload.shiftKey
  1019. )
  1020. },
  1021. updateRotateSession(data, payload: PointerInfo) {
  1022. session.current.update(
  1023. data,
  1024. screenToWorld(payload.point, data),
  1025. payload.shiftKey
  1026. )
  1027. },
  1028. // Dragging / Translating
  1029. startTranslateSession(data) {
  1030. session.current = new Sessions.TranslateSession(
  1031. data,
  1032. screenToWorld(inputs.pointer.origin, data)
  1033. )
  1034. },
  1035. keyUpdateTranslateSession(
  1036. data,
  1037. payload: { shiftKey: boolean; altKey: boolean }
  1038. ) {
  1039. session.current.update(
  1040. data,
  1041. screenToWorld(inputs.pointer.point, data),
  1042. payload.shiftKey,
  1043. payload.altKey
  1044. )
  1045. },
  1046. updateTranslateSession(data, payload: PointerInfo) {
  1047. session.current.update(
  1048. data,
  1049. screenToWorld(payload.point, data),
  1050. payload.shiftKey,
  1051. payload.altKey
  1052. )
  1053. },
  1054. // Handles
  1055. doublePointHandle(data, payload: PointerInfo) {
  1056. const id = setToArray(getSelectedIds(data))[0]
  1057. commands.doublePointHandle(data, id, payload)
  1058. },
  1059. // Dragging Handle
  1060. startHandleSession(data, payload: PointerInfo) {
  1061. const shapeId = Array.from(getSelectedIds(data).values())[0]
  1062. const handleId = payload.target
  1063. session.current = new Sessions.HandleSession(
  1064. data,
  1065. shapeId,
  1066. handleId,
  1067. screenToWorld(inputs.pointer.origin, data)
  1068. )
  1069. },
  1070. keyUpdateHandleSession(
  1071. data,
  1072. payload: { shiftKey: boolean; altKey: boolean }
  1073. ) {
  1074. session.current.update(
  1075. data,
  1076. screenToWorld(inputs.pointer.point, data),
  1077. payload.shiftKey,
  1078. payload.altKey
  1079. )
  1080. },
  1081. updateHandleSession(data, payload: PointerInfo) {
  1082. session.current.update(
  1083. data,
  1084. screenToWorld(payload.point, data),
  1085. payload.shiftKey,
  1086. payload.altKey
  1087. )
  1088. },
  1089. // Transforming
  1090. startTransformSession(
  1091. data,
  1092. payload: PointerInfo & { target: Corner | Edge }
  1093. ) {
  1094. const point = screenToWorld(inputs.pointer.origin, data)
  1095. session.current =
  1096. getSelectedIds(data).size === 1
  1097. ? new Sessions.TransformSingleSession(data, payload.target, point)
  1098. : new Sessions.TransformSession(data, payload.target, point)
  1099. },
  1100. startDrawTransformSession(data, payload: PointerInfo) {
  1101. session.current = new Sessions.TransformSingleSession(
  1102. data,
  1103. Corner.BottomRight,
  1104. screenToWorld(payload.point, data),
  1105. true
  1106. )
  1107. },
  1108. keyUpdateTransformSession(data, payload: PointerInfo) {
  1109. session.current.update(
  1110. data,
  1111. screenToWorld(inputs.pointer.point, data),
  1112. payload.shiftKey,
  1113. payload.altKey
  1114. )
  1115. },
  1116. updateTransformSession(data, payload: PointerInfo) {
  1117. session.current.update(
  1118. data,
  1119. screenToWorld(payload.point, data),
  1120. payload.shiftKey,
  1121. payload.altKey
  1122. )
  1123. },
  1124. // Direction
  1125. startDirectionSession(data) {
  1126. session.current = new Sessions.DirectionSession(
  1127. data,
  1128. screenToWorld(inputs.pointer.origin, data)
  1129. )
  1130. },
  1131. updateDirectionSession(data, payload: PointerInfo) {
  1132. session.current.update(data, screenToWorld(payload.point, data))
  1133. },
  1134. // Drawing
  1135. startDrawSession(data, payload: PointerInfo) {
  1136. const id = Array.from(getSelectedIds(data).values())[0]
  1137. session.current = new Sessions.DrawSession(
  1138. data,
  1139. id,
  1140. screenToWorld(inputs.pointer.origin, data),
  1141. payload.shiftKey
  1142. )
  1143. },
  1144. keyUpdateDrawSession(data, payload: PointerInfo) {
  1145. session.current.update(
  1146. data,
  1147. screenToWorld(inputs.pointer.point, data),
  1148. payload.pressure,
  1149. payload.shiftKey
  1150. )
  1151. },
  1152. updateDrawSession(data, payload: PointerInfo) {
  1153. session.current.update(
  1154. data,
  1155. screenToWorld(payload.point, data),
  1156. payload.pressure,
  1157. payload.shiftKey
  1158. )
  1159. },
  1160. // Arrow
  1161. startArrowSession(data, payload: PointerInfo) {
  1162. const id = Array.from(getSelectedIds(data).values())[0]
  1163. session.current = new Sessions.ArrowSession(
  1164. data,
  1165. id,
  1166. screenToWorld(inputs.pointer.origin, data),
  1167. payload.shiftKey
  1168. )
  1169. },
  1170. keyUpdateArrowSession(data, payload: PointerInfo) {
  1171. session.current.update(
  1172. data,
  1173. screenToWorld(inputs.pointer.point, data),
  1174. payload.shiftKey
  1175. )
  1176. },
  1177. updateArrowSession(data, payload: PointerInfo) {
  1178. session.current.update(
  1179. data,
  1180. screenToWorld(payload.point, data),
  1181. payload.shiftKey
  1182. )
  1183. },
  1184. /* -------------------- Selection ------------------- */
  1185. // Nudges
  1186. nudgeSelection(data, payload: { delta: number[]; shiftKey: boolean }) {
  1187. commands.nudge(
  1188. data,
  1189. vec.mul(
  1190. payload.delta,
  1191. payload.shiftKey
  1192. ? data.settings.nudgeDistanceLarge
  1193. : data.settings.nudgeDistanceSmall
  1194. )
  1195. )
  1196. },
  1197. clearInputs() {
  1198. inputs.clear()
  1199. },
  1200. selectAll(data) {
  1201. const selectedIds = getSelectedIds(data)
  1202. const page = getPage(data)
  1203. selectedIds.clear()
  1204. for (const id in page.shapes) {
  1205. if (page.shapes[id].parentId === data.currentPageId) {
  1206. selectedIds.add(id)
  1207. }
  1208. }
  1209. },
  1210. setHoveredId(data, payload: PointerInfo) {
  1211. data.hoveredId = payload.target
  1212. },
  1213. clearHoveredId(data) {
  1214. data.hoveredId = undefined
  1215. },
  1216. setPointedId(data, payload: PointerInfo) {
  1217. data.pointedId = getPointedId(data, payload.target)
  1218. data.currentParentId = getParentId(data, data.pointedId)
  1219. },
  1220. setDrilledPointedId(data, payload: PointerInfo) {
  1221. data.pointedId = getDrilledPointedId(data, payload.target)
  1222. data.currentParentId = getParentId(data, data.pointedId)
  1223. },
  1224. clearCurrentParentId(data) {
  1225. data.currentParentId = data.currentPageId
  1226. data.pointedId = undefined
  1227. },
  1228. clearPointedId(data) {
  1229. data.pointedId = undefined
  1230. },
  1231. clearSelectedIds(data) {
  1232. setSelectedIds(data, [])
  1233. },
  1234. pullPointedIdFromSelectedIds(data) {
  1235. const { pointedId } = data
  1236. const selectedIds = getSelectedIds(data)
  1237. selectedIds.delete(pointedId)
  1238. },
  1239. pushPointedIdToSelectedIds(data) {
  1240. getSelectedIds(data).add(data.pointedId)
  1241. },
  1242. moveSelection(data, payload: { type: MoveType }) {
  1243. commands.move(data, payload.type)
  1244. },
  1245. moveSelectionToPage(data, payload: { id: string }) {
  1246. commands.moveToPage(data, payload.id)
  1247. },
  1248. alignSelection(data, payload: { type: AlignType }) {
  1249. commands.align(data, payload.type)
  1250. },
  1251. stretchSelection(data, payload: { type: StretchType }) {
  1252. commands.stretch(data, payload.type)
  1253. },
  1254. distributeSelection(data, payload: { type: DistributeType }) {
  1255. commands.distribute(data, payload.type)
  1256. },
  1257. duplicateSelection(data) {
  1258. commands.duplicate(data)
  1259. },
  1260. lockSelection(data) {
  1261. commands.toggle(data, 'isLocked')
  1262. },
  1263. hideSelection(data) {
  1264. commands.toggle(data, 'isHidden')
  1265. },
  1266. aspectLockSelection(data) {
  1267. commands.toggle(data, 'isAspectRatioLocked')
  1268. },
  1269. deleteSelection(data) {
  1270. commands.deleteSelected(data)
  1271. },
  1272. rotateSelectionCcw(data) {
  1273. commands.rotateCcw(data)
  1274. },
  1275. groupSelection(data) {
  1276. commands.group(data)
  1277. },
  1278. ungroupSelection(data) {
  1279. commands.ungroup(data)
  1280. },
  1281. resetShapeBounds(data) {
  1282. commands.resetBounds(data)
  1283. },
  1284. /* --------------------- Editing -------------------- */
  1285. setEditingId(data) {
  1286. const selectedShape = getSelectedShapes(data)[0]
  1287. if (getShapeUtils(selectedShape).canEdit) {
  1288. data.editingId = selectedShape.id
  1289. }
  1290. getPageState(data).selectedIds = new Set([selectedShape.id])
  1291. },
  1292. clearEditingId(data) {
  1293. data.editingId = null
  1294. },
  1295. /* ---------------------- Tool ---------------------- */
  1296. setActiveTool(data, payload: { tool: ShapeType | 'select' }) {
  1297. data.activeTool = payload.tool
  1298. },
  1299. setActiveToolSelect(data) {
  1300. data.activeTool = 'select'
  1301. },
  1302. setActiveToolDraw(data) {
  1303. data.activeTool = ShapeType.Draw
  1304. },
  1305. setActiveToolRectangle(data) {
  1306. data.activeTool = ShapeType.Rectangle
  1307. },
  1308. setActiveToolEllipse(data) {
  1309. data.activeTool = ShapeType.Ellipse
  1310. },
  1311. setActiveToolArrow(data) {
  1312. data.activeTool = ShapeType.Arrow
  1313. },
  1314. setActiveToolDot(data) {
  1315. data.activeTool = ShapeType.Dot
  1316. },
  1317. setActiveToolPolyline(data) {
  1318. data.activeTool = ShapeType.Polyline
  1319. },
  1320. setActiveToolRay(data) {
  1321. data.activeTool = ShapeType.Ray
  1322. },
  1323. setActiveToolLine(data) {
  1324. data.activeTool = ShapeType.Line
  1325. },
  1326. setActiveToolText(data) {
  1327. data.activeTool = ShapeType.Text
  1328. },
  1329. /* --------------------- Camera --------------------- */
  1330. zoomIn(data) {
  1331. const camera = getCurrentCamera(data)
  1332. const i = Math.round((camera.zoom * 100) / 25)
  1333. const center = [window.innerWidth / 2, window.innerHeight / 2]
  1334. const p0 = screenToWorld(center, data)
  1335. camera.zoom = getCameraZoom((i + 1) * 0.25)
  1336. const p1 = screenToWorld(center, data)
  1337. camera.point = vec.add(camera.point, vec.sub(p1, p0))
  1338. setZoomCSS(camera.zoom)
  1339. },
  1340. zoomOut(data) {
  1341. const camera = getCurrentCamera(data)
  1342. const i = Math.round((camera.zoom * 100) / 25)
  1343. const center = [window.innerWidth / 2, window.innerHeight / 2]
  1344. const p0 = screenToWorld(center, data)
  1345. camera.zoom = getCameraZoom((i - 1) * 0.25)
  1346. const p1 = screenToWorld(center, data)
  1347. camera.point = vec.add(camera.point, vec.sub(p1, p0))
  1348. setZoomCSS(camera.zoom)
  1349. },
  1350. zoomCameraToActual(data) {
  1351. const camera = getCurrentCamera(data)
  1352. const center = [window.innerWidth / 2, window.innerHeight / 2]
  1353. const p0 = screenToWorld(center, data)
  1354. camera.zoom = 1
  1355. const p1 = screenToWorld(center, data)
  1356. camera.point = vec.add(camera.point, vec.sub(p1, p0))
  1357. setZoomCSS(camera.zoom)
  1358. },
  1359. zoomCameraToSelectionActual(data) {
  1360. const camera = getCurrentCamera(data)
  1361. const bounds = getSelectedBounds(data)
  1362. const mx = (window.innerWidth - bounds.width) / 2
  1363. const my = (window.innerHeight - bounds.height) / 2
  1364. camera.zoom = 1
  1365. camera.point = vec.add([-bounds.minX, -bounds.minY], [mx, my])
  1366. setZoomCSS(camera.zoom)
  1367. },
  1368. zoomCameraToSelection(data) {
  1369. const camera = getCurrentCamera(data)
  1370. const bounds = getSelectedBounds(data)
  1371. const zoom = getCameraZoom(
  1372. bounds.width > bounds.height
  1373. ? (window.innerWidth - 128) / bounds.width
  1374. : (window.innerHeight - 128) / bounds.height
  1375. )
  1376. const mx = (window.innerWidth - bounds.width * zoom) / 2 / zoom
  1377. const my = (window.innerHeight - bounds.height * zoom) / 2 / zoom
  1378. camera.zoom = zoom
  1379. camera.point = vec.add([-bounds.minX, -bounds.minY], [mx, my])
  1380. setZoomCSS(camera.zoom)
  1381. },
  1382. zoomCameraToFit(data) {
  1383. const camera = getCurrentCamera(data)
  1384. const page = getPage(data)
  1385. const shapes = Object.values(page.shapes)
  1386. if (shapes.length === 0) {
  1387. return
  1388. }
  1389. const bounds = getCommonBounds(
  1390. ...Object.values(shapes).map((shape) =>
  1391. getShapeUtils(shape).getBounds(shape)
  1392. )
  1393. )
  1394. const zoom = getCameraZoom(
  1395. bounds.width > bounds.height
  1396. ? (window.innerWidth - 128) / bounds.width
  1397. : (window.innerHeight - 128) / bounds.height
  1398. )
  1399. const mx = (window.innerWidth - bounds.width * zoom) / 2 / zoom
  1400. const my = (window.innerHeight - bounds.height * zoom) / 2 / zoom
  1401. camera.zoom = zoom
  1402. camera.point = vec.add([-bounds.minX, -bounds.minY], [mx, my])
  1403. setZoomCSS(camera.zoom)
  1404. },
  1405. zoomCamera(data, payload: { delta: number; point: number[] }) {
  1406. const camera = getCurrentCamera(data)
  1407. const next = camera.zoom - (payload.delta / 100) * camera.zoom
  1408. const p0 = screenToWorld(payload.point, data)
  1409. camera.zoom = getCameraZoom(next)
  1410. const p1 = screenToWorld(payload.point, data)
  1411. camera.point = vec.add(camera.point, vec.sub(p1, p0))
  1412. setZoomCSS(camera.zoom)
  1413. },
  1414. panCamera(data, payload: { delta: number[] }) {
  1415. const camera = getCurrentCamera(data)
  1416. camera.point = vec.sub(camera.point, vec.div(payload.delta, camera.zoom))
  1417. },
  1418. updateZoomCSS(data) {
  1419. const camera = getCurrentCamera(data)
  1420. setZoomCSS(camera.zoom)
  1421. },
  1422. pinchCamera(
  1423. data,
  1424. payload: {
  1425. delta: number[]
  1426. distanceDelta: number
  1427. angleDelta: number
  1428. point: number[]
  1429. }
  1430. ) {
  1431. // This is usually replaced with hacks.fastPinchCamera!
  1432. const camera = getCurrentCamera(data)
  1433. camera.point = vec.sub(camera.point, vec.div(payload.delta, camera.zoom))
  1434. const next = camera.zoom - (payload.distanceDelta / 300) * camera.zoom
  1435. const p0 = screenToWorld(payload.point, data)
  1436. camera.zoom = getCameraZoom(next)
  1437. const p1 = screenToWorld(payload.point, data)
  1438. camera.point = vec.add(camera.point, vec.sub(p1, p0))
  1439. setZoomCSS(camera.zoom)
  1440. },
  1441. resetCamera(data) {
  1442. const camera = getCurrentCamera(data)
  1443. camera.zoom = 1
  1444. camera.point = [window.innerWidth / 2, window.innerHeight / 2]
  1445. document.documentElement.style.setProperty('--camera-zoom', '1')
  1446. },
  1447. /* ---------------------- History ---------------------- */
  1448. // History
  1449. popHistory() {
  1450. history.pop()
  1451. },
  1452. enableHistory() {
  1453. history.enable()
  1454. },
  1455. disableHistory() {
  1456. history.disable()
  1457. },
  1458. undo(data) {
  1459. history.undo(data)
  1460. },
  1461. redo(data) {
  1462. history.redo(data)
  1463. },
  1464. resetHistory() {
  1465. history.reset()
  1466. },
  1467. /* --------------------- Styles --------------------- */
  1468. toggleStylePanel(data) {
  1469. data.settings.isStyleOpen = !data.settings.isStyleOpen
  1470. },
  1471. closeStylePanel(data) {
  1472. data.settings.isStyleOpen = false
  1473. },
  1474. updateStyles(data, payload: Partial<ShapeStyles>) {
  1475. Object.assign(data.currentStyle, payload)
  1476. },
  1477. applyStylesToSelection(data, payload: Partial<ShapeStyles>) {
  1478. commands.style(data, payload)
  1479. },
  1480. /* ---------------------- Code ---------------------- */
  1481. closeCodePanel(data) {
  1482. data.settings.isCodeOpen = false
  1483. },
  1484. openCodePanel(data) {
  1485. data.settings.isCodeOpen = true
  1486. },
  1487. toggleCodePanel(data) {
  1488. data.settings.isCodeOpen = !data.settings.isCodeOpen
  1489. },
  1490. setGeneratedShapes(
  1491. data,
  1492. payload: { shapes: Shape[]; controls: CodeControl[] }
  1493. ) {
  1494. commands.generate(data, data.currentPageId, payload.shapes)
  1495. },
  1496. setCodeControls(data, payload: { controls: CodeControl[] }) {
  1497. data.codeControls = Object.fromEntries(
  1498. payload.controls.map((control) => [control.id, control])
  1499. )
  1500. },
  1501. increaseCodeFontSize(data) {
  1502. data.settings.fontSize++
  1503. },
  1504. decreaseCodeFontSize(data) {
  1505. data.settings.fontSize--
  1506. },
  1507. updateControls(data, payload: { [key: string]: any }) {
  1508. for (const key in payload) {
  1509. data.codeControls[key].value = payload[key]
  1510. }
  1511. history.disable()
  1512. setSelectedIds(data, [])
  1513. try {
  1514. const { shapes } = updateFromCode(
  1515. data,
  1516. data.document.code[data.currentCodeFileId].code
  1517. )
  1518. commands.generate(data, data.currentPageId, shapes)
  1519. } catch (e) {
  1520. console.error(e)
  1521. }
  1522. history.enable()
  1523. },
  1524. /* -------------------- Settings -------------------- */
  1525. enablePenLock(data) {
  1526. data.settings.isPenLocked = true
  1527. },
  1528. disablePenLock(data) {
  1529. data.settings.isPenLocked = false
  1530. },
  1531. toggleToolLock(data) {
  1532. data.settings.isToolLocked = !data.settings.isToolLocked
  1533. },
  1534. /* ---------------------- Data ---------------------- */
  1535. copyToSvg(data) {
  1536. clipboard.copySelectionToSvg(data)
  1537. },
  1538. copyToClipboard(data) {
  1539. clipboard.copy(getSelectedShapes(data))
  1540. },
  1541. pasteFromClipboard() {
  1542. clipboard.paste()
  1543. },
  1544. pasteShapesFromClipboard(data, payload: { shapes: Shape[] }) {
  1545. commands.paste(data, payload.shapes)
  1546. },
  1547. restoreSavedData(data) {
  1548. storage.firstLoad(data)
  1549. },
  1550. saveToFileSystem(data) {
  1551. storage.saveToFileSystem(data)
  1552. },
  1553. saveAsToFileSystem(data) {
  1554. storage.saveAsToFileSystem(data)
  1555. },
  1556. loadFromFileSystem() {
  1557. storage.loadDocumentFromFilesystem()
  1558. },
  1559. loadDocumentFromJson(data, payload: { json: any }) {
  1560. storage.loadDocumentFromJson(data, payload.json)
  1561. },
  1562. forceSave(data) {
  1563. storage.saveToFileSystem(data)
  1564. },
  1565. savePage(data) {
  1566. storage.savePage(data)
  1567. },
  1568. loadPage(data) {
  1569. storage.loadPage(data)
  1570. },
  1571. saveCode(data, payload: { code: string }) {
  1572. data.document.code[data.currentCodeFileId].code = payload.code
  1573. storage.saveDocumentToLocalStorage(data)
  1574. },
  1575. clearBoundsRotation(data) {
  1576. data.boundsRotation = 0
  1577. },
  1578. },
  1579. values: {
  1580. selectedIds(data) {
  1581. return new Set(getSelectedIds(data))
  1582. },
  1583. selectedBounds(data) {
  1584. return getSelectionBounds(data)
  1585. },
  1586. currentShapes(data) {
  1587. const page = getPage(data)
  1588. return Object.values(page.shapes)
  1589. .filter((shape) => shape.parentId === page.id)
  1590. .sort((a, b) => a.childIndex - b.childIndex)
  1591. },
  1592. selectedStyle(data) {
  1593. const selectedIds = Array.from(getSelectedIds(data).values())
  1594. const { currentStyle } = data
  1595. if (selectedIds.length === 0) {
  1596. return currentStyle
  1597. }
  1598. const page = getPage(data)
  1599. const shapeStyles = selectedIds.map((id) => page.shapes[id].style)
  1600. const commonStyle: ShapeStyles = {} as ShapeStyles
  1601. const overrides = new Set<string>([])
  1602. for (const shapeStyle of shapeStyles) {
  1603. for (const key in currentStyle) {
  1604. if (overrides.has(key)) continue
  1605. if (commonStyle[key] === undefined) {
  1606. commonStyle[key] = shapeStyle[key]
  1607. } else {
  1608. if (commonStyle[key] === shapeStyle[key]) continue
  1609. commonStyle[key] = currentStyle[key]
  1610. overrides.add(key)
  1611. }
  1612. }
  1613. }
  1614. return commonStyle
  1615. },
  1616. },
  1617. })
  1618. export default state
  1619. export const useSelector = createSelectorHook(state)
  1620. function getParentId(data: Data, id: string) {
  1621. const shape = getPage(data).shapes[id]
  1622. return shape.parentId
  1623. }
  1624. function getPointedId(data: Data, id: string) {
  1625. const shape = getPage(data).shapes[id]
  1626. return shape.parentId === data.currentParentId ||
  1627. shape.parentId === data.currentPageId
  1628. ? id
  1629. : getPointedId(data, shape.parentId)
  1630. }
  1631. function getDrilledPointedId(data: Data, id: string) {
  1632. const shape = getPage(data).shapes[id]
  1633. return shape.parentId === data.currentPageId ||
  1634. shape.parentId === data.pointedId ||
  1635. shape.parentId === data.currentParentId
  1636. ? id
  1637. : getDrilledPointedId(data, shape.parentId)
  1638. }
  1639. // function hasPointedIdInChildren(data: Data, id: string, pointedId: string) {
  1640. // const shape = getPage(data).shapes[id]
  1641. // if (shape.type !== ShapeType.Group) {
  1642. // return false
  1643. // }
  1644. // if (shape.children.includes(pointedId)) {
  1645. // return true
  1646. // }
  1647. // return shape.children.some((childId) =>
  1648. // hasPointedIdInChildren(data, childId, pointedId)
  1649. // )
  1650. // }
  1651. function getSelectionBounds(data: Data) {
  1652. const selectedIds = getSelectedIds(data)
  1653. const page = getPage(data)
  1654. const shapes = Array.from(selectedIds.values())
  1655. .map((id) => page.shapes[id])
  1656. .filter(Boolean)
  1657. if (selectedIds.size === 0) return null
  1658. if (selectedIds.size === 1) {
  1659. if (!shapes[0]) {
  1660. console.error('Could not find that shape! Clearing selected IDs.')
  1661. setSelectedIds(data, [])
  1662. return null
  1663. }
  1664. const shape = shapes[0]
  1665. const shapeUtils = getShapeUtils(shape)
  1666. if (!shapeUtils.canTransform) return null
  1667. let bounds = shapeUtils.getBounds(shape)
  1668. let parentId = shape.parentId
  1669. while (parentId !== data.currentPageId) {
  1670. const parent = page.shapes[parentId]
  1671. bounds = rotateBounds(
  1672. bounds,
  1673. getBoundsCenter(getShapeUtils(parent).getBounds(parent)),
  1674. parent.rotation
  1675. )
  1676. bounds.rotation = parent.rotation
  1677. parentId = parent.parentId
  1678. }
  1679. return bounds
  1680. }
  1681. const uniqueSelectedShapeIds: string[] = Array.from(
  1682. new Set(
  1683. Array.from(selectedIds.values()).flatMap((id) =>
  1684. getDocumentBranch(data, id)
  1685. )
  1686. ).values()
  1687. )
  1688. const commonBounds = getCommonBounds(
  1689. ...uniqueSelectedShapeIds
  1690. .map((id) => page.shapes[id])
  1691. .filter((shape) => shape.type !== ShapeType.Group)
  1692. .map((shape) => getShapeUtils(shape).getRotatedBounds(shape))
  1693. )
  1694. return commonBounds
  1695. }
  1696. // state.enableLog(true)
  1697. // state.onUpdate((s) => console.log(s.log.filter((l) => l !== 'MOVED_POINTER')))