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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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 ProjectUtils {
  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. * @param data
  129. * @param id
  130. */
  131. static getChildIndexAbove(data: Data, id: string): number {
  132. const page = this.getPage(data)
  133. const shape = page.shapes[id]
  134. const siblings = Object.values(page.shapes)
  135. .filter(({ parentId }) => parentId === shape.parentId)
  136. .sort((a, b) => a.childIndex - b.childIndex)
  137. const index = siblings.indexOf(shape)
  138. const nextSibling = siblings[index + 1]
  139. if (!nextSibling) {
  140. return shape.childIndex + 1
  141. }
  142. let nextIndex = (shape.childIndex + nextSibling.childIndex) / 2
  143. if (nextIndex === nextSibling.childIndex) {
  144. this.forceIntegerChildIndices(siblings)
  145. nextIndex = (shape.childIndex + nextSibling.childIndex) / 2
  146. }
  147. return nextIndex
  148. }
  149. /**
  150. * Get the next child index below a shape.
  151. * @param data
  152. * @param id
  153. * @param pageId
  154. */
  155. static getChildIndexBelow(data: Data, id: string): number {
  156. const page = this.getPage(data)
  157. const shape = page.shapes[id]
  158. const siblings = Object.values(page.shapes)
  159. .filter(({ parentId }) => parentId === shape.parentId)
  160. .sort((a, b) => a.childIndex - b.childIndex)
  161. const index = siblings.indexOf(shape)
  162. const prevSibling = siblings[index - 1]
  163. if (!prevSibling) {
  164. return shape.childIndex / 2
  165. }
  166. let nextIndex = (shape.childIndex + prevSibling.childIndex) / 2
  167. if (nextIndex === prevSibling.childIndex) {
  168. this.forceIntegerChildIndices(siblings)
  169. nextIndex = (shape.childIndex + prevSibling.childIndex) / 2
  170. }
  171. return (shape.childIndex + prevSibling.childIndex) / 2
  172. }
  173. /**
  174. * Assert whether a shape can have child shapes.
  175. * @param shape
  176. */
  177. static assertParentShape(shape: Shape): asserts shape is ParentShape {
  178. if (!('children' in shape)) {
  179. throw new AssertionError({
  180. message: `That shape was not a parent (it was a ${shape.type}).`,
  181. })
  182. }
  183. }
  184. /**
  185. * Get the top child index for a shape. This is potentially provisional:
  186. * sorting all shapes on the page for each new created shape will become
  187. * slower as the page grows. High indices aren't a problem, so consider
  188. * tracking the highest index for the page when shapes are created / deleted.
  189. *
  190. * @param data
  191. * @param id
  192. */
  193. static getTopChildIndex(data: Data, parent: Shape | Page): number {
  194. const page = this.getPage(data)
  195. // If the parent is a shape, return either 1 (if no other shapes) or the
  196. // highest sorted child index + 1.
  197. if (parent.type === 'page') {
  198. const children = Object.values(parent.shapes)
  199. if (children.length === 0) return 1
  200. return (
  201. children.sort((a, b) => b.childIndex - a.childIndex)[0].childIndex + 1
  202. )
  203. }
  204. // If the shape is a regular shape that can accept children, return either
  205. // 1 (if no other children) or the highest sorted child index + 1.
  206. this.assertParentShape(parent)
  207. if (parent.children.length === 0) return 1
  208. return (
  209. parent.children
  210. .map((id) => page.shapes[id])
  211. .sort((a, b) => b.childIndex - a.childIndex)[0].childIndex + 1
  212. )
  213. }
  214. /**
  215. * TODO: Make this recursive, so that it works for parented shapes.
  216. * Force all shapes on the page to have integer child indices.
  217. * @param shapes
  218. */
  219. static forceIntegerChildIndices(shapes: Shape[]): void {
  220. for (let i = 0; i < shapes.length; i++) {
  221. const shape = shapes[i]
  222. getShapeUtils(shape).setProperty(shape, 'childIndex', i + 1)
  223. }
  224. }
  225. /**
  226. * Update the zoom CSS variable.
  227. * @param zoom ;
  228. */
  229. static setZoomCSS(zoom: number): void {
  230. document.documentElement.style.setProperty('--camera-zoom', zoom.toString())
  231. }
  232. /* --------------------- Groups --------------------- */
  233. static getParentOffset(
  234. data: Data,
  235. shapeId: string,
  236. offset = [0, 0]
  237. ): number[] {
  238. const shape = this.getShape(data, shapeId)
  239. return shape.parentId === data.currentPageId
  240. ? offset
  241. : this.getParentOffset(data, shape.parentId, vec.add(offset, shape.point))
  242. }
  243. static getParentRotation(data: Data, shapeId: string, rotation = 0): number {
  244. const shape = this.getShape(data, shapeId)
  245. return shape.parentId === data.currentPageId
  246. ? rotation + shape.rotation
  247. : this.getParentRotation(data, shape.parentId, rotation + shape.rotation)
  248. }
  249. static getDocumentBranch(data: Data, id: string): string[] {
  250. const shape = this.getPage(data).shapes[id]
  251. if (shape.type !== ShapeType.Group) return [id]
  252. return [
  253. id,
  254. ...shape.children.flatMap((childId) =>
  255. this.getDocumentBranch(data, childId)
  256. ),
  257. ]
  258. }
  259. static getSelectedIds(data: Data): Set<string> {
  260. return data.pageStates[data.currentPageId].selectedIds
  261. }
  262. static setSelectedIds(data: Data, ids: string[]): Set<string> {
  263. data.pageStates[data.currentPageId].selectedIds = new Set(ids)
  264. return data.pageStates[data.currentPageId].selectedIds
  265. }
  266. static getTopParentId(data: Data, id: string): string {
  267. const shape = this.getPage(data).shapes[id]
  268. return shape.parentId === data.currentPageId ||
  269. shape.parentId === data.currentParentId
  270. ? id
  271. : this.getTopParentId(data, shape.parentId)
  272. }
  273. /* ----------------- Shapes Related ----------------- */
  274. /**
  275. * Get a deep-cloned
  276. * @param data
  277. * @param fn
  278. */
  279. static getSelectedBranchSnapshot<K>(
  280. data: Data,
  281. fn: <T extends Shape>(shape: T) => K
  282. ): ({ id: string } & K)[]
  283. static getSelectedBranchSnapshot(data: Data): Shape[]
  284. static getSelectedBranchSnapshot<
  285. K,
  286. F extends <T extends Shape>(shape: T) => K
  287. >(data: Data, fn?: F): (Shape | K)[] {
  288. const page = this.getPage(data)
  289. const copies = setToArray(this.getSelectedIds(data))
  290. .flatMap((id) =>
  291. this.getDocumentBranch(data, id).map((id) => page.shapes[id])
  292. )
  293. .filter((shape) => !shape.isLocked)
  294. .map(deepClone)
  295. if (fn !== undefined) {
  296. return copies.map((shape) => ({ id: shape.id, ...fn(shape) }))
  297. }
  298. return copies
  299. }
  300. /**
  301. * Get a deep-cloned array of shapes
  302. * @param data
  303. */
  304. static getSelectedShapeSnapshot(data: Data): Shape[]
  305. static getSelectedShapeSnapshot<K>(
  306. data: Data,
  307. fn: <T extends Shape>(shape: T) => K
  308. ): ({ id: string } & K)[]
  309. static getSelectedShapeSnapshot<
  310. K,
  311. F extends <T extends Shape>(shape: T) => K
  312. >(data: Data, fn?: F): (Shape | K)[] {
  313. const copies = this.getSelectedShapes(data)
  314. .filter((shape) => !shape.isLocked)
  315. .map(deepClone)
  316. if (fn !== undefined) {
  317. return copies.map((shape) => ({ id: shape.id, ...fn(shape) }))
  318. }
  319. return copies
  320. }
  321. /**
  322. * Get an array of all unique parentIds among a set of shapes.
  323. * @param data
  324. * @param shapes
  325. */
  326. static getUniqueParentIds(data: Data, shapes: Shape[]): string[] {
  327. return Array.from(new Set(shapes.map((s) => s.parentId)).values()).filter(
  328. (id) => id !== data.currentPageId
  329. )
  330. }
  331. /**
  332. * Make an arbitrary change to shape.
  333. * @param data
  334. * @param ids
  335. * @param fn
  336. */
  337. static mutateShape<T extends Shape>(
  338. data: Data,
  339. id: string,
  340. fn: (shapeUtils: ShapeUtility<T>, shape: T) => void,
  341. updateParents = true
  342. ): T {
  343. const page = this.getPage(data)
  344. const shape = page.shapes[id] as T
  345. fn(getShapeUtils(shape) as ShapeUtility<T>, shape)
  346. if (updateParents) this.updateParents(data, [id])
  347. return shape
  348. }
  349. /**
  350. * Make an arbitrary change to a set of shapes.
  351. * @param data
  352. * @param ids
  353. * @param fn
  354. */
  355. static mutateShapes<T extends Shape>(
  356. data: Data,
  357. ids: string[],
  358. fn: (shape: T, shapeUtils: ShapeUtility<T>, index: number) => T | void,
  359. updateParents = true
  360. ): T[] {
  361. const page = this.getPage(data)
  362. const mutatedShapes = ids.map((id, i) => {
  363. const shape = page.shapes[id] as T
  364. // Define the new shape as either the (maybe new) shape returned by the
  365. // function or the mutated shape.
  366. page.shapes[id] =
  367. fn(shape, getShapeUtils(shape) as ShapeUtility<T>, i) || shape
  368. return page.shapes[id] as T
  369. })
  370. if (updateParents) this.updateParents(data, ids)
  371. return mutatedShapes
  372. }
  373. /**
  374. * Insert shapes into the current page.
  375. * @param data
  376. * @param shapes
  377. */
  378. static insertShapes(data: Data, shapes: Shape[]): void {
  379. const page = this.getPage(data)
  380. shapes.forEach((shape) => {
  381. page.shapes[shape.id] = shape
  382. // Does the shape have a parent?
  383. if (shape.parentId !== data.currentPageId) {
  384. // The parent shape
  385. const parent = page.shapes[shape.parentId]
  386. // If the parent shape doesn't exist, assign the shape as a child
  387. // of the page instead.
  388. if (parent === undefined) {
  389. getShapeUtils(shape).setProperty(
  390. shape,
  391. 'childIndex',
  392. this.getTopChildIndex(data, parent)
  393. )
  394. } else {
  395. // Add the shape's id to the parent's children, then sort the
  396. // new array just to be sure.
  397. getShapeUtils(parent).setProperty(
  398. parent,
  399. 'children',
  400. [...parent.children, shape.id]
  401. .map((id) => page.shapes[id])
  402. .sort((a, b) => a.childIndex - b.childIndex)
  403. .map((shape) => shape.id)
  404. )
  405. }
  406. }
  407. })
  408. // Update any new parents
  409. this.updateParents(
  410. data,
  411. shapes.map((shape) => shape.id)
  412. )
  413. }
  414. static getRotatedBounds(shape: Shape): Bounds {
  415. return getShapeUtils(shape).getRotatedBounds(shape)
  416. }
  417. static getShapeBounds(shape: Shape): Bounds {
  418. return getShapeUtils(shape).getBounds(shape)
  419. }
  420. static getSelectedBounds(data: Data): Bounds {
  421. return getCommonBounds(
  422. ...this.getSelectedShapes(data).map((shape) =>
  423. getShapeUtils(shape).getBounds(shape)
  424. )
  425. )
  426. }
  427. /**
  428. * Recursively update shape parents.
  429. * @param data
  430. * @param changedShapeIds
  431. */
  432. static updateParents(data: Data, changedShapeIds: string[]): void {
  433. if (changedShapeIds.length === 0) return
  434. const { shapes } = this.getPage(data)
  435. const parentToUpdateIds = Array.from(
  436. new Set(changedShapeIds.map((id) => shapes[id].parentId).values())
  437. ).filter((id) => id !== data.currentPageId)
  438. for (const parentId of parentToUpdateIds) {
  439. const parent = shapes[parentId] as GroupShape
  440. getShapeUtils(parent).onChildrenChange(
  441. parent,
  442. parent.children.map((id) => shapes[id])
  443. )
  444. shapes[parentId] = { ...parent }
  445. }
  446. this.updateParents(data, parentToUpdateIds)
  447. }
  448. }