SPB Git

Repository Public

BrowserRootView.swift 23.8 KB 466 lines swift

1import SwiftUI2import WebKit34struct AddressBarFrameKey: PreferenceKey {5    static let defaultValue: Anchor<CGRect>? = nil6    static func reduce(value: inout Anchor<CGRect>?, nextValue: () -> Anchor<CGRect>?) { value = value ?? nextValue() }7}89/// The whole window: optional sidebar, toolbar, tab strip, page area and optional right panel.10struct BrowserRootView: View {11    @Bindable var state: BrowserWindowState12    let environment: AppEnvironment13    @Environment(\.accessibilityReduceMotion) private var reduceMotion14    @Environment(\.auraPolicy) private var policy15    @State private var address = AddressBarModel()1617    private var showsChrome: Bool { !state.focusMode }18    private var showsSidebar: Bool { state.sidebarVisible && showsChrome }19    private var horizontalTabs: Bool { environment.settings.tabLayout == .horizontal }20    /// Space reserved for the window's close/minimise/zoom buttons when no sidebar sits under them.21    private var trafficLightInset: CGFloat { state.isFullScreen ? 10 : 84 }2223    var body: some View {24        GeometryReader { window in25            let density: Aura.Density = window.size.width < 980 ? .compact : .regular26            HStack(spacing: 0) {27                if showsSidebar {28                    AuraSidebar {29                        SidebarView(state: state, environment: environment, topInset: state.isFullScreen ? 8 : BrowserWindowController.toolbarHeight)30                    }31                    .frame(width: density == .compact ? 232 : 264)32                }33                VStack(spacing: 0) {34                    if showsChrome {35                        ToolbarView(state: state, environment: environment, address: address, leadingInset: showsSidebar ? 10 : trafficLightInset, density: density)36                            .frame(height: BrowserWindowController.toolbarHeight)37                        if horizontalTabs {38                            TabStripView(state: state, environment: environment)39                                .frame(height: 36)40                                .transition(AuraTransition.rise(.top, policy))41                        }42                        Divider().overlay(Theme.hairline)43                    }44                    pageArea45                        // AURA Focus Mode: the page takes the whole window; the Focus Trail and a discreet pill float over it.46                        .overlay { if !showsChrome { FocusBar(state: state, environment: environment).transition(.opacity) } }47                }48                if state.rightPanel != .none, showsChrome {49                    AuraSidebar(edge: .trailing) { RightPanelView(state: state, environment: environment) }50                        .frame(width: 372)51                }52            }53        }54        .background(chromeBackground)55        .ignoresSafeArea()56        .auraAnimation(.standard, value: showsSidebar)57        .auraAnimation(.standard, value: state.rightPanel)58        .auraAnimation(.expressive, value: state.focusMode)59        .auraAnimation(.standard, value: horizontalTabs)60        .overlay {61            // Address Bar Transformation: while the user types, the page recedes behind a light veil and the suggestions come forward.62            if address.showsSuggestions {63                Color.black.opacity(0.10).ignoresSafeArea().allowsHitTesting(false).transition(.opacity)64            }65        }66        .overlayPreferenceValue(AddressBarFrameKey.self) { anchor in67            GeometryReader { proxy in68                if let anchor, address.showsSuggestions {69                    let frame = proxy[anchor]70                    SuggestionList(model: address) { suggestion in address.commit(suggestion, state: state) }71                        .frame(width: max(frame.width, 420))72                        .offset(x: frame.minX, y: frame.maxY + 6)73                        .transition(AuraTransition.depth(policy, anchor: .top))74                }75            }76            .ignoresSafeArea()77        }78        .auraAnimation(.standard, value: address.showsSuggestions)79        .overlay { AuraOverlayHost(state: state, environment: environment) }80        .overlay { if state.orbitVisible { OrbitOverlay(state: state, environment: environment) } }81        .overlay { if state.paletteVisible { CommandPaletteView(state: state, environment: environment) } }82        .overlay(alignment: .bottom) {83            // Focus Mode can silence the browser's own notices; errors still show.84            if !(state.focusMode && environment.settings.focusHidesDistractions && !(state.toast.map { AuraToast.symbol(for: $0) == "exclamationmark.circle" } ?? false)) {85                AuraToast(text: $state.toast).padding(.bottom, 22)86            }87        }88        .sheet(isPresented: Binding(get: { state.sheet != .none }, set: { if !$0 { state.sheet = .none } })) {89            SheetContent(state: state, environment: environment)90        }91        .tint(state.isPrivate ? Theme.privateTint : Theme.accent)92        .auraRoot(decorative: environment.settings.ambientMotionEnabled)93    }9495    private var chromeBackground: some View {96        ZStack {97            VisualEffect(material: .sidebar)98            Theme.chrome.opacity(0.72)99            if state.isPrivate { Theme.privateTint.opacity(0.10) }100        }101    }102103    @ViewBuilder private var pageArea: some View {104        ZStack(alignment: .topTrailing) {105            if let split = state.splitTab, let primary = state.selectedTab {106                HSplitView {107                    TabContentView(tab: primary, state: state, environment: environment).frame(minWidth: 260)108                    VStack(spacing: 0) {109                        SplitHeader(tab: split, state: state)110                        Divider().overlay(Theme.hairline)111                        TabContentView(tab: split, state: state, environment: environment)112                    }113                    .frame(minWidth: 260)114                }115            } else if let tab = state.selectedTab {116                // Page Transition: the chrome cross-fades between tabs; the page itself is never animated from the inside.117                TabContentView(tab: tab, state: state, environment: environment)118                    .id(tab.id)119                    .transition(.opacity)120            } else {121                StateView(symbol: "square.dashed", title: L("No tab open"), actionTitle: L("New Tab")) { state.perform(.newTab) }122            }123            if state.findVisible { FindBar(state: state).padding(10).transition(AuraTransition.depth(policy, anchor: .topTrailing)) }124            if let morph = state.morph, morph.tabID == state.selectedTabID {125                MorphVeil(morph: morph, title: state.selectedTab?.displayTitle ?? "") { if state.morph?.id == morph.id { state.morph = nil } }126            }127        }128        .background(Theme.surface)129        .auraAnimation(.quick, value: state.selectedTabID)130        .auraAnimation(.standard, value: state.findVisible)131    }132}133134// MARK: - Toolbar135136struct ToolbarView: View {137    @Bindable var state: BrowserWindowState138    let environment: AppEnvironment139    let address: AddressBarModel140    let leadingInset: CGFloat141    var density: Aura.Density = .regular142143    var body: some View {144        let tab = state.selectedTab145        AuraToolbar(density: density) {146            IconButton(symbol: "sidebar.leading", label: CommandID.toggleSidebar.title, isActive: state.sidebarVisible, size: density.controlSize) { state.perform(.toggleSidebar) }147            HistoryButton(symbol: "chevron.left", label: CommandID.goBack.title, items: tab?.backList ?? [], enabled: tab?.canGoBack ?? false,148                          primary: { state.perform(.goBack) }, pick: { tab?.go(to: $0) })149            HistoryButton(symbol: "chevron.right", label: CommandID.goForward.title, items: tab?.forwardList ?? [], enabled: tab?.canGoForward ?? false,150                          primary: { state.perform(.goForward) }, pick: { tab?.go(to: $0) })151            // One button whose symbol morphs between reload and stop.152            IconButton(symbol: tab?.isLoading == true ? "xmark" : "arrow.clockwise", label: tab?.isLoading == true ? CommandID.stopLoading.title : CommandID.reload.title,153                       size: density.controlSize) { state.perform(tab?.isLoading == true ? .stopLoading : .reload) }154                .disabled(tab?.url == nil && tab?.isLoading != true)155156            AddressBar(state: state, environment: environment, model: address)157                .frame(maxWidth: address.isEditing ? 900 : 760)158                .frame(maxWidth: .infinity)159                .padding(.horizontal, 6)160161            // Smart Chrome: in a narrow window the secondary controls move into the menu instead of crowding the bar.162            if density == .regular, let tab, tab.url != nil, !tab.isSearchPage {163                BlockerButton(state: state, environment: environment, tab: tab)164                IconButton(symbol: tab.readerArticle != nil ? "doc.plaintext.fill" : "doc.plaintext", label: CommandID.toggleReader.title,165                           isActive: tab.readerArticle != nil) { state.perform(.toggleReader) }166            }167            DownloadsButton(state: state, environment: environment)168            if environment.settings.aiEnabled, density == .regular {169                IconButton(symbol: "sparkles", label: CommandID.toggleIntelligence.title, isActive: state.rightPanel == .intelligence) { state.perform(.toggleIntelligence) }170            }171            if density == .regular {172                IconButton(symbol: "rectangle.split.2x1", label: CommandID.toggleSplitView.title, isActive: state.splitTabID != nil) { state.perform(.toggleSplitView) }173            }174            IconButton(symbol: "circle.hexagongrid", label: CommandID.commandOrbit.title, isActive: state.orbitVisible, size: density.controlSize) { state.perform(.commandOrbit) }175                .accessibilityIdentifier("orbit-button")176            MoreMenu(state: state)177        }178        .padding(.leading, leadingInset)179        .padding(.trailing, 10)180        .auraAnimation(.expressive, value: address.isEditing)181        .auraAnimation(.standard, value: density)182    }183}184185/// Back/forward button: click navigates, press-and-hold (or right-click) lists the history of the tab.186struct HistoryButton: View {187    let symbol: String188    let label: String189    let items: [WKBackForwardListItem]190    let enabled: Bool191    let primary: () -> Void192    let pick: (WKBackForwardListItem) -> Void193194    var body: some View {195        IconButton(symbol: symbol, label: label, action: primary)196            .disabled(!enabled)197            .contextMenu {198                ForEach(Array(items.prefix(15).enumerated()), id: \.offset) { _, item in199                    Button(item.title?.isEmpty == false ? item.title! : item.url.absoluteString) { pick(item) }200                }201            }202    }203}204205struct MoreMenu: View {206    let state: BrowserWindowState207208    var body: some View {209        Menu {210            ForEach([CommandID.newTab, .newWindow, .newPrivateWindow], id: \.self, content: item)211            Divider()212            ForEach([CommandID.addBookmark, .addToReadingList, .toggleFavorite, .showBookmarks, .showHistory, .showReadingList, .showOtherDevices, .showNotes, .showSessions], id: \.self, content: item)213            Divider()214            ForEach([CommandID.showConstellation, .showFlow, .showCanvas, .addToCanvas, .showPortal], id: \.self, content: item)215            Divider()216            ForEach([CommandID.findInPage, .zoomIn, .zoomOut, .zoomReset, .toggleReader, .toggleFocusMode, .toggleSplitView], id: \.self, content: item)217            Divider()218            ForEach([CommandID.savePageAsPDF, .capturePage, .printPage, .sharePage], id: \.self, content: item)219            Divider()220            ForEach([CommandID.pageInfo, .pageMetadata, .clearSiteData, .changeUserAgent], id: \.self, content: item)221            Divider()222            ForEach([CommandID.commandPalette, .showAccount, .openSettings], id: \.self, content: item)223        } label: {224            Image(systemName: "ellipsis").font(.system(size: 13.5, weight: .medium)).frame(width: 28, height: 28).contentShape(Rectangle())225        }226        .menuStyle(.borderlessButton)227        .menuIndicator(.hidden)228        .fixedSize()229        .help(L("More"))230        .accessibilityLabel(L("More"))231    }232233    private func item(_ command: CommandID) -> some View {234        Button(command.title) { state.perform(command) }.disabled(!state.isEnabled(command))235    }236}237238struct BlockerButton: View {239    let state: BrowserWindowState240    let environment: AppEnvironment241    let tab: BrowserTab242    @State private var showing = false243244    var body: some View {245        let settings = environment.settings246        let host = tab.url?.host ?? ""247        let active = settings.contentBlockerEnabled && !settings.isBlockerDisabled(forHost: host)248        IconButton(symbol: active ? "shield.lefthalf.filled" : "shield.slash", label: L("Privacy protection"), isActive: active) { showing.toggle() }249            .popover(isPresented: $showing, arrowEdge: .bottom) {250                VStack(alignment: .leading, spacing: 10) {251                    Label(active ? L("Content blocker is on for this site") : L("Content blocker is off for this site"),252                          systemImage: active ? "shield.lefthalf.filled" : "shield.slash").font(.headline)253                    Text(L("%d rules block known third-party trackers and ad servers before they load. SP Browser cannot count what was blocked: WebKit applies the rules itself and reports nothing back.", environment.blocker.ruleCount))254                        .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)255                    if settings.contentBlockerEnabled, !host.isEmpty {256                        Button(active ? L("Turn Off for %@", URLInspector.registrableDomain(of: host)) : L("Turn On for %@", URLInspector.registrableDomain(of: host))) {257                            showing = false258                            state.perform(.toggleBlockerForSite)259                        }260                    } else if !settings.contentBlockerEnabled {261                        Text(L("The content blocker is turned off in Settings.")).font(.callout)262                    }263                    Button(L("Page Information…")) { showing = false; state.rightPanel = .pageInfo }.buttonStyle(.link)264                }265                .padding(16).frame(width: 330)266            }267    }268}269270// MARK: - Focus mode bar and split header271272/// AURA Focus Mode: the chrome is gone; what remains is a quiet line with the title, the progress and the way out,273/// and the Focus Trail under it. The controls stay dim until the pointer comes near.274struct FocusBar: View {275    let state: BrowserWindowState276    let environment: AppEnvironment277278    var body: some View {279        let tab = state.selectedTab280        let tracksProgress = environment.settings.focusTrailEnabled && tab?.readerArticle == nil && (tab?.isLongPage ?? false)281        // The trail runs along the top edge; the pill sits at the bottom, clear of the site's own header.282        VStack(spacing: 0) {283            if tracksProgress { FocusTrail(progress: tab?.readingProgress ?? 0, thickness: 2.5) }284            Spacer(minLength: 0)285            FocusPill(title: tab?.displayTitle ?? "", progress: tracksProgress ? tab?.readingProgress : nil) { state.perform(.toggleFocusMode) }286                .contextMenu {287                    Button(CommandID.openLocation.title) { state.perform(.openLocation) }288                    Button(CommandID.commandOrbit.title) { state.perform(.commandOrbit) }289                    Button(CommandID.toggleReader.title) { state.perform(.toggleReader) }.disabled(!state.isEnabled(.toggleReader))290                }291                .padding(.bottom, 14)292        }293        .allowsHitTesting(true)294    }295}296297struct SplitHeader: View {298    let tab: BrowserTab299    let state: BrowserWindowState300301    var body: some View {302        HStack(spacing: 4) {303            IconButton(symbol: "chevron.left", label: L("Back"), size: 24) { tab.goBack() }.disabled(!tab.canGoBack)304            IconButton(symbol: "chevron.right", label: L("Forward"), size: 24) { tab.goForward() }.disabled(!tab.canGoForward)305            IconButton(symbol: "arrow.clockwise", label: L("Reload Page"), size: 24) { tab.reload() }306            Image(systemName: tab.security.symbol).font(.caption).foregroundStyle(.secondary)307            Text(tab.url?.host ?? tab.displayTitle).font(.callout).lineLimit(1).truncationMode(.middle)308            Spacer()309            IconButton(symbol: "arrow.left.arrow.right", label: CommandID.swapSplit.title, size: 24) { state.swapSplit() }310            IconButton(symbol: "xmark", label: L("Close Split View"), size: 24) { state.toggleSplit() }311        }312        .padding(.horizontal, 8).frame(height: 32).background(Theme.chrome.opacity(0.6))313    }314}315316// MARK: - Page content317318/// Embeds the tab's WKWebView. The web view itself is owned by the tab, so switching tabs never reloads a page.319struct WebViewHost: NSViewRepresentable {320    let tab: BrowserTab321322    func makeNSView(context: Context) -> NSView {323        let container = NSView()324        container.wantsLayer = true325        return container326    }327328    func updateNSView(_ container: NSView, context: Context) {329        let webView = tab.ensureWebView()330        guard webView.superview !== container else { return }331        container.subviews.forEach { $0.removeFromSuperview() }332        webView.removeFromSuperview()333        webView.frame = container.bounds334        webView.autoresizingMask = [.width, .height]335        container.addSubview(webView)336    }337}338339struct TabContentView: View {340    @Bindable var tab: BrowserTab341    let state: BrowserWindowState342    let environment: AppEnvironment343344    var body: some View {345        ZStack {346            if tab.isBlank {347                StartPageView(state: state, environment: environment, tab: tab)348            } else {349                WebViewHost(tab: tab).id(tab.id)350                    .opacity(tab.readerArticle == nil && tab.error == nil && !tab.crashed && !tab.isSearchPage ? 1 : 0)351                    .accessibilityLabel(L("Web page: %@", tab.displayTitle))352                    .accessibilityHidden(tab.isSearchPage)353                if tab.isSearchPage {354                    // Native SP Search results, drawn over the placeholder document that holds the page's place in history.355                    if let model = tab.searchPage {356                        SearchResultsView(model: model, actions: state.searchActions(for: tab)).id(tab.id)357                            // Keep the keyboard on the results (arrow keys, Return) rather than letting the address field take it.358                            .onAppear { DispatchQueue.main.async { if state.selectedTabID == tab.id, state.window?.firstResponder is NSTextView { state.window?.makeFirstResponder(nil) } } }359                    } else {360                        Theme.surface.task { tab.refreshSearchPage() }361                    }362                }363                if let article = tab.readerArticle { ReaderView(article: article, url: tab.url, showsTrail: environment.settings.focusTrailEnabled).transition(.opacity) }364                if let error = tab.error { ErrorPageView(error: error, tab: tab) }365                if tab.crashed { CrashPageView(tab: tab) }366            }367        }368        .overlay { if !tab.isBlank, !tab.isSearchPage, tab.readerArticle == nil { PeekLayer(tab: tab, state: state, environment: environment) } }369        .overlay(alignment: .top) {370            VStack(spacing: 6) {371                if let prompt = tab.permissionPrompt { PermissionBanner(prompt: prompt).transition(AuraTransition.depth(AuraMotion.policy)) }372                if let notice = tab.notice { NoticeBanner(notice: notice, tab: tab).transition(AuraTransition.depth(AuraMotion.policy)) }373            }374            .padding(.top, 8)375            .auraAnimation(.spring, value: tab.notice?.id)376            .auraAnimation(.spring, value: tab.permissionPrompt?.id)377        }378        .dropDestination(for: URL.self) { urls, _ in379            guard let url = urls.first, ["http", "https", "file"].contains(url.scheme?.lowercased() ?? "") else { return false }380            if tab.isBlank { tab.load(url) } else { state.newTab(url: url, select: true) }381            return true382        }383    }384}385386struct PermissionBanner: View {387    let prompt: PermissionPrompt388    @State private var remember = false389390    var body: some View {391        VStack(alignment: .leading, spacing: 10) {392            HStack(spacing: 10) {393                Image(systemName: prompt.permissions.contains(.camera) ? "video.fill" : "mic.fill").font(.title3).foregroundStyle(Theme.accent)394                VStack(alignment: .leading, spacing: 2) {395                    Text(L("%@ wants to use your %@", prompt.host.isEmpty ? L("This page") : prompt.host,396                           prompt.permissions.map { $0.title.lowercased() }.joined(separator: L(" and ")))).font(.headline)397                    Text(L("Nothing is shared until you allow it. You can change this later in Page Information.")).font(.caption).foregroundStyle(.secondary)398                }399            }400            HStack {401                Toggle(L("Remember for this site"), isOn: $remember).toggleStyle(.checkbox).font(.callout)402                Spacer()403                Button(L("Deny")) { prompt.resolve(false, remember) }.keyboardShortcut(.cancelAction)404                Button(L("Allow")) { prompt.resolve(true, remember) }.buttonStyle(.borderedProminent)405            }406        }407        .padding(14).frame(width: 460).cardSurface().shadow(color: .black.opacity(0.18), radius: 14, y: 6)408        .accessibilityElement(children: .contain)409    }410}411412struct NoticeBanner: View {413    let notice: TabNotice414    let tab: BrowserTab415416    var body: some View {417        HStack(spacing: 8) {418            Image(systemName: notice.symbol).foregroundStyle(.orange)419            Text(notice.text).font(.callout).lineLimit(2)420            if case .allowPopups(let host) = notice.action {421                Button(L("Always Allow")) {422                    tab.profile.permissions.set(.allow, for: .popups, host: host)423                    tab.notice = nil424                }425            }426            Button { tab.notice = nil } label: { Image(systemName: "xmark") }.buttonStyle(.plain).accessibilityLabel(L("Dismiss"))427        }428        .padding(.horizontal, 12).padding(.vertical, 8).cardSurface(radius: Theme.radiusM).shadow(color: .black.opacity(0.14), radius: 10, y: 4)429        .task(id: notice.id) {430            try? await Task.sleep(for: .seconds(8))431            if tab.notice?.id == notice.id { tab.notice = nil }432        }433    }434}435436struct FindBar: View {437    @Bindable var state: BrowserWindowState438    @FocusState private var focused: Bool439440    var body: some View {441        HStack(spacing: 6) {442            Image(systemName: "magnifyingglass").foregroundStyle(.secondary)443            TextField(L("Find in page"), text: $state.findQuery)444                .textFieldStyle(.plain).frame(width: 190).focused($focused)445                .onSubmit { state.findRequest(backwards: NSEvent.modifierFlags.contains(.shift)) }446                .onChange(of: state.findQuery) { state.findFound = nil }447                .accessibilityLabel(L("Find in page"))448            if state.findFound == false, !state.findQuery.isEmpty {449                Text(L("Not found")).font(.caption).foregroundStyle(.red)450            }451            IconButton(symbol: "chevron.up", label: CommandID.findPrevious.title, size: 22) { state.findRequest(backwards: true) }452            IconButton(symbol: "chevron.down", label: CommandID.findNext.title, size: 22) { state.findRequest(backwards: false) }453            IconButton(symbol: "xmark", label: L("Close"), size: 22) { state.findVisible = false }454        }455        .padding(.horizontal, 10).padding(.vertical, 6).cardSurface(radius: Theme.radiusM).shadow(color: .black.opacity(0.18), radius: 10, y: 4)456        .onAppear { focused = true }457        .onExitCommand { state.findVisible = false }458    }459}460461/// Kept for call sites written before 3.0: the toast is now the AURA toast.462struct ToastView: View {463    @Binding var text: String?464    var body: some View { AuraToast(text: $text) }465}466
Files main
Menu

Theme