Repository Public
1import Foundation2import Observation34/// What the search UI needs from the app around it.5@MainActor6struct SearchContext {7 let client: SearchClient8 /// Search history and synced preferences; nil in private windows, where nothing is recorded.9 let library: SyncedLibrary?10 let isPrivate: Bool11 var preferences: @MainActor () -> SearchPreferences12 /// Called after the search history changed, so sync can be scheduled.13 var historyChanged: @MainActor () -> Void = {}14}1516/// State of one native results page (one per tab showing SP Search).17@MainActor18@Observable19final class SearchPageModel {20 enum Phase: Equatable { case idle, loading, loaded, failed(BackendError) }2122 private(set) var query = ""23 private(set) var kind: SearchKind = .web24 private(set) var phase: Phase = .idle25 private(set) var web: [WebResult] = []26 private(set) var images: [ImageResult] = []27 private(set) var videos: [VideoResult] = []28 private(set) var answer: SearchAnswer?29 private(set) var notices: [String] = []30 private(set) var provider = ""31 private(set) var hasMore = false32 private(set) var isLoadingMore = false33 private(set) var loadMoreError: BackendError?34 private(set) var tookMs = 035 private(set) var related: [String] = []36 var timeRange: SearchTimeRange? { didSet { if timeRange != oldValue { reload() } } }37 var videoSource: VideoSource? { didSet { if videoSource != oldValue, kind == .videos { reload() } } }38 /// Measured pixel sizes of images whose provider did not report dimensions.39 var measuredSizes: [String: CGSize] = [:]40 /// Images that failed to load are hidden rather than shown as broken tiles.41 var failedImages: Set<String> = []4243 @ObservationIgnored let context: SearchContext44 @ObservationIgnored private var task: Task<Void, Never>?45 @ObservationIgnored private var page = 14647 init(context: SearchContext) { self.context = context }4849 var isEmpty: Bool { phase == .loaded && resultCount == 0 }50 var resultCount: Int {51 switch kind {52 case .web: return web.count53 case .images: return visibleImages.count54 case .videos: return videos.count55 }56 }57 var visibleImages: [ImageResult] { images.filter { !failedImages.contains($0.id) } }5859 /// Shows the results for `query`; a no-op when they are already displayed (e.g. the view reappeared).60 func show(query text: String, kind newKind: SearchKind) {61 let normalized = SearchQuery.normalize(text)62 guard !normalized.isEmpty else { return }63 if normalized == query, newKind == kind, phase != .idle { return }64 query = normalized65 kind = newKind66 if !context.isPrivate, context.preferences().keepSearchHistory, let library = context.library {67 library.recordSearch(normalized)68 context.historyChanged()69 }70 related = context.library?.relatedSearches(to: normalized) ?? []71 reload()72 }7374 private func makeQuery(page: Int) -> SearchQuery {75 SearchQuery(query, kind: kind, preferences: context.preferences(), timeRange: timeRange, source: videoSource, page: page)76 }7778 func reload(ignoringCache: Bool = false) {79 guard !query.isEmpty else { return }80 task?.cancel()81 page = 182 loadMoreError = nil83 isLoadingMore = false84 let request = makeQuery(page: 1)85 phase = .loading86 web = []; images = []; videos = []; answer = nil; notices = []; hasMore = false; failedImages = []87 task = Task { [weak self, client = context.client] in88 do {89 let result = try await client.search(request, ignoringCache: ignoringCache)90 guard !Task.isCancelled, let self else { return }91 self.apply(result, appending: false)92 self.phase = .loaded93 } catch is CancellationError {94 } catch let error as BackendError {95 guard !Task.isCancelled, let self else { return }96 self.phase = .failed(error)97 } catch {98 guard !Task.isCancelled, let self else { return }99 self.phase = .failed(BackendError.transport(error))100 }101 }102 }103104 func loadMore() {105 guard phase == .loaded, hasMore, !isLoadingMore else { return }106 isLoadingMore = true107 loadMoreError = nil108 let request = makeQuery(page: page + 1)109 task = Task { [weak self, client = context.client] in110 do {111 let result = try await client.search(request)112 guard !Task.isCancelled, let self else { return }113 self.page += 1114 self.apply(result, appending: true)115 } catch let error as BackendError {116 self?.loadMoreError = error117 } catch {118 if !(error is CancellationError) { self?.loadMoreError = BackendError.transport(error) }119 }120 self?.isLoadingMore = false121 }122 }123124 private func apply(_ result: SearchPage, appending: Bool) {125 switch result.results {126 case .web(let items):127 let known = Set(web.map(\.id))128 web = appending ? web + items.filter { !known.contains($0.id) } : items129 case .images(let items):130 let known = Set(images.map(\.id))131 images = appending ? images + items.filter { !known.contains($0.id) } : items132 case .videos(let items):133 let known = Set(videos.map(\.id))134 videos = appending ? videos + items.filter { !known.contains($0.id) } : items135 }136 if !appending { answer = result.answer; tookMs = result.tookMs }137 provider = result.provider138 notices = Array(Set(notices + result.notices)).sorted()139 hasMore = result.hasMore140 }141142 func aspectRatio(of image: ImageResult) -> CGFloat {143 if let ratio = image.aspectRatio { return CGFloat(min(max(ratio, 0.45), 2.6)) }144 if let size = measuredSizes[image.id], size.height > 0 { return min(max(size.width / size.height, 0.45), 2.6) }145 return 1.4146 }147148 func dimensions(of image: ImageResult) -> String? {149 if let w = image.width, let h = image.height { return "\(w) × \(h)" }150 if let size = measuredSizes[image.id], size.width > 0 { return "\(Int(size.width)) × \(Int(size.height))" }151 return nil152 }153}154155/// How a result should be opened.156enum OpenDisposition { case current, newTab, backgroundTab }157158/// Actions the results views hand back to the browser.159@MainActor160struct SearchActions {161 var open: (URL, OpenDisposition) -> Void162 /// Run another search (query suggestion, related search, mode switch).163 var search: (String, SearchKind) -> Void164 var share: (URL) -> Void = { _ in }165 var saveImage: (ImageResult) -> Void = { _ in }166 var addToReadingList: ((String, URL) -> Void)?167}168