Skip to content

Commit

Permalink
Add tabs to suggestions/autocomplete on iOS (#998)
Browse files Browse the repository at this point in the history
**Required**:

Task/Issue URL:
https://app.asana.com/0/392891325557410/1208036752520497/f
iOS PR: duckduckgo/iOS#3371
macOS PR: duckduckgo/macos-browser#3309
What kind of version bump will this require?: Major

**Optional**:

Tech Design URL:
https://app.asana.com/0/481882893211075/1208270496320813/f
CC: 

**Description**:
Adds support for tabs to suggestions.

**Steps to test this PR**:
1. See platform specific PRs
  • Loading branch information
brindy authored Sep 22, 2024
1 parent 4ba1125 commit 6e1520b
Show file tree
Hide file tree
Showing 10 changed files with 507 additions and 218 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public enum PrivacyFeature: String {
case syncPromotion
case autofillSurveys
case marketplaceAdPostback
case autocompleteTabs
}

/// An abstraction to be implemented by any "subfeature" of a given `PrivacyConfiguration` feature.
Expand Down
32 changes: 32 additions & 0 deletions Sources/Suggestions/BrowserTab.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//
// BrowserTab.swift
//
// Copyright © 2024 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import Foundation

public protocol BrowserTab {

var url: URL { get }
var title: String { get }

}

extension Score {
init(browserTab: BrowserTab, query: Query) {
self.init(title: browserTab.title, url: browserTab.url, visitCount: 0, query: query)
}
}
23 changes: 15 additions & 8 deletions Sources/Suggestions/Score.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ extension Score {
// swiftlint:disable:next cyclomatic_complexity
init(title: String?, url: URL, visitCount: Int, query: Query, queryTokens: [Query]? = nil) {
// To optimize, query tokens can be precomputed
let query = query.lowercased()
let queryTokens = queryTokens ?? Self.tokens(from: query)

var score = 0
Expand All @@ -39,7 +40,7 @@ extension Score {
score += 300
// Prioritize root URLs most
if url.isRoot { score += 2000 }
} else if lowercasedTitle.starts(with: query) {
} else if lowercasedTitle.leadingBoundaryStartsWith(query) {
score += 200
if url.isRoot { score += 2000 }
} else if queryCount > 2 && domain.contains(query) {
Expand All @@ -52,7 +53,7 @@ extension Score {
var matchesAllTokens = true
for token in queryTokens {
// Match only from the begining of the word to avoid unintuitive matches.
if !lowercasedTitle.starts(with: token) && !lowercasedTitle.contains(" \(token)") && !nakedUrl.starts(with: token) {
if !lowercasedTitle.leadingBoundaryStartsWith(token) && !lowercasedTitle.contains(" \(token)") && !nakedUrl.starts(with: token) {
matchesAllTokens = false
break
}
Expand All @@ -66,7 +67,7 @@ extension Score {
if let firstToken = queryTokens.first { // nakedUrlString - high score boost
if nakedUrl.starts(with: firstToken) {
score += 70
} else if lowercasedTitle.starts(with: firstToken) { // begining of the title - moderate score boost
} else if lowercasedTitle.leadingBoundaryStartsWith(firstToken) { // begining of the title - moderate score boost
score += 50
}
}
Expand Down Expand Up @@ -104,12 +105,18 @@ extension Score {
}

static func tokens(from query: Query) -> [Query] {
return query
.split(whereSeparator: {
$0.unicodeScalars.contains(where: { CharacterSet.whitespacesAndNewlines.contains($0) })
})
return query.components(separatedBy: .whitespacesAndNewlines)
.filter { !$0.isEmpty }
.map { String($0).lowercased() }
.map { $0.lowercased() }
}

}

extension String {

/// e.g. "Cats and Dogs" would match `Cats` or `"Cats`
func leadingBoundaryStartsWith(_ s: String) -> Bool {
return starts(with: s) || trimmingCharacters(in: .alphanumerics.inverted).starts(with: s)
}

}
40 changes: 31 additions & 9 deletions Sources/Suggestions/Suggestion.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,16 @@ public enum Suggestion: Equatable {
case bookmark(title: String, url: URL, isFavorite: Bool, allowedInTopHits: Bool)
case historyEntry(title: String?, url: URL, allowedInTopHits: Bool)
case internalPage(title: String, url: URL)
case openTab(title: String, url: URL)
case unknown(value: String)

var url: URL? {
switch self {
case .website(url: let url),
.historyEntry(title: _, url: let url, allowedInTopHits: _),
.bookmark(title: _, url: let url, isFavorite: _, allowedInTopHits: _),
.internalPage(title: _, url: let url):
.internalPage(title: _, url: let url),
.openTab(title: _, url: let url):
return url
case .phrase, .unknown:
return nil
Expand All @@ -44,7 +46,8 @@ public enum Suggestion: Equatable {
case .historyEntry(title: let title, url: _, allowedInTopHits: _):
return title
case .bookmark(title: let title, url: _, isFavorite: _, allowedInTopHits: _),
.internalPage(title: let title, url: _):
.internalPage(title: let title, url: _),
.openTab(title: let title, url: _):
return title
case .phrase, .website, .unknown:
return nil
Expand All @@ -53,7 +56,7 @@ public enum Suggestion: Equatable {

public var allowedInTopHits: Bool {
switch self {
case .website:
case .website, .openTab:
return true
case .historyEntry(title: _, url: _, allowedInTopHits: let allowedInTopHits):
return allowedInTopHits
Expand All @@ -64,23 +67,38 @@ public enum Suggestion: Equatable {
}
}

var isOpenTab: Bool {
if case .openTab = self {
return true
}
return false
}

var isBookmark: Bool {
if case .bookmark = self {
return true
}
return false
}

}

extension Suggestion {

init?(bookmark: Bookmark) {
init?(bookmark: Bookmark, allowedInTopHits: Bool) {
guard let urlObject = URL(string: bookmark.url) else { return nil }
#if os(macOS)
self = .bookmark(title: bookmark.title,
url: urlObject,
isFavorite: bookmark.isFavorite,
allowedInTopHits: bookmark.isFavorite)
#else
allowedInTopHits: allowedInTopHits)
}

init?(bookmark: Bookmark) {
guard let urlObject = URL(string: bookmark.url) else { return nil }
self = .bookmark(title: bookmark.title,
url: urlObject,
isFavorite: bookmark.isFavorite,
allowedInTopHits: true)
#endif
allowedInTopHits: bookmark.isFavorite)
}

init(historyEntry: HistorySuggestion) {
Expand All @@ -96,6 +114,10 @@ extension Suggestion {
self = .internalPage(title: internalPage.title, url: internalPage.url)
}

init(tab: BrowserTab) {
self = .openTab(title: tab.title, url: tab.url)
}

init(url: URL) {
self = .website(url: url)
}
Expand Down
24 changes: 12 additions & 12 deletions Sources/Suggestions/SuggestionLoading.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,9 @@ import Foundation
public protocol SuggestionLoading: AnyObject {

func getSuggestions(query: Query,
usingDataSource dataSource: SuggestionLoadingDataSource,
completion: @escaping (SuggestionResult?, Error?) -> Void)

var dataSource: SuggestionLoadingDataSource? { get set }

}

public class SuggestionLoader: SuggestionLoading {
Expand All @@ -38,22 +37,15 @@ public class SuggestionLoader: SuggestionLoading {
case failedToProcessData
}

public weak var dataSource: SuggestionLoadingDataSource?
private let processing: SuggestionProcessing
private let urlFactory: (String) -> URL?

public init(dataSource: SuggestionLoadingDataSource? = nil, urlFactory: @escaping (String) -> URL?) {
self.dataSource = dataSource
public init(urlFactory: @escaping (String) -> URL?) {
self.urlFactory = urlFactory
self.processing = SuggestionProcessing(urlFactory: urlFactory)
}

public func getSuggestions(query: Query,
usingDataSource dataSource: SuggestionLoadingDataSource,
completion: @escaping (SuggestionResult?, Error?) -> Void) {
guard let dataSource = dataSource else {
completion(nil, SuggestionLoaderError.noDataSource)
return
}

if query.isEmpty {
completion(.empty, nil)
Expand All @@ -64,6 +56,7 @@ public class SuggestionLoader: SuggestionLoading {
let bookmarks = dataSource.bookmarks(for: self)
let history = dataSource.history(for: self)
let internalPages = dataSource.internalPages(for: self)
let openTabs = dataSource.openTabs(for: self)
var apiResult: APIResult?
var apiError: Error?

Expand Down Expand Up @@ -94,10 +87,13 @@ public class SuggestionLoader: SuggestionLoading {

// 2) Processing it
group.notify(queue: .global(qos: .userInitiated)) { [weak self] in
let result = self?.processing.result(for: query,
guard let self = self else { return }
let processor = SuggestionProcessing(platform: dataSource.platform, urlFactory: self.urlFactory)
let result = processor.result(for: query,
from: history,
bookmarks: bookmarks,
internalPages: internalPages,
openTabs: openTabs,
apiResult: apiResult)
DispatchQueue.main.async {
if let result = result {
Expand All @@ -112,12 +108,16 @@ public class SuggestionLoader: SuggestionLoading {

public protocol SuggestionLoadingDataSource: AnyObject {

var platform: Platform { get }

func bookmarks(for suggestionLoading: SuggestionLoading) -> [Bookmark]

func history(for suggestionLoading: SuggestionLoading) -> [HistorySuggestion]

func internalPages(for suggestionLoading: SuggestionLoading) -> [InternalPage]

func openTabs(for suggestionLoading: SuggestionLoading) -> [BrowserTab]

func suggestionLoading(_ suggestionLoading: SuggestionLoading,
suggestionDataFromUrl url: URL,
withParameters parameters: [String: String],
Expand Down
Loading

0 comments on commit 6e1520b

Please sign in to comment.