summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/View controllers/SelectLocation/LocationDataSourceProtocol.swift
blob: 8227cae41e11d0836060da906578afcccb1308a5 (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
//
//  LocationDataSourceProtocol.swift
//  MullvadVPN
//
//  Created by Mojgan on 2024-02-07.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import Foundation
import MullvadREST
import MullvadTypes

protocol LocationDataSourceProtocol {
    var nodes: [LocationNode] { get }
    var searchableNodes: [LocationNode] { get }
}

extension LocationDataSourceProtocol {
    func search(by text: String) -> [LocationNode] {
        guard !text.isEmpty else {
            return nodes
        }

        var filteredNodes: [LocationNode] = []

        searchableNodes.forEach { node in
            // Use a copy of the node to preserve the expanded state,
            // allowing us to restore the previous view state after a search.
            let countryNode = node.copy()

            countryNode.showsChildren = false

            if countryNode.name.fuzzyMatch(text) {
                filteredNodes.append(countryNode)
            }

            countryNode.children.forEach { cityNode in
                cityNode.showsChildren = false
                cityNode.isHiddenFromSearch = true

                var relaysContainSearchString = false
                cityNode.children.forEach { hostNode in
                    hostNode.isHiddenFromSearch = true

                    if hostNode.name.fuzzyMatch(text) {
                        relaysContainSearchString = true
                        hostNode.isHiddenFromSearch = false
                    }
                }

                if cityNode.name.fuzzyMatch(text) || relaysContainSearchString {
                    if !filteredNodes.contains(countryNode) {
                        filteredNodes.append(countryNode)
                    }

                    countryNode.showsChildren = true
                    cityNode.isHiddenFromSearch = false

                    if relaysContainSearchString {
                        cityNode.showsChildren = true
                    }
                }
            }
        }

        return filteredNodes
    }
}