Repository Public
1import SwiftUI2#if canImport(AppKit)3import AppKit4typealias PlatformImage = NSImage5typealias PlatformColor = NSColor6#else7import UIKit8typealias PlatformImage = UIImage9typealias PlatformColor = UIColor10#endif1112extension Image {13 init(platformImage: PlatformImage) {14 #if canImport(AppKit)15 self.init(nsImage: platformImage)16 #else17 self.init(uiImage: platformImage)18 #endif19 }20}2122extension PlatformImage {23 /// Size in pixels of the underlying bitmap (not points).24 var pixelSize: CGSize {25 #if canImport(AppKit)26 if let rep = representations.first, rep.pixelsWide > 0 { return CGSize(width: rep.pixelsWide, height: rep.pixelsHigh) }27 return size28 #else29 return CGSize(width: size.width * scale, height: size.height * scale)30 #endif31 }32}3334enum PlatformActions {35 @MainActor static func copy(_ text: String) {36 #if canImport(AppKit)37 NSPasteboard.general.clearContents()38 NSPasteboard.general.setString(text, forType: .string)39 #else40 UIPasteboard.general.string = text41 #endif42 }4344 @MainActor static func pasteboardString() -> String? {45 #if canImport(AppKit)46 NSPasteboard.general.string(forType: .string)47 #else48 UIPasteboard.general.string49 #endif50 }5152 /// True while the user holds ⌘ or ⇧ (Mac, or a hardware keyboard): a click then extends the selection.53 @MainActor static var isExtendingSelection: Bool {54 #if canImport(AppKit)55 NSEvent.modifierFlags.contains(.command) || NSEvent.modifierFlags.contains(.shift)56 #else57 false58 #endif59 }6061 @MainActor static func haptic() {62 #if canImport(UIKit)63 UIImpactFeedbackGenerator(style: .light).impactOccurred()64 #endif65 }66}6768/// Loads remote images (search thumbnails, favicons of results) without cookies and keeps them in memory only.69final class RemoteImageLoader: @unchecked Sendable {70 static let shared = RemoteImageLoader()71 private let cache = NSCache<NSURL, PlatformImage>()72 private let session: URLSession7374 init() {75 let config = URLSessionConfiguration.ephemeral76 config.httpShouldSetCookies = false77 config.httpCookieAcceptPolicy = .never78 config.timeoutIntervalForRequest = 1579 config.urlCache = URLCache(memoryCapacity: 48 * 1024 * 1024, diskCapacity: 0)80 config.httpMaximumConnectionsPerHost = 681 session = URLSession(configuration: config)82 cache.totalCostLimit = 160 * 1024 * 102483 }8485 func cached(_ url: URL) -> PlatformImage? { cache.object(forKey: url as NSURL) }8687 func data(from url: URL) async throws -> Data {88 var request = URLRequest(url: url)89 request.setValue("image/avif,image/webp,image/png,image/jpeg,image/*;q=0.8", forHTTPHeaderField: "Accept")90 let (data, response) = try await session.data(for: request)91 guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode), data.count < 30_000_000 else { throw URLError(.badServerResponse) }92 return data93 }9495 func image(from url: URL) async -> PlatformImage? {96 if let hit = cached(url) { return hit }97 guard let scheme = url.scheme?.lowercased(), scheme == "https" || scheme == "http",98 let data = try? await data(from: url), let image = PlatformImage(data: data), image.size.width > 0 else { return nil }99 cache.setObject(image, forKey: url as NSURL, cost: data.count)100 return image101 }102103 func clear() { cache.removeAllObjects() }104}105106/// An image fetched from the network with a placeholder; reports its pixel size once known.107struct RemoteImage<Placeholder: View>: View {108 let url: URL?109 var contentMode: ContentMode = .fill110 var onLoad: ((CGSize) -> Void)?111 var onFailure: (() -> Void)?112 @ViewBuilder var placeholder: () -> Placeholder113 @State private var image: PlatformImage?114 @State private var failed = false115116 var body: some View {117 ZStack {118 if let image {119 Image(platformImage: image).resizable().aspectRatio(contentMode: contentMode).transition(.opacity)120 } else {121 placeholder()122 }123 }124 .task(id: url) {125 guard let url else { return }126 if let hit = RemoteImageLoader.shared.cached(url) { image = hit; onLoad?(hit.pixelSize); return }127 image = nil128 if let loaded = await RemoteImageLoader.shared.image(from: url) {129 withAnimation(.easeOut(duration: 0.18)) { image = loaded }130 onLoad?(loaded.pixelSize)131 } else if !Task.isCancelled {132 failed = true133 onFailure?()134 }135 }136 }137}138139/// A shimmering block used while results load.140struct SkeletonBlock: View {141 var height: CGFloat = 12142 var width: CGFloat?143 var radius: CGFloat = 5144 @State private var phase = false145 @Environment(\.accessibilityReduceMotion) private var reduceMotion146147 var body: some View {148 RoundedRectangle(cornerRadius: radius, style: .continuous)149 .fill(Color.secondary.opacity(phase ? 0.10 : 0.20))150 .frame(width: width, height: height)151 .frame(maxWidth: width == nil ? .infinity : nil, alignment: .leading)152 .onAppear { guard !reduceMotion else { return }; withAnimation(.easeInOut(duration: 0.9).repeatForever(autoreverses: true)) { phase = true } }153 .accessibilityHidden(true)154 }155}156157/// Small rounded site icon with a letter fallback.158struct SiteIcon: View {159 let url: URL?160 let fallback: String161 var size: CGFloat = 18162163 var body: some View {164 RemoteImage(url: url, contentMode: .fit) {165 RoundedRectangle(cornerRadius: size * 0.25, style: .continuous).fill(Color.secondary.opacity(0.2))166 .overlay(Text(String(fallback.prefix(1)).uppercased()).font(.system(size: size * 0.55, weight: .semibold)).foregroundStyle(.secondary))167 }168 .frame(width: size, height: size)169 .clipShape(RoundedRectangle(cornerRadius: size * 0.22, style: .continuous))170 .accessibilityHidden(true)171 }172}173