Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tabs to suggestions/autocomplete on iOS #998

Merged
merged 14 commits into from
Sep 22, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}
20 changes: 12 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()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably not strictly required because usually input will be lowercase, but while testing caused some confusion.

let queryTokens = queryTokens ?? Self.tokens(from: query)

var score = 0
Expand All @@ -39,7 +40,9 @@ extension Score {
score += 300
// Prioritize root URLs most
if url.isRoot { score += 2000 }
} else if lowercasedTitle.starts(with: query) {
} else if lowercasedTitle
.trimmingCharacters(in: .alphanumerics.inverted)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes a bug where if a title was like "Cats and Dogs" Cats would not get matched at all because of the quote.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it mean that matching these characters won't work from now on?
What if I want to find a title starting with a special character?

I checked in the currently released version and I can match a title with quotes which might be a valid use case.

Screenshot 2024-09-20 at 09 45 54

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah that example won't work now because:

  • It won't match the first character any more
  • The second character wouldn't match anyway

But honestly, I think that's gonna be rare? I assume people are more likely to search for HBO than " or "HBO

I can make it an OR condition though if you feel strongly?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new solution looks better to me 👍 Thank you, Brindy!

.starts(with: query) {
score += 200
if url.isRoot { score += 2000 }
} else if queryCount > 2 && domain.contains(query) {
Expand All @@ -52,7 +55,9 @@ 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
.trimmingCharacters(in: .alphanumerics.inverted)
.starts(with: token) && !lowercasedTitle.contains(" \(token)") && !nakedUrl.starts(with: token) {
matchesAllTokens = false
break
}
Expand All @@ -66,7 +71,9 @@ 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
.trimmingCharacters(in: .alphanumerics.inverted)
.starts(with: firstToken) { // begining of the title - moderate score boost
score += 50
}
}
Expand Down Expand Up @@ -104,12 +111,9 @@ extension Score {
}

static func tokens(from query: Query) -> [Query] {
return query
.split(whereSeparator: {
$0.unicodeScalars.contains(where: { CharacterSet.whitespacesAndNewlines.contains($0) })
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seemed superfluous and appeared to result in some strings not tokenising as expected, so this is aligned with the similar code for Bookmarks on iOS.

})
return query.components(separatedBy: .whitespacesAndNewlines)
.filter { !$0.isEmpty }
.map { String($0).lowercased() }
.map { $0.lowercased() }
}

}
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
Loading