summaryrefslogtreecommitdiff
path: root/Sora/Views/Post/Details/PostDetailsCarouselView.swift
blob: 378b9cc618c59ef32d92faa9ae9d6b7352493864 (plain) (blame)
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
import SwiftUI

struct PostDetailsCarouselView: View {
  @EnvironmentObject var manager: BooruManager
  @EnvironmentObject var settings: SettingsManager
  let posts: [BooruPost]
  let focusedPost: BooruPost?
  @Binding var loadingStage: BooruPostLoadingState
  @State private var currentIndex: Int

  init(
    posts: [BooruPost],
    loadingStage: Binding<BooruPostLoadingState>,
    focusedPost: BooruPost? = nil
  ) {
    self.posts = posts
    self.focusedPost = focusedPost
    _loadingStage = loadingStage

    if let focused = focusedPost,
      let index = posts.firstIndex(where: { $0.id == focused.id })
    {
      self._currentIndex = State(initialValue: index)
    } else {
      self._currentIndex = State(initialValue: 0)
    }
  }

  func imageURL(post: BooruPost) -> URL? {
    switch settings.detailViewQuality {
    case .preview:
      post.previewURL

    case .sample:
      post.sampleURL

    case .original:
      post.fileURL
    }
  }

  var body: some View {
    TabView(selection: $currentIndex) {
      ForEach(posts.indices, id: \.self) { index in
        ZStack {
          PostDetailsImageView(
            url: posts[index].previewURL,
            loadingStage: $loadingStage
          )
          .opacity(loadingStage == .loaded ? 0 : 1)

          PostDetailsImageView(
            url: imageURL(post: posts[index]),
            loadingStage: $loadingStage,
            finalLoadingState: .loaded,
            post: posts[index]
          )
        }
        .tag(index)
      }
    }
    .onChange(of: currentIndex) {
      if currentIndex == posts.count - 1 { manager.loadNextPage() }
    }
    #if !os(macOS)
      .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
    #endif
  }
}