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
|
//
// RedeemVoucherContentView.swift
// MullvadVPN
//
// Created by Andreas Lif on 2022-08-05.
// Copyright © 2025 Mullvad VPN AB. All rights reserved.
//
import MullvadREST
import UIKit
enum RedeemVoucherState {
case initial
case success
case verifying
case failure(Error)
case logout
}
final class RedeemVoucherContentView: UIView {
// MARK: - private
private let scrollView: UIScrollView = {
let scrollView = UIScrollView()
return scrollView
}()
private let contentHolderView: UIView = {
let contentHolderView = UIView()
return contentHolderView
}()
private let voucherTextFieldHeight: CGFloat = 54
private let title: UILabel = {
let label = UILabel()
label.font = .mullvadLarge
label.text = NSLocalizedString("Redeem voucher", comment: "")
label.textColor = .white
label.numberOfLines = 0
label.adjustsFontForContentSizeCategory = true
return label
}()
private let enterVoucherLabel: UILabel = {
let label = UILabel()
label.font = .mullvadTinySemiBold
label.text = NSLocalizedString("Enter voucher code", comment: "")
label.textColor = .white
label.numberOfLines = 0
label.adjustsFontForContentSizeCategory = true
return label
}()
private let textField: VoucherTextField = {
let textField = VoucherTextField()
textField.font = UIFontMetrics(forTextStyle: .subheadline)
.scaledFont(for: .monospacedSystemFont(ofSize: 15, weight: .regular))
textField.placeholder = Array(repeating: "XXXX", count: 4).joined(separator: "-")
textField.placeholderTextColor = .lightGray
textField.backgroundColor = .white
textField.cornerRadius = UIMetrics.SettingsRedeemVoucher.cornerRadius
textField.keyboardType = .asciiCapable
textField.autocapitalizationType = .allCharacters
textField.returnKeyType = .done
textField.autocorrectionType = .no
textField.adjustsFontForContentSizeCategory = true
return textField
}()
private let activityIndicator: SpinnerActivityIndicatorView = {
let activityIndicator = SpinnerActivityIndicatorView(style: .medium)
activityIndicator.tintColor = .white
activityIndicator.setContentHuggingPriority(.defaultHigh, for: .horizontal)
activityIndicator.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
return activityIndicator
}()
private let statusLabel: UILabel = {
let label = UILabel()
label.font = .mullvadMiniSemiBold
label.numberOfLines = 2
label.adjustsFontForContentSizeCategory = true
label.lineBreakMode = .byWordWrapping
label.textColor = .red
label.setContentHuggingPriority(.defaultLow, for: .horizontal)
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
label.lineBreakStrategy = []
return label
}()
private lazy var logoutViewForAccountNumberIsEntered: LogoutDialogueView = {
LogoutDialogueView { verifiedAccountView in
verifiedAccountView.isLoading = true
self.logoutAction?()
}
}()
private let redeemButton: AppButton = {
let button = AppButton(style: .success)
button.setTitle(NSLocalizedString("Redeem", comment: ""), for: .normal)
return button
}()
private let cancelButton: AppButton = {
let button = AppButton(style: .default)
button.setTitle(NSLocalizedString("Cancel", comment: ""), for: .normal)
return button
}()
private lazy var statusStack: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [activityIndicator, statusLabel])
stackView.spacing = UIMetrics.padding8
return stackView
}()
private lazy var voucherCodeStackView: UIStackView = {
var arrangedSubviews = [
enterVoucherLabel,
textField,
statusStack,
logoutViewForAccountNumberIsEntered,
]
if configuration.shouldUseCompactStyle == false {
arrangedSubviews.insert(title, at: 0)
}
let stackView = UIStackView(arrangedSubviews: arrangedSubviews)
stackView.axis = .vertical
stackView.setCustomSpacing(UIMetrics.padding8, after: title)
stackView.setCustomSpacing(UIMetrics.padding16, after: enterVoucherLabel)
stackView.setCustomSpacing(UIMetrics.padding8, after: textField)
stackView.setCustomSpacing(UIMetrics.padding16, after: statusLabel)
stackView.setCustomSpacing(UIMetrics.padding10, after: statusStack)
stackView.setContentHuggingPriority(.defaultLow, for: .vertical)
return stackView
}()
private lazy var buttonsStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [redeemButton, cancelButton])
stackView.axis = .vertical
stackView.spacing = UIMetrics.padding16
stackView.setContentCompressionResistancePriority(.required, for: .vertical)
return stackView
}()
private var text: String {
switch state {
case let .failure(error):
guard let restError = error as? REST.Error else {
return error.localizedDescription
}
return restError.description
case .verifying:
return NSLocalizedString("Verifying voucher...", comment: "")
case .logout:
return NSLocalizedString("Logging out...", comment: "")
default: return ""
}
}
private var isRedeemButtonEnabled: Bool {
switch state {
case .initial, .failure:
return true
case .success, .verifying, .logout:
return false
}
}
private var textColor: UIColor {
switch state {
case .failure:
return .dangerColor
default:
return .white
}
}
private var isLoading: Bool {
switch state {
case .verifying, .logout:
return true
default:
return false
}
}
private var keyboardResponder: AutomaticKeyboardResponder?
private var bottomsOfButtonsConstraint: NSLayoutConstraint?
private let configuration: RedeemVoucherViewConfiguration
// MARK: - public
var redeemAction: ((String) -> Void)?
var cancelAction: (() -> Void)?
var logoutAction: (() -> Void)?
var state: RedeemVoucherState = .initial {
didSet {
updateUI()
}
}
var isEditing: Bool {
get {
textField.isEditing
}
set {
guard textField.isFirstResponder != newValue else { return }
if newValue {
textField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
}
}
var isLogoutDialogHidden = true {
didSet {
logoutViewForAccountNumberIsEntered.isHidden = isLogoutDialogHidden
}
}
init(configuration: RedeemVoucherViewConfiguration) {
self.configuration = configuration
super.init(frame: .zero)
commonInit()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func commonInit() {
setupAppearance()
configureUI()
addButtonHandlers()
updateUI()
addKeyboardResponderIfNeeded()
addObservers()
}
private func setupAppearance() {
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = .secondaryColor
directionalLayoutMargins = UIMetrics.contentLayoutMargins
}
private func configureUI() {
addConstrainedSubviews([scrollView]) {
scrollView.pinEdgesToSuperview(.all(configuration.layoutMargins))
}
scrollView.addConstrainedSubviews([contentHolderView]) {
contentHolderView.pinEdgesToSuperview()
contentHolderView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
contentHolderView.heightAnchor.constraint(greaterThanOrEqualTo: scrollView.heightAnchor)
}
contentHolderView.addConstrainedSubviews([voucherCodeStackView, buttonsStackView]) {
voucherCodeStackView.pinEdgesToSuperview(.all().excluding(.bottom))
buttonsStackView.pinEdgesToSuperview(PinnableEdges([.leading(.zero), .trailing(.zero)]))
voucherCodeStackView.bottomAnchor.constraint(
lessThanOrEqualTo: buttonsStackView.topAnchor,
constant: -UIMetrics.padding16
)
}
bottomsOfButtonsConstraint = buttonsStackView.pinEdgesToSuperview(PinnableEdges([.bottom(.zero)])).first
bottomsOfButtonsConstraint?.isActive = true
}
private func addButtonHandlers() {
cancelButton.addTarget(
self,
action: #selector(cancelButtonTapped),
for: .touchUpInside
)
redeemButton.addTarget(
self,
action: #selector(redeemButtonTapped),
for: .touchUpInside
)
}
private func updateUI() {
if isLoading {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
redeemButton.isEnabled = isRedeemButtonEnabled && textField.isVoucherLengthSatisfied
statusLabel.text = text
statusLabel.textColor = textColor
logoutViewForAccountNumberIsEntered.isLoading = isLoading
}
private func addObservers() {
NotificationCenter.default.addObserver(
self,
selector: #selector(textDidChange),
name: UITextField.textDidChangeNotification,
object: textField
)
}
@objc private func cancelButtonTapped(_ sender: AppButton) {
cancelAction?()
}
@objc private func redeemButtonTapped(_ sender: AppButton) {
let code = textField.parsedToken
guard !code.isEmpty else {
return
}
redeemAction?(code)
}
@objc private func textDidChange() {
if textField.parsedToken.isEmpty {
isLogoutDialogHidden = true
}
updateUI()
}
private func addKeyboardResponderIfNeeded() {
guard configuration.adjustViewWhenKeyboardAppears else { return }
keyboardResponder = AutomaticKeyboardResponder(
targetView: self,
handler: { [weak self] _, offset in
guard let self else { return }
self.bottomsOfButtonsConstraint?.constant = isEditing ? -offset : 0
self.layoutIfNeeded()
}
)
}
}
private extension REST.Error {
var description: String {
if compareErrorCode(.invalidVoucher) {
return NSLocalizedString("Voucher code is invalid.", comment: "")
} else if compareErrorCode(.usedVoucher) {
return NSLocalizedString("Voucher code has already been used.", comment: "")
}
return displayErrorDescription ?? ""
}
}
|