2021-01-23 04:48:33 +01:00
|
|
|
// Copyright © 2020 Metabolist. All rights reserved.
|
|
|
|
|
|
|
|
import Combine
|
|
|
|
import Foundation
|
|
|
|
import ServiceLayer
|
|
|
|
|
|
|
|
public final class SearchViewModel: CollectionItemsViewModel {
|
|
|
|
@Published public var query = ""
|
2021-01-25 08:42:39 +01:00
|
|
|
@Published public var scope = SearchScope.all
|
2021-01-23 04:48:33 +01:00
|
|
|
|
|
|
|
private let searchService: SearchService
|
|
|
|
private var cancellables = Set<AnyCancellable>()
|
|
|
|
|
2021-02-15 09:47:30 +01:00
|
|
|
public init(identityContext: IdentityContext) {
|
|
|
|
self.searchService = identityContext.service.searchService()
|
2021-01-23 04:48:33 +01:00
|
|
|
|
2021-01-26 01:06:35 +01:00
|
|
|
super.init(collectionService: searchService, identityContext: identityContext)
|
2021-01-23 04:48:33 +01:00
|
|
|
|
2021-02-09 02:19:25 +01:00
|
|
|
$query.dropFirst()
|
2021-02-07 02:20:15 +01:00
|
|
|
.debounce(for: .seconds(Self.debounceInterval), scheduler: DispatchQueue.global())
|
2021-02-09 02:19:25 +01:00
|
|
|
.removeDuplicates()
|
2021-01-25 03:10:41 +01:00
|
|
|
.combineLatest($scope.removeDuplicates())
|
|
|
|
.sink { [weak self] in
|
2021-03-05 07:16:38 +01:00
|
|
|
self?.cancelRequests()
|
2021-01-25 03:10:41 +01:00
|
|
|
self?.request(
|
|
|
|
maxId: nil,
|
|
|
|
minId: nil,
|
|
|
|
search: .init(query: $0, type: $1.type, limit: $1.limit))
|
|
|
|
}
|
2021-01-23 04:48:33 +01:00
|
|
|
.store(in: &cancellables)
|
|
|
|
}
|
2021-01-24 23:14:35 +01:00
|
|
|
|
2021-01-25 03:10:41 +01:00
|
|
|
public override func requestNextPage(fromIndexPath indexPath: IndexPath) {
|
|
|
|
guard scope != .all else { return }
|
|
|
|
|
|
|
|
request(
|
|
|
|
maxId: nil,
|
|
|
|
minId: nil,
|
|
|
|
search: .init(query: query, type: scope.type, offset: indexPath.item + 1))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-23 04:48:33 +01:00
|
|
|
private extension SearchViewModel {
|
2022-11-08 00:49:26 +01:00
|
|
|
static let debounceInterval: TimeInterval = 0.8
|
2021-01-25 03:10:41 +01:00
|
|
|
}
|
|
|
|
|
2021-01-25 08:42:39 +01:00
|
|
|
private extension SearchScope {
|
2021-01-25 03:10:41 +01:00
|
|
|
var type: Search.SearchType? {
|
|
|
|
switch self {
|
|
|
|
case .all:
|
|
|
|
return nil
|
|
|
|
case .accounts:
|
|
|
|
return .accounts
|
|
|
|
case .statuses:
|
|
|
|
return .statuses
|
|
|
|
case .tags:
|
|
|
|
return .hashtags
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var limit: Int? {
|
|
|
|
switch self {
|
|
|
|
case .all:
|
|
|
|
return 5
|
|
|
|
default:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2021-01-23 04:48:33 +01:00
|
|
|
}
|