diff options
Diffstat (limited to 'Sora/Views/Post/Details/Carousel/PostDetailsCarouselView.swift')
| -rw-r--r-- | Sora/Views/Post/Details/Carousel/PostDetailsCarouselView.swift | 41 |
1 files changed, 36 insertions, 5 deletions
diff --git a/Sora/Views/Post/Details/Carousel/PostDetailsCarouselView.swift b/Sora/Views/Post/Details/Carousel/PostDetailsCarouselView.swift index 94d258e..55d6243 100644 --- a/Sora/Views/Post/Details/Carousel/PostDetailsCarouselView.swift +++ b/Sora/Views/Post/Details/Carousel/PostDetailsCarouselView.swift @@ -2,9 +2,11 @@ import SwiftUI struct PostDetailsCarouselView: View { @EnvironmentObject var manager: BooruManager - @EnvironmentObject var settings: SettingsManager + @Environment(SettingsManager.self) + private var settings let posts: [BooruPost] let focusedPost: BooruPost? + let onFocusedPostChange: (BooruPost) -> Void @Binding var loadingStage: BooruPostLoadingState @State private var currentIndex: Int? private let cacheManager = ImageCacheManager.shared @@ -12,10 +14,14 @@ struct PostDetailsCarouselView: View { init( posts: [BooruPost], loadingStage: Binding<BooruPostLoadingState>, - focusedPost: BooruPost? = nil + focusedPost: BooruPost? = nil, + onFocusedPostChange: @escaping (BooruPost) -> Void = { _ in + // Default no-op callback for previews and callers that don't need focus updates. + } ) { self.posts = posts self.focusedPost = focusedPost + self.onFocusedPostChange = onFocusedPostChange _loadingStage = loadingStage if let focused = focusedPost, @@ -61,7 +67,9 @@ struct PostDetailsCarouselView: View { .scrollIndicators(.hidden) .scrollTargetBehavior(.paging) .onChange(of: currentIndex) { - guard let currentIndex else { return } + guard let currentIndex, posts.indices.contains(currentIndex) else { return } + + onFocusedPostChange(posts[currentIndex]) Task(priority: .utility) { if currentIndex == posts.count - 1 { await manager.loadNextPage() } @@ -69,7 +77,13 @@ struct PostDetailsCarouselView: View { preloadNearbyImages() } - .onAppear(perform: preloadNearbyImages) + .onChange(of: focusedPost?.id) { + syncCurrentIndexWithFocus() + } + .onAppear { + syncCurrentIndexWithFocus() + preloadNearbyImages() + } } private func preloadNearbyImages() { @@ -90,6 +104,23 @@ struct PostDetailsCarouselView: View { urlsToPreload.append(posts[index].previewURL) } - cacheManager.preloadImages(urlsToPreload) + cacheManager.preloadImages( + urlsToPreload, + domain: manager.domain, + sendUserAgent: settings.sendBooruUserAgent, + customUserAgent: settings.customBooruUserAgent + ) + } + + private func syncCurrentIndexWithFocus() { + if let focusedPost, + let index = posts.firstIndex(where: { $0.id == focusedPost.id }) + { + currentIndex = index + onFocusedPostChange(posts[index]) + } else if !posts.isEmpty { + currentIndex = 0 + onFocusedPostChange(posts[0]) + } } } |