summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/SelectLocationViewController.swift
blob: d4ebeacaf827b1cbb5bbe218787c75ac57bc78e6 (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
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
//
//  SelectLocationViewController.swift
//  MullvadVPN
//
//  Created by pronebird on 02/05/2019.
//  Copyright © 2019 Mullvad VPN AB. All rights reserved.
//

import MullvadLogging
import MullvadTypes
import RelayCache
import UIKit

protocol SelectLocationViewControllerDelegate: AnyObject {
    func selectLocationViewController(
        _ controller: SelectLocationViewController,
        didSelectRelayLocation relayLocation: RelayLocation
    )
}

class SelectLocationViewController: UIViewController, UITableViewDelegate {
    static let cellReuseIdentifier = "Cell"

    private var tableView: UITableView?

    private let tableHeaderFooterView = SelectLocationHeaderView()
    private var tableHeaderFooterViewTopConstraints: [NSLayoutConstraint] = []
    private var tableHeaderFooterViewBottomConstraints: [NSLayoutConstraint] = []

    private var dataSource: LocationDataSource?
    private var setCachedRelaysOnViewDidLoad: CachedRelays?
    private var setRelayLocationOnViewDidLoad: RelayLocation?
    private var setScrollPositionOnViewDidLoad: UITableView.ScrollPosition = .none
    private var isViewAppeared = false

    private var showHeaderViewAtTheBottom = false {
        didSet {
            setTableHeaderFooterConstraints()
        }
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    weak var delegate: SelectLocationViewControllerDelegate?
    var scrollToSelectedRelayOnViewWillAppear = true

    init() {
        super.init(nibName: nil, bundle: nil)
    }

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

    // MARK: - View lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.largeTitleDisplayMode = .never
        navigationItem.title = NSLocalizedString(
            "NAVIGATION_TITLE",
            tableName: "SelectLocation",
            value: "Select Location",
            comment: ""
        )

        let tableView = UITableView(frame: view.bounds, style: .plain)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.backgroundColor = .clear
        tableView.separatorColor = .secondaryColor
        tableView.separatorInset = .zero
        tableView.estimatedRowHeight = 53
        tableView.indicatorStyle = .white

        tableView.register(
            SelectLocationCell.self,
            forCellReuseIdentifier: Self.cellReuseIdentifier
        )

        self.tableView = tableView

        view.accessibilityElements = [tableHeaderFooterView, tableView]
        view.backgroundColor = .secondaryColor
        view.addSubview(tableView)

        tableHeaderFooterView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(tableHeaderFooterView)

        dataSource = LocationDataSource(
            tableView: tableView,
            cellProvider: { tableView, indexPath, item in
                return tableView.dequeueReusableCell(
                    withIdentifier: Self.cellReuseIdentifier,
                    for: indexPath
                )
            },
            cellConfigurator: { [weak self] cell, indexPath, item in
                guard let cell = cell as? SelectLocationCell else { return }

                cell.accessibilityIdentifier = item.location.stringRepresentation
                cell.isDisabled = !item.isActive
                cell.locationLabel.text = item.displayName
                cell.showsCollapseControl = item.isCollapsible
                cell.isExpanded = item.showsChildren
                cell.didCollapseHandler = { [weak self] cell in
                    self?.collapseCell(cell)
                }
            }
        )

        tableView.delegate = self
        tableView.dataSource = dataSource

        tableHeaderFooterViewTopConstraints = [
            tableHeaderFooterView.topAnchor.constraint(equalTo: view.topAnchor),
            tableView.topAnchor.constraint(equalTo: tableHeaderFooterView.bottomAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ]
        tableHeaderFooterViewBottomConstraints = [
            tableHeaderFooterView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            tableView.topAnchor.constraint(equalTo: view.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: tableHeaderFooterView.topAnchor),
        ]

        NSLayoutConstraint.activate([
            tableHeaderFooterView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableHeaderFooterView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        ])
        setTableHeaderFooterConstraints()

        if let setCachedRelaysOnViewDidLoad = setCachedRelaysOnViewDidLoad {
            dataSource?.setRelays(setCachedRelaysOnViewDidLoad.relays)
        }

        if let setRelayLocationOnViewDidLoad = setRelayLocationOnViewDidLoad {
            dataSource?.setSelectedRelayLocation(
                setRelayLocationOnViewDidLoad,
                showHiddenParents: true,
                animated: false,
                scrollPosition: setScrollPositionOnViewDidLoad
            )
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Show header view at the bottom when controller is presented inline and show header view
        // at the top of the view when controller is presented modally.
        showHeaderViewAtTheBottom = presentingViewController == nil

        if let indexPath = dataSource?.indexPathForSelectedRelay(),
           scrollToSelectedRelayOnViewWillAppear, !isViewAppeared
        {
            tableView?.scrollToRow(at: indexPath, at: .middle, animated: false)
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        isViewAppeared = true

        tableView?.flashScrollIndicators()
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)

        isViewAppeared = false
    }

    override func viewWillTransition(
        to size: CGSize,
        with coordinator: UIViewControllerTransitionCoordinator
    ) {
        super.viewWillTransition(to: size, with: coordinator)

        coordinator.animate { context in
            if let indexPath = self.dataSource?.indexPathForSelectedRelay() {
                self.tableView?.scrollToRow(at: indexPath, at: .middle, animated: false)
            }
        }
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        updateTableHeaderTopLayoutMargin()
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
        return dataSource?.item(for: indexPath)?.isActive ?? false
    }

    func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
        return dataSource?.item(for: indexPath)?.indentationLevel ?? 0
    }

    func tableView(
        _ tableView: UITableView,
        willDisplay cell: UITableViewCell,
        forRowAt indexPath: IndexPath
    ) {
        if let item = dataSource?.item(for: indexPath),
           item.location == dataSource?.selectedRelayLocation
        {
            cell.setSelected(true, animated: false)
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let item = dataSource?.item(for: indexPath) else { return }

        dataSource?.setSelectedRelayLocation(
            item.location,
            showHiddenParents: false,
            animated: false,
            scrollPosition: .none
        )

        delegate?.selectLocationViewController(self, didSelectRelayLocation: item.location)
    }

    // MARK: - Public

    func setCachedRelays(_ cachedRelays: CachedRelays) {
        guard isViewLoaded else {
            setCachedRelaysOnViewDidLoad = cachedRelays
            return
        }
        dataSource?.setRelays(cachedRelays.relays)
    }

    func setSelectedRelayLocation(
        _ relayLocation: RelayLocation?,
        animated: Bool,
        scrollPosition: UITableView.ScrollPosition
    ) {
        guard isViewLoaded else {
            setRelayLocationOnViewDidLoad = relayLocation
            setScrollPositionOnViewDidLoad = scrollPosition
            return
        }

        dataSource?.setSelectedRelayLocation(
            relayLocation,
            showHiddenParents: true,
            animated: animated,
            scrollPosition: scrollPosition
        )
    }

    // MARK: - Collapsible cells

    private func collapseCell(_ cell: SelectLocationCell) {
        guard let cellIndexPath = tableView?.indexPath(for: cell),
              let dataSource = dataSource,
              let location = dataSource.relayLocation(for: cellIndexPath)
        else {
            return
        }

        dataSource.toggleChildren(location, animated: true)
    }

    // MARK: - Private

    private func updateTableHeaderTopLayoutMargin() {
        // When contained within the navigation controller, we want the distance between
        // the navigation title and the table header label to be exactly 24pt.
        if let navigationBar = navigationController?.navigationBar as? CustomNavigationBar,
           !showHeaderViewAtTheBottom
        {
            tableHeaderFooterView.topLayoutMarginAdjustmentForNavigationBarTitle = navigationBar
                .titleLabelBottomInset
        } else {
            tableHeaderFooterView.topLayoutMarginAdjustmentForNavigationBarTitle = 0
        }
    }

    private func setTableHeaderFooterConstraints() {
        if showHeaderViewAtTheBottom {
            NSLayoutConstraint.deactivate(
                tableHeaderFooterViewTopConstraints
            )
            NSLayoutConstraint.activate(tableHeaderFooterViewBottomConstraints)
        } else {
            NSLayoutConstraint.deactivate(
                tableHeaderFooterViewBottomConstraints
            )
            NSLayoutConstraint.activate(tableHeaderFooterViewTopConstraints)
        }
        view.layoutIfNeeded()
    }
}