You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

state.ts 54KB

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