summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/View controllers/RedeemVoucher/VoucherTextField.swift
blob: 4092aa5805900f3fe2b842d374bdc30a354bc079 (plain)
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
//
//  VoucherTextField.swift
//  MullvadVPN
//
//  Created by Andreas Lif on 2022-08-05.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import Foundation
import UIKit

class VoucherTextField: CustomTextField, UITextFieldDelegate {
    private let inputFormatter = InputTextFormatter(
        configuration: InputTextFormatter.Configuration(
            allowedInput: .alphanumeric(isUpperCase: true),
            groupSeparator: "-",
            groupSize: 4,
            maxGroups: 4
        ))

    private var voucherLength: UInt8 {
        let maxGroups = inputFormatter.configuration.maxGroups
        let groupSize = inputFormatter.configuration.groupSize
        return maxGroups * groupSize + (maxGroups - 1)
    }

    var parsedToken: String {
        inputFormatter.string
    }

    var isVoucherLengthSatisfied: Bool {
        let length = text?.count ?? 0
        return length >= voucherLength
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        delegate = self
        autocorrectionType = .no
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(captureTextFromCamera(_:)) { return false }
        return super.canPerformAction(action, withSender: sender)
    }

    // MARK: - UITextFieldDelegate

    func textField(
        _ textField: UITextField,
        shouldChangeCharactersIn range: NSRange,
        replacementString string: String
    ) -> Bool {
        inputFormatter.textField(
            textField,
            shouldChangeCharactersIn: range,
            replacementString: string
        )
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}