Repository Public
1import SwiftUI23/// The native SP Search results page: mode tabs (All · Images · Videos), filters, results and their states.4struct SearchResultsView: View {5 @Bindable var model: SearchPageModel6 let actions: SearchActions7 /// Extra space at the top for chrome that overlaps the page (iOS toolbars).8 var topInset: CGFloat = 09 var bottomInset: CGFloat = 010 @State private var draft = ""11 @State private var preview: ImageResult?12 @State private var playing: VideoResult?13 @State private var selection: Int?14 @FocusState private var fieldFocused: Bool15 @Environment(\.horizontalSizeClass) private var sizeClass16 @AppStorage("spsearch.videoGrid") private var videoGrid = true1718 private var compact: Bool { sizeClass == .compact }19 private var contentWidth: CGFloat { model.kind == .web ? 760 : 1180 }2021 var body: some View {22 VStack(spacing: 0) {23 header24 Divider().overlay(SPTheme.hairline)25 ScrollViewReader { proxy in26 ScrollView {27 VStack(alignment: .leading, spacing: 0) {28 Color.clear.frame(height: 1).id("top")29 content30 }31 .frame(maxWidth: contentWidth, alignment: .leading)32 .padding(.horizontal, compact ? 14 : 28)33 .padding(.top, 14).padding(.bottom, 28 + bottomInset)34 .frame(maxWidth: .infinity, alignment: compact ? .leading : .center)35 }36 .onChange(of: model.query + model.kind.rawValue) { proxy.scrollTo("top", anchor: .top); selection = nil }37 }38 }39 .padding(.top, topInset)40 .background(SPTheme.surface)41 .overlay { if let preview { ImagePreviewView(image: preview, model: model, actions: actions) { self.preview = nil }.transition(.opacity) } }42 .animation(.easeOut(duration: 0.18), value: preview)43 .sheet(item: $playing) { video in VideoPlayerSheet(video: video, actions: actions) }44 .onAppear { draft = model.query }45 .onChange(of: model.query) { draft = model.query }46 #if os(macOS)47 .onKeyPress(.downArrow) { moveSelection(1) }48 .onKeyPress(.upArrow) { moveSelection(-1) }49 .onKeyPress(.return) { openSelection() }50 #endif51 }5253 // MARK: Header5455 private var header: some View {56 VStack(alignment: .leading, spacing: 10) {57 HStack(spacing: 12) {58 if !compact {59 Text("SP Search").font(.system(size: 17, weight: .bold, design: .rounded)).foregroundStyle(SPTheme.brandGradient)60 .accessibilityAddTraits(.isHeader)61 }62 HStack(spacing: 8) {63 Image(systemName: "magnifyingglass").foregroundStyle(.secondary).accessibilityHidden(true)64 TextField(L("Search the web with SP Search"), text: $draft)65 .textFieldStyle(.plain).font(.system(size: 15)).focused($fieldFocused)66 .onSubmit { actions.search(draft, model.kind) }67 #if os(iOS)68 .textInputAutocapitalization(.never).autocorrectionDisabled().submitLabel(.search)69 #endif70 .accessibilityLabel(L("Search query"))71 if !draft.isEmpty {72 Button { draft = ""; fieldFocused = true } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(.tertiary) }73 .buttonStyle(.plain).accessibilityLabel(L("Clear"))74 }75 }76 .padding(.horizontal, 12).frame(height: 36).frame(maxWidth: 620)77 .background(RoundedRectangle(cornerRadius: 18, style: .continuous).fill(SPTheme.field))78 .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(fieldFocused ? SPTheme.accent : SPTheme.hairline, lineWidth: fieldFocused ? 1.5 : 1))79 Spacer(minLength: 0)80 }81 if compact {82 // On a narrow screen the modes and filters scroll sideways instead of being squeezed.83 ScrollView(.horizontal, showsIndicators: false) {84 HStack(spacing: 4) {85 ForEach(SearchKind.allCases) { kind in86 ModeTab(kind: kind, isSelected: model.kind == kind) { if model.kind != kind { actions.search(model.query, kind) } }.fixedSize()87 }88 filters89 }90 }91 } else {92 HStack(spacing: 6) {93 ForEach(SearchKind.allCases) { kind in94 ModeTab(kind: kind, isSelected: model.kind == kind) { if model.kind != kind { actions.search(model.query, kind) } }95 }96 Spacer(minLength: 8)97 filters98 }99 }100 }101 .padding(.horizontal, compact ? 14 : 28).padding(.top, 12).padding(.bottom, 8)102 .frame(maxWidth: .infinity, alignment: .leading)103 .background(SPTheme.surface)104 }105106 @ViewBuilder private var filters: some View {107 if model.kind == .videos {108 Menu {109 Picker(L("Source"), selection: $model.videoSource) {110 Text(L("All platforms")).tag(VideoSource?.none)111 ForEach(VideoSource.allCases) { Text($0.title).tag(VideoSource?.some($0)) }112 }113 } label: { FilterChip(text: model.videoSource?.title ?? L("All platforms"), symbol: "play.tv", isActive: model.videoSource != nil) }114 .menuStyle(.borderlessButton).fixedSize()115 if !compact {116 Button { videoGrid.toggle() } label: { Image(systemName: videoGrid ? "list.bullet" : "square.grid.2x2").frame(width: 28, height: 26) }117 .buttonStyle(.plain).foregroundStyle(.secondary).help(videoGrid ? L("List view") : L("Grid view"))118 .accessibilityLabel(videoGrid ? L("List view") : L("Grid view"))119 }120 }121 Menu {122 Picker(L("Date"), selection: $model.timeRange) {123 Text(L("Any time")).tag(SearchTimeRange?.none)124 ForEach(SearchTimeRange.allCases) { Text($0.title).tag(SearchTimeRange?.some($0)) }125 }126 } label: { FilterChip(text: model.timeRange?.title ?? L("Any time"), symbol: "calendar", isActive: model.timeRange != nil) }127 .menuStyle(.borderlessButton).fixedSize()128 }129130 // MARK: Content131132 @ViewBuilder private var content: some View {133 switch model.phase {134 case .idle, .loading:135 skeleton136 case .failed(let error):137 SearchErrorView(error: error) { model.reload(ignoringCache: true) }138 case .loaded:139 if model.isEmpty {140 SearchEmptyView(query: model.query, kind: model.kind, hasFilters: model.timeRange != nil || model.videoSource != nil) {141 model.timeRange = nil; model.videoSource = nil142 }143 } else {144 switch model.kind {145 case .web: webResults146 case .images: imageResults147 case .videos: videoResults148 }149 footer150 }151 }152 }153154 private var webResults: some View {155 VStack(alignment: .leading, spacing: 22) {156 if let answer = model.answer { AnswerCard(answer: answer, query: model.query) }157 ForEach(Array(model.web.enumerated()), id: \.element.id) { index, result in158 WebResultRow(result: result, query: model.query, isSelected: selection == index, actions: actions)159 .id(result.id)160 .onAppear { if index >= model.web.count - 3 { model.loadMore() } }161 }162 if !model.related.isEmpty {163 VStack(alignment: .leading, spacing: 10) {164 Text(L("Related from your searches")).font(.headline)165 FlowLayout(spacing: 8) {166 ForEach(model.related, id: \.self) { text in167 Button { actions.search(text, .web) } label: {168 Label(text, systemImage: "clock.arrow.circlepath").font(.callout).lineLimit(1)169 .padding(.horizontal, 12).padding(.vertical, 7)170 .background(Capsule().fill(SPTheme.card)).overlay(Capsule().strokeBorder(SPTheme.hairline))171 }172 .buttonStyle(.plain)173 }174 }175 }176 .padding(.top, 6)177 }178 }179 }180181 private var imageResults: some View {182 MasonryLayout(columnWidth: compact ? 150 : 220, spacing: 10) {183 ForEach(Array(model.visibleImages.enumerated()), id: \.element.id) { index, image in184 ImageTile(image: image, model: model) { preview = image }185 .aspectRatio(model.aspectRatio(of: image), contentMode: .fit)186 .onAppear { if index >= model.visibleImages.count - 6 { model.loadMore() } }187 }188 }189 }190191 @ViewBuilder private var videoResults: some View {192 if videoGrid || compact {193 LazyVGrid(columns: [GridItem(.adaptive(minimum: compact ? 260 : 270), spacing: 18, alignment: .top)], alignment: .leading, spacing: 22) {194 ForEach(model.videos) { video in VideoCard(video: video, query: model.query, actions: actions, isList: false) { playing = video } }195 }196 } else {197 VStack(alignment: .leading, spacing: 18) {198 ForEach(model.videos) { video in VideoCard(video: video, query: model.query, actions: actions, isList: true) { playing = video } }199 }200 }201 if model.notices.contains("video-duration-unavailable-without-youtube-data-api") {202 Text(L("Duration and date are shown when the platform publishes them. YouTube does not without its data API."))203 .font(.caption).foregroundStyle(.tertiary).padding(.top, 14)204 }205 }206207 @ViewBuilder private var footer: some View {208 VStack(spacing: 10) {209 if model.isLoadingMore {210 ProgressView().controlSize(.small)211 } else if let error = model.loadMoreError {212 Text(error.message).font(.callout).foregroundStyle(.secondary)213 Button(L("Try Again")) { model.loadMore() }214 } else if model.hasMore {215 Button(model.kind == .web ? L("More results") : L("Show more")) { model.loadMore() }.buttonStyle(.bordered).controlSize(.large)216 }217 Text(providerLine).font(.caption).foregroundStyle(.tertiary).multilineTextAlignment(.center)218 }219 .frame(maxWidth: .infinity).padding(.top, 26)220 }221222 private var providerLine: String {223 let source: String224 switch model.provider {225 case "tavily+wikimedia-commons": source = "Tavily · Wikimedia Commons"226 case "tavily+oembed": source = L("Tavily · confirmed by each video platform")227 case "youtube": source = "YouTube Data API"228 default: source = "Tavily"229 }230 return L("SP Search · results retrieved with %@", source)231 }232233 @ViewBuilder private var skeleton: some View {234 switch model.kind {235 case .web:236 VStack(alignment: .leading, spacing: 26) {237 ForEach(0..<6, id: \.self) { _ in238 VStack(alignment: .leading, spacing: 8) {239 HStack(spacing: 8) { SkeletonBlock(height: 18, width: 18, radius: 4); SkeletonBlock(height: 10, width: 150) }240 SkeletonBlock(height: 17, width: 380)241 SkeletonBlock(height: 11); SkeletonBlock(height: 11, width: 420)242 }243 }244 }245 .accessibilityLabel(L("Loading results"))246 case .images:247 MasonryLayout(columnWidth: compact ? 150 : 220, spacing: 10) {248 ForEach(0..<12, id: \.self) { i in SkeletonBlock(height: [150, 210, 130, 180][i % 4], radius: 10) }249 }250 .accessibilityLabel(L("Loading results"))251 case .videos:252 LazyVGrid(columns: [GridItem(.adaptive(minimum: 260), spacing: 18)], spacing: 22) {253 ForEach(0..<6, id: \.self) { _ in254 VStack(alignment: .leading, spacing: 8) { SkeletonBlock(height: 150, radius: 10); SkeletonBlock(height: 14); SkeletonBlock(height: 11, width: 140) }255 }256 }257 .accessibilityLabel(L("Loading results"))258 }259 }260261 // MARK: Keyboard262263 private func moveSelection(_ delta: Int) -> KeyPress.Result {264 guard model.kind == .web, !model.web.isEmpty, !fieldFocused else { return .ignored }265 selection = min(max((selection ?? (delta > 0 ? -1 : model.web.count)) + delta, 0), model.web.count - 1)266 return .handled267 }268269 private func openSelection() -> KeyPress.Result {270 guard !fieldFocused, model.kind == .web, let index = selection, model.web.indices.contains(index), let url = URL(string: model.web[index].url) else { return .ignored }271 actions.open(url, .current)272 return .handled273 }274}275276// MARK: - Pieces277278private struct ModeTab: View {279 let kind: SearchKind280 let isSelected: Bool281 let action: () -> Void282283 var body: some View {284 Button(action: action) {285 Label(kind.title, systemImage: kind.symbol).font(.system(size: 13, weight: isSelected ? .semibold : .regular))286 .padding(.horizontal, 12).padding(.vertical, 6)287 .foregroundStyle(isSelected ? SPTheme.accent : .secondary)288 .background(Capsule().fill(isSelected ? SPTheme.accent.opacity(0.14) : .clear))289 .contentShape(Capsule())290 }291 .buttonStyle(.plain)292 .accessibilityAddTraits(isSelected ? [.isSelected, .isButton] : .isButton)293 .accessibilityIdentifier("search-tab-\(kind.rawValue)")294 }295}296297private struct FilterChip: View {298 let text: String299 let symbol: String300 let isActive: Bool301302 var body: some View {303 Label(text, systemImage: symbol).font(.system(size: 12)).lineLimit(1)304 .foregroundStyle(isActive ? SPTheme.accent : .secondary)305 .padding(.horizontal, 9).padding(.vertical, 5)306 .background(Capsule().strokeBorder(isActive ? SPTheme.accent.opacity(0.5) : SPTheme.hairline))307 }308}309310/// Text with the query's terms emphasised.311struct HighlightedText: View {312 let text: String313 let query: String314 var body: some View { Self.make(text, query: query) }315316 static func make(_ text: String, query: String) -> Text {317 SearchHighlighter.segments(of: text, query: query).reduce(Text("")) { partial, segment in318 partial + (segment.isMatch ? Text(segment.text).fontWeight(.semibold) : Text(segment.text))319 }320 }321}322323private struct AnswerCard: View {324 let answer: SearchAnswer325 let query: String326 @State private var expanded = false327328 var body: some View {329 VStack(alignment: .leading, spacing: 8) {330 Label(L("AI summary"), systemImage: "sparkles").font(.caption.weight(.semibold)).foregroundStyle(SPTheme.brandGradient)331 Text(answer.text).font(.system(size: 14.5)).lineSpacing(3).lineLimit(expanded ? nil : 5).textSelection(.enabled)332 .fixedSize(horizontal: false, vertical: true)333 HStack {334 Text(L("Generated by the search provider from the results below. It can be wrong: check the sources."))335 .font(.caption2).foregroundStyle(.tertiary)336 Spacer()337 if answer.text.count > 380 { Button(expanded ? L("Less") : L("More")) { expanded.toggle() }.buttonStyle(.plain).font(.caption).foregroundStyle(SPTheme.accent) }338 }339 }340 .padding(14)341 .background(RoundedRectangle(cornerRadius: SPTheme.radiusL, style: .continuous).fill(SPTheme.card))342 .overlay(RoundedRectangle(cornerRadius: SPTheme.radiusL, style: .continuous).strokeBorder(SPTheme.hairline))343 .accessibilityElement(children: .combine)344 }345}346347private struct WebResultRow: View {348 let result: WebResult349 let query: String350 let isSelected: Bool351 let actions: SearchActions352 @State private var hovering = false353354 private var url: URL? { URL(string: result.url) }355 private var displayPath: String {356 guard let url, let host = url.host else { return result.url }357 let parts = url.pathComponents.filter { $0 != "/" }.prefix(3)358 return ([host] + parts).joined(separator: " › ")359 }360361 var body: some View {362 VStack(alignment: .leading, spacing: 4) {363 HStack(spacing: 8) {364 SiteIcon(url: result.favicon.flatMap(URL.init(string:)), fallback: result.domain, size: 20)365 VStack(alignment: .leading, spacing: 0) {366 Text(result.domain).font(.system(size: 12.5, weight: .medium)).lineLimit(1)367 Text(displayPath).font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)368 }369 }370 Button { if let url { actions.open(url, .current) } } label: {371 HighlightedText(text: result.title, query: query).font(.system(size: 18)).foregroundStyle(SPTheme.link)372 .multilineTextAlignment(.leading).lineLimit(2).underline(hovering)373 .frame(maxWidth: .infinity, alignment: .leading)374 }375 .buttonStyle(.plain)376 .accessibilityAddTraits(.isLink)377 if !result.snippet.isEmpty || result.publishedDate != nil {378 (dateText + HighlightedText.make(result.snippet, query: query))379 .font(.system(size: 13.5)).lineSpacing(2).lineLimit(3).foregroundStyle(.secondary)380 }381 }382 .padding(8)383 .background(RoundedRectangle(cornerRadius: SPTheme.radiusM, style: .continuous).fill(isSelected ? SPTheme.hover : .clear))384 .padding(-8)385 .onHover { hovering = $0 }386 .contextMenu {387 if let url {388 Button(L("Open")) { actions.open(url, .current) }389 Button(L("Open in New Tab")) { actions.open(url, .newTab) }390 Button(L("Open in Background Tab")) { actions.open(url, .backgroundTab) }391 Divider()392 Button(L("Copy Link")) { PlatformActions.copy(result.url) }393 Button(L("Share…")) { actions.share(url) }394 if let add = actions.addToReadingList { Button(L("Add to Reading List")) { add(result.title, url) } }395 }396 }397 .accessibilityElement(children: .combine)398 .accessibilityLabel("\(result.title), \(result.domain)")399 .accessibilityHint(result.snippet)400 .accessibilityIdentifier("web-result")401 }402403 private var dateText: Text {404 guard let date = SearchDate.display(result.publishedDate) else { return Text("") }405 return Text(date + " — ")406 }407}408409struct SearchErrorView: View {410 let error: BackendError411 let retry: () -> Void412413 private var symbol: String {414 switch error.kind {415 case .offline: return "wifi.slash"416 case .timeout: return "clock.badge.exclamationmark"417 case .rateLimited: return "hourglass"418 default: return "exclamationmark.triangle"419 }420 }421422 private var title: String {423 switch error.code {424 case "offline", "network": return L("You are offline")425 case "timeout", "provider_timeout": return L("The search took too long")426 case "rate_limited", "provider_rate_limited": return L("Too many searches right now")427 case "budget_exhausted", "provider_quota": return L("The search quota is used up for today")428 case "provider_not_configured", "provider_auth": return L("SP Search is not available")429 default: return L("The search could not be completed")430 }431 }432433 var body: some View {434 VStack(spacing: 12) {435 Image(systemName: symbol).font(.system(size: 40, weight: .light)).foregroundStyle(.secondary).accessibilityHidden(true)436 Text(title).font(.title3.weight(.semibold))437 Text(error.kind == .offline ? L("Check the internet connection, then try again. Pages you already opened stay available.") : error.message)438 .font(.callout).foregroundStyle(.secondary).multilineTextAlignment(.center).frame(maxWidth: 420)439 Button(L("Try Again"), action: retry).buttonStyle(.borderedProminent).padding(.top, 4)440 }441 .frame(maxWidth: .infinity).padding(.vertical, 60)442 .accessibilityElement(children: .contain)443 }444}445446struct SearchEmptyView: View {447 let query: String448 let kind: SearchKind449 let hasFilters: Bool450 let clearFilters: () -> Void451452 var body: some View {453 VStack(spacing: 10) {454 Image(systemName: kind.symbol).font(.system(size: 38, weight: .light)).foregroundStyle(.secondary).accessibilityHidden(true)455 Text(L("No results for “%@”", query)).font(.title3.weight(.semibold)).multilineTextAlignment(.center)456 Text(kind == .videos ? L("No video on YouTube, Vimeo or Dailymotion could be confirmed for this search.") : L("Try other words, or fewer of them."))457 .font(.callout).foregroundStyle(.secondary).multilineTextAlignment(.center)458 if hasFilters { Button(L("Remove Filters"), action: clearFilters).padding(.top, 4) }459 }460 .frame(maxWidth: .infinity).padding(.vertical, 60)461 }462}463464/// Lays children out left to right, wrapping to new lines (chips).465struct FlowLayout: Layout {466 var spacing: CGFloat = 8467468 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {469 arrange(width: proposal.width ?? .infinity, subviews: subviews).size470 }471472 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {473 for (index, point) in arrange(width: bounds.width, subviews: subviews).points.enumerated() {474 subviews[index].place(at: CGPoint(x: bounds.minX + point.x, y: bounds.minY + point.y), proposal: .unspecified)475 }476 }477478 private func arrange(width: CGFloat, subviews: Subviews) -> (size: CGSize, points: [CGPoint]) {479 var points: [CGPoint] = [], x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, maxX: CGFloat = 0480 for subview in subviews {481 let size = subview.sizeThatFits(.unspecified)482 if x > 0, x + size.width > width { x = 0; y += rowHeight + spacing; rowHeight = 0 }483 points.append(CGPoint(x: x, y: y))484 x += size.width + spacing485 rowHeight = max(rowHeight, size.height)486 maxX = max(maxX, x - spacing)487 }488 return (CGSize(width: maxX, height: y + rowHeight), points)489 }490}491492/// Adaptive masonry: as many equal columns as fit, each child placed in the shortest column at its own aspect ratio.493struct MasonryLayout: Layout {494 var columnWidth: CGFloat = 220495 var spacing: CGFloat = 10496497 private func columns(for width: CGFloat) -> (count: Int, width: CGFloat) {498 let count = max(2, Int((width + spacing) / (columnWidth + spacing)))499 return (count, (width - CGFloat(count - 1) * spacing) / CGFloat(count))500 }501502 private func arrange(width: CGFloat, subviews: Subviews) -> (height: CGFloat, frames: [CGRect]) {503 guard width.isFinite, width > 0 else { return (0, []) }504 let (count, itemWidth) = columns(for: width)505 var heights = [CGFloat](repeating: 0, count: count)506 var frames: [CGRect] = []507 for subview in subviews {508 let column = heights.indices.min { heights[$0] < heights[$1] } ?? 0509 let height = subview.sizeThatFits(ProposedViewSize(width: itemWidth, height: nil)).height510 frames.append(CGRect(x: CGFloat(column) * (itemWidth + spacing), y: heights[column], width: itemWidth, height: height))511 heights[column] += height + spacing512 }513 return (max((heights.max() ?? 0) - spacing, 0), frames)514 }515516 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {517 let width = proposal.width ?? 600518 return CGSize(width: width, height: arrange(width: width, subviews: subviews).height)519 }520521 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {522 for (index, frame) in arrange(width: bounds.width, subviews: subviews).frames.enumerated() {523 subviews[index].place(at: CGPoint(x: bounds.minX + frame.minX, y: bounds.minY + frame.minY),524 proposal: ProposedViewSize(width: frame.width, height: frame.height))525 }526 }527}528