SPB Git

Repository Public

BrowserWindowState+Aura.swift 18.2 KB 396 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Browser9// File             : SPBrowser/Features/Aura/BrowserWindowState+Aura.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 AppKit88import SwiftUI89import WebKit9091enum AuraOverlay: Equatable { case none, constellation, flow, canvas, portal }9293/// A tab that was just opened from a link, and the point of the page it grows out of.94struct TabMorph: Equatable {95    let id = UUID()96    var tabID: UUID97    /// Unit coordinates in the page area, origin top-left.98    var origin: CGPoint99}100101/// AURA surfaces of a browser window: Constellation, Flow, Canvas, Portal, Orbit and Peek.102/// Everything here builds on the window's existing tabs, groups, history and sync — nothing is duplicated.103extension BrowserWindowState {104    // MARK: Presentation105106    func toggleAura(_ overlay: AuraOverlay) {107        dismissPeek()108        orbitVisible = false109        paletteVisible = false110        if overlay == .constellation { selectedTab?.captureThumbnail() }111        if overlay == .canvas { _ = canvas }112        AuraMotion.perform(.cinematic) { auraOverlay = auraOverlay == overlay ? .none : overlay }113    }114115    func dismissAura() {116        guard auraOverlay != .none else { return }117        AuraMotion.perform(.expressive) { auraOverlay = .none }118        window?.makeFirstResponder(selectedTab?.webView)119    }120121    // MARK: Constellation122123    var constellationItems: [ConstellationItem] {124        visibleTabs.map { tab in125            let group = group(id: tab.groupID)126            return ConstellationItem(id: tab.id, title: tab.displayTitle, url: tab.url?.absoluteString, groupID: tab.groupID, groupName: group?.name,127                                     colorIndex: group?.colorIndex, parentID: tab.openerID, workspaceID: tab.workspaceID, isPinned: tab.isPinned,128                                     isPrivate: isPrivate, lastActive: tab.lastActive)129        }130    }131132    func constellationOpen(_ id: UUID) {133        if let tab = tab(id: id) { select(tab) }134        dismissAura()135    }136137    func constellationClose(_ ids: Set<UUID>) {138        let victims = tabs.filter { ids.contains($0.id) }139        let closesEverything = victims.count >= tabs.count140        AuraMotion.perform(.spring) { victims.forEach(close) }141        if closesEverything { auraOverlay = .none }142    }143144    func constellationGroup(_ ids: Set<UUID>) {145        let members = visibleTabs.filter { ids.contains($0.id) }146        guard members.count > 1 else { return }147        AuraMotion.perform(.spring) {148            let group = createGroup(name: "", with: members[0])149            members.dropFirst().forEach { setGroup(group.id, for: $0) }150        }151        toast = L("%d tabs grouped", members.count)152    }153154    /// A tab was dropped on a constellation: it joins that group, or leaves its group when the target is not one.155    func constellationMove(_ id: UUID, to cluster: ConstellationMap.Cluster) {156        guard let tab = tab(id: id) else { return }157        AuraMotion.perform(.spring) {158            if cluster.kind == .group, let groupID = cluster.groupID { setGroup(groupID, for: tab) } else if tab.groupID != nil { setGroup(nil, for: tab) }159        }160    }161162    // MARK: Flow163164    var flowTrail: FlowTrail { _ = flowRevision; return profile.flow.trail }165    var flowCursor: UUID? { selectedTabID.flatMap { profile.flow.trail.cursor[$0] } }166167    /// Returns to a step of the path (in this tab), or opens it in a new tab — which starts a branch from that step.168    func flowOpen(_ node: FlowNode, inNewTab: Bool) {169        guard let url = URL(string: node.url) else { return }170        if inNewTab {171            let tab = newTab(select: true)172            let tabID = tab.id173            profile.flow.update { $0.moveCursor(tabID: tabID, to: node.id) }174            tab.load(url)175        } else if let tab = selectedTab {176            let tabID = tab.id177            profile.flow.update { $0.moveCursor(tabID: tabID, to: node.id) }178            tab.load(url)179        }180        dismissAura()181    }182183    func flowForget(journey rootID: UUID) {184        profile.flow.update { $0.removeJourney(rootID: rootID) }185        flowRevision += 1186    }187188    // MARK: Canvas189190    var canvas: CanvasController {191        if let canvasController { return canvasController }192        let controller = CanvasController(store: profile.canvas)193        controller.onChange = { [weak self, weak controller] in194            // Only boards the user chose to synchronize trigger a sync.195            if controller?.board.isSynced == true || self?.environment.services.mirror.count(SyncCollection.canvas) ?? 0 > 0 { self?.environment.services.localChange(syncAfter: 6) }196        }197        canvasController = controller198        return controller199    }200201    func addCurrentPageToCanvas() {202        guard let tab = selectedTab, let url = tab.url else { return }203        let board = canvas204        let text = tab.isSearchPage ? L("SP Search: %@", tab.searchQuery ?? "") : ""205        guard board.add(url.pathExtension.lowercased() == "pdf" ? .pdf : .tab, title: tab.displayTitle, text: text, url: url.absoluteString) != nil else { return }206        board.flush()207        toast = L("Added to canvas “%@”", board.board.name)208    }209210    var canvasHost: CanvasHost {211        CanvasHost(212            currentPage: { [weak self] in213                guard let tab = self?.selectedTab, let url = tab.url else { return nil }214                return (tab.displayTitle, url.absoluteString)215            },216            open: { [weak self] url in self?.newTab(url: url, select: true); self?.dismissAura() },217            // A capture is only ever taken from this explicit menu command, and never in a private window.218            capture: isPrivate ? nil : { [weak self] in await self?.capturePNG() },219            export: { [weak self] markdown, name in self?.exportMarkdown(markdown, name: name) },220            canSync: environment.services.account.isSignedIn && environment.settings.syncEnabled && !isPrivate && profile === environment.defaultContext,221            dismiss: { [weak self] in self?.dismissAura() })222    }223224    private func capturePNG() async -> Data? {225        guard let webView = selectedTab?.webView else { return nil }226        return await withCheckedContinuation { continuation in227            webView.takeSnapshot(with: nil) { image, _ in228                let data = image?.tiffRepresentation.flatMap { NSBitmapImageRep(data: $0) }?.representation(using: .png, properties: [:])229                continuation.resume(returning: data)230            }231        }232    }233234    private func exportMarkdown(_ markdown: String, name: String) {235        guard let window else { return }236        let panel = NSSavePanel()237        panel.allowedContentTypes = [.init(filenameExtension: "md") ?? .plainText]238        panel.nameFieldStringValue = DownloadSafety.sanitize(filename: name + ".md")239        panel.beginSheetModal(for: window) { [weak self] response in240            guard response == .OK, let url = panel.url else { return }241            let ok = (try? Data(markdown.utf8).write(to: url, options: .atomic)) != nil242            Task { @MainActor in self?.toast = ok ? L("Canvas exported.") : L("The canvas could not be exported.") }243        }244    }245246    // MARK: Portal247248    var portalHost: PortalHost {249        let services = environment.services250        return PortalHost(251            isSignedIn: services.account.isSignedIn, syncDescription: services.syncDescription, lastSync: services.sync.lastSync,252            isSyncing: services.sync.phase == .syncing, canSend: !isPrivate && services.account.isSignedIn,253            open: { [weak self] tab, inNewTab in254                guard let url = URL(string: tab.url) else { return }255                self?.open(url, inNewTab: inNewTab)256                self?.dismissAura()257            },258            openAll: { [weak self] tabs in259                let urls = tabs.compactMap { URL(string: $0.url) }260                for (index, url) in urls.enumerated() { self?.newTab(url: url, select: index == urls.count - 1) }261                self?.dismissAura()262            },263            send: { [weak self] device in self?.sendTabs(to: device) },264            accept: { [weak self] item in self?.acceptHandoff(item) },265            decline: { [weak self] item in self?.environment.services.consumeHandoff(item) },266            syncNow: { [weak self] in self?.perform(.syncNow) },267            showAccount: { [weak self] in self?.dismissAura(); self?.perform(.showAccount) },268            dismiss: { [weak self] in self?.dismissAura() })269    }270271    /// Explicit session transfer: the tabs of this (regular) window are offered to another device.272    func sendTabs(to device: PortalDevice?) {273        guard !isPrivate else { return }274        let tabs = visibleTabs.compactMap { tab -> RemoteTab? in275            guard let url = tab.url, HistoryStore.isRecordable(url) else { return nil }276            return RemoteTab(title: tab.displayTitle, url: url.absoluteString)277        }278        if environment.services.sendHandoff(tabs, title: activeWorkspace?.name ?? "", to: device) {279            toast = device.map { L("%d tabs sent to %@. They appear there at its next synchronization.", tabs.count, $0.name) }280                ?? L("%d tabs sent to your other devices.", tabs.count)281        } else {282            toast = L("There is no web page to send.")283        }284    }285286    func acceptHandoff(_ item: HandoffItem) {287        let urls = item.tabs.compactMap { URL(string: $0.url) }288        for (index, url) in urls.enumerated() { newTab(url: url, select: index == urls.count - 1) }289        environment.services.consumeHandoff(item)290        dismissAura()291        toast = L("%d tabs opened from %@", urls.count, item.fromDeviceName)292    }293294    // MARK: Orbit295296    var orbitContext: OrbitContext {297        let tab = selectedTab298        return OrbitContext(platform: .mac, hasPage: tab?.url != nil, isSearchPage: tab?.isSearchPage ?? false, isPrivate: isPrivate,299                            isReader: tab?.readerArticle != nil, aiEnabled: environment.settings.aiEnabled,300                            isSignedIn: environment.services.account.isSignedIn, tabCount: visibleTabs.count,301                            hasOtherDevices: !environment.services.otherDevices.isEmpty)302    }303304    func toggleOrbit() {305        dismissPeek()306        if orbitVisible { AuraMotion.perform(.quick) { orbitVisible = false }; return }307        paletteVisible = false308        // Orbit opens where the pointer is when it is over the window; otherwise at the centre of the page.309        orbitAnchor = nil310        if let window, let content = window.contentView {311            let point = content.convert(window.mouseLocationOutsideOfEventStream, from: nil)312            if content.bounds.contains(point) { orbitAnchor = CGPoint(x: point.x, y: content.bounds.height - point.y) }313        }314        AuraMotion.perform(.spring) { orbitVisible = true }315    }316317    func orbitRun(_ command: CommandID) {318        AuraMotion.perform(.quick) { orbitVisible = false }319        window?.makeFirstResponder(selectedTab?.webView)320        perform(command)321    }322323    /// Typing in Orbit hands over to the palette — the same commands, the full list.324    func orbitHandOver(_ text: String) {325        palettePrefill = text326        AuraMotion.perform(.expressive) { orbitVisible = false; paletteVisible = true }327    }328329    // MARK: Peek330331    func showPeek(_ link: HoveredLink) {332        guard peek?.url != link.url else { return }333        guard environment.settings.warnOnDeceptiveURLs || true else { return }334        peek?.cancel()335        let model = PeekModel(url: link.url, linkText: link.text)336        let sourceIsLocal = selectedTab?.url.map { $0.isFileURL || LinkPreviewPolicy.isLocalHost($0.host ?? "") } ?? false337        model.load(with: environment.services.peek, isPrivate: isPrivate, sourceIsLocal: sourceIsLocal)338        peekLink = link339        AuraMotion.perform(.spring) { peek = model }340    }341342    func dismissPeek() {343        guard peek != nil else { return }344        peek?.cancel()345        AuraMotion.perform(.quick) { peek = nil }346        peekLink = nil347    }348349    var peekActions: [AuraMenuItem] {350        guard let model = peek else { return [] }351        let url = model.url352        let title: () -> String = { [weak model] in353            if case .loaded(let preview)? = model?.state, !preview.title.isEmpty { return preview.title }354            return model?.linkText.isEmpty == false ? model!.linkText : (url.host ?? url.absoluteString)355        }356        var items = [357            AuraMenuItem(id: "open", title: L("Open"), symbol: "arrow.up.forward") { [weak self] in self?.dismissPeek(); self?.selectedTab?.load(url, userInitiated: false) },358            AuraMenuItem(id: "newtab", title: L("New Tab"), symbol: "plus.square.on.square") { [weak self] in359                guard let self else { return }360                self.dismissPeek(); self.newTab(url: url, select: false, after: self.selectedTab); self.toast = L("Opened in a background tab")361            },362            AuraMenuItem(id: "compare", title: L("Compare"), symbol: "rectangle.split.2x1") { [weak self] in363                guard let self else { return }364                self.dismissPeek()365                let tab = self.newTab(url: url, select: false, after: self.selectedTab)366                self.openInSplit(tab)367            },368        ]369        if !isPrivate {370            items.append(AuraMenuItem(id: "later", title: L("Read Later"), symbol: "eyeglasses") { [weak self] in self?.addToReadingList(title: title(), url: url.absoluteString); self?.dismissPeek() })371        }372        items.append(AuraMenuItem(id: "canvas", title: L("To Canvas"), symbol: "plus.rectangle.on.rectangle") { [weak self, weak model] in373            guard let self else { return }374            var text = ""375            if case .loaded(let preview)? = model?.state { text = preview.summary.isEmpty ? preview.excerpt : preview.summary }376            if self.canvas.add(.link, title: title(), text: text, url: url.absoluteString) != nil { self.canvas.flush(); self.toast = L("Added to canvas “%@”", self.canvas.board.name) }377            self.dismissPeek()378        })379        if let group = group(id: selectedTab?.groupID) {380            items.append(AuraMenuItem(id: "group", title: group.name, symbol: "square.stack.3d.up") { [weak self] in381                guard let self else { return }382                self.dismissPeek(); self.newTab(url: url, select: false, after: self.selectedTab)383            })384        }385        if environment.settings.aiEnabled {386            // The summary goes through SP Intelligence and its consent screen: nothing is sent to a provider from the preview itself.387            items.append(AuraMenuItem(id: "summary", title: L("Summarize"), symbol: "sparkles") { [weak self] in388                guard let self else { return }389                self.dismissPeek(); self.newTab(url: url, select: true, after: self.selectedTab); self.rightPanel = .intelligence390            })391        }392        items.append(AuraMenuItem(id: "copy", title: L("Copy Link"), symbol: "doc.on.doc") { [weak self] in PlatformActions.copy(url.absoluteString); self?.toast = L("Link copied"); self?.dismissPeek() })393        return items394    }395}396
Files main
Menu

Theme