compact.ts 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { sortLayout } from "./sort";
  2. import { getFirstCollison } from "./collison";
  3. import { DragactLayoutItem, mapLayout } from "../dragact-type";
  4. import { GridItemEvent } from "../GridItem";
  5. /**
  6. * 压缩单个元素,使得每一个元素都会紧挨着边界或者相邻的元素
  7. * @param {*} finishedLayout 压缩完的元素会放进这里来,用来对比之后的每一个元素是否需要压缩
  8. * @param {*} item
  9. */
  10. export const compactItem = (finishedLayout: DragactLayoutItem[], item: DragactLayoutItem) => {
  11. if (item.static) return item;
  12. const newItem = { ...item, key: item.key + '' }
  13. if (finishedLayout.length === 0) {
  14. return { ...newItem, GridY: 0 }
  15. }
  16. /**
  17. * 类似一个递归调用
  18. */
  19. while (true) {
  20. let FirstCollison = getFirstCollison(finishedLayout, newItem)
  21. if (FirstCollison) {
  22. /**第一次发生碰撞时,就可以返回了 */
  23. newItem.GridY = FirstCollison.GridY + FirstCollison.h
  24. return newItem
  25. }
  26. newItem.GridY--
  27. if (newItem.GridY < 0) return { ...newItem, GridY: 0 }/**碰到边界的时候,返回 */
  28. }
  29. }
  30. /**
  31. * 压缩layout,使得每一个元素都会紧挨着边界或者相邻的元素
  32. * @param {*} layout
  33. */
  34. export const compactLayout = function () {
  35. var _cache: any = {
  36. };
  37. return function (layout: DragactLayoutItem[], movingItem: GridItemEvent | undefined, mapedLayout: mapLayout | undefined) {
  38. if (movingItem) {
  39. if (_cache.GridX === movingItem.GridX
  40. && _cache.GridY === movingItem.GridY &&
  41. _cache.w === movingItem.w &&
  42. _cache.h === movingItem.h &&
  43. _cache.UniqueKey === movingItem.UniqueKey
  44. ) {
  45. return {
  46. compacted: layout,
  47. mapLayout: mapedLayout
  48. };
  49. }
  50. _cache = movingItem;
  51. }
  52. let sorted = sortLayout(layout)//把静态的放在前面
  53. const needCompact = Array(layout.length)
  54. const compareList = []
  55. const mapLayout: mapLayout = {};
  56. for (let i = 0, length = sorted.length; i < length; i++) {
  57. let finished = compactItem(compareList, sorted[i])
  58. if (movingItem) {
  59. if (movingItem.UniqueKey === finished.key) {
  60. movingItem.GridX = finished.GridX;
  61. movingItem.GridY = finished.GridY;
  62. finished.isUserMove = true
  63. } else
  64. finished.isUserMove = false
  65. }
  66. else
  67. finished.isUserMove = false
  68. compareList.push(finished)
  69. needCompact[i] = finished
  70. mapLayout[finished.key + ''] = finished;
  71. }
  72. return {
  73. compacted: needCompact,
  74. mapLayout
  75. }
  76. }
  77. }()