File size: 2,210 Bytes
89ce340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { storeToRefs } from 'pinia'
import { nanoid } from 'nanoid'
import { useSlidesStore } from '@/store'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'
import useSlideHandler from '@/hooks/useSlideHandler'

export default () => {
  const slidesStore = useSlidesStore()
  const { slides } = storeToRefs(slidesStore)

  const { addHistorySnapshot } = useHistorySnapshot()
  const { deleteSlide } = useSlideHandler()

  const createSection = () => {
    slidesStore.updateSlide({
      sectionTag: {
        id: nanoid(6),
      },
    })
    addHistorySnapshot()
  }

  const removeSection = (sectionId: string) => {
    if (!sectionId) return

    const slide = slides.value.find(slide => slide.sectionTag?.id === sectionId)!
    slidesStore.removeSlideProps({
      id: slide.id,
      propName: 'sectionTag',
    })
    addHistorySnapshot()
  }

  const removeAllSection = () => {
    const _slides = slides.value.map(slide => {
      if (slide.sectionTag) delete slide.sectionTag
      return slide
    })
    slidesStore.setSlides(_slides)
    addHistorySnapshot()
  }

  const removeSectionSlides = (sectionId: string) => {
    let startIndex = 0
    if (sectionId) {
      startIndex = slides.value.findIndex(slide => slide.sectionTag?.id === sectionId)
    }
    const ids: string[] = []
    
    for (let i = startIndex; i < slides.value.length; i++) {
      const slide = slides.value[i]
      if (i !== startIndex && slide.sectionTag) break

      ids.push(slide.id)
    }

    deleteSlide(ids)
  }

  const updateSectionTitle = (sectionId: string, title: string) => {
    if (!title) return

    if (sectionId === 'default') {
      slidesStore.updateSlide({
        sectionTag: {
          id: nanoid(6),
          title,
        },
      }, slides.value[0].id)
    }
    else {
      const slide = slides.value.find(slide => slide.sectionTag?.id === sectionId)
      if (!slide) return

      slidesStore.updateSlide({
        sectionTag: {
          ...slide.sectionTag!,
          title,
        },
      }, slide.id)
    }
    addHistorySnapshot()
  }

  return {
    createSection,
    removeSection,
    removeAllSection,
    removeSectionSlides,
    updateSectionTitle,
  }
}