Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

state.ts 66KB

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