您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

state.ts 54KB

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