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 58KB

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