SPB Git

Repository Public

PeekAndPortalViews.swift 20.1 KB 434 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Browser9// File             : SPBrowser/Shared/Aura/Features/PeekAndPortalViews.swift10// Module           : SPBrowser11// Repository       : https://git.spboucher.ai/sp-browser12// Created          : 2026-11-1913// Last Modified    : 2026-11-1914//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import SwiftUI8889// MARK: - Peek9091/// Loads and holds the preview of one link.92@MainActor93@Observable94final class PeekModel: Identifiable {95    enum State: Equatable { case loading, loaded(LinkPreview), failed, refused }96    let id = UUID()97    let url: URL98    let linkText: String99    private(set) var state: State = .loading100    @ObservationIgnored private var task: Task<Void, Never>?101102    init(url: URL, linkText: String = "") {103        self.url = url104        self.linkText = linkText105    }106107    func load(with loader: LinkPreviewLoader, isPrivate: Bool, sourceIsLocal: Bool) {108        guard task == nil else { return }109        task = Task { [weak self, url] in110            do {111                let preview = try await loader.preview(for: url, isPrivate: isPrivate, sourceIsLocal: sourceIsLocal)112                guard !Task.isCancelled else { return }113                AuraMotion.perform(.standard) { self?.state = .loaded(preview) }114            } catch LinkPreviewError.notAllowed {115                self?.state = .refused116            } catch {117                if !Task.isCancelled { self?.state = .failed }118            }119        }120    }121122    func cancel() { task?.cancel() }123}124125/// AURA Peek: what is behind a link, before opening it. The page is never executed: this is a text preview fetched without cookies.126struct PeekCard: View {127    let model: PeekModel128    var actions: [AuraMenuItem] = []129    var width: CGFloat = 340130131    var body: some View {132        VStack(alignment: .leading, spacing: 0) {133            switch model.state {134            case .loading: loading135            case .loaded(let preview): loaded(preview)136            case .failed: unavailable(L("No preview available"), L("The site did not answer or does not allow previews. You can still open the link."))137            case .refused: unavailable(L("Preview not shown"), L("Links to this device or the local network are not previewed."))138            }139            if !actions.isEmpty {140                Rectangle().fill(Aura.Palette.hairline).frame(height: 1)141                actionBar142            }143        }144        .frame(width: width)145        .accessibilityElement(children: .contain)146        .accessibilityIdentifier("peek-card")147    }148149    private var addressLine: some View {150        HStack(spacing: 5) {151            Image(systemName: model.url.scheme == "https" ? "lock.fill" : "exclamationmark.triangle.fill").font(.system(size: 9.5, weight: .semibold))152                .foregroundStyle(model.url.scheme == "https" ? AnyShapeStyle(.secondary) : AnyShapeStyle(Color.orange))153            Text(model.url.host ?? model.url.absoluteString).font(.system(size: 11.5, weight: .medium)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)154        }155    }156157    private var loading: some View {158        VStack(alignment: .leading, spacing: 9) {159            addressLine160            SkeletonBlock(height: 15, width: 230)161            SkeletonBlock(height: 11)162            SkeletonBlock(height: 11, width: 260)163            AuraProgressIndicator(progress: nil, label: L("Loading preview"))164        }165        .padding(14)166    }167168    private func loaded(_ preview: LinkPreview) -> some View {169        VStack(alignment: .leading, spacing: 0) {170            if let image = preview.imageURL {171                RemoteImage(url: image, contentMode: .fill) { Aura.Palette.card }172                    .frame(width: width, height: 150).clipped()173                    .accessibilityHidden(true)174            }175            VStack(alignment: .leading, spacing: 6) {176                HStack(spacing: 6) {177                    addressLine178                    if !preview.siteName.isEmpty, preview.siteName.lowercased() != (model.url.host ?? "") { Text("· " + preview.siteName).font(.system(size: 11.5)).foregroundStyle(.tertiary).lineLimit(1) }179                    Spacer(minLength: 0)180                    if preview.content != .page { AuraChip(text: preview.content == .pdf ? "PDF" : (preview.content == .image ? L("Image") : L("File")), tint: Aura.Palette.cyan) }181                }182                if preview.wasRedirectedToAnotherSite {183                    Label(L("Leads to %@", preview.finalURL.host ?? ""), systemImage: "arrow.turn.down.right").font(.caption.weight(.medium)).foregroundStyle(.orange)184                }185                Text(preview.title.isEmpty ? (model.linkText.isEmpty ? model.url.absoluteString : model.linkText) : preview.title)186                    .font(.system(size: 15, weight: .semibold)).lineLimit(3).fixedSize(horizontal: false, vertical: true)187                if !preview.summary.isEmpty {188                    Text(preview.summary).font(.system(size: 12.5)).foregroundStyle(.secondary).lineLimit(4).fixedSize(horizontal: false, vertical: true)189                }190                if !preview.excerpt.isEmpty, preview.excerpt != preview.summary {191                    Text(preview.excerpt).font(.system(size: 12, design: .serif)).foregroundStyle(.secondary).lineLimit(preview.summary.isEmpty ? 7 : 4)192                        .padding(.leading, 9).overlay(alignment: .leading) { Capsule().fill(Aura.gradient).frame(width: 2.5) }.padding(.top, 2)193                        .fixedSize(horizontal: false, vertical: true)194                }195            }196            .padding(14)197        }198    }199200    private func unavailable(_ title: String, _ message: String) -> some View {201        VStack(alignment: .leading, spacing: 6) {202            addressLine203            Text(title).font(.system(size: 14, weight: .semibold))204            Text(message).font(.system(size: 12.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)205        }206        .padding(14)207    }208209    private var actionBar: some View {210        HStack(spacing: 2) {211            ForEach(actions) { action in212                Button(action: action.action) {213                    VStack(spacing: 3) {214                        Image(systemName: action.symbol).font(.system(size: 14, weight: .medium))215                        Text(action.title).font(.system(size: 9.5, weight: .medium)).lineLimit(1).minimumScaleFactor(0.8)216                    }217                    .frame(maxWidth: .infinity).frame(height: 42).contentShape(Rectangle())218                }219                .buttonStyle(AuraPressStyle(scale: 0.92, haptic: .tap))220                .disabled(!action.isEnabled).opacity(action.isEnabled ? 1 : 0.35)221                .help(action.title)222                .accessibilityLabel(action.title)223                .accessibilityIdentifier("peek-" + action.id)224            }225        }226        .padding(.horizontal, 6).padding(.vertical, 4)227    }228}229230// MARK: - Portal231232/// What Portal needs from the app.233struct PortalHost {234    var isSignedIn: Bool235    var syncDescription: String236    var lastSync: Date?237    var isSyncing: Bool238    /// False in private browsing: nothing is sent from a private context.239    var canSend: Bool240    var open: (RemoteTab, _ inNewTab: Bool) -> Void241    var openAll: ([RemoteTab]) -> Void242    /// Sends this window's tabs to a device (nil = any of the user's devices).243    var send: (PortalDevice?) -> Void244    var accept: (HandoffItem) -> Void245    var decline: (HandoffItem) -> Void246    var syncNow: () -> Void247    var showAccount: () -> Void248    var dismiss: () -> Void249}250251/// AURA Portal: the user's other devices, what is open on each, and explicit hand-off in both directions.252struct PortalView: View {253    let devices: [PortalDevice]254    let handoffs: [HandoffItem]255    let host: PortalHost256    @Environment(\.auraPolicy) private var policy257    @State private var expanded = Set<String>()258259    var body: some View {260        VStack(spacing: 0) {261            header262            Rectangle().fill(Aura.Palette.hairline).frame(height: 1)263            if !host.isSignedIn {264                AuraEmptyState(symbol: "laptopcomputer.and.iphone", title: L("Continue on your other devices"),265                               message: L("Sign in to see what is open on your other Macs, iPhones and iPads, and to send tabs between them. Everything is encrypted on the device before it leaves it."),266                               actionTitle: L("Account…"), action: host.showAccount)267            } else if devices.isEmpty && handoffs.isEmpty {268                AuraEmptyState(symbol: "laptopcomputer.and.iphone", title: L("No other device yet"),269                               message: L("Open SP Browser on another device signed in to your account. Its tabs appear here after it synchronizes."),270                               actionTitle: L("Synchronize Now"), action: host.syncNow)271            } else {272                ScrollView {273                    LazyVStack(spacing: 14) {274                        ForEach(handoffs) { item in HandoffBanner(item: item, host: host).transition(AuraTransition.depth(policy)) }275                        ForEach(devices) { device in276                            PortalDeviceCard(device: device, isExpanded: expanded.contains(device.id), host: host) {277                                AuraMotion.perform(.spring) { if expanded.contains(device.id) { expanded.remove(device.id) } else { expanded.insert(device.id) } }278                            }279                        }280                        if host.canSend {281                            Button { host.send(nil) } label: { Label(L("Send This Window's Tabs to All My Devices"), systemImage: "paperplane").font(.callout) }282                                .buttonStyle(.bordered).padding(.top, 4)283                        }284                    }285                    .padding(16)286                    .animation(AuraMotion.animation(.spring, policy: policy), value: handoffs)287                }288            }289        }290        .background(Aura.Palette.surface)291        .accessibilityIdentifier("portal")292    }293294    private var header: some View {295        HStack(spacing: 10) {296            Image(systemName: "laptopcomputer.and.iphone").font(.title3).foregroundStyle(Aura.gradient)297            VStack(alignment: .leading, spacing: 1) {298                Text("Portal").font(.headline)299                SyncStatusLine(host: host)300            }301            Spacer()302            if host.isSignedIn { AuraIconButton(symbol: "arrow.triangle.2.circlepath", label: L("Synchronize Now"), action: host.syncNow).disabled(host.isSyncing) }303            Button(L("Done"), action: host.dismiss).keyboardShortcut(.cancelAction).accessibilityIdentifier("portal-done")304        }305        .padding(.horizontal, 16).padding(.vertical, 12)306    }307}308309/// "Synchronized 3 minutes ago" — the honest version: sync is periodic, so the line always says when.310struct SyncStatusLine: View {311    let host: PortalHost312313    var body: some View {314        HStack(spacing: 5) {315            if host.isSyncing {316                AuraProgressIndicator(progress: nil, style: .ring, thickness: 1.5).frame(width: 10, height: 10)317                Text(L("Synchronizing…"))318            } else if let last = host.lastSync, host.isSignedIn {319                Circle().fill(Color.green.opacity(0.85)).frame(width: 6, height: 6)320                Text(L("Synchronized %@", last.formatted(.relative(presentation: .named))))321            } else {322                Text(host.syncDescription)323            }324        }325        .font(.caption).foregroundStyle(.secondary)326        .accessibilityElement(children: .combine)327        .accessibilityIdentifier("sync-status")328    }329}330331private struct HandoffBanner: View {332    let item: HandoffItem333    let host: PortalHost334335    var body: some View {336        VStack(alignment: .leading, spacing: 8) {337            HStack(spacing: 8) {338                Image(systemName: PortalDevice.symbol(for: item.fromPlatform)).font(.title3).foregroundStyle(Aura.gradient)339                VStack(alignment: .leading, spacing: 1) {340                    Text(L("Sent from %@", item.fromDeviceName)).font(.subheadline.weight(.semibold))341                    Text(L("%d tabs", item.tabs.count) + " · " + item.sentAt.formatted(.relative(presentation: .named))).font(.caption).foregroundStyle(.secondary)342                }343                Spacer()344            }345            ForEach(Array(item.tabs.prefix(3).enumerated()), id: \.offset) { _, tab in346                Text(tab.title.isEmpty ? tab.url : tab.title).font(.callout).lineLimit(1)347            }348            if item.tabs.count > 3 { Text(L("and %d more", item.tabs.count - 3)).font(.caption).foregroundStyle(.secondary) }349            HStack {350                Button(L("Open Here")) { host.accept(item) }.buttonStyle(.borderedProminent).accessibilityIdentifier("handoff-accept")351                Button(L("Dismiss")) { host.decline(item) }.buttonStyle(.bordered)352            }353        }354        .padding(14)355        .frame(maxWidth: 640, alignment: .leading)356        .auraSurface(.floating, radius: 18, tint: Aura.Palette.violet, luminous: true)357    }358}359360struct PortalDeviceCard: View {361    let device: PortalDevice362    var isExpanded = false363    let host: PortalHost364    var toggle: () -> Void = {}365366    private var freshness: (Color, String) {367        switch device.freshness() {368        case .live: return (.green, L("Active recently"))369        case .recent: return (.orange, L("Earlier today"))370        case .stale: return (.gray, L("Not seen for a while"))371        }372    }373374    var body: some View {375        let shown = isExpanded ? device.tabs : Array(device.tabs.prefix(4))376        VStack(alignment: .leading, spacing: 8) {377            HStack(spacing: 10) {378                Image(systemName: device.symbol).font(.system(size: 22, weight: .light)).foregroundStyle(Aura.gradient).frame(width: 34)379                VStack(alignment: .leading, spacing: 1) {380                    Text(device.name).font(.subheadline.weight(.semibold)).lineLimit(1)381                    HStack(spacing: 5) {382                        Circle().fill(freshness.0).frame(width: 6, height: 6)383                        Text(L("Tabs as of %@", device.updatedAt.formatted(.relative(presentation: .named)))).font(.caption).foregroundStyle(.secondary).lineLimit(1)384                    }385                    .accessibilityElement(children: .ignore)386                    .accessibilityLabel(freshness.1 + ", " + L("Tabs as of %@", device.updatedAt.formatted(.relative(presentation: .named))))387                }388                Spacer(minLength: 0)389                Menu {390                    if !device.tabs.isEmpty { Button { host.openAll(device.tabs) } label: { Label(L("Open All %d Tabs Here", device.tabs.count), systemImage: "square.stack") } }391                    if host.canSend { Button { host.send(device) } label: { Label(L("Send This Window's Tabs to %@", device.name), systemImage: "paperplane") } }392                } label: { Image(systemName: "ellipsis.circle").font(.system(size: 16)).frame(width: 30, height: 30).contentShape(Rectangle()) }393                    .menuStyle(.borderlessButton).fixedSize().accessibilityLabel(L("More"))394            }395            if device.tabs.isEmpty && device.closed.isEmpty {396                Text(L("No open tabs")).font(.callout).foregroundStyle(.secondary)397            }398            ForEach(Array(shown.enumerated()), id: \.offset) { _, tab in row(tab, symbol: "arrow.up.forward") }399            if device.tabs.count > 4 {400                Button(isExpanded ? L("Show Less") : L("Show All %d Tabs", device.tabs.count), action: toggle).buttonStyle(.plain).font(.caption.weight(.medium)).foregroundStyle(Aura.Palette.accent)401            }402            if isExpanded, !device.closed.isEmpty {403                AuraSectionHeader(text: L("Recently closed")).padding(.top, 4)404                ForEach(Array(device.closed.prefix(8).enumerated()), id: \.offset) { _, tab in row(tab, symbol: "arrow.uturn.backward") }405            }406        }407        .padding(14)408        .frame(maxWidth: 640, alignment: .leading)409        .auraSurface(.panel, radius: 18, interactive: true)410        .accessibilityElement(children: .contain)411        .accessibilityIdentifier("portal-device")412    }413414    private func row(_ tab: RemoteTab, symbol: String) -> some View {415        Button { host.open(tab, true) } label: {416            HStack(spacing: 8) {417                Image(systemName: symbol).font(.system(size: 11, weight: .semibold)).foregroundStyle(.secondary).frame(width: 18)418                VStack(alignment: .leading, spacing: 0) {419                    Text(tab.title.isEmpty ? tab.url : tab.title).font(.system(size: 13)).lineLimit(1)420                    Text(URL(string: tab.url)?.host ?? tab.url).font(.system(size: 10.5)).foregroundStyle(.secondary).lineLimit(1)421                }422                Spacer(minLength: 0)423            }424            .padding(.vertical, 3).contentShape(Rectangle())425        }426        .buttonStyle(AuraPressStyle(scale: 0.98, haptic: .tap))427        .contextMenu {428            Button(L("Open in This Tab")) { host.open(tab, false) }429            Button(L("Copy Link")) { PlatformActions.copy(tab.url) }430        }431        .accessibilityIdentifier("portal-tab")432    }433}434
Files main
Menu

Theme