summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/Extensions/UIView+AutoLayoutBuilder.swift
blob: c13a4ee8ab9d5e1de86c7ba747e843a78d0b35dc (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
//
//  UIView+AutoLayoutBuilder.swift
//  MullvadVPN
//
//  Created by pronebird on 24/03/2023.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import UIKit

/**
 Protocol that describes common AutoLayout properties of `UIView` and `UILayoutGuide` and helps to remove distinction
 between two of them when creating constraints.
 */
protocol AutoLayoutAnchorsProtocol {
    var topAnchor: NSLayoutYAxisAnchor { get }
    var bottomAnchor: NSLayoutYAxisAnchor { get }
    var leadingAnchor: NSLayoutXAxisAnchor { get }
    var trailingAnchor: NSLayoutXAxisAnchor { get }
}

extension UIView: @preconcurrency AutoLayoutAnchorsProtocol {}
extension UILayoutGuide: @preconcurrency AutoLayoutAnchorsProtocol {}

extension UIView {
    /**
     Pin all edges to edges of other view.
     */
    func pinEdgesTo(_ other: AutoLayoutAnchorsProtocol) -> [NSLayoutConstraint] {
        pinEdges(.all(), to: other)
    }

    /**
     Pin edges to edges of other view.
     */
    func pinEdges(_ edges: PinnableEdges, to other: AutoLayoutAnchorsProtocol) -> [NSLayoutConstraint] {
        edges.makeConstraints(firstView: self, secondView: other)
    }

    /**
     Pin edges to superview edges.
     */
    func pinEdgesToSuperview(_ edges: PinnableEdges = .all()) -> [NSLayoutConstraint] {
        guard let superview else { return [] }

        return pinEdges(edges, to: superview)
    }

    /**
     Pin edges to superview margins.
     */
    func pinEdgesToSuperviewMargins(_ edges: PinnableEdges = .all()) -> [NSLayoutConstraint] {
        guard let superview else { return [] }

        return pinEdges(edges, to: superview.layoutMarginsGuide)
    }

    /**
     Pin single edge to superview edge.
     */
    func pinEdgeToSuperview(_ edge: PinnableEdges.Edge) -> [NSLayoutConstraint] {
        guard let superview else { return [] }

        return pinEdges(PinnableEdges([edge]), to: superview)
    }

    /**
     Pin single edge to superview margin edge.
     */
    func pinEdgeToSuperviewMargin(_ edge: PinnableEdges.Edge) -> [NSLayoutConstraint] {
        guard let superview else { return [] }

        return pinEdges(PinnableEdges([edge]), to: superview.layoutMarginsGuide)
    }
}

/**
 AutoLayout builder.

 Use it in conjunction with `NSLayoutConstraint.activate()`, for example:

 ```
 let view = UIView()
 let subview = UIView()

 subview.translatesAutoresizingMaskIntoConstraints = false

 view.addSubview(subview)

 NSLayoutConstraint.activate {
    // Pin top, leading and trailing edges to superview.
    subview.pinEdgesToSuperview(.init([.top(8), .leading(16), .trailing(8)]))

    // Pin bottom to safe area layout guide.
    subview.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
 }
 ```
 */
@resultBuilder enum AutoLayoutBuilder {
    static func buildBlock(_ components: [NSLayoutConstraint]...) -> [NSLayoutConstraint] {
        components.flatMap { $0 }
    }

    static func buildExpression(_ expression: NSLayoutConstraint) -> [NSLayoutConstraint] {
        [expression]
    }

    static func buildExpression(_ expression: [NSLayoutConstraint]) -> [NSLayoutConstraint] {
        expression
    }

    static func buildOptional(_ components: [NSLayoutConstraint]?) -> [NSLayoutConstraint] {
        components ?? []
    }

    static func buildEither(first components: [NSLayoutConstraint]) -> [NSLayoutConstraint] {
        components
    }

    static func buildEither(second components: [NSLayoutConstraint]) -> [NSLayoutConstraint] {
        components
    }

    static func buildArray(_ components: [[NSLayoutConstraint]]) -> [NSLayoutConstraint] {
        components.flatMap { $0 }
    }
}

extension NSLayoutConstraint {
    /**
     Activate constraints produced by a builder.
     */
    static func activate(@AutoLayoutBuilder builder: () -> [NSLayoutConstraint]) {
        activate(builder())
    }
}

extension UIView {
    /**
     Add subviews using AutoLayout and configure constraints.
     */
    @MainActor
    func addConstrainedSubviews(
        _ subviews: [UIView],
        @AutoLayoutBuilder builder: () -> [NSLayoutConstraint]
    ) {
        for subview in subviews {
            subview.configureForAutoLayout()
            addSubview(subview)
        }

        NSLayoutConstraint.activate(builder())
    }

    /**
     Add subviews using AutoLayout without configuring constraints.
     */
    func addConstrainedSubviews(_ subviews: [UIView]) {
        addConstrainedSubviews(subviews) {}
    }

    /**
     Configure view for AutoLayout by disabling automatic autoresizing mask translation into
     constraints.
     */
    func configureForAutoLayout() {
        translatesAutoresizingMaskIntoConstraints = false
    }
}

/**
 Struct describing a relationship between AutoLayout anchors.
 */
struct PinnableEdges {
    /**
     Enum describing each inidividual edge with associated inset value.
     */
    enum Edge: Hashable {
        case top(CGFloat)
        case bottom(CGFloat)
        case leading(CGFloat)
        case trailing(CGFloat)

        var rectEdge: NSDirectionalRectEdge {
            switch self {
            case .top:
                return .top
            case .bottom:
                return .bottom
            case .leading:
                return .leading
            case .trailing:
                return .trailing
            }
        }

        func hash(into hasher: inout Hasher) {
            hasher.combine(rectEdge.rawValue)
        }

        static func == (lhs: Self, rhs: Self) -> Bool {
            lhs.rectEdge == rhs.rectEdge
        }

        @MainActor
        func makeConstraint(
            firstView: AutoLayoutAnchorsProtocol,
            secondView: AutoLayoutAnchorsProtocol
        ) -> NSLayoutConstraint {
            switch self {
            case let .top(inset):
                return firstView.topAnchor.constraint(equalTo: secondView.topAnchor, constant: inset)

            case let .bottom(inset):
                return firstView.bottomAnchor.constraint(equalTo: secondView.bottomAnchor, constant: -inset)

            case let .leading(inset):
                return firstView.leadingAnchor.constraint(equalTo: secondView.leadingAnchor, constant: inset)

            case let .trailing(inset):
                return firstView.trailingAnchor.constraint(equalTo: secondView.trailingAnchor, constant: -inset)
            }
        }
    }

    /**
     Inner set of `Edge` objects.
     */
    var inner: Set<Edge>

    /**
     Designated initializer.
     */
    init(_ edges: Set<Edge>) {
        inner = edges
    }

    /**
     Returns new `PinnableEdges` with the given edge(s) excluded.
     */
    func excluding(_ excludeEdges: NSDirectionalRectEdge) -> Self {
        Self(inner.filter { !excludeEdges.contains($0.rectEdge) })
    }

    /**
     Returns new `PinnableEdges` initialized with four edges and corresponding insets from
     `NSDirectionalEdgeInsets`.
     */
    static func all(_ directionalEdgeInsets: NSDirectionalEdgeInsets = .zero) -> Self {
        Self([
            .top(directionalEdgeInsets.top),
            .bottom(directionalEdgeInsets.bottom),
            .leading(directionalEdgeInsets.leading),
            .trailing(directionalEdgeInsets.trailing),
        ])
    }

    /**
     Returns new constraints pinning edges of the corresponding views.
     */
    @MainActor
    func makeConstraints(
        firstView: AutoLayoutAnchorsProtocol,
        secondView: AutoLayoutAnchorsProtocol
    ) -> [NSLayoutConstraint] {
        inner.map { $0.makeConstraint(firstView: firstView, secondView: secondView) }
    }
}