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.

tld.ts 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. import { clamp, deepClone, getCommonBounds, setToArray } 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. } from 'types'
  16. import { AssertionError } from 'assert'
  17. export default class StateUtils {
  18. static getCameraZoom(zoom: number): number {
  19. return clamp(zoom, 0.1, 5)
  20. }
  21. static screenToWorld(point: number[], data: Data): number[] {
  22. const camera = this.getCurrentCamera(data)
  23. return vec.sub(vec.div(point, camera.zoom), camera.point)
  24. }
  25. static getViewport(data: Data): Bounds {
  26. const [minX, minY] = this.screenToWorld([0, 0], data)
  27. const [maxX, maxY] = this.screenToWorld(
  28. [window.innerWidth, window.innerHeight],
  29. data
  30. )
  31. return {
  32. minX,
  33. minY,
  34. maxX,
  35. maxY,
  36. height: maxX - minX,
  37. width: maxY - minY,
  38. }
  39. }
  40. static getCurrentCamera(data: Data): {
  41. point: number[]
  42. zoom: number
  43. } {
  44. return data.pageStates[data.currentPageId].camera
  45. }
  46. /**
  47. * Get a shape from the project.
  48. * @param data
  49. * @param shapeId
  50. */
  51. static getShape(data: Data, shapeId: string): Shape {
  52. return data.document.pages[data.currentPageId].shapes[shapeId]
  53. }
  54. /**
  55. * Get the current page.
  56. * @param data
  57. */
  58. static getPage(data: Data): Page {
  59. return data.document.pages[data.currentPageId]
  60. }
  61. /**
  62. * Get the current page's page state.
  63. * @param data
  64. */
  65. static getPageState(data: Data): PageState {
  66. return data.pageStates[data.currentPageId]
  67. }
  68. /**
  69. * Get the current page's code file.
  70. * @param data
  71. * @param fileId
  72. */
  73. static getCurrentCode(data: Data, fileId: string): CodeFile {
  74. return data.document.code[fileId]
  75. }
  76. /**
  77. * Get the current page's shapes as an array.
  78. * @param data
  79. */
  80. static getShapes(data: Data): Shape[] {
  81. const page = this.getPage(data)
  82. return Object.values(page.shapes)
  83. }
  84. /**
  85. * Get the current selected shapes as an array.
  86. * @param data
  87. */
  88. static getSelectedShapes(data: Data): Shape[] {
  89. const page = this.getPage(data)
  90. const ids = setToArray(this.getSelectedIds(data))
  91. return ids.map((id) => page.shapes[id])
  92. }
  93. /**
  94. * Get a shape's parent.
  95. * @param data
  96. * @param id
  97. */
  98. static getParent(data: Data, id: string): Shape | Page {
  99. const page = this.getPage(data)
  100. const shape = page.shapes[id]
  101. return page.shapes[shape.parentId] || data.document.pages[shape.parentId]
  102. }
  103. /**
  104. * Get a shape's children.
  105. * @param data
  106. * @param id
  107. */
  108. static getChildren(data: Data, id: string): Shape[] {
  109. const page = this.getPage(data)
  110. return Object.values(page.shapes)
  111. .filter(({ parentId }) => parentId === id)
  112. .sort((a, b) => a.childIndex - b.childIndex)
  113. }
  114. /**
  115. * Get a shape's siblings.
  116. * @param data
  117. * @param id
  118. */
  119. static getSiblings(data: Data, id: string): Shape[] {
  120. const page = this.getPage(data)
  121. const shape = page.shapes[id]
  122. return Object.values(page.shapes)
  123. .filter(({ parentId }) => parentId === shape.parentId)
  124. .sort((a, b) => a.childIndex - b.childIndex)
  125. }
  126. /**
  127. * Get the next child index above a shape.
  128. * TODO: Make work for grouped shapes, make faster.
  129. * @param data
  130. * @param id
  131. */
  132. static getChildIndexAbove(data: Data, id: string): number {
  133. const page = this.getPage(data)
  134. const shape = page.shapes[id]
  135. const siblings = Object.values(page.shapes)
  136. .filter(({ parentId }) => parentId === shape.parentId)
  137. .sort((a, b) => a.childIndex - b.childIndex)
  138. const index = siblings.indexOf(shape)
  139. const nextSibling = siblings[index + 1]
  140. if (!nextSibling) return shape.childIndex + 1
  141. let nextIndex = (shape.childIndex + nextSibling.childIndex) / 2
  142. if (nextIndex === nextSibling.childIndex) {
  143. this.forceIntegerChildIndices(siblings)
  144. nextIndex = (shape.childIndex + nextSibling.childIndex) / 2
  145. }
  146. return nextIndex
  147. }
  148. /**
  149. * Get the next child index below a shape.
  150. * @param data
  151. * @param id
  152. * @param pageId
  153. */
  154. static getChildIndexBelow(data: Data, id: string): number {
  155. const page = this.getPage(data)
  156. const shape = page.shapes[id]
  157. const siblings = Object.values(page.shapes)
  158. .filter(({ parentId }) => parentId === shape.parentId)
  159. .sort((a, b) => a.childIndex - b.childIndex)
  160. const index = siblings.indexOf(shape)
  161. const prevSibling = siblings[index - 1]
  162. if (!prevSibling) {
  163. return shape.childIndex / 2
  164. }
  165. let nextIndex = (shape.childIndex + prevSibling.childIndex) / 2
  166. if (nextIndex === prevSibling.childIndex) {
  167. this.forceIntegerChildIndices(siblings)
  168. nextIndex = (shape.childIndex + prevSibling.childIndex) / 2
  169. }
  170. return (shape.childIndex + prevSibling.childIndex) / 2
  171. }
  172. /**
  173. * Assert whether a shape can have child shapes.
  174. * @param shape
  175. */
  176. static assertParentShape(shape: Shape): asserts shape is ParentShape {
  177. if (!('children' in shape)) {
  178. throw new AssertionError({
  179. message: `That shape was not a parent (it was a ${shape.type}).`,
  180. })
  181. }
  182. }
  183. /**
  184. * Get the top child index for a shape. This is potentially provisional:
  185. * sorting all shapes on the page for each new created shape will become
  186. * slower as the page grows. High indices aren't a problem, so consider
  187. * tracking the highest index for the page when shapes are created / deleted.
  188. *
  189. * @param data
  190. * @param id
  191. */
  192. static getTopChildIndex(data: Data, parent: Shape | Page): number {
  193. const page = this.getPage(data)
  194. // If the parent is a shape, return either 1 (if no other shapes) or the
  195. // highest sorted child index + 1.
  196. if (parent.type === 'page') {
  197. const children = Object.values(parent.shapes)
  198. if (children.length === 0) return 1
  199. return (
  200. children.sort((a, b) => b.childIndex - a.childIndex)[0].childIndex + 1
  201. )
  202. }
  203. // If the shape is a regular shape that can accept children, return either
  204. // 1 (if no other children) or the highest sorted child index + 1.
  205. this.assertParentShape(parent)
  206. if (parent.children.length === 0) return 1
  207. return (
  208. parent.children
  209. .map((id) => page.shapes[id])
  210. .sort((a, b) => b.childIndex - a.childIndex)[0].childIndex + 1
  211. )
  212. }
  213. /**
  214. * TODO: Make this recursive, so that it works for parented shapes.
  215. * Force all shapes on the page to have integer child indices.
  216. * @param shapes
  217. */
  218. static forceIntegerChildIndices(shapes: Shape[]): void {
  219. for (let i = 0; i < shapes.length; i++) {
  220. const shape = shapes[i]
  221. getShapeUtils(shape).setProperty(shape, 'childIndex', i + 1)
  222. }
  223. }
  224. /**
  225. * Update the zoom CSS variable.
  226. * @param zoom ;
  227. */
  228. static setZoomCSS(zoom: number): void {
  229. document.documentElement.style.setProperty('--camera-zoom', zoom.toString())
  230. }
  231. /* --------------------- Groups --------------------- */
  232. static getParentOffset(
  233. data: Data,
  234. shapeId: string,
  235. offset = [0, 0]
  236. ): number[] {
  237. const shape = this.getShape(data, shapeId)
  238. return shape.parentId === data.currentPageId
  239. ? offset
  240. : this.getParentOffset(data, shape.parentId, vec.add(offset, shape.point))
  241. }
  242. static getParentRotation(data: Data, shapeId: string, rotation = 0): number {
  243. const shape = this.getShape(data, shapeId)
  244. return shape.parentId === data.currentPageId
  245. ? rotation + shape.rotation
  246. : this.getParentRotation(data, shape.parentId, rotation + shape.rotation)
  247. }
  248. static getDocumentBranch(data: Data, id: string): string[] {
  249. const shape = this.getPage(data).shapes[id]
  250. if (shape.type !== ShapeType.Group) return [id]
  251. return [
  252. id,
  253. ...shape.children.flatMap((childId) =>
  254. this.getDocumentBranch(data, childId)
  255. ),
  256. ]
  257. }
  258. static getSelectedIds(data: Data): Set<string> {
  259. return data.pageStates[data.currentPageId].selectedIds
  260. }
  261. static setSelectedIds(data: Data, ids: string[]): Set<string> {
  262. data.pageStates[data.currentPageId].selectedIds = new Set(ids)
  263. return data.pageStates[data.currentPageId].selectedIds
  264. }
  265. static getTopParentId(data: Data, id: string): string {
  266. const shape = this.getPage(data).shapes[id]
  267. return shape.parentId === data.currentPageId ||
  268. shape.parentId === data.currentParentId
  269. ? id
  270. : this.getTopParentId(data, shape.parentId)
  271. }
  272. /* ----------------- Shapes Related ----------------- */
  273. /**
  274. * Get a deep-cloned
  275. * @param data
  276. * @param fn
  277. */
  278. static getSelectedBranchSnapshot<K>(
  279. data: Data,
  280. fn: <T extends Shape>(shape: T) => K
  281. ): ({ id: string } & K)[]
  282. static getSelectedBranchSnapshot(data: Data): Shape[]
  283. static getSelectedBranchSnapshot<
  284. K,
  285. F extends <T extends Shape>(shape: T) => K
  286. >(data: Data, fn?: F): (Shape | K)[] {
  287. const page = this.getPage(data)
  288. const copies = setToArray(this.getSelectedIds(data))
  289. .flatMap((id) =>
  290. this.getDocumentBranch(data, id).map((id) => page.shapes[id])
  291. )
  292. .filter((shape) => !shape.isLocked)
  293. .map(deepClone)
  294. if (fn !== undefined) {
  295. return copies.map((shape) => ({ id: shape.id, ...fn(shape) }))
  296. }
  297. return copies
  298. }
  299. /**
  300. * Get a deep-cloned array of shapes
  301. * @param data
  302. */
  303. static getSelectedShapeSnapshot(data: Data): Shape[]
  304. static getSelectedShapeSnapshot<K>(
  305. data: Data,
  306. fn: <T extends Shape>(shape: T) => K
  307. ): ({ id: string } & K)[]
  308. static getSelectedShapeSnapshot<
  309. K,
  310. F extends <T extends Shape>(shape: T) => K
  311. >(data: Data, fn?: F): (Shape | K)[] {
  312. const copies = this.getSelectedShapes(data)
  313. .filter((shape) => !shape.isLocked)
  314. .map(deepClone)
  315. if (fn !== undefined) {
  316. return copies.map((shape) => ({ id: shape.id, ...fn(shape) }))
  317. }
  318. return copies
  319. }
  320. /**
  321. * Get an array of all unique parentIds among a set of shapes.
  322. * @param data
  323. * @param shapes
  324. */
  325. static getUniqueParentIds(data: Data, shapes: Shape[]): string[] {
  326. return Array.from(new Set(shapes.map((s) => s.parentId)).values()).filter(
  327. (id) => id !== data.currentPageId
  328. )
  329. }
  330. /**
  331. * Make an arbitrary change to shape.
  332. * @param data
  333. * @param ids
  334. * @param fn
  335. */
  336. static mutateShape<T extends Shape>(
  337. data: Data,
  338. id: string,
  339. fn: (shapeUtils: ShapeUtility<T>, shape: T) => void,
  340. updateParents = true
  341. ): T {
  342. const page = this.getPage(data)
  343. const shape = page.shapes[id] as T
  344. fn(getShapeUtils(shape) as ShapeUtility<T>, shape)
  345. if (updateParents) this.updateParents(data, [id])
  346. return shape
  347. }
  348. /**
  349. * Make an arbitrary change to a set of shapes.
  350. * @param data
  351. * @param ids
  352. * @param fn
  353. */
  354. static mutateShapes<T extends Shape>(
  355. data: Data,
  356. ids: string[],
  357. fn: (shape: T, shapeUtils: ShapeUtility<T>, index: number) => T | void,
  358. updateParents = true
  359. ): T[] {
  360. const page = this.getPage(data)
  361. const mutatedShapes = ids.map((id, i) => {
  362. const shape = page.shapes[id] as T
  363. // Define the new shape as either the (maybe new) shape returned by the
  364. // function or the mutated shape.
  365. page.shapes[id] =
  366. fn(shape, getShapeUtils(shape) as ShapeUtility<T>, i) || shape
  367. return page.shapes[id] as T
  368. })
  369. if (updateParents) this.updateParents(data, ids)
  370. return mutatedShapes
  371. }
  372. /**
  373. * Insert shapes into the current page.
  374. * @param data
  375. * @param shapes
  376. */
  377. static insertShapes(data: Data, shapes: Shape[]): void {
  378. const page = this.getPage(data)
  379. shapes.forEach((shape) => {
  380. page.shapes[shape.id] = shape
  381. // Does the shape have a parent?
  382. if (shape.parentId !== data.currentPageId) {
  383. // The parent shape
  384. const parent = page.shapes[shape.parentId]
  385. // If the parent shape doesn't exist, assign the shape as a child
  386. // of the page instead.
  387. if (parent === undefined) {
  388. getShapeUtils(shape).setProperty(
  389. shape,
  390. 'childIndex',
  391. this.getTopChildIndex(data, parent)
  392. )
  393. } else {
  394. // Add the shape's id to the parent's children, then sort the
  395. // new array just to be sure.
  396. getShapeUtils(parent).setProperty(
  397. parent,
  398. 'children',
  399. [...parent.children, shape.id]
  400. .map((id) => page.shapes[id])
  401. .sort((a, b) => a.childIndex - b.childIndex)
  402. .map((shape) => shape.id)
  403. )
  404. }
  405. }
  406. })
  407. // Update any new parents
  408. this.updateParents(
  409. data,
  410. shapes.map((shape) => shape.id)
  411. )
  412. }
  413. static getRotatedBounds(shape: Shape): Bounds {
  414. return getShapeUtils(shape).getRotatedBounds(shape)
  415. }
  416. static getShapeBounds(shape: Shape): Bounds {
  417. return getShapeUtils(shape).getBounds(shape)
  418. }
  419. static getSelectedBounds(data: Data): Bounds {
  420. return getCommonBounds(
  421. ...this.getSelectedShapes(data).map((shape) =>
  422. getShapeUtils(shape).getBounds(shape)
  423. )
  424. )
  425. }
  426. /**
  427. * Recursively update shape parents.
  428. * @param data
  429. * @param changedShapeIds
  430. */
  431. static updateParents(data: Data, changedShapeIds: string[]): void {
  432. if (changedShapeIds.length === 0) return
  433. const { shapes } = this.getPage(data)
  434. const parentToUpdateIds = Array.from(
  435. new Set(changedShapeIds.map((id) => shapes[id].parentId).values())
  436. ).filter((id) => id !== data.currentPageId)
  437. for (const parentId of parentToUpdateIds) {
  438. const parent = shapes[parentId] as GroupShape
  439. getShapeUtils(parent).onChildrenChange(
  440. parent,
  441. parent.children.map((id) => shapes[id])
  442. )
  443. shapes[parentId] = { ...parent }
  444. }
  445. this.updateParents(data, parentToUpdateIds)
  446. }
  447. }