-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathDomainListSaveable.swift
96 lines (82 loc) · 3.25 KB
/
DomainListSaveable.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
//
// DomainListSaveable.swift
// Lockdown
//
// Created by Pavel Vilbik on 23.06.23.
// Copyright © 2023 Confirmed Inc. All rights reserved.
//
import UIKit
protocol DomainListSaveable {
func showCreateList(
initialListName: String?,
forDomainList domains: Set<String>,
completion: @escaping (Set<String>, String) -> Void
)
}
extension DomainListSaveable where Self: UIViewController {
func showCreateList(
initialListName: String?,
forDomainList domains: Set<String>,
completion: @escaping (Set<String>, String) -> Void
) {
let alertController = UIAlertController(title: "Create New List", message: nil, preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save", style: .default) { [weak self] (_) in
if let txtField = alertController.textFields?.first, let text = txtField.text {
self?.validateListName(text, forDomainList: domains, completion: completion)
}
}
saveAction.isEnabled = false
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { [weak self] (_) in
guard let self else { return }
self.dismiss(animated: true)
}
alertController.addTextField { (textField) in
textField.text = initialListName
textField.placeholder = NSLocalizedString("List Name", comment: "")
}
NotificationCenter.default.addObserver(
forName: UITextField.textDidChangeNotification,
object: alertController.textFields?.first,
queue: .main) { (notification) -> Void in
guard let textFieldText = alertController.textFields?.first?.text else { return }
saveAction.isEnabled = textFieldText.isValid(.listName)
}
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
private func validateListName(
_ name: String,
forDomainList domains: Set<String>,
completion: @escaping (Set<String>, String) -> Void
) {
guard !getBlockedLists().userBlockListsDefaults.keys.contains(name) else {
showAlertAboutExistingListName { [weak self] in
self?.showCreateList(
initialListName: name,
forDomainList: domains,
completion: completion
)
}
return
}
completion(domains, name)
}
private func showAlertAboutExistingListName(completion: @escaping () -> Void) {
let alertController = UIAlertController(
title: NSLocalizedString("This list name is already exist!", comment: ""),
message: NSLocalizedString("Please choose another name.", comment: ""),
preferredStyle: .alert
)
alertController.addAction(
.init(
title: NSLocalizedString("Ok", comment: ""),
style: .default,
handler: { _ in
completion()
}
)
)
present(alertController, animated: true)
}
}