DomainDig/SectionState.swift
56 lines · 2328 bytes
1import Foundation
2
3/// One inspection section's state as a single value.
4///
5/// Each section used to be three independent stored properties — a value, a
6/// `*Loading` flag and a `*Error` string. There were 20 flags and 19 error
7/// strings (A2), and nothing tied each trio together: a section could be left
8/// loading forever because one of three assignments was missed, or report an
9/// error while still claiming to load.
10///
11/// Deliberately **not** an exclusive `loaded | failed` enum, which is what A2
12/// proposed. A section really can have both: the TLS card renders a stale
13/// certificate next to a handshake error, and `AppStatusFactory.tls` takes
14/// `sslInfo` and `error` together. An enum would have to drop one of them.
15/// `SectionStateTests.testAnErrorAndAValueTogetherKeepBothReachable` pins that.
16///
17/// Whether a section is still moving. Declared outside `SectionState` so one
18/// value can be applied across sections holding different value types.
19enum SectionPhase {
20 /// Not started, or cleared because a new lookup began.
21 case idle
22 /// In flight.
23 case loading
24 /// Finished, with a value, an error, or both.
25 case settled
26}
27
28/// One inspection section's state as a single value: see `SectionPhase` above
29/// for the phases. What this fixes is that the value, the phase and the error
30/// travel together, so they are written as one or not at all.
31struct SectionState<Value> {
32 var phase: SectionPhase = .idle
33 var value: Value?
34 var error: String?
35
36 var isLoading: Bool { phase == .loading }
37
38 /// Finished moving, either way. `resultsLoaded` used to ask fifteen
39 /// separate loading flags this question.
40 var isSettled: Bool { phase == .settled }
41
42 static var idle: Self { Self() }
43 static var loading: Self { Self(phase: .loading) }
44
45 /// Finished with whatever the lookup produced. Both arguments are optional
46 /// because a snapshot carries them independently.
47 static func settled(value: Value?, error: String? = nil) -> Self {
48 Self(phase: .settled, value: value, error: error)
49 }
50}
51
52extension SectionState where Value: ExpressibleByArrayLiteral {
53 /// The value, or an empty collection — what the row builders want, rather
54 /// than an optional they would immediately coalesce.
55 var items: Value { value ?? [] }
56}