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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. import { clamp, deepClone, getCommonBounds } from 'utils'
  2. import { getShapeUtils } from 'state/shape-utils'
  3. import vec from './vec'
  4. import {
  5. Data,
  6. Bounds,
  7. Shape,
  8. GroupShape,
  9. ShapeType,
  10. CodeFile,
  11. Page,
  12. PageState,
  13. ShapeUtility,
  14. ParentShape,
  15. ShapeTreeNode,
  16. } from 'types'
  17. import { AssertionError } from 'assert'
  18. import { lerp } from './utils'
  19. export default class StateUtils {
  20. static getCameraZoom(zoom: number): number {
  21. return clamp(zoom, 0.1, 5)
  22. }
  23. static screenToWorld(point: number[], data: Data): number[] {
  24. const camera = this.getCurrentCamera(data)
  25. return vec.sub(vec.div(point, camera.zoom), camera.point)
  26. }
  27. static getViewport(data: Data): Bounds {
  28. const [minX, minY] = this.screenToWorld([0, 0], data)
  29. const [maxX, maxY] = this.screenToWorld(
  30. [window.innerWidth, window.innerHeight],
  31. data
  32. )
  33. return {
  34. minX,
  35. minY,
  36. maxX,
  37. maxY,
  38. height: maxX - minX,
  39. width: maxY - minY,
  40. }
  41. }
  42. static getCurrentCamera(data: Data): {
  43. point: number[]
  44. zoom: number
  45. } {
  46. return data.pageStates[data.currentPageId].camera
  47. }
  48. /**
  49. * Get a shape from the project.
  50. * @param data
  51. * @param shapeId
  52. */
  53. static getShape(data: Data, shapeId: string): Shape {
  54. return data.document.pages[data.currentPageId].shapes[shapeId]
  55. }
  56. /**
  57. * Get the current page.
  58. * @param data
  59. */
  60. static getPage(data: Data): Page {
  61. return data.document.pages[data.currentPageId]
  62. }
  63. /**
  64. * Get the current page's page state.
  65. * @param data
  66. */
  67. static getPageState(data: Data): PageState {
  68. return data.pageStates[data.currentPageId]
  69. }
  70. /**
  71. * Get the current page's code file.
  72. * @param data
  73. * @param fileId
  74. */
  75. static getCurrentCode(data: Data, fileId: string): CodeFile {
  76. return data.document.code[fileId]
  77. }
  78. /**
  79. * Get the current page's shapes as an array.
  80. * @param data
  81. */
  82. static getShapes(data: Data): Shape[] {
  83. const page = this.getPage(data)
  84. return Object.values(page.shapes)
  85. }
  86. /**
  87. * Add the shapes to the current page.
  88. *
  89. * ### Example
  90. *
  91. *```ts
  92. * tld.createShape(data, [shape1])
  93. * tld.createShape(data, [shape1, shape2, shape3])
  94. *```
  95. */
  96. static createShapes(data: Data, shapes: Shape[]): void {
  97. const page = this.getPage(data)
  98. const shapeIds = shapes.map((shape) => shape.id)
  99. // Update selected ids
  100. this.setSelectedIds(data, shapeIds)
  101. // Restore deleted shapes
  102. shapes.forEach((shape) => {
  103. const newShape = { ...shape }
  104. page.shapes[shape.id] = newShape
  105. })
  106. // Update parents
  107. shapes.forEach((shape) => {
  108. if (shape.parentId === data.currentPageId) return
  109. const parent = page.shapes[shape.parentId]
  110. getShapeUtils(parent)
  111. .setProperty(
  112. parent,
  113. 'children',
  114. parent.children.includes(shape.id)
  115. ? parent.children
  116. : [...parent.children, shape.id]
  117. )
  118. .onChildrenChange(
  119. parent,
  120. parent.children.map((id) => page.shapes[id])
  121. )
  122. })
  123. }
  124. /**
  125. * Delete the shapes from the current page.
  126. *
  127. * ### Example
  128. *
  129. *```ts
  130. * tld.deleteShape(data, [shape1])
  131. * tld.deleteShape(data, [shape1, shape1, shape1])
  132. *```
  133. */
  134. static deleteShapes(
  135. data: Data,
  136. shapeIds: string[] | Shape[],
  137. shapesDeleted: Shape[] = []
  138. ): Shape[] {
  139. const ids =
  140. typeof shapeIds[0] === 'string'
  141. ? (shapeIds as string[])
  142. : (shapeIds as Shape[]).map((shape) => shape.id)
  143. const parentsToDelete: string[] = []
  144. const page = this.getPage(data)
  145. const parentIds = new Set(ids.map((id) => page.shapes[id].parentId))
  146. // Delete shapes
  147. ids.forEach((id) => {
  148. shapesDeleted.push(deepClone(page.shapes[id]))
  149. delete page.shapes[id]
  150. })
  151. // Update parents
  152. parentIds.forEach((id) => {
  153. const parent = page.shapes[id]
  154. // The parent was either deleted or a is a page.
  155. if (!parent) return
  156. const utils = getShapeUtils(parent)
  157. // Remove deleted ids from the parent's children and update the parent
  158. utils
  159. .setProperty(
  160. parent,
  161. 'children',
  162. parent.children.filter((childId) => !ids.includes(childId))
  163. )
  164. .onChildrenChange(
  165. parent,
  166. parent.children.map((id) => page.shapes[id])
  167. )
  168. if (utils.shouldDelete(parent)) {
  169. // If the parent decides it should delete, then we need to reparent
  170. // the parent's remaining children to the parent's parent, and
  171. // assign them correct child indices, and then delete the parent on
  172. // the next recursive step.
  173. const nextIndex = this.getChildIndexAbove(data, parent.id)
  174. const len = parent.children.length
  175. // Reparent the children and assign them new child indices
  176. parent.children.forEach((childId, i) => {
  177. const child = this.getShape(data, childId)
  178. getShapeUtils(child)
  179. .setProperty(child, 'parentId', parent.parentId)
  180. .setProperty(
  181. child,
  182. 'childIndex',
  183. lerp(parent.childIndex, nextIndex, i / len)
  184. )
  185. })
  186. if (parent.parentId !== page.id) {
  187. // If the parent is not a page, then we add the parent's children
  188. // to the parent's parent shape before emptying that array. If the
  189. // parent is a page, then we don't need to do this step.
  190. // TODO: Consider adding explicit children array to page shapes.
  191. const grandParent = page.shapes[parent.parentId]
  192. getShapeUtils(grandParent)
  193. .setProperty(grandParent, 'children', [...parent.children])
  194. .onChildrenChange(
  195. grandParent,
  196. grandParent.children.map((id) => page.shapes[id])
  197. )
  198. }
  199. // Empty the parent's children array and delete the parent on the next
  200. // iteration step.
  201. getShapeUtils(parent).setProperty(parent, 'children', [])
  202. parentsToDelete.push(parent.id)
  203. }
  204. })
  205. if (parentsToDelete.length > 0) {
  206. return this.deleteShapes(data, parentsToDelete, shapesDeleted)
  207. }
  208. return shapesDeleted
  209. }
  210. /**
  211. * Get the current selected shapes as an array.
  212. * @param data
  213. */
  214. static getSelectedShapes(data: Data): Shape[] {
  215. const page = this.getPage(data)
  216. const ids = this.getSelectedIds(data)
  217. return ids.map((id) => page.shapes[id])
  218. }
  219. /**
  220. * Get a shape's parent.
  221. * @param data
  222. * @param id
  223. */
  224. static getParent(data: Data, id: string): Shape | Page {
  225. const page = this.getPage(data)
  226. const shape = page.shapes[id]
  227. return page.shapes[shape.parentId] || data.document.pages[shape.parentId]
  228. }
  229. /**
  230. * Get a shape's children.
  231. * @param data
  232. * @param id
  233. */
  234. static getChildren(data: Data, id: string): Shape[] {
  235. const page = this.getPage(data)
  236. return Object.values(page.shapes)
  237. .filter(({ parentId }) => parentId === id)
  238. .sort((a, b) => a.childIndex - b.childIndex)
  239. }
  240. /**
  241. * Get a shape's siblings.
  242. * @param data
  243. * @param id
  244. */
  245. static getSiblings(data: Data, id: string): Shape[] {
  246. const page = this.getPage(data)
  247. const shape = page.shapes[id]
  248. return Object.values(page.shapes)
  249. .filter(({ parentId }) => parentId === shape.parentId)
  250. .sort((a, b) => a.childIndex - b.childIndex)
  251. }
  252. /**
  253. * Get the next child index above a shape.
  254. * TODO: Make work for grouped shapes, make faster.
  255. * @param data
  256. * @param id
  257. */
  258. static getChildIndexAbove(data: Data, id: string): number {
  259. const page = this.getPage(data)
  260. const shape = page.shapes[id]
  261. const siblings = Object.values(page.shapes)
  262. .filter(({ parentId }) => parentId === shape.parentId)
  263. .sort((a, b) => a.childIndex - b.childIndex)
  264. const index = siblings.indexOf(shape)
  265. const nextSibling = siblings[index + 1]
  266. if (!nextSibling) return shape.childIndex + 1
  267. let nextIndex = (shape.childIndex + nextSibling.childIndex) / 2
  268. if (nextIndex === nextSibling.childIndex) {
  269. this.forceIntegerChildIndices(siblings)
  270. nextIndex = (shape.childIndex + nextSibling.childIndex) / 2
  271. }
  272. return nextIndex
  273. }
  274. /**
  275. * Get the next child index below a shape.
  276. * @param data
  277. * @param id
  278. * @param pageId
  279. */
  280. static getChildIndexBelow(data: Data, id: string): number {
  281. const page = this.getPage(data)
  282. const shape = page.shapes[id]
  283. const siblings = Object.values(page.shapes)
  284. .filter(({ parentId }) => parentId === shape.parentId)
  285. .sort((a, b) => a.childIndex - b.childIndex)
  286. const index = siblings.indexOf(shape)
  287. const prevSibling = siblings[index - 1]
  288. if (!prevSibling) {
  289. return shape.childIndex / 2
  290. }
  291. let nextIndex = (shape.childIndex + prevSibling.childIndex) / 2
  292. if (nextIndex === prevSibling.childIndex) {
  293. this.forceIntegerChildIndices(siblings)
  294. nextIndex = (shape.childIndex + prevSibling.childIndex) / 2
  295. }
  296. return (shape.childIndex + prevSibling.childIndex) / 2
  297. }
  298. /**
  299. * Assert whether a shape can have child shapes.
  300. * @param shape
  301. */
  302. static assertParentShape(shape: Shape): asserts shape is ParentShape {
  303. if (!('children' in shape)) {
  304. throw new AssertionError({
  305. message: `That shape was not a parent (it was a ${shape.type}).`,
  306. })
  307. }
  308. }
  309. /**
  310. * Get the top child index for a shape. This is potentially provisional:
  311. * sorting all shapes on the page for each new created shape will become
  312. * slower as the page grows. High indices aren't a problem, so consider
  313. * tracking the highest index for the page when shapes are created / deleted.
  314. *
  315. * @param data
  316. * @param id
  317. */
  318. static getTopChildIndex(data: Data, parent: Shape | Page): number {
  319. const page = this.getPage(data)
  320. // If the parent is a shape, return either 1 (if no other shapes) or the
  321. // highest sorted child index + 1.
  322. if (parent.type === 'page') {
  323. const children = Object.values(parent.shapes)
  324. if (children.length === 0) return 1
  325. return (
  326. children.sort((a, b) => b.childIndex - a.childIndex)[0].childIndex + 1
  327. )
  328. }
  329. // If the shape is a regular shape that can accept children, return either
  330. // 1 (if no other children) or the highest sorted child index + 1.
  331. this.assertParentShape(parent)
  332. if (parent.children.length === 0) return 1
  333. return (
  334. parent.children
  335. .map((id) => page.shapes[id])
  336. .sort((a, b) => b.childIndex - a.childIndex)[0].childIndex + 1
  337. )
  338. }
  339. /**
  340. * TODO: Make this recursive, so that it works for parented shapes.
  341. * Force all shapes on the page to have integer child indices.
  342. * @param shapes
  343. */
  344. static forceIntegerChildIndices(shapes: Shape[]): void {
  345. for (let i = 0; i < shapes.length; i++) {
  346. const shape = shapes[i]
  347. getShapeUtils(shape).setProperty(shape, 'childIndex', i + 1)
  348. }
  349. }
  350. /**
  351. * Update the zoom CSS variable.
  352. * @param zoom ;
  353. */
  354. static setZoomCSS(zoom: number): void {
  355. document.documentElement.style.setProperty('--camera-zoom', zoom.toString())
  356. }
  357. /* --------------------- Groups --------------------- */
  358. static getParentOffset(
  359. data: Data,
  360. shapeId: string,
  361. offset = [0, 0]
  362. ): number[] {
  363. const shape = this.getShape(data, shapeId)
  364. return shape.parentId === data.currentPageId
  365. ? offset
  366. : this.getParentOffset(data, shape.parentId, vec.add(offset, shape.point))
  367. }
  368. static getParentRotation(data: Data, shapeId: string, rotation = 0): number {
  369. const shape = this.getShape(data, shapeId)
  370. return shape.parentId === data.currentPageId
  371. ? rotation + shape.rotation
  372. : this.getParentRotation(data, shape.parentId, rotation + shape.rotation)
  373. }
  374. static getDocumentBranch(data: Data, id: string): string[] {
  375. const shape = this.getPage(data).shapes[id]
  376. if (shape.type !== ShapeType.Group) return [id]
  377. return [
  378. id,
  379. ...shape.children.flatMap((childId) =>
  380. this.getDocumentBranch(data, childId)
  381. ),
  382. ]
  383. }
  384. static getSelectedIds(data: Data): string[] {
  385. return data.pageStates[data.currentPageId].selectedIds
  386. }
  387. static setSelectedIds(data: Data, ids: string[]): string[] {
  388. data.pageStates[data.currentPageId].selectedIds = [...ids]
  389. return data.pageStates[data.currentPageId].selectedIds
  390. }
  391. static getTopParentId(data: Data, id: string): string {
  392. const shape = this.getPage(data).shapes[id]
  393. if (shape.parentId === shape.id) {
  394. console.error('Shape has the same id as its parent!', deepClone(shape))
  395. return shape.parentId
  396. }
  397. return shape.parentId === data.currentPageId ||
  398. shape.parentId === data.currentParentId
  399. ? id
  400. : this.getTopParentId(data, shape.parentId)
  401. }
  402. /* ----------------- Shapes Related ----------------- */
  403. /**
  404. * Get a deep-cloned
  405. * @param data
  406. * @param fn
  407. */
  408. static getSelectedBranchSnapshot<K>(
  409. data: Data,
  410. fn: <T extends Shape>(shape: T) => K
  411. ): ({ id: string } & K)[]
  412. static getSelectedBranchSnapshot(data: Data): Shape[]
  413. static getSelectedBranchSnapshot<
  414. K,
  415. F extends <T extends Shape>(shape: T) => K
  416. >(data: Data, fn?: F): (Shape | K)[] {
  417. const page = this.getPage(data)
  418. const copies = this.getSelectedIds(data)
  419. .flatMap((id) =>
  420. this.getDocumentBranch(data, id).map((id) => page.shapes[id])
  421. )
  422. .filter((shape) => !shape.isLocked)
  423. .map(deepClone)
  424. if (fn !== undefined) {
  425. return copies.map((shape) => ({ id: shape.id, ...fn(shape) }))
  426. }
  427. return copies
  428. }
  429. /**
  430. * Get a deep-cloned array of shapes
  431. * @param data
  432. */
  433. static getSelectedShapeSnapshot(data: Data): Shape[]
  434. static getSelectedShapeSnapshot<K>(
  435. data: Data,
  436. fn: <T extends Shape>(shape: T) => K
  437. ): ({ id: string } & K)[]
  438. static getSelectedShapeSnapshot<
  439. K,
  440. F extends <T extends Shape>(shape: T) => K
  441. >(data: Data, fn?: F): (Shape | K)[] {
  442. const copies = this.getSelectedShapes(data)
  443. .filter((shape) => !shape.isLocked)
  444. .map(deepClone)
  445. if (fn !== undefined) {
  446. return copies.map((shape) => ({ id: shape.id, ...fn(shape) }))
  447. }
  448. return copies
  449. }
  450. /**
  451. * Get an array of all unique parentIds among a set of shapes.
  452. * @param data
  453. * @param shapes
  454. */
  455. static getUniqueParentIds(data: Data, shapes: Shape[]): string[] {
  456. return Array.from(new Set(shapes.map((s) => s.parentId)).values()).filter(
  457. (id) => id !== data.currentPageId
  458. )
  459. }
  460. /**
  461. * Make an arbitrary change to shape.
  462. * @param data
  463. * @param ids
  464. * @param fn
  465. */
  466. static mutateShape<T extends Shape>(
  467. data: Data,
  468. id: string,
  469. fn: (shapeUtils: ShapeUtility<T>, shape: T) => void,
  470. updateParents = true
  471. ): T {
  472. const page = this.getPage(data)
  473. const shape = page.shapes[id] as T
  474. fn(getShapeUtils(shape) as ShapeUtility<T>, shape)
  475. if (updateParents) this.updateParents(data, [id])
  476. return shape
  477. }
  478. /**
  479. * Make an arbitrary change to a set of shapes.
  480. * @param data
  481. * @param ids
  482. * @param fn
  483. */
  484. static mutateShapes<T extends Shape>(
  485. data: Data,
  486. ids: string[],
  487. fn: (shape: T, shapeUtils: ShapeUtility<T>, index: number) => T | void,
  488. updateParents = true
  489. ): T[] {
  490. const page = this.getPage(data)
  491. const mutatedShapes = ids.map((id, i) => {
  492. const shape = page.shapes[id] as T
  493. // Define the new shape as either the (maybe new) shape returned by the
  494. // function or the mutated shape.
  495. page.shapes[id] =
  496. fn(shape, getShapeUtils(shape) as ShapeUtility<T>, i) || shape
  497. return page.shapes[id] as T
  498. })
  499. if (updateParents) this.updateParents(data, ids)
  500. return mutatedShapes
  501. }
  502. /**
  503. * Insert shapes into the current page.
  504. * @param data
  505. * @param shapes
  506. */
  507. static insertShapes(data: Data, shapes: Shape[]): void {
  508. const page = this.getPage(data)
  509. shapes.forEach((shape) => {
  510. page.shapes[shape.id] = shape
  511. // Does the shape have a parent?
  512. if (shape.parentId !== data.currentPageId) {
  513. // The parent shape
  514. const parent = page.shapes[shape.parentId]
  515. // If the parent shape doesn't exist, assign the shape as a child
  516. // of the page instead.
  517. if (parent === undefined) {
  518. getShapeUtils(shape).setProperty(
  519. shape,
  520. 'childIndex',
  521. this.getTopChildIndex(data, parent)
  522. )
  523. } else {
  524. // Add the shape's id to the parent's children, then sort the
  525. // new array just to be sure.
  526. getShapeUtils(parent).setProperty(
  527. parent,
  528. 'children',
  529. [...parent.children, shape.id]
  530. .map((id) => page.shapes[id])
  531. .sort((a, b) => a.childIndex - b.childIndex)
  532. .map((shape) => shape.id)
  533. )
  534. }
  535. }
  536. })
  537. // Update any new parents
  538. this.updateParents(
  539. data,
  540. shapes.map((shape) => shape.id)
  541. )
  542. }
  543. static getRotatedBounds(shape: Shape): Bounds {
  544. return getShapeUtils(shape).getRotatedBounds(shape)
  545. }
  546. static getShapeBounds(shape: Shape): Bounds {
  547. return getShapeUtils(shape).getBounds(shape)
  548. }
  549. static getSelectedBounds(data: Data): Bounds {
  550. return getCommonBounds(
  551. ...this.getSelectedShapes(data).map((shape) =>
  552. getShapeUtils(shape).getBounds(shape)
  553. )
  554. )
  555. }
  556. /**
  557. * Recursively update shape parents.
  558. * @param data
  559. * @param changedShapeIds
  560. */
  561. static updateParents(data: Data, changedShapeIds: string[]): void {
  562. if (changedShapeIds.length === 0) return
  563. const { shapes } = this.getPage(data)
  564. const parentToUpdateIds = Array.from(
  565. new Set(changedShapeIds.map((id) => shapes[id].parentId).values())
  566. ).filter((id) => id !== data.currentPageId)
  567. for (const parentId of parentToUpdateIds) {
  568. const parent = shapes[parentId] as GroupShape
  569. getShapeUtils(parent).onChildrenChange(
  570. parent,
  571. parent.children.map((id) => shapes[id])
  572. )
  573. shapes[parentId] = { ...parent }
  574. }
  575. this.updateParents(data, parentToUpdateIds)
  576. }
  577. /**
  578. * Populate the shape tree. This helper is recursive and only one call is needed.
  579. *
  580. * ### Example
  581. *
  582. *```ts
  583. * addDataToTree(data, selectedIds, allowHovers, branch, shape)
  584. *```
  585. */
  586. static addToShapeTree(
  587. data: Data,
  588. selectedIds: string[],
  589. branch: ShapeTreeNode[],
  590. shape: Shape
  591. ): void {
  592. const node = {
  593. shape,
  594. children: [],
  595. isHovered: data.hoveredId === shape.id,
  596. isCurrentParent: data.currentParentId === shape.id,
  597. isEditing: data.editingId === shape.id,
  598. isDarkMode: data.settings.isDarkMode,
  599. isSelected: selectedIds.includes(shape.id),
  600. }
  601. branch.push(node)
  602. if (shape.children) {
  603. shape.children
  604. .map((id) => this.getShape(data, id))
  605. .sort((a, b) => a.childIndex - b.childIndex)
  606. .forEach((childShape) => {
  607. this.addToShapeTree(data, selectedIds, node.children, childShape)
  608. })
  609. }
  610. }
  611. }