Repository Public License
1import LunarDesign2import NavigatorCore3import SwiftUI4import WebRuntime56#if canImport(UIKit)7import UIKit8#endif910/// What prevents the page from being shown. Derived from the engine's observable state.11enum PageIssue: Equatable {12 case certificate(CertificateError)13 case httpsUpgrade(HTTPSUpgradeFailure)14 case load(PageLoadError)15 case crashed16 case blocked(BlockedNavigation)1718 @MainActor init?(engine: WebEngine) {19 if let error = engine.certificateError { self = .certificate(error) }20 else if let failure = engine.httpsUpgradeFailure { self = .httpsUpgrade(failure) }21 else if let error = engine.loadError { self = .load(error) }22 else if engine.processState.isTerminated { self = .crashed }23 else { return nil }24 }25}2627/// What one tab shows: its web view, the native new-tab page, or the native page for a certificate error, a28/// failed load, a crash or a refused address. The building block for web-area providers that show several tabs29/// (Split) — the shell's own web area is one `TabContentView` for the selected tab.30public struct TabContentView: View {31 @Environment(\.lunarTheme) private var theme32 private let window: WindowModel33 private let tab: TabModel34 private let options: WebEngineViewOptions35 private let bottomInset: CGFloat3637 /// - Parameters:38 /// - options: pass `WebAreaContext.webOptions` when called from a provider.39 /// - bottomInset: room floating chrome covers at the bottom (`WebAreaContext.bottomChromeInset`).40 public init(window: WindowModel, tab: TabModel, options: WebEngineViewOptions = WebEngineViewOptions(),41 bottomInset: CGFloat = 0) {42 self.window = window; self.tab = tab; self.options = options; self.bottomInset = bottomInset43 }4445 public var body: some View {46 if tab.isBlank {47 if let blocked = tab.engine.blockedNavigations.first(where: \.isMainFrame) {48 IssuePage(window: window, tab: tab, issue: .blocked(blocked))49 } else {50 NewTabPage(window: window, bottomInset: bottomInset)51 }52 } else if let issue = PageIssue(engine: tab.engine) {53 IssuePage(window: window, tab: tab, issue: issue).padding(.bottom, bottomInset)54 } else {55 ZStack {56 if tab.engine.webView == nil, let thumbnail = tab.thumbnail {57 // Suspended tab being resumed: its last snapshot fills the gap until the page is back.58 Image(platformImage: thumbnail).resizable().scaledToFill().accessibilityHidden(true)59 }60 WebEngineView(engine: tab.engine, options: options)61 }62 #if os(iOS)63 .task(id: tab.engine.webView.map(ObjectIdentifier.init)) {64 PhonePlatformSupport.installRefreshControl(on: tab.engine, tint: UIColor(theme.accent.color))65 }66 #endif67 .onChange(of: tab.engine.blockedNavigations.count) { old, new in68 guard new > old, let last = tab.engine.blockedNavigations.first, last.isMainFrame else { return }69 window.showToast(BlockedNavigationText.message(for: last.reason), status: .warning)70 }71 }72 }73}7475/// The dominant surface of a window: the page of the selected tab — or what a feature's web-area provider puts76/// there — with the window's banners, find bar, page prompts and toasts on top. A building block for tab77/// layouts.78public struct WebAreaView: View {79 @Environment(\.lunarTheme) private var theme80 @Environment(BrowserStore.self) private var store81 let window: WindowModel82 var shape: LunarShape = .md83 /// Rounded, outlined container (regular width). The phone layout shows the page edge to edge.84 var isFramed = true85 var webOptions = WebEngineViewOptions()86 /// Extra room kept clear at the bottom for floating chrome (phone dock).87 var bottomChromeInset: CGFloat = 088 /// Omnibox suggestions drop from the top edge (regular width; the phone has its own search cover).89 var showsSuggestions = true9091 /// The framed web area of a regular-width window.92 public init(window: WindowModel) { self.window = window }9394 init(window: WindowModel, shape: LunarShape, isFramed: Bool, webOptions: WebEngineViewOptions, bottomChromeInset: CGFloat) {95 self.window = window; self.shape = shape; self.isFramed = isFramed; self.webOptions = webOptions96 self.bottomChromeInset = bottomChromeInset97 self.showsSuggestions = false98 }99100 public var body: some View {101 ZStack {102 Rectangle().fill(pageBackground)103 if let provider = store.registry.activeWebAreaProvider(for: window) {104 provider.makeContent(WebAreaContext(window: window, webOptions: webOptions, bottomChromeInset: bottomChromeInset,105 isCompactWidth: !isFramed))106 .id(provider.id)107 } else if let tab = window.selectedTab {108 TabContentView(window: window, tab: tab, options: webOptions, bottomInset: bottomChromeInset).id(tab.id)109 }110 }111 .overlay(alignment: .top) { banners }112 .overlay(alignment: .topTrailing) {113 if window.isFindVisible { FindBar(window: window).padding(LunarSpacing.sm).lunarTransition(anchor: .topTrailing) }114 }115 .overlay { if let prompt = window.currentPrompt { PromptOverlay(window: window, prompt: prompt) } }116 .overlay(alignment: .bottom) {117 if let toast = window.toast {118 LunarToast(toast.text, status: toast.status == .success ? .success : toast.status == .warning ? .warning : .neutral)119 .padding(.bottom, LunarSpacing.md + bottomChromeInset)120 .lunarTransition(anchor: .bottom)121 .accessibilityIdentifier("toast")122 }123 }124 .modifier(WebAreaFrame(shape: shape, isFramed: isFramed))125 .overlay(alignment: .top) { if showsSuggestions { suggestions } }126 .lunarAnimation(.snappy, value: window.toast)127 .lunarAnimation(.snappy, value: window.isFindVisible)128 .accessibilityElement(children: .contain)129 .accessibilityIdentifier("webArea")130 }131132 @ViewBuilder private var suggestions: some View {133 let omnibox = window.omnibox134 if omnibox.isEditing, !omnibox.suggestions.isEmpty || omnibox.notice != nil {135 SuggestionList(omnibox: omnibox)136 .padding(LunarSpacing.xs)137 .frame(maxWidth: 560)138 .lunarGlass(.md, style: .dense, elevation: .floating)139 .padding(.horizontal, LunarSpacing.lg)140 .offset(y: -LunarSpacing.unit)141 .lunarTransition(anchor: .top)142 }143 }144145 private var pageBackground: LunarRGBA {146 theme.isDark ? theme.windowBackground.mixed(with: theme.textPrimary, 0.045) : .white147 }148149 @ViewBuilder private var banners: some View {150 VStack(spacing: LunarSpacing.xs) {151 if store.offersSessionRestore {152 // Written out rather than a `LunarBanner`: the text must wrap on a phone, with the actions below it.153 VStack(alignment: .leading, spacing: LunarSpacing.xs) {154 HStack(alignment: .top, spacing: LunarSpacing.xs) {155 LunarIconView(.symbol("arrow.counterclockwise.circle"), size: 22).foregroundStyle(theme.accent)156 VStack(alignment: .leading, spacing: 2) {157 Text(L("Restore previous session?")).lunarFont(.headline).foregroundStyle(theme.textPrimary)158 .fixedSize(horizontal: false, vertical: true)159 Text(L("ORIX Navigator did not shut down cleanly. Your tabs are kept; nothing was reloaded."))160 .lunarFont(.footnote).foregroundStyle(theme.textSecondary)161 .fixedSize(horizontal: false, vertical: true)162 }163 Spacer(minLength: 0)164 }165 HStack(spacing: LunarSpacing.xs) {166 Spacer(minLength: 0)167 Button(L("Not Now")) { store.dismissSessionRestore() }168 .buttonStyle(.lunar(.secondary, size: .compact))169 .accessibilityIdentifier("banner.restore.dismiss")170 Button(L("Restore")) { store.restorePreviousSession() }171 .buttonStyle(.lunar(.primary, size: .compact))172 .accessibilityIdentifier("banner.restore.accept")173 }174 }175 .padding(LunarSpacing.sm)176 .lunarGlass(.md, style: .dense, elevation: .floating)177 .accessibilityElement(children: .contain)178 .accessibilityIdentifier("banner.restore")179 }180 }181 .frame(maxWidth: 620)182 .padding(LunarSpacing.sm)183 }184}185186private struct WebAreaFrame: ViewModifier {187 let shape: LunarShape188 let isFramed: Bool189190 func body(content: Content) -> some View {191 if isFramed {192 content.clipShape(shape).lunarHairline(shape).lunarShadow(.raised)193 } else {194 content195 }196 }197}198199// MARK: - Find in page200201struct FindBar: View {202 @Environment(\.lunarTheme) private var theme203 let window: WindowModel204 @FocusState private var focused: Bool205206 var body: some View {207 @Bindable var window = window208 let outcome = window.selectedTab?.engine.lastFind209 HStack(spacing: LunarSpacing.unit) {210 LunarIconView(.symbol("magnifyingglass"), size: 16).foregroundStyle(theme.textSecondary)211 TextField("", text: $window.findQuery, prompt: Text(L("Find in page")).foregroundStyle(theme.textTertiary))212 .textFieldStyle(.plain)213 .lunarFont(.body)214 .foregroundStyle(theme.textPrimary)215 .focused($focused)216 .frame(minWidth: 120, maxWidth: 200)217 .onSubmit { window.find() }218 .accessibilityLabel(L("Find in page"))219 .accessibilityIdentifier("find.field")220 #if os(iOS)221 .textInputAutocapitalization(.never)222 .autocorrectionDisabled()223 .submitLabel(.search)224 #endif225 if let outcome, outcome.query == window.findQuery, !window.findQuery.isEmpty {226 Text(outcome.matchFound ? (outcome.matchCount.map { L("%d matches", $0) } ?? L("Found")) : L("No match"))227 .lunarFont(.caption).lunarTabularDigits()228 .foregroundStyle(outcome.matchFound ? theme.textSecondary : theme.warning)229 .accessibilityIdentifier("find.count")230 }231 LunarIconButton(systemName: "chevron.up", label: L("Previous match"), diameter: 28) { window.find(backwards: true) }232 .disabled(window.findQuery.isEmpty)233 LunarIconButton(systemName: "chevron.down", label: L("Next match"), diameter: 28) { window.find() }234 .disabled(window.findQuery.isEmpty)235 LunarIconButton(systemName: "xmark", label: L("Close find bar"), diameter: 28) { window.hideFind() }236 .accessibilityIdentifier("find.close")237 }238 .padding(.leading, LunarSpacing.sm)239 .padding(.trailing, LunarSpacing.unit)240 .frame(minHeight: LunarMetrics.barHeight)241 .lunarGlass(.capsule, style: .dense, elevation: .floating)242 .onAppear { focused = true }243 .onChange(of: window.findFocusRequest) { focused = true }244 .onChange(of: window.findQuery) { window.find() }245 #if os(macOS)246 .onExitCommand { window.hideFind() }247 #endif248 .accessibilityElement(children: .contain)249 .accessibilityIdentifier("find.bar")250 }251}252253// MARK: - Native pages for errors254255struct IssuePage: View {256 @Environment(\.lunarTheme) private var theme257 let window: WindowModel258 let tab: TabModel259 let issue: PageIssue260 @State private var showsAdvanced = false261262 var body: some View {263 ScrollView {264 VStack(spacing: LunarSpacing.md) {265 ZStack {266 Circle().fill(tone.withAlpha(theme.isDark ? 0.16 : 0.12)).frame(width: 76, height: 76)267 LunarIconView(.symbol(symbol), size: 38).foregroundStyle(tone)268 }269 .padding(.top, LunarSpacing.xl)270 Text(title).lunarFont(.title).foregroundStyle(theme.textPrimary).multilineTextAlignment(.center)271 .accessibilityAddTraits(.isHeader)272 .accessibilityIdentifier("issue.title")273 Text(message).lunarFont(.body).foregroundStyle(theme.textSecondary).multilineTextAlignment(.center)274 .fixedSize(horizontal: false, vertical: true)275 if let address {276 Text(address).lunarFont(.mono).foregroundStyle(theme.textTertiary).lineLimit(2).truncationMode(.middle)277 .multilineTextAlignment(.center).textSelection(.enabled)278 }279 actions.padding(.top, LunarSpacing.xs)280 details281 }282 .frame(maxWidth: 520)283 .padding(.horizontal, LunarSpacing.lg)284 .padding(.bottom, LunarSpacing.xl)285 .frame(maxWidth: .infinity)286 }287 .background(theme.windowGradient)288 .accessibilityElement(children: .contain)289 .accessibilityIdentifier(identifier)290 }291292 private var identifier: String {293 switch issue {294 case .certificate: "issue.certificate"295 case .httpsUpgrade: "issue.httpsOnly"296 case .load: "issue.network"297 case .crashed: "issue.crashed"298 case .blocked: "issue.blocked"299 }300 }301302 private var tone: LunarRGBA {303 switch issue {304 case .certificate: theme.danger305 case .httpsUpgrade, .blocked: theme.warning306 case .load, .crashed: theme.accent307 }308 }309310 private var symbol: String {311 switch issue {312 case .certificate: "lock.trianglebadge.exclamationmark"313 case .httpsUpgrade: "lock.open"314 case .load(let error):315 switch error.kind {316 case .offline: "wifi.slash"317 case .timedOut: "clock.badge.exclamationmark"318 case .hostNotFound: "questionmark.circle"319 default: "bolt.horizontal.circle"320 }321 case .crashed: "exclamationmark.arrow.circlepath"322 case .blocked: "hand.raised"323 }324 }325326 private var title: String {327 switch issue {328 case .certificate: L("This connection is not private")329 case .httpsUpgrade: L("No secure version of this site")330 case .load(let error):331 switch error.kind {332 case .offline: L("You are offline")333 case .hostNotFound: L("Site not found")334 case .timedOut: L("The site took too long to respond")335 case .connectionFailed: L("Could not connect to the site")336 case .connectionLost: L("The connection was interrupted")337 case .tooManyRedirects: L("Too many redirects")338 case .secureConnectionFailed: L("A secure connection could not be established")339 case .unsupportedURL: L("This address cannot be opened")340 case .fileNotFound: L("File not found")341 case .blockedByContentRule: L("This page was blocked")342 case .other: L("This page could not be loaded")343 }344 case .crashed: L("This page stopped working")345 case .blocked: L("This address was not opened")346 }347 }348349 private var message: String {350 switch issue {351 case .certificate(let error):352 L("The certificate presented by %@ could not be verified. Someone may be trying to intercept what you send to this site, such as passwords or card numbers.", error.host)353 case .httpsUpgrade(let failure):354 L("HTTPS-Only mode is on and %@ does not answer over a secure connection. Nothing was loaded over an insecure connection.", URLDisplay.host(failure.originalURL))355 case .load(let error):356 switch error.kind {357 case .offline: L("Check your network connection, then try again.")358 case .hostNotFound: L("The address may be mistyped, or the site may no longer exist.")359 case .timedOut, .connectionFailed, .connectionLost: L("The site may be down, or your network may be blocking it.")360 default: error.message361 }362 case .crashed: L("The process showing this page ended unexpectedly. Reloading brings the page back.")363 case .blocked(let blocked): BlockedNavigationText.message(for: blocked.reason)364 }365 }366367 private var address: String? {368 switch issue {369 case .certificate(let error): error.failingURL.map(URLDisplay.short) ?? error.host370 case .httpsUpgrade(let failure): failure.originalURL.absoluteString371 case .load(let error): error.url.map(URLDisplay.short)372 case .crashed: tab.engine.url.map(URLDisplay.short)373 case .blocked(let blocked): blocked.url.scheme.map { $0 + ":" }374 }375 }376377 @ViewBuilder private var actions: some View {378 switch issue {379 case .certificate:380 Button(L("Go Back")) { leave() }381 .buttonStyle(.lunar(.primary, size: .large))382 .keyboardShortcut(.defaultAction)383 .accessibilityIdentifier("issue.goBack")384 case .httpsUpgrade:385 HStack(spacing: LunarSpacing.sm) {386 Button(L("Go Back")) { leave() }.buttonStyle(.lunar(.primary, size: .large)).keyboardShortcut(.defaultAction)387 Button(L("Try Again")) { tab.engine.reload() }.buttonStyle(.lunar(.secondary, size: .large))388 }389 case .load:390 Button(L("Try Again")) { tab.engine.reload() }391 .buttonStyle(.lunar(.primary, size: .large))392 .accessibilityIdentifier("issue.retry")393 case .crashed:394 Button(L("Reload")) { tab.engine.reload() }395 .buttonStyle(.lunar(.primary, size: .large))396 .accessibilityIdentifier("issue.reload")397 case .blocked:398 Button(L("Go Back")) { leave() }399 .buttonStyle(.lunar(.primary, size: .large))400 .accessibilityIdentifier("issue.goBack")401 }402 }403404 @ViewBuilder private var details: some View {405 switch issue {406 case .certificate(let error):407 advanced {408 VStack(alignment: .leading, spacing: LunarSpacing.sm) {409 detailRow(L("Site"), error.port == 443 ? error.host : "\(error.host):\(error.port)")410 detailRow(L("Reason"), CertificateText.reason(error.reason))411 if !error.systemMessage.isEmpty { detailRow(L("System"), error.systemMessage) }412 if let certificate = error.certificate {413 LunarHairline()414 CertificateSummaryView(certificate: certificate, chainCount: error.chain.count)415 }416 LunarHairline()417 Text(L("If you understand the risk, you can open the site for this session only. The exception is forgotten when you quit."))418 .lunarFont(.footnote).foregroundStyle(theme.textSecondary).fixedSize(horizontal: false, vertical: true)419 Button(L("Proceed to %@ (unsafe)", error.host)) { tab.engine.proceedIgnoringCertificateError() }420 .buttonStyle(.lunar(.destructive, size: .compact))421 .accessibilityIdentifier("issue.proceed")422 }423 }424 case .httpsUpgrade(let failure):425 advanced {426 VStack(alignment: .leading, spacing: LunarSpacing.sm) {427 if let error = failure.error { detailRow(L("Reason"), error.message) }428 if let error = failure.certificateError { detailRow(L("Reason"), CertificateText.reason(error.reason)) }429 Text(L("You can open the insecure version for this session. What you send can be read or changed by others on the network."))430 .lunarFont(.footnote).foregroundStyle(theme.textSecondary).fixedSize(horizontal: false, vertical: true)431 Button(L("Continue to the insecure site")) { tab.engine.proceedWithInsecureHTTP() }432 .buttonStyle(.lunar(.destructive, size: .compact))433 .accessibilityIdentifier("issue.proceedInsecure")434 }435 }436 case .load(let error):437 Text(verbatim: "\(error.domain) \(error.code)").lunarFont(.caption).foregroundStyle(theme.textTertiary)438 .accessibilityLabel(L("Error code %@", "\(error.domain) \(error.code)"))439 case .crashed, .blocked:440 EmptyView()441 }442 }443444 private func advanced<Content: View>(@ViewBuilder _ content: () -> Content) -> some View {445 VStack(spacing: LunarSpacing.sm) {446 Button { showsAdvanced.toggle() } label: {447 HStack(spacing: LunarSpacing.unit) {448 Text(L("Details and advanced options")).lunarFont(.subheadline)449 LunarIconView(.symbol(showsAdvanced ? "chevron.up" : "chevron.down"), size: 12)450 }451 .foregroundStyle(theme.textSecondary)452 .lunarHitTarget(.capsule)453 }454 .buttonStyle(LunarPressStyle())455 .accessibilityIdentifier("issue.advanced")456 .accessibilityValue(showsAdvanced ? L("Expanded") : L("Collapsed"))457 if showsAdvanced {458 LunarCard(padding: LunarSpacing.md, shape: .sm) { content().frame(maxWidth: .infinity, alignment: .leading) }459 .lunarTransition(anchor: .top)460 }461 }462 .lunarAnimation(.snappy, value: showsAdvanced)463 }464465 private func detailRow(_ name: String, _ value: String) -> some View {466 HStack(alignment: .firstTextBaseline, spacing: LunarSpacing.xs) {467 Text(name).lunarFont(.caption).foregroundStyle(theme.textTertiary).frame(width: 84, alignment: .leading)468 Text(value).lunarFont(.footnote).foregroundStyle(theme.textPrimary).fixedSize(horizontal: false, vertical: true)469 .textSelection(.enabled)470 }471 .accessibilityElement(children: .combine)472 }473474 /// "Go back": the page that was shown before comes back as it is, without a reload; a tab that never showed475 /// a page returns to the new-tab page.476 private func leave() {477 tab.engine.dismissInterstitial()478 }479}480481enum CertificateText {482 static func reason(_ reason: CertificateError.Reason) -> String {483 switch reason {484 case .expired: L("The certificate has expired.")485 case .notYetValid: L("The certificate is not valid yet.")486 case .hostnameMismatch: L("The certificate belongs to a different site.")487 case .untrustedIssuer: L("The certificate was issued by an authority this device does not trust.")488 case .selfSigned: L("The certificate is self-signed.")489 case .revoked: L("The certificate was revoked.")490 case .weakOrInvalid: L("The certificate is invalid or uses weak cryptography.")491 case .unknown: L("The certificate could not be verified.")492 }493 }494}495