/
ShipmentProvidersViewController.swift
334 lines (267 loc) · 10.7 KB
/
ShipmentProvidersViewController.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
import UIKit
import Yosemite
protocol ShipmentProviderListDelegate: AnyObject {
func shipmentProviderList(_ list: ShipmentProvidersViewController, didSelect: ShipmentTrackingProvider, groupName: String)
}
final class ShipmentProvidersViewController: UIViewController {
private let viewModel: ShippingProvidersViewModel
private weak var delegate: ShipmentProviderListDelegate?
@IBOutlet weak var table: UITableView!
private lazy var searchController: UISearchController = {
let returnValue = UISearchController(searchResultsController: nil)
returnValue.hidesNavigationBarDuringPresentation = false
returnValue.obscuresBackgroundDuringPresentation = false
returnValue.searchResultsUpdater = self
returnValue.delegate = self
return returnValue
}()
/// Dedicated NoticePresenter (use this here instead of ServiceLocator.noticePresenter)
///
private lazy var noticePresenter: DefaultNoticePresenter = {
let noticePresenter = DefaultNoticePresenter()
noticePresenter.presentingViewController = self
return noticePresenter
}()
/// Footer spinner shown when loading data for the first time
///
private lazy var footerSpinnerView = {
return FooterSpinnerView(tableViewStyle: table.style)
}()
private lazy var keyboardFrameObserver: KeyboardFrameObserver = {
let keyboardFrameObserver = KeyboardFrameObserver { [weak self] keyboardFrame in
self?.handleKeyboardFrameUpdate(keyboardFrame: keyboardFrame)
}
return keyboardFrameObserver
}()
/// Deinitializer
///
init(viewModel: ShippingProvidersViewModel, delegate: ShipmentProviderListDelegate) {
self.viewModel = viewModel
self.delegate = delegate
super.init(nibName: type(of: self).nibName, bundle: nil)
self.configureViewModel()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
configureBackground()
configureNavigation()
configureSearchController()
configureTable()
fetchGroups()
startListeningToNotifications()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
searchController.dismiss(animated: false, completion: nil)
}
}
// MARK: - Fetch data
//
private extension ShipmentProvidersViewController {
/// Loads shipment tracking groups
///
func fetchGroups() {
footerSpinnerView.startAnimating()
guard let siteID = ServiceLocator.stores.sessionManager.defaultStoreID else {
return
}
let orderID = viewModel.order.orderID
let loadGroupsAction = ShipmentAction.synchronizeShipmentTrackingProviders(siteID: siteID,
orderID: orderID) { [weak self] error in
if let error = error {
self?.presentNotice(error)
}
ServiceLocator.analytics.track(.orderTrackingProvidersLoaded)
self?.footerSpinnerView.stopAnimating()
}
ServiceLocator.stores.dispatch(loadGroupsAction)
}
}
// MARK: - Configure UI
//
private extension ShipmentProvidersViewController {
func configureBackground() {
view.backgroundColor = .listBackground
}
func configureNavigation() {
configureTitle()
}
func configureTitle() {
title = viewModel.title
}
func configureSearchController() {
searchController.searchBar.textField?.backgroundColor = .listBackground
guard table.tableHeaderView == nil else {
return
}
table.tableHeaderView = searchController.searchBar
}
func configureTable() {
registerTableViewCells()
styleTableView()
if viewModel.isListEmpty {
table.tableFooterView = footerSpinnerView
}
table.dataSource = self
table.delegate = self
}
/// Registers all of the available TableViewCells
///
func registerTableViewCells() {
let cells = [WooBasicTableViewCell.self]
for cell in cells {
table.register(cell.loadNib(), forCellReuseIdentifier: cell.reuseIdentifier)
}
}
func styleTableView() {
table.estimatedRowHeight = Constants.rowHeight
table.rowHeight = UITableView.automaticDimension
table.backgroundColor = .listBackground
}
}
// MARK: - Keyboard management
//
private extension ShipmentProvidersViewController {
/// Registers for all of the related Notifications
///
func startListeningToNotifications() {
keyboardFrameObserver.startObservingKeyboardFrame()
}
}
extension ShipmentProvidersViewController: KeyboardScrollable {
var scrollable: UIScrollView {
return table
}
}
// MARK: - View model configuration and binding
//
private extension ShipmentProvidersViewController {
func configureViewModel() {
viewModel.onDataLoaded = { [weak self] in
self?.table.reloadData()
}
viewModel.configureResultsController()
}
}
// MARK: - Conformance to UITableViewDataSource
//
extension ShipmentProvidersViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfSections()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRowsInSection(section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: WooBasicTableViewCell.reuseIdentifier,
for: indexPath) as? WooBasicTableViewCell else {
fatalError()
}
cell.bodyLabel?.text = viewModel.titleForCellAt(indexPath)
cell.applyListSelectorStyle()
cell.accessoryType = viewModel.isSelected(indexPath) ? .checkmark : .none
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return viewModel.titleForHeaderInSection(section)
}
}
// MARK: - Conformance to UITableViewDelegate
//
extension ShipmentProvidersViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if viewModel.isCustom(indexPath: indexPath) {
addCustomProvider()
return
}
guard let provider = viewModel.provider(at: indexPath),
let groupName = viewModel.groupName(at: indexPath) else {
return
}
delegate?.shipmentProviderList(self, didSelect: provider, groupName: groupName)
navigationController?.popViewController(animated: true)
}
}
// MARK: - Search and filtering
//
extension ShipmentProvidersViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
resetUIState(searchTerm: searchController.searchBar.text)
}
}
extension ShipmentProvidersViewController: UISearchControllerDelegate {
func willDismissSearchController(_ searchController: UISearchController) {
resetUIState(searchTerm: "")
}
}
// MARK: - Error handling
//
private extension ShipmentProvidersViewController {
func presentNotice(_ error: Error) {
let title = NSLocalizedString(
"Unable to load Shipment Carriers",
comment: "Content of error presented when loading the list of shipment carriers failed. It reads: Unable to load Shipment Carriers"
)
let actionTitle = NSLocalizedString("Retry", comment: "Retry Action")
let notice = Notice(title: title,
message: nil,
feedbackType: .error,
actionTitle: actionTitle) { [weak self] in
self?.fetchGroups()
}
noticePresenter.enqueue(notice: notice)
}
}
// MARK: - Empty state
//
private extension ShipmentProvidersViewController {
func resetUIState(searchTerm: String?) {
guard let searchTerm = searchTerm,
searchTerm.isEmpty == false else {
viewModel.clearFilters()
table.reloadData()
presentEmptyStateIfNecessary()
return
}
viewModel.filter(by: searchTerm)
table.reloadData()
presentEmptyStateIfNecessary(term: searchTerm)
}
func presentEmptyStateIfNecessary(term: String = "") {
guard viewModel.isListEmpty else {
removeEmptyState()
return
}
let emptyState: EmptyListMessageWithActionView = EmptyListMessageWithActionView.instantiateFromNib()
emptyState.messageText = NSLocalizedString("No results found for \(term)\nAdd a custom carrier",
comment: "Empty state for the list of shipment carriers. It reads: 'No results for DHL. Add a custom carrier'")
emptyState.actionText = NSLocalizedString("Custom Carrier",
comment: "Title of button to add a custom tracking carrier if filtering the list yields no results."
)
emptyState.onAction = { [weak self] in
self?.addCustomProvider()
}
emptyState.attach(to: view)
}
func removeEmptyState() {
for subview in view.subviews where subview is EmptyListMessageWithActionView {
subview.removeFromSuperview()
}
}
func addCustomProvider() {
ServiceLocator.analytics.track(.orderShipmentTrackingCustomProviderSelected)
let initialCustomProviderName = searchController.searchBar.text
let addCustomTrackingViewModel = AddCustomTrackingViewModel(order: viewModel.order,
initialName: initialCustomProviderName)
let addCustomTrackingViewController = ManualTrackingViewController(viewModel: addCustomTrackingViewModel)
navigationController?.pushViewController(addCustomTrackingViewController, animated: true)
}
}
// MARK: - Private constants
//
private struct Constants {
static let rowHeight = CGFloat(48)
}