SPB Git

Repository Public

SearchMediaViews.swift 13.1 KB 263 lines swift

1import SwiftUI2import WebKit34// MARK: - Images56struct ImageTile: View {7    let image: ImageResult8    let model: SearchPageModel9    let open: () -> Void10    @State private var hovering = false1112    var body: some View {13        Button(action: open) {14            RemoteImage(url: image.displayURL, contentMode: .fill,15                        onLoad: { size in if image.width == nil, model.measuredSizes[image.id] == nil, image.thumbnailURL == nil { model.measuredSizes[image.id] = size } },16                        onFailure: { model.failedImages.insert(image.id) }) {17                Rectangle().fill(Color.secondary.opacity(0.12))18            }19            .frame(maxWidth: .infinity, maxHeight: .infinity)20            .clipShape(RoundedRectangle(cornerRadius: SPTheme.radiusM, style: .continuous))21            .overlay(alignment: .bottomLeading) {22                if hovering {23                    Text(image.sourceDomain ?? image.imageDomain).font(.caption2.weight(.medium)).lineLimit(1)24                        .padding(.horizontal, 7).padding(.vertical, 3).background(.ultraThinMaterial, in: Capsule()).padding(6)25                }26            }27            .overlay(RoundedRectangle(cornerRadius: SPTheme.radiusM, style: .continuous).strokeBorder(hovering ? SPTheme.accent.opacity(0.7) : SPTheme.hairline, lineWidth: hovering ? 2 : 1))28            .contentShape(Rectangle())29        }30        .buttonStyle(.plain)31        .onHover { hovering = $0 }32        .accessibilityLabel(image.description ?? image.sourceTitle ?? L("Image from %@", image.sourceDomain ?? image.imageDomain))33        .accessibilityAddTraits(.isImage)34    }35}3637/// Full-size preview of one image with its attribution and actions.38struct ImagePreviewView: View {39    let image: ImageResult40    let model: SearchPageModel41    let actions: SearchActions42    let close: () -> Void43    @Environment(\.horizontalSizeClass) private var sizeClass44    @State private var copied = false4546    var body: some View {47        ZStack {48            Color.black.opacity(0.62).ignoresSafeArea().onTapGesture(perform: close).accessibilityHidden(true)49            Group {50                if sizeClass == .compact {51                    VStack(spacing: 0) { picture; ScrollView { details.padding(16) }.frame(maxHeight: 260) }52                } else {53                    HStack(spacing: 0) { picture; ScrollView { details.padding(20) }.frame(width: 320) }54                }55            }56            .background(SPTheme.surface)57            .clipShape(RoundedRectangle(cornerRadius: SPTheme.radiusXL, style: .continuous))58            .overlay(alignment: .topTrailing) {59                Button(action: close) { Image(systemName: "xmark.circle.fill").font(.title2).symbolRenderingMode(.hierarchical).foregroundStyle(.secondary) }60                    .buttonStyle(.plain).padding(10).keyboardShortcut(.cancelAction).accessibilityLabel(L("Close"))61            }62            .shadow(color: .black.opacity(0.35), radius: 30, y: 12)63            .padding(sizeClass == .compact ? 12 : 44)64            .frame(maxWidth: 1180, maxHeight: 820)65        }66        .accessibilityAddTraits(.isModal)67    }6869    private var picture: some View {70        RemoteImage(url: URL(string: image.imageURL), contentMode: .fit,71                    onLoad: { size in model.measuredSizes[image.id] = size }) {72            RemoteImage(url: image.displayURL, contentMode: .fit) { ProgressView() }73        }74        .frame(maxWidth: .infinity, maxHeight: .infinity)75        .background(Color.black.opacity(0.88))76    }7778    private var details: some View {79        VStack(alignment: .leading, spacing: 12) {80            if let title = image.sourceTitle, !title.isEmpty { Text(title).font(.headline).lineLimit(3) }81            if let description = image.description, description != image.sourceTitle { Text(description).font(.callout).foregroundStyle(.secondary).lineLimit(6) }82            VStack(alignment: .leading, spacing: 5) {83                if let domain = image.sourceDomain { Label(domain, systemImage: "globe").lineLimit(1) }84                if image.sourceDomain == nil { Label(image.imageDomain, systemImage: "photo").lineLimit(1) }85                if let dimensions = model.dimensions(of: image) { Label(L("%@ pixels", dimensions), systemImage: "aspectratio") }86                if let author = image.author { Label(author, systemImage: "person").lineLimit(1) }87                if let license = image.license { Label(license, systemImage: "c.circle") }88            }89            .font(.caption).foregroundStyle(.secondary)90            VStack(spacing: 8) {91                if let source = image.sourceURL.flatMap(URL.init(string:)) {92                    Button { close(); actions.open(source, .current) } label: { Label(L("Open Source Page"), systemImage: "safari").frame(maxWidth: .infinity) }93                        .buttonStyle(.borderedProminent)94                }95                if let original = URL(string: image.imageURL) {96                    Button { close(); actions.open(original, .newTab) } label: { Label(L("Open Original Image"), systemImage: "arrow.up.right.square").frame(maxWidth: .infinity) }97                    HStack(spacing: 8) {98                        Button { PlatformActions.copy(image.imageURL); copied = true } label: { Label(copied ? L("Copied") : L("Copy URL"), systemImage: copied ? "checkmark" : "doc.on.doc").frame(maxWidth: .infinity) }99                        Button { actions.saveImage(image) } label: { Label(L("Save"), systemImage: "square.and.arrow.down").frame(maxWidth: .infinity) }100                    }101                    ShareLink(item: original) { Label(L("Share…"), systemImage: "square.and.arrow.up").frame(maxWidth: .infinity) }102                }103            }104            .buttonStyle(.bordered).controlSize(.regular).padding(.top, 4)105            if image.license == nil {106                Text(L("Images may be protected by copyright. Check the source page before reusing one.")).font(.caption2).foregroundStyle(.tertiary)107            }108        }109        .frame(maxWidth: .infinity, alignment: .leading)110    }111}112113// MARK: - Videos114115struct VideoCard: View {116    let video: VideoResult117    let query: String118    let actions: SearchActions119    let isList: Bool120    let play: () -> Void121    @State private var hovering = false122123    private var url: URL? { URL(string: video.url) }124125    var body: some View {126        Group {127            if isList {128                HStack(alignment: .top, spacing: 14) { thumbnail.frame(width: 250); text }129            } else {130                VStack(alignment: .leading, spacing: 9) { thumbnail; text }131            }132        }133        .onHover { hovering = $0 }134        .contextMenu {135            if let url {136                Button(L("Open")) { actions.open(url, .current) }137                Button(L("Open in New Tab")) { actions.open(url, .newTab) }138                if video.embedURL != nil { Button(L("Preview Here")) { play() } }139                Divider()140                Button(L("Copy Link")) { PlatformActions.copy(video.url) }141                Button(L("Share…")) { actions.share(url) }142            }143        }144        .accessibilityElement(children: .combine)145        .accessibilityLabel("\(video.title), \(video.platformName)\(video.channel.map { ", " + $0 } ?? "")\(video.durationText.map { ", " + $0 } ?? "")")146        .accessibilityAddTraits(.isLink)147    }148149    private var thumbnail: some View {150        Button { if let url { actions.open(url, .current) } } label: {151            RemoteImage(url: video.thumbnail.flatMap(URL.init(string:)), contentMode: .fill) {152                ZStack { Rectangle().fill(Color.secondary.opacity(0.14)); Image(systemName: "play.rectangle").font(.title).foregroundStyle(.tertiary) }153            }154            .aspectRatio(16.0 / 9.0, contentMode: .fit)155            .frame(maxWidth: .infinity)156            .clipShape(RoundedRectangle(cornerRadius: SPTheme.radiusM, style: .continuous))157            .overlay(alignment: .bottomTrailing) {158                if let duration = video.durationText {159                    Text(duration).font(.caption2.weight(.semibold).monospacedDigit()).foregroundStyle(.white)160                        .padding(.horizontal, 5).padding(.vertical, 2).background(Color.black.opacity(0.78), in: RoundedRectangle(cornerRadius: 4)).padding(6)161                }162            }163            .overlay(alignment: .topLeading) {164                Text(video.platformName).font(.caption2.weight(.semibold)).padding(.horizontal, 6).padding(.vertical, 2)165                    .background(.ultraThinMaterial, in: Capsule()).padding(6)166            }167            .overlay {168                if hovering, video.embedURL != nil {169                    Button(action: play) {170                        Image(systemName: "play.circle.fill").font(.system(size: 46)).symbolRenderingMode(.palette).foregroundStyle(.white, Color.black.opacity(0.55))171                    }172                    .buttonStyle(.plain).help(L("Preview Here")).accessibilityLabel(L("Preview Here"))173                }174            }175            .overlay(RoundedRectangle(cornerRadius: SPTheme.radiusM, style: .continuous).strokeBorder(SPTheme.hairline))176        }177        .buttonStyle(.plain)178    }179180    private var text: some View {181        VStack(alignment: .leading, spacing: 4) {182            Button { if let url { actions.open(url, .current) } } label: {183                HighlightedText(text: video.title, query: query).font(.system(size: isList ? 17 : 14.5, weight: .medium)).foregroundStyle(SPTheme.link)184                    .lineLimit(2).multilineTextAlignment(.leading).frame(maxWidth: .infinity, alignment: .leading)185            }186            .buttonStyle(.plain)187            let meta = [video.channel, SearchDate.display(video.publishedDate)].compactMap { $0 }.joined(separator: " · ")188            if !meta.isEmpty { Text(meta).font(.caption).foregroundStyle(.secondary).lineLimit(1) }189            if let description = video.description {190                Text(description).font(.system(size: 12.5)).foregroundStyle(.secondary).lineLimit(isList ? 3 : 2)191            }192        }193    }194}195196/// Plays a video with the platform's own embeddable player, inside the app.197struct VideoPlayerSheet: View {198    let video: VideoResult199    let actions: SearchActions200    @Environment(\.dismiss) private var dismiss201202    var body: some View {203        VStack(spacing: 0) {204            HStack(spacing: 10) {205                VStack(alignment: .leading, spacing: 1) {206                    Text(video.title).font(.headline).lineLimit(1)207                    Text([video.platformName, video.channel].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(.secondary).lineLimit(1)208                }209                Spacer()210                if let url = URL(string: video.url) {211                    Button(L("Open Page")) { dismiss(); actions.open(url, .current) }212                    ShareLink(item: url) { Image(systemName: "square.and.arrow.up") }.accessibilityLabel(L("Share…"))213                }214                Button(L("Done")) { dismiss() }.keyboardShortcut(.cancelAction)215            }216            .padding(12)217            if let embed = video.embedURL.flatMap(URL.init(string:)) {218                EmbeddedPlayer(embedURL: embed).aspectRatio(16.0 / 9.0, contentMode: .fit).background(Color.black)219            }220        }221        #if os(macOS)222        .frame(minWidth: 720, idealWidth: 900)223        #endif224    }225}226227/// A minimal, non-persistent web view that hosts only the platform's embed player.228struct EmbeddedPlayer {229    let embedURL: URL230231    @MainActor func makeView() -> WKWebView {232        let configuration = WKWebViewConfiguration()233        configuration.websiteDataStore = .nonPersistent()234        #if os(iOS)235        configuration.allowsInlineMediaPlayback = true236        #endif237        configuration.mediaTypesRequiringUserActionForPlayback = []238        let view = WKWebView(frame: .zero, configuration: configuration)239        let allowed = Set(["www.youtube-nocookie.com", "player.vimeo.com", "www.dailymotion.com"])240        guard embedURL.scheme == "https", let host = embedURL.host, allowed.contains(host) else { return view }241        let html = """242        <!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0;height:100%;background:#000}iframe{border:0;width:100%;height:100%}</style></head>243        <body><iframe src="\(embedURL.absoluteString)?autoplay=1&playsinline=1" allow="autoplay; encrypted-media; picture-in-picture; fullscreen" allowfullscreen referrerpolicy="strict-origin-when-cross-origin"></iframe></body></html>244        """245        view.loadHTMLString(html, baseURL: URL(string: "https://browser.spboucher.ai/"))246        return view247    }248}249250#if os(macOS)251extension EmbeddedPlayer: NSViewRepresentable {252    func makeNSView(context: Context) -> WKWebView { makeView() }253    func updateNSView(_ view: WKWebView, context: Context) {}254    static func dismantleNSView(_ view: WKWebView, coordinator: ()) { view.loadHTMLString("", baseURL: nil) }255}256#else257extension EmbeddedPlayer: UIViewRepresentable {258    func makeUIView(context: Context) -> WKWebView { makeView() }259    func updateUIView(_ view: WKWebView, context: Context) {}260    static func dismantleUIView(_ view: WKWebView, coordinator: ()) { view.loadHTMLString("", baseURL: nil) }261}262#endif263
Files main
Menu

Theme