Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

state.ts 54KB

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