Repository Public
1import SwiftUI23struct AddressSuggestion: Identifiable, Equatable {4 enum Kind: Equatable { case search, pastSearch, address, history, bookmark, tab(UUID) }5 let id = UUID()6 var kind: Kind7 var title: String8 var subtitle: String9 /// Text that is navigated to when the suggestion is chosen.10 var value: String1112 var symbol: String {13 switch kind {14 case .search: return "magnifyingglass"15 case .pastSearch: return "clock.arrow.circlepath"16 case .address: return "globe"17 case .history: return "clock"18 case .bookmark: return "bookmark.fill"19 case .tab: return "square.on.square"20 }21 }2223 static func == (lhs: AddressSuggestion, rhs: AddressSuggestion) -> Bool {24 lhs.kind == rhs.kind && lhs.title == rhs.title && lhs.value == rhs.value25 }26}2728/// State of the unified address/search field, shared between the field and the suggestion overlay.29@MainActor30@Observable31final class AddressBarModel {32 var text = ""33 var isEditing = false34 var userTyped = false35 /// Set while the field's text is being filled in by the app (on focus), so that it does not count as typing.36 var isFilling = false37 var suggestions: [AddressSuggestion] = []38 var selection: Int?3940 var showsSuggestions: Bool { isEditing && userTyped && !suggestions.isEmpty }4142 /// Local suggestions only: nothing typed here is sent to a search engine until the user confirms.43 func refresh(state: BrowserWindowState, environment: AppEnvironment) {44 let query = text.trimmingCharacters(in: .whitespaces)45 guard isEditing, userTyped, !query.isEmpty else { suggestions = []; selection = nil; return }46 let settings = environment.settings47 var result: [AddressSuggestion] = []48 var seen = Set<String>()4950 if let resolved = AddressResolver.resolve(query, engine: settings.activeSearchEngine(), engines: settings.allSearchEngines()) {51 switch resolved {52 case .url(let url):53 result.append(AddressSuggestion(kind: .address, title: url.absoluteString, subtitle: L("Open address"), value: query))54 case .search(let url):55 let engine = settings.allSearchEngines().first { URL(string: $0.template.replacingOccurrences(of: "%s", with: "x"))?.host == url.host }56 result.append(AddressSuggestion(kind: .search, title: query, subtitle: L("Search with %@", engine?.name ?? settings.activeSearchEngine().name), value: query))57 }58 }59 // Query suggestions come from the user's own search history (the search provider offers no suggestion service).60 if !state.isPrivate, environment.services.searchPreferences.keepSearchHistory {61 for item in environment.services.library.searchSuggestions(for: query, limit: 4) where seen.insert("search:" + item.query.lowercased()).inserted {62 result.append(AddressSuggestion(kind: .pastSearch, title: item.query, subtitle: L("Search again"), value: item.query))63 }64 }65 let lower = query.lowercased()66 for tab in state.tabs where tab.id != state.selectedTabID {67 guard let url = tab.url?.absoluteString, tab.displayTitle.lowercased().contains(lower) || url.lowercased().contains(lower) else { continue }68 if seen.insert(url).inserted, result.count < 4 {69 result.append(AddressSuggestion(kind: .tab(tab.id), title: tab.displayTitle, subtitle: L("Switch to tab"), value: url))70 }71 }72 if settings.suggestFromBookmarks {73 for bookmark in state.profile.bookmarks.search(query, limit: 3) {74 guard let url = bookmark.url, seen.insert(url).inserted else { continue }75 result.append(AddressSuggestion(kind: .bookmark, title: bookmark.title, subtitle: url, value: url))76 }77 }78 if settings.suggestFromHistory, !state.isPrivate {79 for entry in state.profile.history.suggestions(for: query, limit: 5) where seen.insert(entry.url).inserted {80 result.append(AddressSuggestion(kind: .history, title: entry.title.isEmpty ? entry.url : entry.title, subtitle: entry.url, value: entry.url))81 }82 }83 if result != suggestions { suggestions = result; selection = nil }84 }8586 func moveSelection(by offset: Int) {87 guard !suggestions.isEmpty else { return }88 let next = (selection.map { $0 + offset } ?? (offset > 0 ? 0 : suggestions.count - 1))89 selection = (next + suggestions.count) % suggestions.count90 }9192 func commit(_ suggestion: AddressSuggestion, state: BrowserWindowState) {93 endEditing()94 if case .tab(let id) = suggestion.kind, let tab = state.tab(id: id) {95 state.select(tab)96 } else if suggestion.kind == .pastSearch {97 // A past query is always searched, even when it looks like an address.98 if let tab = state.selectedTab { tab.search(suggestion.value) } else if let url = SPSearchURL.make(query: suggestion.value) { state.newTab(url: url, select: true) }99 } else {100 state.navigate(suggestion.value)101 }102 state.window?.makeFirstResponder(state.selectedTab?.webView)103 }104105 func endEditing() {106 text = ""107 isEditing = false108 userTyped = false109 suggestions = []110 selection = nil111 }112}113114struct AddressBar: View {115 let state: BrowserWindowState116 let environment: AppEnvironment117 @Bindable var model: AddressBarModel118 @FocusState private var focused: Bool119 @State private var showsWarnings = false120121 private var tab: BrowserTab? { state.selectedTab }122123 var body: some View {124 HStack(spacing: 7) {125 securityIndicator126 ZStack(alignment: .leading) {127 TextField(L("Search or enter address"), text: $model.text)128 .textFieldStyle(.plain)129 .font(.system(size: 13.5))130 .focused($focused)131 .opacity(focused ? 1 : 0.011)132 .onSubmit(submit)133 .onKeyPress(.downArrow) { model.moveSelection(by: 1); return .handled }134 .onKeyPress(.upArrow) { model.moveSelection(by: -1); return .handled }135 .onKeyPress(.escape) { cancel(); return .handled }136 .onChange(of: model.text) { if model.isFilling { model.isFilling = false } else if focused { model.userTyped = true } }137 .accessibilityLabel(L("Address and search"))138 .accessibilityValue(tab?.url?.absoluteString ?? "")139 if !focused { displayText.allowsHitTesting(false) }140 }141 if let tab, tab.url != nil, !focused, !tab.isSearchPage {142 if tab.zoom < 0.99 || tab.zoom > 1.01 {143 Button("\(Int((tab.zoom * 100).rounded())) %") { tab.setZoom(1) }144 .buttonStyle(.plain).font(.caption.monospacedDigit()).padding(.horizontal, 6).padding(.vertical, 2)145 .background(Theme.hover, in: Capsule()).help(CommandID.zoomReset.title)146 }147 let bookmarked = state.bookmarksRevision >= 0 && state.profile.bookmarks.isBookmarked(tab.url?.absoluteString ?? "")148 IconButton(symbol: bookmarked ? "bookmark.fill" : "bookmark", label: CommandID.addBookmark.title, isActive: bookmarked, size: 24) {149 state.perform(.addBookmark)150 }151 }152 }153 .padding(.leading, 10).padding(.trailing, 6)154 .frame(height: focused ? 34 : 32)155 .overlay(alignment: .bottom) { progressBar.clipShape(RoundedRectangle(cornerRadius: focused ? 17 : Theme.radiusM, style: .continuous)) }156 // Address Bar Transformation: on focus the bar rounds into a search field, lifts and lights up.157 .auraField(focused: focused, radius: focused ? 17 : Theme.radiusM, tint: state.isPrivate ? Theme.privateTint.opacity(0.5) : nil)158 .auraAnimation(.expressive, value: focused)159 .anchorPreference(key: AddressBarFrameKey.self, value: .bounds) { $0 }160 .onChange(of: focused) { _, isFocused in161 if isFocused {162 model.isEditing = true163 model.userTyped = false164 let filled = tab?.searchQuery ?? tab?.url?.absoluteString ?? ""165 model.isFilling = filled != model.text166 model.text = filled167 DispatchQueue.main.async { NSApp.sendAction(#selector(NSText.selectAll(_:)), to: nil, from: nil) }168 } else {169 model.endEditing()170 }171 }172 .onChange(of: state.addressFocusRequest) { focused = true }173 .onChange(of: state.selectedTabID) { if focused { focused = false } }174 .task(id: model.text) {175 // Debounce: suggestions are recomputed once typing pauses briefly.176 try? await Task.sleep(for: .milliseconds(90))177 if !Task.isCancelled { model.refresh(state: state, environment: environment) }178 }179 }180181 @ViewBuilder private var securityIndicator: some View {182 let security = tab?.security ?? .none183 let warnings = tab?.warnings ?? []184 let deceptive = warnings.contains(where: \.isDeceptive)185 Button {186 if security == .none { focused = true } else { showsWarnings.toggle() }187 } label: {188 Image(systemName: deceptive ? "exclamationmark.triangle.fill" : (tab?.isSearchPage == true ? "magnifyingglass" : security.symbol))189 .font(.system(size: 11.5, weight: .semibold))190 .foregroundStyle(deceptive || security == .insecure ? Color.orange : (security == .mixed ? .yellow : .secondary))191 .frame(width: 18, height: 22)192 }193 .buttonStyle(.plain)194 .help(security.title.isEmpty ? L("Search or enter address") : security.title)195 .accessibilityLabel(security.title.isEmpty ? L("Search") : security.title)196 .popover(isPresented: $showsWarnings, arrowEdge: .bottom) {197 VStack(alignment: .leading, spacing: 8) {198 Label(security.title, systemImage: security.symbol).font(.headline)199 if let host = tab?.url?.host { Text(host).font(.callout.monospaced()).textSelection(.enabled) }200 ForEach(warnings, id: \.self) { warning in201 Label(warning.message, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.secondary)202 .fixedSize(horizontal: false, vertical: true)203 }204 Button(L("Page Information…")) { showsWarnings = false; state.rightPanel = .pageInfo }.buttonStyle(.link)205 }206 .padding(14).frame(width: 320)207 }208 }209210 /// When the field is not being edited, the site's registrable domain is emphasised and the rest is dimmed,211 /// which makes look-alike addresses easier to spot.212 @ViewBuilder private var displayText: some View {213 if let query = tab?.searchQuery {214 Text(query).font(.system(size: 13.5)).lineLimit(1).truncationMode(.tail)215 } else if let url = tab?.url {216 if environment.settings.showFullURL || url.host == nil {217 Text(url.absoluteString).font(.system(size: 13.5)).lineLimit(1).truncationMode(.middle)218 } else {219 let host = url.host ?? ""220 let domain = URLInspector.registrableDomain(of: host)221 let prefix = host.hasSuffix(domain) ? String(host.dropLast(domain.count)) : ""222 let rest = url.path == "/" ? "" : url.path223 (Text(prefix).foregroundStyle(.secondary) + Text(host.hasSuffix(domain) ? domain : host).fontWeight(.medium) + Text(rest).foregroundStyle(.secondary))224 .font(.system(size: 13.5)).lineLimit(1).truncationMode(.tail)225 }226 } else {227 Text(L("Search or enter address")).font(.system(size: 13.5)).foregroundStyle(.tertiary)228 }229 }230231 @ViewBuilder private var progressBar: some View {232 if let tab, tab.isLoading {233 AuraProgressIndicator(progress: tab.progress).transition(.opacity)234 }235 }236237 private func submit() {238 if let index = model.selection, model.suggestions.indices.contains(index) {239 model.commit(model.suggestions[index], state: state)240 } else {241 let text = model.text242 let inNewTab = NSEvent.modifierFlags.contains(.option)243 model.endEditing()244 state.navigate(text, newTab: inNewTab)245 state.window?.makeFirstResponder(state.selectedTab?.webView)246 }247 focused = false248 }249250 private func cancel() {251 if model.showsSuggestions { model.suggestions = []; model.selection = nil; return }252 focused = false253 state.window?.makeFirstResponder(state.selectedTab?.webView)254 }255}256257struct SuggestionList: View {258 let model: AddressBarModel259 let choose: (AddressSuggestion) -> Void260261 var body: some View {262 VStack(spacing: 1) {263 ForEach(Array(model.suggestions.enumerated()), id: \.element.id) { index, suggestion in264 Button { choose(suggestion) } label: {265 HoverRow(isSelected: model.selection == index) {266 HStack(spacing: 10) {267 Image(systemName: suggestion.symbol).font(.system(size: 12)).foregroundStyle(model.selection == index ? AnyShapeStyle(Theme.accent) : AnyShapeStyle(.secondary)).frame(width: 18)268 Text(suggestion.title).lineLimit(1)269 Text(suggestion.subtitle).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)270 Spacer(minLength: 0)271 }272 .font(.system(size: 13)).padding(.horizontal, 10).padding(.vertical, 7)273 }274 }275 .buttonStyle(.plain)276 .accessibilityLabel("\(suggestion.title), \(suggestion.subtitle)")277 }278 }279 .padding(5)280 .auraSurface(.overlay, radius: Theme.radiusL + 2)281 }282}283