SPB Git

Repository Public

AddressEditor.swift 7.9 KB 160 lines swift

1import SwiftUI2import UIKit34struct MobileSuggestion: Identifiable, Equatable {5    enum Kind: Equatable { case search, pastSearch, address, history, bookmark, tab(UUID) }6    let id = UUID()7    var kind: Kind8    var title: String9    var subtitle: String10    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 == (a: MobileSuggestion, b: MobileSuggestion) -> Bool { a.kind == b.kind && a.title == b.title && a.value == b.value }24}2526enum SuggestionBuilder {27    /// Local suggestions only: nothing typed is sent anywhere until the user confirms.28    @MainActor29    static func suggestions(for text: String, model: BrowserModel, environment: MobileEnvironment) -> [MobileSuggestion] {30        let query = text.trimmingCharacters(in: .whitespaces)31        let library = environment.services.library32        let isPrivate = model.isPrivate33        guard !query.isEmpty else {34            guard !isPrivate, environment.services.searchPreferences.keepSearchHistory else { return [] }35            return library.recentSearches(limit: 6).map { MobileSuggestion(kind: .pastSearch, title: $0.query, subtitle: L("Recent search"), value: $0.query) }36        }37        let settings = environment.settings38        var result: [MobileSuggestion] = []39        var seen = Set<String>()40        if let resolved = AddressResolver.resolve(query, engine: settings.activeSearchEngine(), engines: settings.allSearchEngines()) {41            switch resolved {42            case .url(let url): result.append(MobileSuggestion(kind: .address, title: url.absoluteString, subtitle: L("Open address"), value: query))43            case .search: result.append(MobileSuggestion(kind: .search, title: query, subtitle: L("Search with %@", settings.activeSearchEngine().name), value: query))44            }45        }46        if !isPrivate, environment.services.searchPreferences.keepSearchHistory {47            for item in library.searchSuggestions(for: query, limit: 4) where seen.insert("q:" + item.query.lowercased()).inserted {48                result.append(MobileSuggestion(kind: .pastSearch, title: item.query, subtitle: L("Search again"), value: item.query))49            }50        }51        let lower = query.lowercased()52        for tab in model.visibleTabs where tab.id != model.selectedTabID {53            guard let url = tab.url?.absoluteString, HistoryStore.isRecordable(tab.url!), tab.displayTitle.lowercased().contains(lower) || url.lowercased().contains(lower),54                  seen.insert(url).inserted else { continue }55            result.append(MobileSuggestion(kind: .tab(tab.id), title: tab.displayTitle, subtitle: L("Switch to tab"), value: url))56        }57        if settings.suggestFromBookmarks {58            for bookmark in environment.bookmarks.search(query, limit: 3) {59                guard let url = bookmark.url, seen.insert(url).inserted else { continue }60                result.append(MobileSuggestion(kind: .bookmark, title: bookmark.title, subtitle: url, value: url))61            }62        }63        if settings.suggestFromHistory, !isPrivate {64            for entry in environment.history.suggestions(for: query, limit: 5) where seen.insert(entry.url).inserted {65                result.append(MobileSuggestion(kind: .history, title: entry.title.isEmpty ? entry.url : entry.title, subtitle: entry.url, value: entry.url))66            }67        }68        return result69    }70}7172/// Full-screen editing of the address: the field, then suggestions that stay above the keyboard.73struct AddressEditor: View {74    @Bindable var model: BrowserModel75    let environment: MobileEnvironment76    @State private var text = ""77    @State private var suggestions: [MobileSuggestion] = []78    @FocusState private var focused: Bool7980    var body: some View {81        VStack(spacing: 0) {82            HStack(spacing: 10) {83                HStack(spacing: 8) {84                    Image(systemName: "magnifyingglass").foregroundStyle(.secondary)85                    TextField(L("Search or enter address"), text: $text)86                        .textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.webSearch).submitLabel(.go)87                        .focused($focused)88                        .onSubmit { commit(text) }89                        .accessibilityIdentifier("address-field")90                    if !text.isEmpty {91                        Button { text = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(.tertiary) }.buttonStyle(.plain).accessibilityLabel(L("Clear"))92                    }93                }94                .padding(.horizontal, 12).frame(height: 44)95                .auraField(focused: focused, radius: 15)96                Button(L("Cancel")) { model.isEditingAddress = false }.accessibilityIdentifier("address-cancel")97            }98            .padding(.horizontal, 12).padding(.vertical, 8)99            List {100                ForEach(suggestions) { suggestion in101                    Button { choose(suggestion) } label: {102                        HStack(spacing: 12) {103                            Image(systemName: suggestion.symbol).foregroundStyle(.secondary).frame(width: 24)104                            VStack(alignment: .leading, spacing: 1) {105                                Text(suggestion.title).lineLimit(1).foregroundStyle(.primary)106                                Text(suggestion.subtitle).font(.caption).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)107                            }108                            Spacer(minLength: 0)109                            if suggestion.kind == .pastSearch || suggestion.kind == .search {110                                Button { text = suggestion.value + " " } label: { Image(systemName: "arrow.up.left").foregroundStyle(.tertiary) }111                                    .buttonStyle(.borderless).accessibilityLabel(L("Edit this search"))112                            }113                        }114                    }115                    .listRowBackground(Color.clear)116                }117            }118            .listStyle(.plain)119            .scrollDismissesKeyboard(.immediately)120        }121        .background(.regularMaterial)122        .onAppear {123            let tab = model.selectedTab124            text = tab?.searchQuery ?? (tab?.url.flatMap { HistoryStore.isRecordable($0) ? $0.absoluteString : nil } ?? "")125            suggestions = SuggestionBuilder.suggestions(for: "", model: model, environment: environment)126            focused = true127            DispatchQueue.main.async { UIApplication.shared.sendAction(#selector(UIResponder.selectAll(_:)), to: nil, from: nil, for: nil) }128        }129        .task(id: text) {130            // Debounce while typing.131            try? await Task.sleep(for: .milliseconds(110))132            if !Task.isCancelled { suggestions = SuggestionBuilder.suggestions(for: text == initialText ? "" : text, model: model, environment: environment) }133        }134    }135136    private var initialText: String {137        let tab = model.selectedTab138        return tab?.searchQuery ?? (tab?.url?.absoluteString ?? "")139    }140141    private func commit(_ value: String) {142        guard !value.trimmingCharacters(in: .whitespaces).isEmpty else { model.isEditingAddress = false; return }143        model.navigate(value)144    }145146    private func choose(_ suggestion: MobileSuggestion) {147        PlatformActions.haptic()148        switch suggestion.kind {149        case .tab(let id):150            if let tab = model.tabs.first(where: { $0.id == id }) { model.select(tab) }151            model.isEditingAddress = false152        case .pastSearch:153            (model.selectedTab ?? model.newTab()).search(suggestion.value)154            model.isEditingAddress = false155        default:156            model.navigate(suggestion.value)157        }158    }159}160
Files main
Menu

Theme