SPB Git

Repository Public License

OmniboxViews.swift 18.0 KB 418 lines swift

1import LunarDesign2import NavigatorCore3import SwiftUI4import WebRuntime56/// Site icon with a monogram fallback. The icon comes from the profile's cache only: showing a row never7/// contacts the site (see `FaviconStore`).8struct FaviconView: View {9    @Environment(\.lunarTheme) private var theme10    @Environment(BrowserStore.self) private var store11    /// Address of the page (not of the icon).12    let page: URL?13    let title: String14    var size: CGFloat = 1815    /// Profile whose cache is read; `nil` means the default profile.16    var profile: ProfileID?1718    init(page: URL?, title: String, size: CGFloat = 18, profile: ProfileID? = nil) {19        self.page = page; self.title = title; self.size = size; self.profile = profile20    }2122    /// The icon of an open tab.23    @MainActor init(tab: TabModel, size: CGFloat = 18) {24        self.init(page: tab.isBlank ? nil : tab.engine.url, title: tab.title, size: size,25                  profile: tab.engine.profile.profile.id)26    }2728    var body: some View {29        if let image = store.favicons.image(forPage: page, profile: profile ?? store.profile.id) {30            Image(platformImage: image)31                .resizable()32                .interpolation(.high)33                .scaledToFit()34                .frame(width: size, height: size)35                // Many site icons are dark marks on a transparent ground: a light plate keeps them visible on36                // dark themes.37                .padding(theme.isDark ? size * 0.08 : 0)38                .background { if theme.isDark { RoundedRectangle(cornerRadius: size * 0.24, style: .continuous).fill(Color.white.opacity(0.92)) } }39                .clipShape(RoundedRectangle(cornerRadius: size * 0.24, style: .continuous))40                .accessibilityHidden(true)41        } else {42            LunarMonogram(title, tint: FaviconView.tint(for: title), size: size)43        }44    }4546    /// A stable tint per title, so that monograms are told apart at a glance.47    static func tint(for text: String) -> LunarTint {48        let tints = LunarTint.allCases49        let sum = text.unicodeScalars.reduce(0) { ($0 &+ Int($1.value)) % 9_973 }50        return tints[sum % tints.count]51    }52}5354extension TabModel {55    @MainActor func faviconImage(in store: BrowserStore, window: WindowModel) -> Image? {56        guard !isBlank else { return nil }57        return store.favicons.image(forPage: engine.url, profile: window.profile.id).map(Image.init(platformImage:))58    }5960    var audioState: LunarTabAudio {61        engine.isMuted ? (engine.isPlayingAudio || engine.mediaActivity.audibleElements > 0 ? .muted : .silent)62            : (engine.isPlayingAudio ? .playing : .silent)63    }64}6566/// What the security indicator says about the page.67enum SecurityState: Equatable {68    case none, secure, exception, mixedContent, notSecure, local6970    @MainActor init(engine: WebEngine?) {71        guard let engine, let url = engine.url, let scheme = url.scheme?.lowercased() else { self = .none; return }72        switch scheme {73        case "https":74            if engine.serverTrust?.usesUserException == true { self = .exception }75            else if engine.isLoading && engine.serverTrust == nil { self = .none }76            else { self = engine.hasOnlySecureContent || engine.serverTrust != nil ? .secure : .mixedContent }77        case "http": self = .notSecure78        case "file": self = .local79        default: self = .none80        }81    }8283    var symbol: String {84        switch self {85        case .none: "magnifyingglass"86        case .secure: "lock.fill"87        case .exception: "lock.trianglebadge.exclamationmark.fill"88        case .mixedContent, .notSecure: "exclamationmark.triangle.fill"89        case .local: "doc.fill"90        }91    }9293    var label: String {94        switch self {95        case .none: L("Search or address")96        case .secure: L("Connection is secure")97        case .exception: L("Certificate accepted by you")98        case .mixedContent: L("Some content is not secure")99        case .notSecure: L("Connection is not secure")100        case .local: L("Local file")101        }102    }103}104105struct SecurityIndicator: View {106    @Environment(\.lunarTheme) private var theme107    let engine: WebEngine?108    var size: CGFloat = 16109    @State private var showsDetails = false110111    var body: some View {112        let state = SecurityState(engine: engine)113        Button { if state != .none { showsDetails = true } } label: {114            LunarIconView(.symbol(state.symbol), size: size)115                .foregroundStyle(color(state))116                .frame(width: 28, height: 28)117                .contentShape(Circle())118        }119        .buttonStyle(LunarPressStyle())120        .disabled(state == .none)121        .accessibilityLabel(state.label)122        .accessibilityHint(state == .none ? "" : L("Shows connection details"))123        .accessibilityIdentifier("omnibox.security")124        .help(state.label)125        .popover(isPresented: $showsDetails) {126            ConnectionDetailsView(engine: engine, state: state)127                .lunarTheme(theme)128        }129    }130131    private func color(_ state: SecurityState) -> LunarRGBA {132        switch state {133        case .none, .local: theme.textSecondary134        case .secure: theme.textSecondary.mixed(with: theme.textPrimary, 0.4)135        case .exception, .mixedContent, .notSecure: theme.warning136        }137    }138}139140struct ConnectionDetailsView: View {141    @Environment(\.lunarTheme) private var theme142    let engine: WebEngine?143    let state: SecurityState144145    var body: some View {146        VStack(alignment: .leading, spacing: LunarSpacing.sm) {147            HStack(spacing: LunarSpacing.xs) {148                LunarIconView(.symbol(state.symbol), size: 18)149                    .foregroundStyle(state == .secure ? theme.success : theme.warning)150                Text(state.label).lunarFont(.headline).foregroundStyle(theme.textPrimary)151            }152            if let host = engine?.url.map(URLDisplay.host) {153                Text(host).lunarFont(.mono).foregroundStyle(theme.textSecondary).textSelection(.enabled)154            }155            Text(explanation).lunarFont(.callout).foregroundStyle(theme.textSecondary)156                .fixedSize(horizontal: false, vertical: true)157            if let leaf = engine?.serverTrust?.leaf {158                LunarHairline()159                CertificateSummaryView(certificate: leaf, chainCount: engine?.serverTrust?.chain.count ?? 1)160            }161        }162        .padding(LunarSpacing.md)163        .frame(minWidth: 280, idealWidth: 340, maxWidth: 380, alignment: .leading)164        .background(theme.elevatedSurface)165        .presentationCompactAdaptation(.popover)166        .accessibilityElement(children: .contain)167        .accessibilityIdentifier("connection.details")168    }169170    private var explanation: String {171        switch state {172        case .secure: L("Information you send to this site is encrypted and the site's identity was verified by a certificate.")173        case .exception: L("The certificate of this site is not valid. You chose to continue for this session.")174        case .mixedContent: L("The page is encrypted, but some of its resources were requested over an insecure connection.")175        case .notSecure: L("Information you send to this site is not encrypted and could be read or changed by others.")176        case .local: L("This page is a file stored on this device.")177        case .none: ""178        }179    }180}181182struct CertificateSummaryView: View {183    @Environment(\.lunarTheme) private var theme184    let certificate: CertificateSummary185    var chainCount = 1186187    var body: some View {188        VStack(alignment: .leading, spacing: LunarSpacing.unit + 2) {189            row(L("Issued to"), certificate.commonName ?? certificate.subject)190            if let from = certificate.notValidBefore { row(L("Valid from"), from.formatted(date: .abbreviated, time: .omitted)) }191            if let until = certificate.notValidAfter { row(L("Valid until"), until.formatted(date: .abbreviated, time: .omitted)) }192            if certificate.isSelfIssued { row(L("Issuer"), L("Self-signed")) }193            if chainCount > 1 { row(L("Chain"), L("%d certificates", chainCount)) }194            row(L("SHA-256"), Self.shortened(certificate.sha256Fingerprint))195        }196        .accessibilityElement(children: .contain)197    }198199    private func row(_ name: String, _ value: String) -> some View {200        HStack(alignment: .firstTextBaseline, spacing: LunarSpacing.xs) {201            Text(name).lunarFont(.caption).foregroundStyle(theme.textTertiary).frame(width: 84, alignment: .leading)202            Text(value).lunarFont(.footnote).foregroundStyle(theme.textPrimary).textSelection(.enabled)203                .fixedSize(horizontal: false, vertical: true)204        }205        .accessibilityElement(children: .combine)206    }207208    static func shortened(_ fingerprint: String) -> String {209        let compact = fingerprint.replacingOccurrences(of: ":", with: "").replacingOccurrences(of: " ", with: "")210        guard compact.count > 24 else { return fingerprint }211        return compact.prefix(12) + "…" + compact.suffix(12)212    }213}214215/// The capsule address field used in regular-width layouts (Mac, iPad).216struct OmniboxBar: View {217    @Environment(\.lunarTheme) private var theme218    @Environment(BrowserStore.self) private var store219    let window: WindowModel220221    var body: some View {222        let omnibox = window.omnibox223        let tab = window.selectedTab224        let engine = tab?.engine225        HStack(spacing: LunarSpacing.unit) {226            SecurityIndicator(engine: omnibox.isEditing ? nil : engine)227            OmniboxTextField(228                text: Binding(get: { omnibox.text }, set: { omnibox.setText($0) }),229                displayText: engine?.url.flatMap { InternalAddress.isInternal($0) ? nil : URLDisplay.short($0) } ?? "",230                prompt: L("Search or enter an address"),231                isEditing: omnibox.isEditing,232                focusRequest: omnibox.focusRequest,233                textColor: theme.textPrimary.color,234                promptColor: theme.textTertiary.color,235                tintColor: theme.accent.color,236                identifier: "omnibox.field",237                onBeginEditing: { omnibox.focus() },238                onEndEditing: { omnibox.fieldDidEndEditing() },239                onSubmit: { omnibox.submit() },240                onMove: { omnibox.moveHighlight(by: $0) },241                onCancel: { omnibox.cancel() })242                .frame(height: 22)243            if !omnibox.isEditing, let tab {244                if !tab.pendingPopups.isEmpty { PopupIndicator(window: window, tab: tab) }245                if let engine, abs(engine.pageZoom - 1) > 0.01 {246                    Button { window.resetZoom() } label: {247                        Text(verbatim: "\(Int((engine.pageZoom * 100).rounded())) %")248                            .lunarFont(.caption).lunarTabularDigits()249                            .foregroundStyle(theme.textSecondary)250                            .padding(.horizontal, 6).frame(height: 20)251                            .background { Capsule().fill(theme.textPrimary.withAlpha(0.08)) }252                    }253                    .buttonStyle(LunarPressStyle())254                    .accessibilityLabel(L("Zoom %d percent", Int((engine.pageZoom * 100).rounded())))255                    .accessibilityHint(L("Resets the zoom"))256                    .help(L("Reset zoom"))257                }258                ForEach(store.registry.toolbarItems(in: .addressField)) { item in259                    ContributedToolbarButton(window: window, item: item, diameter: 28)260                }261                if !tab.isBlank {262                    LunarIconButton(systemName: window.isLoading ? "xmark" : "arrow.clockwise",263                                    label: window.isLoading ? L("Stop loading") : L("Reload"), diameter: 28) {264                        window.run(window.isLoading ? ShellCommandID.stop : ShellCommandID.reload, source: .toolbar)265                    }266                    .accessibilityIdentifier("omnibox.reload")267                }268            }269        }270        .padding(.leading, LunarSpacing.unit)271        .padding(.trailing, LunarSpacing.unit + 2)272        .frame(minHeight: LunarMetrics.controlHeight + LunarSpacing.unit)273        .lunarGlass(.capsule, style: .control, elevation: .flat)274        .overlay(alignment: .bottom) {275            if let engine, engine.isLoading {276                LunarProgressBar(value: max(0.05, engine.estimatedProgress), label: L("Page loading"), height: 2)277                    .padding(.horizontal, LunarSpacing.md)278                    .transition(.opacity)279            }280        }281        .lunarFocusRing(.capsule, isFocused: omnibox.isEditing)282        .lunarAnimation(.quick, value: engine?.isLoading ?? false)283    }284}285286/// "Pop-up blocked" badge with the choice to open it anyway.287struct PopupIndicator: View {288    @Environment(\.lunarTheme) private var theme289    let window: WindowModel290    let tab: TabModel291    @State private var isPresented = false292293    var body: some View {294        LunarIconButton(systemName: "rectangle.on.rectangle.slash", label: L("Pop-up blocked"), isActive: true, diameter: 28) {295            isPresented = true296        }297        .accessibilityIdentifier("omnibox.popupBlocked")298        .popover(isPresented: $isPresented) {299            VStack(alignment: .leading, spacing: LunarSpacing.sm) {300                Text(L("This page tried to open %d pop-up window(s).", tab.pendingPopups.count))301                    .lunarFont(.callout).foregroundStyle(theme.textPrimary)302                    .fixedSize(horizontal: false, vertical: true)303                ForEach(tab.pendingPopups.prefix(3)) { popup in304                    if let url = popup.url {305                        Button {306                            isPresented = false307                            tab.acknowledgedPopupCount = tab.engine.blockedPopups.count308                            window.newTab(url: url, opener: tab, transition: .link)309                        } label: {310                            Text(L("Open %@ anyway", URLDisplay.short(url))).lineLimit(1).truncationMode(.middle)311                        }312                        .buttonStyle(.lunar(.secondary, size: .compact))313                    }314                }315                Button(L("Keep blocking")) {316                    isPresented = false317                    tab.acknowledgedPopupCount = tab.engine.blockedPopups.count318                }319                .buttonStyle(.lunar(.secondary, size: .compact))320            }321            .padding(LunarSpacing.md)322            .frame(width: 300, alignment: .leading)323            .background(theme.elevatedSurface)324            .presentationCompactAdaptation(.popover)325            .lunarTheme(theme)326        }327    }328}329330/// Rows under the omnibox: local suggestions and the inline notice for refused schemes.331struct SuggestionList: View {332    @Environment(\.lunarTheme) private var theme333    let omnibox: OmniboxModel334    var rowHeight: CGFloat = 44335336    var body: some View {337        VStack(alignment: .leading, spacing: 2) {338            if let notice = omnibox.notice {339                HStack(alignment: .top, spacing: LunarSpacing.xs) {340                    LunarIconView(.symbol("hand.raised.fill"), size: 18).foregroundStyle(theme.warning)341                    Text(notice).lunarFont(.callout).foregroundStyle(theme.textPrimary)342                        .fixedSize(horizontal: false, vertical: true)343                }344                .padding(LunarSpacing.sm)345                .accessibilityElement(children: .combine)346                .accessibilityIdentifier("omnibox.notice")347            }348            ForEach(Array(omnibox.suggestions.enumerated()), id: \.element.id) { index, suggestion in349                SuggestionRow(suggestion: suggestion, isHighlighted: omnibox.highlightedIndex == index, minHeight: rowHeight) {350                    omnibox.accept(suggestion)351                }352            }353        }354        .accessibilityElement(children: .contain)355        .accessibilityIdentifier("omnibox.suggestions")356    }357}358359struct SuggestionRow: View {360    @Environment(\.lunarTheme) private var theme361    let suggestion: OmniboxSuggestion362    let isHighlighted: Bool363    var minHeight: CGFloat = 44364    let action: () -> Void365366    var body: some View {367        Button(action: action) {368            LunarHoverRow(isSelected: isHighlighted) {369                HStack(spacing: LunarSpacing.sm) {370                    LunarIconView(.symbol(symbol), size: 16)371                        .foregroundStyle(isHighlighted ? theme.accent : theme.textSecondary)372                        .frame(width: 24)373                    VStack(alignment: .leading, spacing: 1) {374                        Text(suggestion.title).lunarFont(.bodyEmphasized).foregroundStyle(theme.textPrimary).lineLimit(1)375                        Text(suggestion.subtitle).lunarFont(.caption).foregroundStyle(theme.textSecondary).lineLimit(1)376                            .truncationMode(.middle)377                    }378                    Spacer(minLength: 0)379                    if isHighlighted { LunarKeyCap("↩") }380                }381                .padding(.horizontal, LunarSpacing.sm)382                .frame(minHeight: minHeight)383            }384        }385        .buttonStyle(LunarPressStyle())386        .accessibilityElement(children: .combine)387        .accessibilityAddTraits(isHighlighted ? .isSelected : [])388        .accessibilityIdentifier("suggestion." + suggestion.id)389    }390391    private var symbol: String {392        switch suggestion.kind {393        case .navigate: "globe"394        case .search: "magnifyingglass"395        case .history: "clock"396        case .bookmark: "bookmark"397        case .openTab: "square.on.square"398        }399    }400}401402/// Row background that answers to the pointer.403struct LunarHoverRow<Content: View>: View {404    @Environment(\.lunarTheme) private var theme405    var isSelected = false406    var shape: LunarShape = .xs407    @ViewBuilder var content: Content408    @State private var hovering = false409410    var body: some View {411        content412            .frame(maxWidth: .infinity, alignment: .leading)413            .background { shape.fill(isSelected ? theme.selection : theme.textPrimary.withAlpha(hovering ? 0.06 : 0)) }414            .contentShape(shape)415            .onHover { hovering = $0 }416    }417}418
Files main
Menu

Theme