r-compact.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { sortLayout } from "./sort";
  2. import { getFirstCollison } from "./collison";
  3. /**
  4. * 压缩单个元素,使得每一个元素都会紧挨着边界或者相邻的元素
  5. * @param {*} finishedLayout 压缩完的元素会放进这里来,用来对比之后的每一个元素是否需要压缩
  6. * @param {*} item
  7. */
  8. export const compactItem = (finishedLayout, item) => {
  9. if (item.static) return item;
  10. const newItem = { ...item }
  11. if (finishedLayout.length === 0) {
  12. return { ...newItem, GridY: 0 }
  13. }
  14. /**
  15. * 类似一个递归调用
  16. */
  17. while (true) {
  18. let FirstCollison = getFirstCollison(finishedLayout, newItem)
  19. if (FirstCollison) {
  20. /**第一次发生碰撞时,就可以返回了 */
  21. newItem.GridY = FirstCollison.GridY + FirstCollison.h
  22. return newItem
  23. }
  24. newItem.GridY--
  25. if (newItem.GridY < 0) return { ...newItem, GridY: 0 }/**碰到边界的时候,返回 */
  26. }
  27. return newItem
  28. }
  29. /**
  30. * 压缩layout,使得每一个元素都会紧挨着边界或者相邻的元素
  31. * @param {*} layout
  32. */
  33. export const compactLayout = (layout) => {
  34. let sorted = sortLayout(layout)
  35. const needCompact = Array(layout.length)
  36. const compareList = []
  37. for (let i = 0, length = sorted.length; i < length; i++) {
  38. let finished = compactItem(compareList, sorted[i])
  39. finished.isUserMove = false
  40. compareList.push(finished)
  41. needCompact[i] = finished
  42. }
  43. return needCompact
  44. }