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

state.ts 53KB

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