aboutsummaryrefslogtreecommitdiff
path: root/DomainDig/DomainDigUI.swift
blob: 9c63e73e03ec81b262fdff918f2f13afe1761ae7 (plain) (blame)
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import SwiftUI

#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif

enum AppDensity: String, CaseIterable, Identifiable {
    case compact
    case comfortable

    static let userDefaultsKey = "appDensity"

    var id: String { rawValue }

    var title: String {
        switch self {
        case .compact:
            return "Compact"
        case .comfortable:
            return "Comfortable"
        }
    }

    var metrics: AppDensityMetrics {
        switch self {
        case .compact:
            return AppDensityMetrics(
                sectionSpacing: 14,
                cardSpacing: 6,
                cardPadding: 10,
                rowSpacing: 4,
                rowMinHeight: 30,
                controlVerticalPadding: 10,
                controlMinHeight: 42,
                cardCornerRadius: 10
            )
        case .comfortable:
            return AppDensityMetrics(
                sectionSpacing: 18,
                cardSpacing: 10,
                cardPadding: 14,
                rowSpacing: 7,
                rowMinHeight: 38,
                controlVerticalPadding: 14,
                controlMinHeight: 48,
                cardCornerRadius: 14
            )
        }
    }

    func font(_ textStyle: Font.TextStyle, design: Font.Design = .monospaced, weight: Font.Weight? = nil) -> Font {
        var font = Font.system(textStyle, design: design)
        if let weight {
            font = font.weight(weight)
        }
        return font
    }
}

struct AppDensityMetrics: Equatable {
    let sectionSpacing: CGFloat
    let cardSpacing: CGFloat
    let cardPadding: CGFloat
    let rowSpacing: CGFloat
    let rowMinHeight: CGFloat
    let controlVerticalPadding: CGFloat
    let controlMinHeight: CGFloat
    let cardCornerRadius: CGFloat
}

private struct AppDensityKey: EnvironmentKey {
    static let defaultValue: AppDensity = .compact
}

extension EnvironmentValues {
    var appDensity: AppDensity {
        get { self[AppDensityKey.self] }
        set { self[AppDensityKey.self] = newValue }
    }
}

struct AppStatusBadgeModel: Equatable {
    let title: String
    let systemImage: String?
    let foregroundColor: Color
    let backgroundColor: Color
}

enum AppStatusFactory {
    static func availability(_ status: DomainAvailabilityStatus?) -> AppStatusBadgeModel {
        switch status {
        case .available:
            return .init(title: "Available", systemImage: "checkmark.circle.fill", foregroundColor: Color(.statusPositive), backgroundColor: Color(.statusPositive).opacity(0.16))
        case .registered:
            return .init(title: "Registered", systemImage: "circle.fill", foregroundColor: Color(.statusWarning), backgroundColor: Color(.statusWarning).opacity(0.16))
        case .unknown, .none:
            return .init(title: "Unknown", systemImage: "questionmark.circle", foregroundColor: .secondary, backgroundColor: Color(.appSurfaceElevated))
        }
    }

    static func tls(sslInfo: SSLCertificateInfo?, error: String?) -> AppStatusBadgeModel {
        if error != nil || sslInfo == nil {
            return .init(title: "Invalid", systemImage: "xmark.octagon.fill", foregroundColor: Color(.statusCritical), backgroundColor: Color(.statusCritical).opacity(0.16))
        }
        if let sslInfo, sslInfo.daysUntilExpiry <= 14 {
            return .init(title: "Expiring", systemImage: "exclamationmark.triangle.fill", foregroundColor: Color(.statusWarning), backgroundColor: Color(.statusWarning).opacity(0.16))
        }
        return .init(title: "Valid", systemImage: "lock.fill", foregroundColor: Color(.statusPositive), backgroundColor: Color(.statusPositive).opacity(0.16))
    }

    static func email(_ result: EmailSecurityResult?, error: String?) -> AppStatusBadgeModel {
        guard error == nil, let result else {
            return .init(title: "Missing", systemImage: "minus.circle", foregroundColor: .secondary, backgroundColor: Color(.appSurfaceElevated))
        }

        let foundCount = [result.spf.found, result.dmarc.found, result.dkim.found].filter { $0 }.count
        switch foundCount {
        case 3:
            return .init(title: "Secure", systemImage: "checkmark.shield.fill", foregroundColor: Color(.statusPositive), backgroundColor: Color(.statusPositive).opacity(0.16))
        case 1, 2:
            return .init(title: "Partial", systemImage: "shield.lefthalf.filled", foregroundColor: Color(.statusWarning), backgroundColor: Color(.statusWarning).opacity(0.16))
        default:
            return .init(title: "Missing", systemImage: "minus.circle", foregroundColor: .secondary, backgroundColor: Color(.appSurfaceElevated))
        }
    }

    static func change(_ summary: DomainChangeSummary?) -> AppStatusBadgeModel {
        guard let summary else {
            return .init(title: "Unchanged", systemImage: "circle", foregroundColor: .secondary, backgroundColor: Color(.appSurfaceElevated))
        }
        if summary.hasChanges {
            return .init(title: "Changed", systemImage: "arrow.triangle.2.circlepath", foregroundColor: Color(.statusInfo), backgroundColor: Color(.statusInfo).opacity(0.16))
        }
        return .init(title: "Unchanged", systemImage: "checkmark.circle", foregroundColor: .secondary, backgroundColor: Color(.appSurfaceElevated))
    }
}

struct AppStatusBadgeView: View {
    @Environment(\.appDensity) private var appDensity

    let model: AppStatusBadgeModel

    var body: some View {
        HStack(spacing: 6) {
            if let systemImage = model.systemImage {
                Image(systemName: systemImage)
                    .font(.caption2)
            }
            Text(model.title)
        }
        .font(appDensity.font(.caption, weight: .semibold))
        .foregroundStyle(model.foregroundColor)
        .padding(.horizontal, 9)
        .padding(.vertical, 5)
        .background(model.backgroundColor)
        .clipShape(Capsule())
    }
}

struct AppCopyButton: View {
    @Environment(\.appDensity) private var appDensity
    @State private var didCopy = false

    let value: String
    let label: String

    var body: some View {
        Button {
            AppClipboard.copy(value)
            AppHaptics.copy()
            withAnimation(.easeInOut(duration: 0.18)) {
                didCopy = true
            }
            Task {
                try? await Task.sleep(nanoseconds: 900_000_000)
                await MainActor.run {
                    withAnimation(.easeInOut(duration: 0.18)) {
                        didCopy = false
                    }
                }
            }
        } label: {
            Image(systemName: didCopy ? "checkmark" : "doc.on.doc")
                .font(appDensity.font(.caption))
                .foregroundStyle(didCopy ? Color(.statusPositive) : .secondary)
                .frame(width: 30, height: 30)
                .background(Color(.appSurfaceElevated))
                .clipShape(RoundedRectangle(cornerRadius: 8))
        }
        .buttonStyle(.plain)
        .accessibilityLabel(didCopy ? "\(label) copied" : label)
    }
}

enum AppClipboard {
    static func copy(_ value: String) {
        #if canImport(UIKit)
        UIPasteboard.general.string = value
        #elseif canImport(AppKit)
        NSPasteboard.general.clearContents()
        NSPasteboard.general.setString(value, forType: .string)
        #endif
    }
}

enum AppHaptics {
    static func copy() {
        #if canImport(UIKit)
        let generator = UINotificationFeedbackGenerator()
        generator.notificationOccurred(.success)
        #endif
    }

    static func refresh() {
        #if canImport(UIKit)
        let generator = UIImpactFeedbackGenerator(style: .light)
        generator.impactOccurred()
        #endif
    }

    static func track() {
        #if canImport(UIKit)
        let generator = UIImpactFeedbackGenerator(style: .soft)
        generator.impactOccurred()
        #endif
    }
}

struct EmptyStateCardView: View {
    @Environment(\.appDensity) private var appDensity

    let title: String
    let message: String
    let suggestion: String
    let systemImage: String
    let showsCardBackground: Bool

    init(
        title: String,
        message: String,
        suggestion: String,
        systemImage: String,
        showsCardBackground: Bool = true
    ) {
        self.title = title
        self.message = message
        self.suggestion = suggestion
        self.systemImage = systemImage
        self.showsCardBackground = showsCardBackground
    }

    var body: some View {
        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
            Label(title, systemImage: systemImage)
                .font(appDensity.font(.headline, weight: .semibold))
                .foregroundStyle(.primary)

            Text(message)
                .font(appDensity.font(.body))
                .foregroundStyle(.secondary)
                .fixedSize(horizontal: false, vertical: true)

            Text(suggestion)
                .font(appDensity.font(.caption))
                .foregroundStyle(Color(.statusInfo))
        }
        .frame(maxWidth: .infinity, alignment: .leading)
        .padding(appDensity.metrics.cardPadding)
        .background(showsCardBackground ? Color(.appSurface) : Color.clear)
        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
    }
}

struct CollapsibleSectionView<HeaderTrailing: View, Content: View>: View {
    @Environment(\.appDensity) private var appDensity

    let title: String
    @Binding var isCollapsed: Bool
    let subtitle: String?
    @ViewBuilder let trailing: () -> HeaderTrailing
    @ViewBuilder let content: () -> Content

    init(
        title: String,
        isCollapsed: Binding<Bool>,
        subtitle: String? = nil,
        @ViewBuilder trailing: @escaping () -> HeaderTrailing = { EmptyView() },
        @ViewBuilder content: @escaping () -> Content
    ) {
        self.title = title
        self._isCollapsed = isCollapsed
        self.subtitle = subtitle
        self.trailing = trailing
        self.content = content
    }

    var body: some View {
        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
            Button {
                withAnimation(.easeInOut(duration: 0.2)) {
                    isCollapsed.toggle()
                }
            } label: {
                HStack(alignment: .center, spacing: 10) {
                    VStack(alignment: .leading, spacing: 3) {
                        Text(title)
                            .font(appDensity.font(.headline, design: .default, weight: .semibold))
                            .foregroundStyle(.primary)
                        if let subtitle {
                            Text(subtitle)
                                .font(appDensity.font(.caption))
                                .foregroundStyle(.secondary)
                        }
                    }
                    Spacer(minLength: 8)
                    trailing()
                    Image(systemName: isCollapsed ? "chevron.down" : "chevron.up")
                        .font(.caption.weight(.semibold))
                        .foregroundStyle(.secondary)
                }
                .contentShape(Rectangle())
                .frame(minHeight: appDensity.metrics.controlMinHeight, alignment: .center)
            }
            .buttonStyle(.plain)

            if !isCollapsed {
                content()
                    .transition(.opacity.combined(with: .move(edge: .top)))
            }
        }
    }
}

/// A horizontally scrolling row of read-only tag chips, e.g. for a tracked
/// domain's detail view.
struct TagChipRowView: View {
    let tags: [String]

    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 8) {
                ForEach(tags, id: \.self) { tag in
                    Text(tag)
                        .font(.caption)
                        .padding(.horizontal, 10)
                        .padding(.vertical, 5)
                        .background(Color(.appSurfaceElevated), in: Capsule())
                }
            }
        }
    }
}

/// A horizontally scrolling row of selectable tag chips used to filter a list,
/// with an "All" chip to clear the selection.
struct TagFilterChipRowView: View {
    let tags: [String]
    @Binding var selection: String?

    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 8) {
                filterChip(title: "All", isSelected: selection == nil) {
                    selection = nil
                }
                ForEach(tags, id: \.self) { tag in
                    filterChip(title: tag, isSelected: selection == tag) {
                        selection = (selection == tag) ? nil : tag
                    }
                }
            }
        }
    }

    private func filterChip(title: String, isSelected: Bool, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            Text(title)
                .font(.caption)
                .padding(.horizontal, 10)
                .padding(.vertical, 5)
                .background(isSelected ? Color(.statusInfo).opacity(0.3) : Color(.appSurfaceElevated), in: Capsule())
                .foregroundStyle(isSelected ? Color(.statusInfo) : Color.primary)
        }
        .buttonStyle(.plain)
    }
}