-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ReaderSearchViewController.swift
420 lines (338 loc) · 14.3 KB
/
ReaderSearchViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import Foundation
import WordPressShared
import Gridicons
/// Displays a version of the post stream with a search bar positioned above the
/// list of posts. The user supplied search phrase is converted into a ReaderSearchTopic
/// the results of which are displayed in the embedded ReaderStreamViewController.
///
@objc open class ReaderSearchViewController: UIViewController {
fileprivate enum Section: Int, FilterTabBarItem {
case posts
case sites
var title: String {
switch self {
case .posts: return NSLocalizedString("Posts", comment: "Title of a Reader tab showing Posts matching a user's search query")
case .sites: return NSLocalizedString(
"reader.search.tab.blogs",
value: "Blogs",
comment: "Title of a Reader tab showing Sites matching a user's search query"
)
}
}
var trackingValue: String {
switch self {
case .posts: return "posts"
case .sites: return "sites"
}
}
}
private enum SearchSource: String {
case userInput = "user_input"
case searchHistory = "search_history"
}
// MARK: - Properties
@IBOutlet fileprivate weak var searchBar: UISearchBar!
@IBOutlet fileprivate weak var filterBar: FilterTabBar!
fileprivate var backgroundTapRecognizer: UITapGestureRecognizer!
fileprivate var streamController: ReaderStreamViewController?
fileprivate lazy var jpSiteSearchController = JetpackBannerWrapperViewController(
childVC: ReaderSiteSearchViewController(),
screen: .readerSearch
)
fileprivate var siteSearchController: ReaderSiteSearchViewController? {
return jpSiteSearchController.childVC as? ReaderSiteSearchViewController
}
fileprivate var suggestionsController: ReaderSearchSuggestionsViewController?
fileprivate var didBumpStats = false
private lazy var bannerView: JetpackBannerView = {
let textProvider = JetpackBrandingTextProvider(screen: JetpackBannerScreen.readerSearch)
let bannerView = JetpackBannerView()
bannerView.configure(title: textProvider.brandingText()) { [weak self] in
guard let self else {
return
}
JetpackBrandingCoordinator.presentOverlay(from: self)
JetpackBrandingAnalyticsHelper.trackJetpackPoweredBannerTapped(screen: .readerSearch)
}
bannerView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: JetpackBannerView.minimumHeight)
return bannerView
}()
fileprivate let sections: [Section] = [ .posts, .sites ]
var onViewWillDisappear: (() -> Void)?
/// A convenience method for instantiating the controller from the storyboard.
///
/// - Returns: An instance of the controller.
///
@objc open class func controller() -> ReaderSearchViewController {
let storyboard = UIStoryboard(name: "Reader", bundle: Bundle.main)
let controller = storyboard.instantiateViewController(withIdentifier: "ReaderSearchViewController") as! ReaderSearchViewController
return controller
}
@objc open class func controller(withSearchText searchText: String) -> ReaderSearchViewController {
let controller = controller()
controller.loadViewIfNeeded()
controller.searchBar.searchTextField.text = searchText
controller.performSearch()
return controller
}
// MARK: Lifecycle methods
open override func awakeAfter(using aDecoder: NSCoder) -> Any? {
return super.awakeAfter(using: aDecoder)
}
open override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
streamController = segue.destination as? ReaderStreamViewController
}
open override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("Search", comment: "Title of the Reader's search feature")
navigationItem.largeTitleDisplayMode = .never
WPStyleGuide.configureColors(view: view, tableView: nil)
setupSearchBar()
configureFilterBar()
configureBackgroundTapRecognizer()
configureSiteSearchViewController()
configureNavigationBar()
}
open override func didMove(toParent parent: UIViewController?) {
super.didMove(toParent: parent)
if let _ = parent {
return
}
// When the parent is nil then we've been removed from the nav stack.
// Clean up any search topics at this point.
ReaderTopicService(coreDataStack: ContextManager.shared).deleteAllSearchTopics()
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
bumpStats()
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Dismiss the keyboard if it was visible.
endSearch()
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
onViewWillDisappear?()
}
// MARK: - Analytics
@objc func bumpStats() {
if didBumpStats {
return
}
WPAppAnalytics.track(.readerSearchLoaded)
didBumpStats = true
}
// MARK: - Configuration
private func setupSearchBar() {
// Appearance must be set before the search bar is added to the view hierarchy.
let placeholderText = NSLocalizedString("Search WordPress", comment: "Placeholder text for the Reader search feature.")
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self, ReaderSearchViewController.self]).placeholder = placeholderText
searchBar.becomeFirstResponder()
WPStyleGuide.configureSearchBar(searchBar)
guard JetpackBrandingVisibility.all.enabled else {
return
}
searchBar.inputAccessoryView = bannerView
hideBannerViewIfNeeded()
}
/// hides the Jetpack powered banner on iPhone landscape
private func hideBannerViewIfNeeded() {
guard JetpackBrandingVisibility.all.enabled else {
return
}
// hide the banner on iPhone landscape
bannerView.isHidden = traitCollection.verticalSizeClass == .compact
}
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
hideBannerViewIfNeeded()
}
func configureFilterBar() {
WPStyleGuide.configureFilterTabBar(filterBar)
filterBar.tabSizingStyle = .equalWidths
filterBar.items = sections
filterBar.addTarget(self, action: #selector(selectedFilterDidChange(_:)), for: .valueChanged)
}
@objc func configureBackgroundTapRecognizer() {
backgroundTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ReaderSearchViewController.handleBackgroundTap(_:)))
backgroundTapRecognizer.cancelsTouchesInView = true
backgroundTapRecognizer.isEnabled = false
backgroundTapRecognizer.delegate = self
view.addGestureRecognizer(backgroundTapRecognizer)
}
private func configureSiteSearchViewController() {
jpSiteSearchController.view.translatesAutoresizingMaskIntoConstraints = false
addChild(jpSiteSearchController)
view.addSubview(jpSiteSearchController.view)
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: jpSiteSearchController.view.leadingAnchor),
view.trailingAnchor.constraint(equalTo: jpSiteSearchController.view.trailingAnchor),
filterBar.bottomAnchor.constraint(equalTo: jpSiteSearchController.view.topAnchor),
view.bottomAnchor.constraint(equalTo: jpSiteSearchController.view.bottomAnchor),
])
jpSiteSearchController.didMove(toParent: self)
jpSiteSearchController.view.isHidden = true
}
private func configureNavigationBar() {
guard isModal() else {
return
}
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done,
target: self,
action: #selector(doneButtonPressed))
}
// MARK: - Actions
@objc func endSearch() {
searchBar.resignFirstResponder()
}
/// Constructs a ReaderSearchTopic from the search phrase and sets the
/// embedded stream to the topic.
///
private func performSearch(source: SearchSource = .userInput) {
guard let phrase = searchBar.text?.trim(), !phrase.isEmpty else {
return
}
performPostsSearch(for: phrase)
performSitesSearch(for: phrase)
trackSearchPerformed(source: source)
}
private func trackSearchPerformed(source: SearchSource) {
let selectedTab: Section = Section(rawValue: filterBar.selectedIndex) ?? .posts
let properties: [AnyHashable: Any] = [
"source": source.rawValue,
"type": selectedTab.trackingValue
]
WPAppAnalytics.track(.readerSearchPerformed, withProperties: properties)
}
private func performPostsSearch(for phrase: String) {
guard let streamController = streamController else {
return
}
let previousTopic = streamController.readerTopic
let service = ReaderTopicService(coreDataStack: ContextManager.shared)
service.createSearchTopic(forSearchPhrase: phrase) { topicID in
assert(Thread.isMainThread)
self.endSearch()
guard let topicID, let topic = try? ContextManager.shared.mainContext.existingObject(with: topicID) as? ReaderAbstractTopic else {
DDLogError("Failed to create a search topic")
return
}
streamController.readerTopic = topic
if let previousTopic, topic != previousTopic {
service.delete(previousTopic)
}
}
}
private func performSitesSearch(for query: String) {
siteSearchController?.searchQuery = query
}
@objc func handleBackgroundTap(_ gesture: UITapGestureRecognizer) {
endSearch()
}
@objc private func selectedFilterDidChange(_ filterBar: FilterTabBar) {
let section = sections[filterBar.selectedIndex]
switch section {
case .posts:
streamController?.view.isHidden = false
jpSiteSearchController.view.isHidden = true
case .sites:
streamController?.view.isHidden = true
jpSiteSearchController.view.isHidden = false
}
}
@objc private func doneButtonPressed() {
dismiss(animated: true)
}
// MARK: - Autocomplete
/// Display the search suggestions view
///
@objc func presentAutoCompleteView() {
let controller = ReaderSearchSuggestionsViewController.controller()
controller.delegate = self
addChild(controller)
guard let autoView = controller.view, let searchBar = searchBar else {
fatalError("Unexpected")
}
autoView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(autoView)
let views = [
"searchBar": searchBar,
"autoView": autoView
]
// Match the width of the search bar.
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "[autoView(==searchBar)]",
options: .alignAllLastBaseline,
metrics: nil,
views: views))
// Pin below the search bar.
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[searchBar][autoView]",
options: .alignAllCenterX,
metrics: nil,
views: views))
// Center on the search bar.
view.addConstraint(NSLayoutConstraint(
item: autoView,
attribute: .centerX,
relatedBy: .equal,
toItem: searchBar,
attribute: .centerX,
multiplier: 1,
constant: 0))
view.setNeedsUpdateConstraints()
controller.didMove(toParent: self)
suggestionsController = controller
}
/// Remove the search suggestions view.
///
@objc func dismissAutoCompleteView() {
guard let controller = suggestionsController else {
return
}
controller.willMove(toParent: nil)
controller.view.removeFromSuperview()
controller.removeFromParent()
suggestionsController = nil
}
}
extension ReaderSearchViewController: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
guard let suggestionsView = suggestionsController?.view else {
return true
}
// The gesture recognizer should not handle touches inside the suggestions view.
// We want those taps to be processed normally.
let point = touch.location(in: suggestionsView)
if suggestionsView.bounds.contains(point) {
return false
}
return true
}
}
extension ReaderSearchViewController: UISearchBarDelegate {
public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// update the autocomplete suggestions
suggestionsController?.phrase = searchText.trim()
}
public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
backgroundTapRecognizer.isEnabled = true
// prepare autocomplete view
presentAutoCompleteView()
}
public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
// remove auto complete view
dismissAutoCompleteView()
backgroundTapRecognizer.isEnabled = false
}
public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
performSearch()
}
public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
endSearch()
}
}
extension ReaderSearchViewController: ReaderSearchSuggestionsDelegate {
@objc func searchSuggestionsController(_ controller: ReaderSearchSuggestionsViewController, selectedItem: String) {
searchBar.text = selectedItem
performSearch(source: .searchHistory)
}
}