Repository Public
1import SwiftUI23/// What a new tab shows: SP Search, favorites, visited sites, searches, bookmarks, other devices' tabs. Entirely native.4struct StartPageView: View {5 let state: BrowserWindowState6 let environment: AppEnvironment7 let tab: BrowserTab8 @State private var query = ""9 @State private var showsCustomize = false10 @State private var selection: Int?11 @FocusState private var focused: Bool12 @Environment(\.colorScheme) private var scheme1314 private var services: BrowserServices { environment.services }15 private var library: SyncedLibrary { services.library }1617 private var suggestions: [SearchHistoryItem] {18 guard focused, !state.isPrivate, services.searchPreferences.keepSearchHistory else { return [] }19 return library.searchSuggestions(for: query, limit: 5)20 }2122 var body: some View {23 let options = environment.settings.startPage24 let theme: AmbientTheme = options.ambient25 // Reading the revisions makes the page refresh when sync or another window changes the data.26 let _ = (services.libraryRevision, state.historyRevision, state.bookmarksRevision)27 ScrollView {28 VStack(spacing: 28) {29 VStack(spacing: 12) {30 Image("BrandMark").resizable().frame(width: 58, height: 58).accessibilityHidden(true)31 .shadow(color: Aura.Palette.violet.opacity(0.35), radius: 18)32 Text(state.isPrivate ? L("Private Browsing") : "SP Browser")33 .font(.system(size: 32, weight: .bold, design: .rounded))34 .foregroundStyle(state.isPrivate ? AnyShapeStyle(Theme.violet) : AnyShapeStyle(Aura.horizontalGradient))35 .accessibilityAddTraits(.isHeader)36 if options.showGreeting, !state.isPrivate {37 HStack(spacing: 8) {38 Text(greeting).font(.callout).foregroundStyle(.secondary)39 if let workspace = state.activeWorkspace {40 Label(workspace.name, systemImage: workspace.symbol).font(.callout.weight(.medium)).foregroundStyle(Theme.color(workspace.colorIndex))41 }42 }43 }44 }45 .padding(.top, 64)46 .auraAppear(0)4748 if options.showSearch { searchField.auraAppear(1) }4950 if state.isPrivate {51 PrivateExplanation().frame(maxWidth: 680).auraAppear(2)52 } else {53 sections(options)54 }55 Spacer(minLength: 30)56 }57 .frame(maxWidth: .infinity)58 .padding(.horizontal, 30)59 }60 .background(AmbientBackground(theme: theme, isPrivate: state.isPrivate))61 // Obsidian and Cosmos only exist in a dark rendition: the page content follows.62 .environment(\.colorScheme, theme.isAlwaysDark ? .dark : scheme)63 .overlay(alignment: .bottomTrailing) {64 if !state.isPrivate {65 Button { showsCustomize.toggle() } label: { Label(L("Customize"), systemImage: "slider.horizontal.3").font(.callout) }66 .buttonStyle(.bordered).padding(16)67 .popover(isPresented: $showsCustomize, arrowEdge: .top) { StartPageCustomizer(environment: environment) }68 .accessibilityIdentifier("start-customize")69 }70 }71 .onAppear { if state.selectedTabID == tab.id { focused = true } }72 }7374 // MARK: Search field7576 private var searchField: some View {77 VStack(spacing: 6) {78 HStack(spacing: 10) {79 Image(systemName: "magnifyingglass").foregroundStyle(.secondary).font(.system(size: 16, weight: .medium))80 TextField(environment.settings.activeSearchEngine().isNative ? L("Search the web with SP Search")81 : L("Search with %@ or enter address", environment.settings.activeSearchEngine().name), text: $query)82 .textFieldStyle(.plain).font(.system(size: 17)).focused($focused)83 .onSubmit(submit)84 .onKeyPress(.downArrow) { moveSelection(1) }85 .onKeyPress(.upArrow) { moveSelection(-1) }86 .onChange(of: query) { selection = nil }87 .accessibilityLabel(L("Search or enter address"))88 .accessibilityIdentifier("start-search-field")89 if !query.isEmpty {90 Button { query = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(.tertiary) }.buttonStyle(.plain).accessibilityLabel(L("Clear"))91 }92 }93 .padding(.horizontal, 18).frame(height: 52).frame(maxWidth: 680)94 .auraField(focused: focused, radius: 26)9596 let items = suggestions97 if !items.isEmpty {98 VStack(spacing: 1) {99 ForEach(Array(items.enumerated()), id: \.element.id) { index, item in100 Button { run(item.query) } label: {101 HoverRow(isSelected: selection == index) {102 Label(item.query, systemImage: "clock.arrow.circlepath").font(.system(size: 14)).lineLimit(1).padding(.horizontal, 12).padding(.vertical, 7)103 }104 }105 .buttonStyle(.plain)106 }107 }108 .padding(5).frame(maxWidth: 680)109 .auraSurface(.floating, radius: Theme.radiusL)110 .transition(AuraTransition.depth(AuraMotion.policy))111 }112 }113 }114115 private func submit() {116 let items = suggestions117 if let index = selection, items.indices.contains(index) { run(items[index].query); return }118 let text = query119 query = ""120 state.navigate(text, in: tab)121 }122123 private func run(_ text: String) {124 query = ""125 tab.search(text)126 }127128 private func moveSelection(_ delta: Int) -> KeyPress.Result {129 let count = suggestions.count130 guard count > 0 else { return .ignored }131 selection = ((selection ?? (delta > 0 ? -1 : count)) + delta + count) % count132 return .handled133 }134135 // MARK: Sections136137 @ViewBuilder private func sections(_ options: StartPageSettings) -> some View {138 let handoffs = services.pendingHandoffs139 if !handoffs.isEmpty {140 VStack(spacing: 10) {141 ForEach(handoffs.prefix(2)) { item in142 HStack(spacing: 10) {143 Image(systemName: PortalDevice.symbol(for: item.fromPlatform)).font(.title3).foregroundStyle(Aura.gradient)144 VStack(alignment: .leading, spacing: 1) {145 Text(L("Sent from %@", item.fromDeviceName)).font(.subheadline.weight(.semibold))146 Text(item.tabs.first.map { $0.title.isEmpty ? $0.url : $0.title } ?? "").font(.caption).foregroundStyle(.secondary).lineLimit(1)147 }148 Spacer()149 Button(L("Open %d Tabs", item.tabs.count)) { state.acceptHandoff(item) }.buttonStyle(.borderedProminent)150 Button(L("Dismiss")) { services.consumeHandoff(item) }.buttonStyle(.bordered)151 }152 .padding(12).auraSurface(.floating, radius: 16, tint: Aura.Palette.violet, luminous: true)153 }154 }155 .frame(maxWidth: 680).auraAppear(2)156 }157 if options.showWorkspaces, state.workspaces.count > 1 {158 VStack(alignment: .leading, spacing: 10) {159 SectionLabel(text: L("Workspaces"))160 HStack(spacing: 10) {161 ForEach(state.workspaces) { workspace in162 let count = state.tabs.filter { $0.workspaceID == workspace.id }.count163 Button { state.switchWorkspace(to: workspace.id) } label: {164 HStack(spacing: 8) {165 Image(systemName: workspace.symbol).font(.system(size: 13, weight: .semibold)).foregroundStyle(Theme.color(workspace.colorIndex))166 .frame(width: 28, height: 28).background(Circle().fill(Theme.color(workspace.colorIndex).opacity(0.16)))167 VStack(alignment: .leading, spacing: 0) {168 Text(workspace.name).font(.system(size: 12.5, weight: .medium)).lineLimit(1)169 Text(L("%d tabs", count)).font(.system(size: 10.5)).foregroundStyle(.secondary)170 }171 Spacer(minLength: 0)172 }173 .padding(9).frame(maxWidth: .infinity)174 .auraSurface(.panel, radius: Theme.radiusM, interactive: true, luminous: workspace.id == state.activeWorkspaceID)175 }176 .buttonStyle(AuraPressStyle(scale: 0.97))177 .accessibilityLabel(workspace.name).accessibilityValue(L("%d tabs", count))178 .accessibilityAddTraits(workspace.id == state.activeWorkspaceID ? .isSelected : [])179 }180 }181 }182 .frame(maxWidth: 680).auraAppear(2)183 }184 if options.showSyncedFavorites {185 let favorites = library.favorites()186 if !favorites.isEmpty {187 tiles(title: L("Favorites"), items: favorites.map { Tile(title: $0.title, url: $0.url, removal: .favorite) })188 }189 }190 if options.showFavorites, let favorites = state.activeWorkspace?.favorites, !favorites.isEmpty {191 tiles(title: L("Workspace favorites"), items: favorites.map { Tile(title: $0.title, url: $0.url) })192 }193 if options.showTopSites {194 let sites = state.profile.history.topSites(limit: 8)195 if !sites.isEmpty { tiles(title: L("Frequently visited"), items: sites.map { Tile(title: displayTitle($0), url: $0.url, removal: .history) }) }196 }197 if options.showRecentlyVisited {198 let top = Set(options.showTopSites ? state.profile.history.topSites(limit: 8).map(\.url) : [])199 let recent = state.profile.history.recentPages(limit: 16).filter { !top.contains($0.url) }.prefix(8)200 if !recent.isEmpty { tiles(title: L("Recently visited"), items: recent.map { Tile(title: displayTitle($0), url: $0.url, removal: .history) }) }201 }202 if options.showRecentSearches, services.searchPreferences.keepSearchHistory {203 let searches = library.recentSearches(limit: 10)204 if !searches.isEmpty {205 VStack(alignment: .leading, spacing: 10) {206 SectionLabel(text: L("Recent searches"))207 FlowLayout(spacing: 8) {208 ForEach(searches) { item in209 Button { tab.search(item.query) } label: {210 Label(item.query, systemImage: "magnifyingglass").font(.callout).lineLimit(1)211 .padding(.horizontal, 12).padding(.vertical, 7)212 .background(Capsule().fill(Theme.field)).overlay(Capsule().strokeBorder(Theme.hairline))213 }214 .buttonStyle(.plain)215 .contextMenu { Button(L("Remove from Search History")) { library.removeSearch(item); services.localChange() } }216 }217 }218 }219 .frame(maxWidth: 680)220 }221 }222 if options.showOtherDevices {223 let devices = services.portalDevices.filter { !$0.tabs.isEmpty }224 if !devices.isEmpty {225 VStack(alignment: .leading, spacing: 12) {226 HStack {227 SectionLabel(text: L("Continue from another device"))228 SyncStatusLine(host: state.portalHost).fixedSize()229 Button(L("Portal")) { state.perform(.showPortal) }.buttonStyle(.link).font(.caption)230 }231 ForEach(devices.prefix(2)) { device in PortalDeviceCard(device: device, host: state.portalHost) }232 }233 .frame(maxWidth: 680)234 .accessibilityIdentifier("start-other-devices")235 .auraAppear(4)236 }237 }238 if options.showRecentSessions {239 let sessions = environment.sessionStore.listNamed().prefix(3)240 if !sessions.isEmpty {241 VStack(alignment: .leading, spacing: 4) {242 SectionLabel(text: L("Recent sessions"))243 ForEach(Array(sessions)) { session in244 Button { state.sidebarPanel = .sessions; state.sidebarVisible = true } label: {245 HoverRow {246 HStack(spacing: 8) {247 Image(systemName: "tray.full").foregroundStyle(.secondary).frame(width: 18)248 Text(session.name.isEmpty ? L("Untitled session") : session.name).lineLimit(1)249 Text(L("%d tabs", session.tabCount) + " · " + session.savedAt.relativeShort).foregroundStyle(.secondary).lineLimit(1)250 Spacer(minLength: 0)251 }252 .font(.system(size: 13)).padding(.horizontal, 8).padding(.vertical, 6)253 }254 }255 .buttonStyle(.plain)256 }257 }258 .frame(maxWidth: 680).auraAppear(5)259 }260 }261 if options.showBookmarks {262 let bookmarks = state.profile.bookmarks.all().filter { !$0.isFolder && $0.url != nil }.prefix(8)263 if !bookmarks.isEmpty { tiles(title: L("Bookmarks"), items: bookmarks.map { Tile(title: $0.title, url: $0.url ?? "") }) }264 }265 if options.showReadingList {266 let unread = library.readingList().filter { !$0.isRead }.prefix(5)267 if !unread.isEmpty {268 VStack(alignment: .leading, spacing: 4) {269 SectionLabel(text: L("Reading list"))270 ForEach(Array(unread)) { item in linkRow(title: item.title, url: item.url, symbol: "eyeglasses") }271 }272 .frame(maxWidth: 680)273 }274 }275 if options.showRecentlyClosed, !state.recentlyClosed.isEmpty {276 VStack(alignment: .leading, spacing: 4) {277 SectionLabel(text: L("Recently closed tabs"))278 ForEach(state.recentlyClosed.prefix(5)) { snapshot in279 Button { state.reopen(snapshot) } label: {280 HoverRow { Label(snapshot.title.isEmpty ? (snapshot.url ?? "") : snapshot.title, systemImage: "arrow.uturn.backward").lineLimit(1).padding(8) }281 }282 .buttonStyle(.plain)283 }284 }285 .frame(maxWidth: 680)286 }287 if options.showPrivacyDashboard { privacyDashboard }288 if options.showPrivacyNote {289 Label(services.account.isSignedIn && environment.settings.syncEnabled290 ? L("No telemetry. What you synchronize is encrypted on this Mac before it leaves it.")291 : L("SP Browser sends no telemetry. History, bookmarks and notes stay on this Mac."), systemImage: "lock.shield")292 .font(.caption).foregroundStyle(.tertiary)293 }294 }295296 private var privacyDashboard: some View {297 VStack(alignment: .leading, spacing: 10) {298 SectionLabel(text: L("Privacy"))299 HStack(spacing: 12) {300 stat(symbol: "shield.lefthalf.filled", value: environment.settings.contentBlockerEnabled ? "\(environment.blocker.ruleCount)" : L("Off"), label: L("blocking rules"))301 stat(symbol: "clock", value: "\(state.profile.history.count)", label: L("visits kept on this Mac"))302 stat(symbol: "arrow.triangle.2.circlepath", value: syncStatus, label: "SP Sync")303 }304 }305 .frame(maxWidth: 680)306 }307308 private var syncStatus: String {309 switch services.sync.phase {310 case .off: return L("Off")311 case .signedOut: return L("Signed out")312 case .waitingForKey: return L("Waiting")313 case .offline: return L("Offline")314 case .failed: return L("Error")315 case .idle, .syncing: return L("Encrypted")316 }317 }318319 private func stat(symbol: String, value: String, label: String) -> some View {320 VStack(alignment: .leading, spacing: 3) {321 Image(systemName: symbol).foregroundStyle(Theme.accent)322 Text(value).font(.title3.weight(.semibold).monospacedDigit()).lineLimit(1).minimumScaleFactor(0.7)323 Text(label).font(.caption).foregroundStyle(.secondary).lineLimit(2)324 }325 .padding(12).frame(maxWidth: .infinity, alignment: .leading).cardSurface(radius: Theme.radiusM)326 .accessibilityElement(children: .combine)327 }328329 private func displayTitle(_ page: HistorySuggestion) -> String { page.title.isEmpty ? (URL(string: page.url)?.host ?? page.url) : page.title }330331 private func linkRow(title: String, url: String, symbol: String) -> some View {332 Button { if let target = URL(string: url) { tab.load(target) } } label: {333 HoverRow {334 HStack(spacing: 8) {335 Image(systemName: symbol).foregroundStyle(.secondary).frame(width: 18)336 Text(title.isEmpty ? url : title).lineLimit(1)337 Text(URL(string: url)?.host ?? "").foregroundStyle(.secondary).lineLimit(1)338 Spacer(minLength: 0)339 }340 .font(.system(size: 13)).padding(.horizontal, 8).padding(.vertical, 6)341 }342 }343 .buttonStyle(.plain)344 .help(url)345 .contextMenu {346 Button(L("Open in New Tab")) { if let target = URL(string: url) { state.newTab(url: target, select: true) } }347 Button(L("Copy Link")) { PlatformActions.copy(url) }348 }349 }350351 private var greeting: String {352 switch Calendar.current.component(.hour, from: Date()) {353 case 5..<12: return L("Good morning")354 case 12..<18: return L("Good afternoon")355 default: return L("Good evening")356 }357 }358359 private struct Tile {360 enum Removal { case none, favorite, history }361 var title: String362 var url: String363 var removal: Removal = .none364 }365366 private func tiles(title: String, items: [Tile]) -> some View {367 VStack(alignment: .leading, spacing: 10) {368 SectionLabel(text: title)369 LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 12)], spacing: 12) {370 ForEach(Array(items.enumerated()), id: \.offset) { _, item in371 Button {372 if let url = URL(string: item.url) { tab.load(url) }373 } label: {374 SiteTile(title: item.title, url: item.url)375 }376 .buttonStyle(.plain)377 .accessibilityLabel(item.title)378 .accessibilityAddTraits(.isLink)379 .contextMenu {380 Button(L("Open in New Tab")) { if let url = URL(string: item.url) { state.newTab(url: url, select: true) } }381 Button(L("Copy Link")) { PlatformActions.copy(item.url) }382 if item.removal == .favorite {383 Button(L("Remove from Favorites")) { library.removeFavorite(url: item.url); services.localChange() }384 } else {385 if !library.isFavorite(item.url) { Button(L("Add to Favorites")) { library.addFavorite(title: item.title, url: item.url); services.localChange() } }386 if item.removal == .history { Button(L("Remove from History")) { state.profile.history.delete(url: item.url); state.profile.flow.update { $0.forget(url: item.url) }; state.historyRevision += 1; services.localChange() } }387 }388 }389 }390 }391 }392 .frame(maxWidth: 680)393 .auraAppear(3)394 }395}396397/// Lets the user choose what the start page shows and how it looks.398struct StartPageCustomizer: View {399 @Bindable var environment: AppEnvironment400401 var body: some View {402 let page = $environment.settings.startPage403 VStack(alignment: .leading, spacing: 8) {404 Text(L("Start page")).font(.headline)405 Group {406 Toggle(L("Greeting"), isOn: page.showGreeting)407 Toggle(L("Workspaces"), isOn: page.showWorkspaces)408 Toggle(L("Recent sessions"), isOn: page.showRecentSessions)409 Toggle(L("Favorites"), isOn: page.showSyncedFavorites)410 Toggle(L("Workspace favorites"), isOn: page.showFavorites)411 Toggle(L("Frequently visited"), isOn: page.showTopSites)412 Toggle(L("Recently visited"), isOn: page.showRecentlyVisited)413 Toggle(L("Recent searches"), isOn: page.showRecentSearches)414 Toggle(L("Continue from another device"), isOn: page.showOtherDevices)415 Toggle(L("Bookmarks"), isOn: page.showBookmarks)416 Toggle(L("Reading list"), isOn: page.showReadingList)417 Toggle(L("Recently closed tabs"), isOn: page.showRecentlyClosed)418 Toggle(L("Privacy dashboard"), isOn: page.showPrivacyDashboard)419 }420 .toggleStyle(.checkbox)421 Divider().padding(.vertical, 2)422 Text(L("Ambient theme")).font(.subheadline.weight(.medium))423 LazyVGrid(columns: [GridItem(.adaptive(minimum: 84), spacing: 10)], spacing: 10) {424 ForEach(AmbientTheme.allCases) { theme in425 Button { AuraMotion.perform(.expressive) { environment.settings.startPage.ambient = theme } } label: {426 AmbientThemeSwatch(theme: theme, isSelected: environment.settings.startPage.ambient == theme)427 }428 .buttonStyle(AuraPressStyle(scale: 0.95)).help(theme.summary)429 }430 }431 Toggle(L("Animate the background"), isOn: $environment.settings.ambientMotionEnabled).toggleStyle(.checkbox)432 Text(L("Motion always stops with Reduce Motion, in Low Power Mode and when the window is in the background.")).font(.caption).foregroundStyle(.secondary)433 .fixedSize(horizontal: false, vertical: true)434 }435 .padding(16).frame(width: 320)436 }437}438439struct SiteTile: View {440 let title: String441 let url: String442443 var body: some View {444 HStack(spacing: 10) {445 Favicon(image: FaviconLoader.shared.cached(forHost: URL(string: url)?.host), fallback: title, size: 24)446 VStack(alignment: .leading, spacing: 1) {447 Text(title).font(.system(size: 12.5, weight: .medium)).lineLimit(1)448 Text(URL(string: url)?.host ?? url).font(.system(size: 10.5)).foregroundStyle(.secondary).lineLimit(1)449 }450 Spacer(minLength: 0)451 }452 .padding(10)453 .auraSurface(.panel, radius: Theme.radiusM + 2, interactive: true)454 .help(url)455 }456}457458/// Says plainly what private browsing does and does not protect against.459struct PrivateExplanation: View {460 var body: some View {461 VStack(alignment: .leading, spacing: 14) {462 row("checkmark.circle.fill", .green, L("Not kept on this Mac"),463 L("Pages you visit are not added to history. Cookies, cache and site data live in memory only and are discarded when the last private window closes."))464 row("checkmark.circle.fill", .green, L("Separate from your normal session"),465 L("Private windows start signed out everywhere: they do not see the cookies of your regular profile."))466 row("exclamationmark.triangle.fill", .orange, L("Not invisible"),467 L("Websites, your employer or school, and your internet provider can still see your activity. Files you download and bookmarks you add are kept."))468 }469 .padding(18)470 .cardSurface()471 }472473 private func row(_ symbol: String, _ color: Color, _ title: String, _ text: String) -> some View {474 HStack(alignment: .top, spacing: 12) {475 Image(systemName: symbol).foregroundStyle(color).font(.title3).accessibilityHidden(true)476 VStack(alignment: .leading, spacing: 2) {477 Text(title).font(.headline)478 Text(text).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)479 }480 }481 .accessibilityElement(children: .combine)482 }483}484485// MARK: - Error, crash and reader pages486487struct ErrorPageView: View {488 let error: PageError489 let tab: BrowserTab490 @State private var showsDetails = false491492 var body: some View {493 VStack(spacing: 0) {494 StateView(symbol: error.symbol, title: error.title, message: error.advice, tint: error.kind == .tls || error.kind == .blocked ? .orange : .secondary,495 actionTitle: error.kind == .blocked ? nil : L("Try Again"), action: { tab.reload() })496 .frame(maxHeight: 360)497 if let host = error.url?.host { Text(host).font(.callout.monospaced()).foregroundStyle(.secondary).textSelection(.enabled) }498 DisclosureGroup(L("Technical details"), isExpanded: $showsDetails) {499 // Only the error itself is shown: no cookies, headers or page content.500 Text("\(error.domain) \(error.code)\n\(error.detail)").font(.caption.monospaced()).foregroundStyle(.secondary)501 .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(.top, 4)502 }503 .frame(maxWidth: 420).padding(.top, 16)504 Spacer()505 }506 .padding(.top, 40)507 .frame(maxWidth: .infinity, maxHeight: .infinity)508 .background(Theme.surface)509 }510}511512struct CrashPageView: View {513 let tab: BrowserTab514515 var body: some View {516 StateView(symbol: "bolt.trianglebadge.exclamationmark", title: L("This page stopped responding"),517 message: tab.crashCount > 2518 ? L("The page has crashed several times. It may use more memory than available, or contain a fault. Other tabs are not affected.")519 : L("The web content process for this tab quit unexpectedly. Other tabs are not affected."),520 tint: .orange, actionTitle: L("Reload Page")) { tab.reload() }521 .background(Theme.surface)522 }523}524525/// The Mac reader is the shared AURA reader.526struct ReaderView: View {527 let article: ReaderArticle528 let url: URL?529 var showsTrail = true530 var body: some View { AuraReaderView(article: article, url: url, showsTrail: showsTrail) }531}532