summaryrefslogtreecommitdiff
path: root/Sora/Views/Post/Grid/PostGridView.swift
blob: 7cfa20686b2a38aed40cde762dc4391a30d3b416 (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// swiftlint:disable file_length

import SwiftUI
import WaterfallGrid

struct PostGridView: View {  // swiftlint:disable:this type_body_length
  @EnvironmentObject var settings: SettingsManager
  @EnvironmentObject var manager: BooruManager
  @State private var isSearchHistoryPresented = false
  @Binding var selectedTab: Int
  @State private var isSearchablePresented = false
  @State private var cachedSuggestions: [Either<BooruTag, BooruSearchQuery>] = []
  @State private var suppressNextSearchSubmit = false
  @State private var searchTask: Task<Void, Never>?
  @State private var suggestions: [BooruTag] = []
  @State private var cachedColumnsData: ColumnsDataCache?
  let initialTag: String?
  @Binding var navigationPath: NavigationPath
  @State private var localPosts: [BooruPost] = []
  @State private var localIsLoading = false
  @State private var localCurrentPage = 1
  @State private var localSearchText = ""
  @State private var localEndOfData = false
  @State private var localError: Error?
  @State private var hasAppearedBefore = false
  @State private var currentLocalTask: Task<Void, Never>?
  @State private var previousNavigationPathCount = 0

  init(
    selectedTab: Binding<Int>, navigationPath: Binding<NavigationPath>, initialTag: String? = nil
  ) {
    self._selectedTab = selectedTab
    self.initialTag = initialTag
    self._navigationPath = navigationPath
  }

  @Environment(\.isSearching)
  private var isSearching

  private var activePosts: [BooruPost] {
    let posts = initialTag != nil ? localPosts : manager.posts

    return posts.filter { settings.displayRatings.contains($0.rating) }
  }

  private var isLoading: Bool {
    initialTag != nil ? localIsLoading : manager.isLoading
  }

  private var searchText: Binding<String> {
    if initialTag != nil {
      return Binding(
        get: { localSearchText },
        set: { localSearchText = $0 }
      )
    }

    return Binding(
      get: { manager.searchText },
      set: { manager.searchText = $0 }
    )
  }

  @ViewBuilder private var gridContent: some View {
    if let error = (initialTag != nil ? localError : manager.error) {
      ContentUnavailableView(
        "Provider Error",
        systemImage: "exclamationmark.triangle.fill",
        description: Text(error.localizedDescription)
      )
    }

    if activePosts.isEmpty, isLoading {
      placeholderGrid
    } else {
      gridView(columnCount: settings.thumbnailGridColumns)
    }
  }

  @ViewBuilder private var placeholderGrid: some View {
    let gridItems = Array(
      repeating: GridItem(.flexible()),
      count: settings.thumbnailGridColumns
    )

    LazyVGrid(columns: gridItems) {
      ForEach(0..<(50 / settings.thumbnailGridColumns), id: \.self) { _ in
        PostGridThumbnailPlaceholderView()
      }
    }
    #if os(macOS)
      .padding(8)
    #else
      .padding(.horizontal)
    #endif
    .transition(.opacity)
  }

  @ViewBuilder
  private func gridView(columnCount: Int) -> some View {
    if settings.alternativeThumbnailGrid {
      let columnsData = getColumnsData(columnCount: columnCount)

      HStack(alignment: .top) {
        ForEach(0..<columnCount, id: \.self) { columnIndex in
          LazyVStack {
            ForEach(columnsData[columnIndex], id: \.id) { post in
              waterfallGridContent(post: post)
                .id(post.id)
            }
          }
          .transaction { $0.animation = nil }
        }
      }
      #if os(macOS)
        .padding(8)
      #else
        .padding(.horizontal)
      #endif
      .transition(.opacity)
    } else {
      WaterfallGrid(activePosts, id: \.id) { post in
        waterfallGridContent(post: post)
          .id(post.id)
      }
      .gridStyle(columns: columnCount)
      .transaction { $0.animation = nil }
      #if os(macOS)
        .padding(8)
      #else
        .padding(.horizontal)
      #endif
      .transition(.opacity)
    }
  }

  private func getColumnsData(columnCount: Int) -> [[BooruPost]] {
    if let cached = cachedColumnsData,
      cached
        == ColumnsDataCache(
          data: cached.data,
          columnCount: columnCount,
          posts: activePosts
        )
    {
      return cached.data
    }

    let computedData = (0..<columnCount).map { columnIndex in
      activePosts.enumerated().compactMap { index, post in
        index % columnCount == columnIndex ? post : nil
      }
    }

    cachedColumnsData = ColumnsDataCache(
      data: computedData,
      columnCount: columnCount,
      posts: activePosts
    )

    return computedData
  }

  var body: some View {
    ScrollView {
      gridContent
        .transition(.opacity)
    }
    #if os(iOS)
      .searchable(
        text: searchText,
        isPresented: $isSearchablePresented,
        placement: .navigationBarDrawer(displayMode: .automatic),
        prompt: "Tags"
      )
    #else
      .searchable(
        text: searchText,
        isPresented: $isSearchablePresented,
        prompt: "Tags"
      )
    #endif
    .searchSuggestions {
      if settings.searchSuggestionsMode != .disabled && isSearchablePresented {
        SearchSuggestionsView(
          items: searchSuggestionsItems(),
          searchText: searchText,
          suppressNextSearchSubmit: $suppressNextSearchSubmit
        )
      }
    }
    .onChange(of: searchText.wrappedValue) { _, newValue in
      if settings.searchSuggestionsMode == .tags {
        searchTask?.cancel()

        searchTask = Task {
          try? await Task.sleep(nanoseconds: 300_000_000)

          guard !Task.isCancelled else { return }

          let searchTag = newValue.split(separator: " ").last.map(String.init) ?? ""

          if !searchTag.isEmpty {
            suggestions = await manager.searchTags(name: searchTag)
          } else {
            suggestions = []
          }
        }
      }
    }
    .onSubmit(of: .search) {
      if suppressNextSearchSubmit {
        suppressNextSearchSubmit = false
        return
      }

      Task(priority: .userInitiated) {
        if initialTag != nil {
          await performLocalSearch()
        } else {
          await manager.performSearch(settings: settings)
        }
      }
    }
    .onChange(of: isSearchablePresented) { _, isPresented in
      if !isPresented, searchText.wrappedValue.isEmpty, !manager.isNavigatingHistory {
        Task(priority: .userInitiated) {
          if initialTag != nil {
            await performLocalSearch()
          } else {
            await manager.performSearch()
          }
        }
      }
    }
    .onChange(of: navigationPath) { _, newPath in
      let currentPathCount = newPath.count

      previousNavigationPathCount = currentPathCount
    }
    .onAppear {
      previousNavigationPathCount = navigationPath.count

      if let initialTag {
        if localSearchText.isEmpty || !hasAppearedBefore {
          localSearchText = initialTag
        }

        if !hasAppearedBefore {
          hasAppearedBefore = true

          Task(priority: .userInitiated) {
            await performLocalSearch()
          }
        } else {
          let currentTags = localSearchText.components(separatedBy: .whitespaces).filter { tag in
            !tag.isEmpty
          }
          let hasPosts = !localPosts.isEmpty
          let initialTags = initialTag.components(separatedBy: .whitespaces).filter { !$0.isEmpty }
          let needsFetch = !hasPosts || currentTags != initialTags

          if needsFetch {
            currentLocalTask?.cancel()

            currentLocalTask = Task(priority: .userInitiated) {
              await fetchLocalPosts(
                page: 1,
                tags: currentTags,
                replace: true
              )
            }
          }
        }
      } else {
        if manager.posts.isEmpty && !manager.isNavigatingHistory && !manager.isLoading {
          Task(priority: .userInitiated) {
            await manager.fetchPosts(page: 1, tags: manager.tags, replace: true)
          }
        }
      }
    }
    .toolbar {
      #if os(macOS)
        ToolbarItem {
          Button(action: {
            if initialTag != nil {
              currentLocalTask?.cancel()

              currentLocalTask = Task(priority: .userInitiated) {
                await fetchLocalPosts(
                  page: 1,
                  tags: localSearchText.components(separatedBy: .whitespaces).filter { component in
                    !component.isEmpty
                  },
                  replace: true
                )
              }
            } else {
              Task(priority: .userInitiated) {
                await manager.fetchPosts(page: 1, tags: manager.tags, replace: true)
              }
            }
          }) {
            Label("Refresh", systemImage: "arrow.clockwise")
          }
          .disabled(isLoading)
        }
      #endif

      #if !os(macOS)
        PlatformSpecificToolbarItem {
          Button(action: { Task { isSearchHistoryPresented.toggle() } }) {
            Label("Search History", systemImage: "clock.arrow.circlepath")
          }
        }

        if #available(iOS 26, *), isLoading || manager.isNavigatingHistory {
          ToolbarItem(placement: .status) { ProgressView() }
        }
      #endif

      PlatformSpecificToolbarItem(placement: .automatic) {
        PostGridBookmarkButtonView(
          tags: initialTag != nil
            ? localSearchText.components(separatedBy: .whitespaces).filter { component in
              !component.isEmpty
            }
            : manager.tags,
          provider: manager.provider
        )
        .disabled(searchText.wrappedValue.isEmpty)
      }

      PlatformSpecificToolbarItem {
        Button(
          action: {
            Task(priority: .userInitiated) {
              if initialTag != nil {
                await loadLocalNextPage()
              } else {
                await manager.loadNextPage()
              }
            }
          }
        ) {
          Label(
            "Manually Load Next Page",
            systemImage: "arrow.down.to.line"
          )
        }
        .disabled(isLoading)
      }

      #if !os(macOS)
        if #unavailable(iOS 26), isLoading || manager.isNavigatingHistory {
          ToolbarItem(placement: .topBarTrailing) { ProgressView() }
        }
      #endif

      #if os(macOS)
        let placement = ToolbarItemPlacement.navigation
      #else
        let placement = ToolbarItemPlacement.topBarLeading
      #endif

      if initialTag == nil {
        PlatformSpecificToolbarItem(placement: placement) {
          Menu {
            ForEach(
              Array(manager.searchHistory.enumerated().filter { $0.offset < manager.historyIndex }),
              id: \.offset
            ) { offset, query in
              Button(action: {
                manager.historyIndex = offset
              }) {
                Text(query.tags.isEmpty ? "No Tags" : query.tags.joined(separator: " "))
              }
            }
          } label: {
            Label("Previous Search", systemImage: "chevron.left")
          } primaryAction: {
            withAnimation {
              manager.goBackInHistory()
            }
          }
          .disabled(!manager.canGoBackInHistory)
          .id("previousSearchMenu")
        }

        PlatformSpecificToolbarItem(placement: placement) {
          Menu {
            ForEach(
              Array(manager.searchHistory.enumerated().filter { $0.offset > manager.historyIndex }),
              id: \.offset
            ) { offset, query in
              Button(action: {
                manager.historyIndex = offset
              }) {
                Text(query.tags.isEmpty ? "No Tags" : query.tags.joined(separator: " "))
              }
            }
          } label: {
            Label("Next Search", systemImage: "chevron.right")
          } primaryAction: {
            withAnimation {
              manager.goForwardInHistory()
            }
          }
          .disabled(!manager.canGoForwardInHistory)
          .id("nextSearchMenu")
        }
      }
    }
    .navigationTitle(initialTag != nil ? initialTag! : "Posts")
    .refreshable {
      if initialTag != nil {
        currentLocalTask?.cancel()

        currentLocalTask = Task(priority: .userInitiated) {
          await fetchLocalPosts(
            page: 1,
            tags: localSearchText.components(separatedBy: .whitespaces).filter { component in
              !component.isEmpty
            },
            replace: true
          )
        }
        await currentLocalTask?.value
      } else {
        manager.clearCachedPages()
        Task(priority: .userInitiated) {
          await manager.fetchPosts(page: 1, tags: manager.tags, replace: true)
        }
      }
    }
    .sheet(isPresented: $isSearchHistoryPresented) {
      PostGridSearchHistoryView(
        selectedTab: $selectedTab,
        isPresented: $isSearchHistoryPresented
      )
    }
    #if os(iOS)
      .gesture(
        DragGesture()
          .onEnded { value in
            if initialTag == nil {
              if value.startLocation.x < 50 && value.translation.width > 100 {
                withAnimation {
                  manager.goBackInHistory()
                }

                debugPrint("ContentView: Swipe left, \(manager.searchHistory)")
              }

              if value.startLocation.x > (UIScreen.main.bounds.width - 50)
                && value.translation.width < -100
              {
                withAnimation {
                  manager.goForwardInHistory()
                }

                debugPrint("ContentView: Swipe right, \(manager.searchHistory)")
              }
            }
          }
      )
    #endif
  }

  private func waterfallGridContent(post: BooruPost) -> some View {
    Button(action: {
      let context = PostWithContext(
        post: post,
        posts: initialTag != nil ? localPosts : nil,
        baseSearchText: initialTag != nil ? localSearchText : nil
      )

      navigationPath.append(context)
    }) {
      PostGridThumbnailView(
        post: post,
        posts: activePosts,
        isNestedView: initialTag != nil,
        endOfData: initialTag != nil ? localEndOfData : manager.endOfData,
        onLoadNextPage: {
          if initialTag != nil {
            await loadLocalNextPage()
          } else {
            await manager.loadNextPage()
          }
        },
        selectedPost: initialTag != nil ? nil : manager.selectedPost
      )
    }
    .buttonStyle(PlainButtonStyle())
    .contextMenu {
      let isFavorited = settings.isFavorite(postId: post.id, provider: manager.provider)

      Button(action: {
        if isFavorited {
          settings.removeFavorite(withPostId: post.id, provider: manager.provider)
        } else {
          settings.addFavorite(post: post, provider: manager.provider)
        }
      }) {
        if isFavorited {
          Label("Remove from Favorites", systemImage: "heart.fill")
        } else {
          Label("Add to Favorites", systemImage: "heart")
        }
      }

      Menu {
        ForEach(settings.folders.filter { $0.topLevelName == nil }, id: \.id) { folder in
          Button(action: {
            settings.addFavorite(post: post, provider: manager.provider, folder: folder.id)
          }) {
            Label(folder.name, systemImage: "folder")
          }
          .disabled(isFavoritedInFolder(post: post, folderId: folder.id))
        }

        let topLevelFolders = settings.folders
          .reduce(into: [String: [SettingsFolder]]()) { result, folder in
            guard let topLevelName = folder.topLevelName else { return }

            result[topLevelName, default: []].append(folder)
          }

        ForEach(topLevelFolders.keys.sorted(), id: \.self) { topLevelName in
          Menu {
            ForEach(topLevelFolders[topLevelName] ?? [], id: \.id) { folder in
              Button(action: {
                settings.addFavorite(post: post, provider: manager.provider, folder: folder.id)
              }) {
                Text(folder.shortName)
              }
              .disabled(isFavoritedInFolder(post: post, folderId: folder.id))
            }
          } label: {
            Text(topLevelName)
          }
        }
      } label: {
        Label("Add to Collection", systemImage: "folder.badge.plus")
      }
    }
  }

  private func isFavoritedInFolder(post: BooruPost, folderId: UUID) -> Bool {
    settings.favorites.contains { favorite in
      favorite.folder == folderId && favorite.postId == post.id
        && favorite.provider == manager.provider
    }
  }

  private func searchSuggestionsItems() -> [Either<BooruTag, BooruSearchQuery>] {
    switch settings.searchSuggestionsMode {
    case .tags:
      return suggestions.map { .left($0) }

    case .history:
      return settings.searchHistory.map { .right($0) }

    case .disabled:
      return []
    }
  }

  // MARK: - Local Search Methods
  private func performLocalSearch() async {
    let inputTags = localSearchText.components(separatedBy: .whitespaces).filter { component in
      !component.isEmpty
    }

    guard !inputTags.isEmpty else { return }

    let query = BooruSearchQuery(
      provider: manager.provider,
      tags: inputTags
    )

    settings.appendToSearchHistory(query)
    currentLocalTask?.cancel()

    currentLocalTask = Task(priority: .userInitiated) {
      await fetchLocalPosts(page: 1, tags: inputTags, replace: true)
    }

    await currentLocalTask?.value
  }

  private func loadLocalNextPage() async {
    guard !localIsLoading else { return }

    localCurrentPage += 1

    let inputTags = localSearchText.components(separatedBy: .whitespaces).filter { component in
      !component.isEmpty
    }

    currentLocalTask?.cancel()

    currentLocalTask = Task(priority: .userInitiated) {
      await fetchLocalPosts(page: localCurrentPage, tags: inputTags, replace: false)
    }

    await currentLocalTask?.value
  }

  private func fetchLocalPosts(
    page: Int = 1, limit: Int = 100, tags: [String] = [], replace: Bool = false
  ) async {
    guard !localIsLoading else { return }

    localIsLoading = true
    localError = nil

    defer {
      localIsLoading = false
    }

    let flavor = manager.flavor
    let provider = manager.provider
    let pageValue = flavor == .gelbooru ? page - 1 : page

    guard let url = manager.url(forPosts: pageValue, limit: limit, tags: tags) else { return }

    do {
      let data = try await manager.requestURL(url)

      guard !Task.isCancelled else { return }

      let newPosts = await withCheckedContinuation { continuation in
        DispatchQueue.global(qos: .userInitiated).async {
          let parsedPosts = BooruManager.parsePosts(
            from: data,
            flavor: flavor,
            provider: provider
          )
          .sorted { $0.createdAt > $1.createdAt }

          continuation.resume(returning: parsedPosts)
        }
      }

      guard !Task.isCancelled else { return }

      withAnimation(nil) {
        if replace {
          localPosts = newPosts
          localCurrentPage = 1
        } else {
          localPosts.append(contentsOf: newPosts)
        }

        localEndOfData = newPosts.isEmpty
      }
    } catch {
      if (error as? URLError)?.code != .cancelled {
        localError = error

        debugPrint("PostGridView.fetchLocalPosts: \(error)")
      }
    }
  }
}