useCombineElement.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { Ref } from 'vue'
  2. import { useStore } from 'vuex'
  3. import { State, MutationTypes } from '@/store'
  4. import { PPTElement } from '@/types/slides'
  5. import { createRandomCode } from '@/utils/common'
  6. export default (elementList: Ref<PPTElement[]>, activeElementList: Ref<PPTElement[]>, activeElementIdList: Ref<string[]>) => {
  7. const store = useStore<State>()
  8. // 组合元素(为当前所有激活元素添加一个相同的groupId)
  9. const combineElements = () => {
  10. if(!activeElementList.value.length) return null
  11. let newElementList: PPTElement[] = JSON.parse(JSON.stringify(elementList))
  12. const groupId = createRandomCode()
  13. const combineElementList: PPTElement[] = []
  14. for(const element of newElementList) {
  15. if(activeElementIdList.value.includes(element.elId)) {
  16. element.groupId = groupId
  17. combineElementList.push(element)
  18. }
  19. }
  20. // 注意,组合元素的层级应该是连续的,所以需要获取该组元素中最顶层的元素,将组内其他成员从原位置移动到最顶层的元素的下面
  21. const combineElementMaxIndex = newElementList.findIndex(_element => _element.elId === combineElementList[combineElementList.length - 1].elId)
  22. const combineElementIdList = combineElementList.map(_element => _element.elId)
  23. newElementList = newElementList.filter(_element => !combineElementIdList.includes(_element.elId))
  24. const insertIndex = combineElementMaxIndex - combineElementList.length + 1
  25. newElementList.splice(insertIndex, 0, ...combineElementList)
  26. store.commit(MutationTypes.UPDATE_SLIDE, { elements: newElementList })
  27. }
  28. // 取消组合元素(移除所有被激活元素的groupId)
  29. const uncombineElements = () => {
  30. if(!activeElementList.value.length) return null
  31. const hasElementInGroup = activeElementList.value.some(item => item.groupId)
  32. if(!hasElementInGroup) return null
  33. const newElementList: PPTElement[] = JSON.parse(JSON.stringify(elementList))
  34. for(const element of newElementList) {
  35. if(activeElementIdList.value.includes(element.elId) && element.groupId) delete element.groupId
  36. }
  37. store.commit(MutationTypes.UPDATE_SLIDE, { elements: newElementList })
  38. }
  39. return {
  40. combineElements,
  41. uncombineElements,
  42. }
  43. }