-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathSignupUsernameTableViewController.swift
270 lines (224 loc) · 9.71 KB
/
SignupUsernameTableViewController.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
import SVProgressHUD
import WordPressAuthenticator
class SignupUsernameTableViewController: NUXTableViewController {
open var currentUsername: String?
open var displayName: String?
open var delegate: SignupUsernameViewControllerDelegate?
private var service: AccountSettingsService?
private var suggestions: [String] = []
private var isSearching: Bool = false
private var selectedCell: UITableViewCell?
override func awakeFromNib() {
super.awakeFromNib()
let bundle = Bundle(for: WordPressAuthenticator.self)
tableView.register(UINib(nibName: "SearchTableViewCell", bundle: bundle), forCellReuseIdentifier: SearchTableViewCell.reuseIdentifier)
setupBackgroundTapGestureRecognizer()
}
override func viewDidLoad() {
super.viewDidLoad()
WPStyleGuide.configureColors(for: view, andTableView: tableView)
tableView.layoutMargins = WPStyleGuide.edgeInsetForLoginTextFields()
navigationItem.title = NSLocalizedString("Pick username", comment: "Title for selecting a new username in the site creation flow.")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// only procede with initial search if we don't have site title suggestions yet (hopefully only the first time)
guard suggestions.count < 1,
let nameToSearch = displayName else {
return
}
suggestUsernames(for: nameToSearch) { [weak self] (suggestions) in
self?.suggestions = suggestions
self?.tableView.reloadSections(IndexSet(integersIn: Sections.searchField.rawValue...Sections.suggestions.rawValue), with: .automatic)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
SVProgressHUD.dismiss()
}
private func suggestUsernames(for searchTerm: String, addSuggestions: @escaping ([String]) ->()) {
guard !isSearching else {
return
}
isSearching = true
let context = ContextManager.sharedInstance().mainContext
let accountService = AccountService(managedObjectContext: context)
guard let account = accountService.defaultWordPressComAccount(),
let api = account.wordPressComRestApi else {
return
}
SVProgressHUD.show(withStatus: NSLocalizedString("Loading usernames", comment: "Shown while the app waits for the username suggestions web service to return during the site creation process."))
let service = AccountSettingsService(userID: account.userID.intValue, api: api)
service.suggestUsernames(base: searchTerm) { [weak self] (newSuggestions) in
if newSuggestions.count == 0 {
defer {
WordPressAuthenticator.track(.signupEpilogueUsernameSuggestionsFailed)
}
}
self?.isSearching = false
SVProgressHUD.dismiss()
addSuggestions(newSuggestions)
}
}
func setupBackgroundTapGestureRecognizer() {
let gestureRecognizer = UITapGestureRecognizer()
gestureRecognizer.on(call: { [weak self] (gesture) in
self?.view.endEditing(true)
})
gestureRecognizer.cancelsTouchesInView = false
view.addGestureRecognizer(gestureRecognizer)
}
}
// MARK: UITableViewDataSource
extension SignupUsernameTableViewController {
fileprivate enum Sections: Int {
case titleAndDescription = 0
case searchField = 1
case suggestions = 2
static var count: Int {
return suggestions.rawValue + 1
}
}
private enum SuggestionStyles {
static let indentationWidth: CGFloat = 20.0
static let indentationLevel = 1
}
override func numberOfSections(in tableView: UITableView) -> Int {
return Sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case Sections.titleAndDescription.rawValue:
return 1
case Sections.searchField.rawValue:
return 1
case Sections.suggestions.rawValue:
return suggestions.count + 1
default:
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell
switch indexPath.section {
case Sections.titleAndDescription.rawValue:
cell = titleAndDescriptionCell()
case Sections.searchField.rawValue:
cell = searchFieldCell()
case Sections.suggestions.rawValue:
fallthrough
default:
if indexPath.row == 0 {
cell = suggestionCell(username: currentUsername ?? "username not found", checked: true)
selectedCell = cell
} else {
cell = suggestionCell(username: suggestions[indexPath.row - 1], checked: false)
}
}
return cell
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == Sections.suggestions.rawValue {
let footer = UIView()
footer.backgroundColor = WPStyleGuide.greyLighten20()
return footer
}
return nil
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == Sections.suggestions.rawValue {
return 0.5
}
return 0
}
// MARK: table view cells
private func titleAndDescriptionCell() -> UITableViewCell {
let descriptionStyled = buildHeaderDescription()
let cell = LoginSocialErrorCell(title: "", description: descriptionStyled)
cell.selectionStyle = .none
return cell
}
private func buildHeaderDescription() -> NSAttributedString {
guard let currentUsername = currentUsername, let displayName = displayName else {
return NSAttributedString(string: "")
}
let baseDescription = String(format: NSLocalizedString("Your current username is %@. With few exceptions, others will only ever see your display name, %@.", comment: "Instructional text that displays the current username and display name."), currentUsername, displayName)
guard let rangeOfUsername = baseDescription.range(of: currentUsername),
let rangeOfDisplayName = baseDescription.range(of: displayName) else {
return NSAttributedString(string: baseDescription)
}
let boldFont = WPStyleGuide.mediumWeightFont(forStyle: .subheadline)
let plainFont = UIFont.preferredFont(forTextStyle: .subheadline)
let description = NSMutableAttributedString(string: baseDescription, attributes: [.font: plainFont])
description.addAttribute(.font, value: boldFont, range: baseDescription.nsRange(from: rangeOfUsername))
description.addAttribute(.font, value: boldFont, range: baseDescription.nsRange(from: rangeOfDisplayName))
return description
}
private func searchFieldCell() -> SearchTableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: SearchTableViewCell.reuseIdentifier) as? SearchTableViewCell else {
fatalError()
}
cell.placeholder = NSLocalizedString("Type a keyword for more ideas", comment: "Placeholder text for domain search during site creation.")
cell.delegate = self
cell.selectionStyle = .none
return cell
}
private func suggestionCell(username: String, checked: Bool) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = username
cell.textLabel?.textColor = WPStyleGuide.darkGrey()
cell.indentationWidth = SuggestionStyles.indentationWidth
cell.indentationLevel = SuggestionStyles.indentationLevel
if checked {
cell.accessoryType = .checkmark
}
return cell
}
}
extension String {
private func nsRange(from range: Range<Index>) -> NSRange {
let from = range.lowerBound
let to = range.upperBound
let location = distance(from: startIndex, to: from)
let length = distance(from: from, to: to)
return NSRange(location: location, length: length)
}
}
extension SignupUsernameTableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedUsername: String
switch indexPath.section {
case Sections.suggestions.rawValue:
if indexPath.row == 0 {
selectedUsername = currentUsername ?? ""
} else {
selectedUsername = suggestions[indexPath.row - 1]
}
default:
return
}
delegate?.usernameSelected(selectedUsername)
tableView.deselectSelectedRowWithAnimation(true)
// Uncheck the previously selected cell.
if let selectedCell = selectedCell {
selectedCell.accessoryType = .none
}
// Check the currently selected cell.
if let cell = self.tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
selectedCell = cell
}
}
}
// MARK: - SearchTableViewCellDelegate
extension SignupUsernameTableViewController: SearchTableViewCellDelegate {
func startSearch(for searchTerm: String) {
guard searchTerm.count > 0 else {
return
}
suggestUsernames(for: searchTerm) { [weak self] suggestions in
self?.suggestions = suggestions
self?.tableView.reloadSections(IndexSet(integer: Sections.suggestions.rawValue), with: .automatic)
}
}
}