Repository Public
1// Building blocks shared by the screens of the app (macOS and iOS).2import CoreImage.CIFilterBuiltins3import SharedVaultKit4import SwiftUI56// ── page scaffold for tool pages (Security Center, Devices, Activity, …) ──78/// A scrolling page with a serif title, used for every tool page in the detail column (macOS / iPad) or pushed in9/// a navigation stack (iPhone). Content is laid out in a readable column.10struct ToolPage<Content: View, Actions: View>: View {11 let title: String12 var subtitle: String?13 @ViewBuilder var actions: () -> Actions14 @ViewBuilder var content: () -> Content1516 init(_ title: String, subtitle: String? = nil, @ViewBuilder actions: @escaping () -> Actions = { EmptyView() }, @ViewBuilder content: @escaping () -> Content) {17 self.title = title; self.subtitle = subtitle; self.actions = actions; self.content = content18 }1920 var body: some View {21 ScrollView {22 VStack(alignment: .leading, spacing: 18) {23 HStack(alignment: .firstTextBaseline, spacing: 12) {24 VStack(alignment: .leading, spacing: 4) {25 Text(title).font(.vaultLargeTitle).foregroundStyle(Palette.text).accessibilityAddTraits(.isHeader)26 if let subtitle { Text(subtitle).font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true) }27 }28 Spacer(minLength: 8)29 actions()30 }31 content()32 }33 .frame(maxWidth: 760, alignment: .leading)34 .padding(.horizontal, pagePadding).padding(.vertical, 22)35 .frame(maxWidth: .infinity, alignment: .center)36 }37 .scrollContentBackground(.hidden)38 .vaultBackground()39 #if os(iOS)40 .navigationBarTitleDisplayMode(.inline)41 #endif42 }4344 private var pagePadding: CGFloat {45 #if os(macOS)46 2847 #else48 1849 #endif50 }51}5253/// A titled group of rows inside a card.54struct SectionCard<Content: View, Trailing: View>: View {55 var title: String?56 var footer: String?57 @ViewBuilder var trailing: () -> Trailing58 @ViewBuilder var content: () -> Content5960 init(_ title: String? = nil, footer: String? = nil, @ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() }, @ViewBuilder content: @escaping () -> Content) {61 self.title = title; self.footer = footer; self.trailing = trailing; self.content = content62 }6364 var body: some View {65 VStack(alignment: .leading, spacing: 8) {66 if title != nil || Trailing.self != EmptyView.self {67 HStack(alignment: .center) {68 if let title { Eyebrow(title) }69 Spacer(minLength: 8)70 trailing()71 }72 }73 VStack(alignment: .leading, spacing: 0) { content() }.vaultCard()74 if let footer { Text(footer).font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true) }75 }76 }77}7879/// One row of a `SectionCard`: padding and a hairline below (hidden on the last row with `.last`).80struct CardRow<Content: View>: View {81 var last = false82 @ViewBuilder var content: () -> Content83 var body: some View {84 VStack(spacing: 0) {85 content().padding(.horizontal, Metrics.rowPadding).padding(.vertical, 11).frame(maxWidth: .infinity, alignment: .leading)86 if !last { Rectangle().fill(Palette.line).frame(height: 1) }87 }88 }89}9091struct EmptyState: View {92 let symbol: String93 let title: String94 var text: String?95 var body: some View {96 VStack(spacing: 10) {97 Image(systemName: symbol).font(.system(size: 34, weight: .light)).foregroundStyle(Palette.muted.opacity(0.7)).accessibilityHidden(true)98 Text(title).font(.vaultHeadline).foregroundStyle(Palette.text)99 if let text { Text(text).font(.callout).foregroundStyle(Palette.muted).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true) }100 }101 .frame(maxWidth: 340).padding(24).frame(maxWidth: .infinity, maxHeight: .infinity)102 .accessibilityElement(children: .combine)103 }104}105106// ── toasts ──107108struct ToastOverlay: ViewModifier {109 @Environment(AppModel.self) private var model110 func body(content: Content) -> some View {111 content.overlay(alignment: .bottom) {112 if let t = model.toast {113 HStack(spacing: 9) {114 Image(systemName: t.kind == .error ? "exclamationmark.triangle.fill" : (t.kind == .info ? "info.circle" : "checkmark"))115 .foregroundStyle(t.kind == .error ? Palette.danger : Palette.accent).accessibilityHidden(true)116 Text(t.text).font(.callout).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true)117 }118 .padding(.horizontal, 14).padding(.vertical, 10)119 .background(Palette.s3, in: RoundedRectangle(cornerRadius: Metrics.radius, style: .continuous))120 .overlay(RoundedRectangle(cornerRadius: Metrics.radius, style: .continuous).strokeBorder(Palette.lineStrong, lineWidth: 1))121 .shadow(color: .black.opacity(0.25), radius: 14, y: 6)122 .padding(.horizontal, 16).padding(.bottom, toastInset)123 .transition(.move(edge: .bottom).combined(with: .opacity))124 .id(t.id)125 .accessibilityElement(children: .combine)126 .accessibilityIdentifier("toast")127 .onTapGesture { model.toast = nil }128 }129 }130 .animation(.spring(duration: 0.3), value: model.toast)131 }132 private var toastInset: CGFloat {133 #if os(macOS)134 18135 #else136 70137 #endif138 }139}140141extension View {142 func toasts() -> some View { modifier(ToastOverlay()) }143}144145// ── fields ──146147/// Label above a value, with trailing actions — the row of an item detail card.148struct FieldRow<Value: View, Actions: View>: View {149 let label: String150 @ViewBuilder var value: () -> Value151 @ViewBuilder var actions: () -> Actions152 var body: some View {153 HStack(alignment: .center, spacing: 6) {154 VStack(alignment: .leading, spacing: 4) {155 Text(label).font(.caption.weight(.medium)).foregroundStyle(Palette.muted)156 value()157 }158 Spacer(minLength: 8)159 actions()160 }161 }162}163164/// A secret: masked by default, never read aloud while masked, revealed on demand, copied with an expiring clipboard.165struct SecretRow: View {166 @Environment(AppModel.self) private var model167 let label: String168 let value: String169 var multiline = false170 var testID: String = "secret"171 @State private var revealed = false172173 var body: some View {174 FieldRow(label: label) {175 Group {176 if revealed { ColoredSecret(text: value).lineLimit(multiline ? 12 : 3).accessibilityLabel("\(label), revealed") .accessibilityValue(value) }177 else { Text(String(repeating: "•", count: min(max(value.count, 8), 14))).font(.secret).foregroundStyle(Palette.muted).accessibilityLabel("\(label), hidden") }178 }179 .accessibilityIdentifier("\(testID)-value")180 } actions: {181 IconButton(systemName: revealed ? "eye.slash" : "eye", label: revealed ? "Hide \(label)" : "Reveal \(label)", tint: revealed ? Palette.accent : Palette.muted) {182 revealed.toggle(); model.touch()183 }184 .accessibilityIdentifier("\(testID)-reveal")185 IconButton(systemName: "doc.on.doc", label: "Copy \(label)") { model.copy(value, label: label) }186 .accessibilityIdentifier("\(testID)-copy")187 }188 .onChange(of: model.isUnlocked) { _, _ in revealed = false }189 }190}191192/// A plain (non-secret) value with a copy button.193struct TextValueRow: View {194 @Environment(AppModel.self) private var model195 let label: String196 let value: String197 var mono = false198 var testID: String = "field"199 var body: some View {200 FieldRow(label: label) {201 Text(value).font(mono ? .secret : .body).foregroundStyle(Palette.text).textSelection(.enabled).lineLimit(6)202 .accessibilityIdentifier("\(testID)-value")203 } actions: {204 IconButton(systemName: "doc.on.doc", label: "Copy \(label)") { model.copy(value, label: label, secret: false) }205 .accessibilityIdentifier("\(testID)-copy")206 }207 }208}209210/// Live one-time code with its countdown ring.211struct TotpRow: View {212 @Environment(AppModel.self) private var model213 let secret: String214 var label = "One-time code"215216 var body: some View {217 TimelineView(.periodic(from: .now, by: 1)) { ctx in218 let params = try? SPV1.parseTotp(secret)219 let code = params.flatMap { try? SPV1.totp($0, atMs: ctx.date.timeIntervalSince1970 * 1000) }220 FieldRow(label: label) {221 if let code, let params {222 HStack(spacing: 12) {223 Text(Self.spaced(code.code)).font(.system(.title2, design: .monospaced).weight(.semibold)).foregroundStyle(Palette.accent)224 .contentTransition(.numericText()).accessibilityLabel("One-time code").accessibilityValue(code.code.map(String.init).joined(separator: " "))225 .accessibilityIdentifier("totp-code")226 CountdownRing(remaining: code.remaining, period: params.period)227 }228 } else {229 Text("Invalid one-time-code secret").font(.callout).foregroundStyle(Palette.danger)230 }231 } actions: {232 if let code { IconButton(systemName: "doc.on.doc", label: "Copy one-time code") { model.copy(code.code, label: "One-time code") }.accessibilityIdentifier("totp-copy") }233 }234 }235 }236237 static func spaced(_ code: String) -> String {238 let mid = code.count / 2239 return code.count >= 6 ? "\(code.prefix(mid)) \(code.suffix(code.count - mid))" : code240 }241}242243struct CountdownRing: View {244 let remaining: Int245 let period: Int246 var body: some View {247 ZStack {248 Circle().stroke(Palette.line, lineWidth: 2.5)249 Circle().trim(from: 0, to: CGFloat(remaining) / CGFloat(max(period, 1)))250 .stroke(remaining <= 5 ? Palette.brass : Palette.accent, style: StrokeStyle(lineWidth: 2.5, lineCap: .round)).rotationEffect(.degrees(-90))251 Text("\(remaining)").font(.system(size: 9, weight: .semibold, design: .monospaced)).foregroundStyle(Palette.muted)252 }253 .frame(width: 24, height: 24)254 .animation(.linear(duration: 0.3), value: remaining)255 .accessibilityLabel("\(remaining) seconds left")256 }257}258259// ── strength ──260261struct StrengthMeter: View {262 let bits: Double263 var body: some View {264 let g = SPV1.entropyGuidance(bits: bits)265 let (level, tint): (Int, Color) = switch g.level {266 case .weak: (1, Palette.danger)267 case .fair: (2, Palette.brass)268 case .strong: (3, Palette.accent)269 case .excellent: (4, Palette.accent)270 }271 VStack(alignment: .leading, spacing: 5) {272 HStack(spacing: 4) {273 ForEach(1...4, id: \.self) { i in274 Capsule().fill(i <= level ? tint : Palette.line).frame(height: 4)275 }276 }277 Text("\(Int(bits.rounded())) bits · \(g.text)").font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)278 }279 .accessibilityElement(children: .ignore)280 .accessibilityLabel("Strength: \(g.level.rawValue), about \(Int(bits.rounded())) bits")281 }282}283284// ── QR ──285286struct QRCodeView: View {287 let payload: String288 var size: CGFloat = 200289 var body: some View {290 Group {291 if let image = Self.image(payload) {292 Image(decorative: image, scale: 1).interpolation(.none).resizable().scaledToFit()293 } else {294 Rectangle().fill(Palette.s2)295 }296 }297 .frame(width: size, height: size)298 .padding(10)299 .background(Color.white, in: RoundedRectangle(cornerRadius: 10, style: .continuous))300 .accessibilityLabel("QR code")301 }302303 static func image(_ payload: String) -> CGImage? {304 let filter = CIFilter.qrCodeGenerator()305 filter.message = Data(payload.utf8)306 filter.correctionLevel = "M"307 guard let out = filter.outputImage else { return nil }308 return CIContext().createCGImage(out, from: out.extent)309 }310}311312// ── recovery key ──313314/// The recovery key as numbered groups (`SPV1-XXXX-…`): readable, printable, comparable.315struct RecoveryKeyGrid: View {316 let key: String317 private var groups: [String] { key.split(separator: "-").map(String.init) }318 var body: some View {319 let g = groups320 let prefix = g.first ?? "SPV1"321 let rest = Array(g.dropFirst())322 HStack(alignment: .top, spacing: 12) {323 Text(prefix).font(.system(.callout, design: .monospaced).weight(.bold)).foregroundStyle(Palette.accent).fixedSize().padding(.top, 13)324 LazyVGrid(columns: Array(repeating: GridItem(.flexible(minimum: 52), spacing: 10, alignment: .leading), count: columns), alignment: .leading, spacing: 10) {325 ForEach(Array(rest.enumerated()), id: \.offset) { i, group in326 VStack(alignment: .leading, spacing: 1) {327 Text("\(i + 1)").font(.system(size: 9, design: .monospaced)).foregroundStyle(Palette.muted)328 Text(group).font(.system(.body, design: .monospaced).weight(.bold)).foregroundStyle(Palette.text).kerning(1.2)329 }330 .accessibilityElement(children: .ignore)331 .accessibilityLabel("Group \(i + 1)")332 .accessibilityValue(group)333 .accessibilityIdentifier("kit-group-\(i + 1)")334 }335 }336 }337 .padding(16)338 .background(Palette.bg, in: RoundedRectangle(cornerRadius: Metrics.radius, style: .continuous))339 .overlay(RoundedRectangle(cornerRadius: Metrics.radius, style: .continuous).strokeBorder(Palette.lineStrong, lineWidth: 1))340 }341 private var columns: Int {342 #if os(macOS)343 5344 #else345 4346 #endif347 }348}349350// ── forms ──351352/// A labelled form field with a hint or an error underneath.353struct LabeledField<Content: View>: View {354 let label: String355 var hint: String?356 var error: String?357 @ViewBuilder var content: () -> Content358 var body: some View {359 VStack(alignment: .leading, spacing: 5) {360 Text(label).font(.caption.weight(.semibold)).foregroundStyle(Palette.muted)361 content()362 if let error { Text(error).font(.caption).foregroundStyle(Palette.danger).fixedSize(horizontal: false, vertical: true) }363 else if let hint { Text(hint).font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true) }364 }365 }366}367368struct VaultFieldStyle: TextFieldStyle {369 var mono = false370 func _body(configuration: TextField<Self._Label>) -> some View {371 configuration372 .textFieldStyle(.plain)373 .font(mono ? .secret : .body)374 .padding(.horizontal, 10).padding(.vertical, fieldPadding)375 .background(Palette.bg, in: RoundedRectangle(cornerRadius: 8, style: .continuous))376 .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.lineStrong, lineWidth: 1))377 }378 private var fieldPadding: CGFloat {379 #if os(macOS)380 7381 #else382 12383 #endif384 }385}386387extension TextFieldStyle where Self == VaultFieldStyle {388 static var vault: VaultFieldStyle { VaultFieldStyle() }389 static var vaultMono: VaultFieldStyle { VaultFieldStyle(mono: true) }390}391392extension View {393 /// No autocorrection, no capitalisation, no predictive bar: for handles, codes, URLs and secrets.394 func rawTextInput() -> some View {395 #if os(iOS)396 return self.autocorrectionDisabled().textInputAutocapitalization(.never).keyboardType(.asciiCapable)397 #else398 return self.autocorrectionDisabled()399 #endif400 }401}402403/// A destructive or sensitive confirmation that names what will happen.404struct ConfirmRequest: Identifiable {405 let id = UUID()406 var title: String407 var message: String408 var confirmLabel: String409 var destructive = true410 /// When set, the user must type this text to enable the confirm button.411 var typed: String?412 var action: () async -> Void413}414415struct ConfirmSheet: ViewModifier {416 @Binding var request: ConfirmRequest?417 @State private var typed = ""418 func body(content: Content) -> some View {419 content.sheet(item: $request) { r in420 VStack(alignment: .leading, spacing: 14) {421 Text(r.title).font(.vaultTitle).foregroundStyle(Palette.text)422 Text(r.message).font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)423 if let t = r.typed {424 LabeledField(label: "Type \(t) to confirm") {425 TextField("", text: $typed).textFieldStyle(.vaultMono).rawTextInput().accessibilityIdentifier("confirm-typed")426 }427 }428 HStack {429 Spacer()430 Button("Cancel") { request = nil }.buttonStyle(.vaultSecondary).keyboardShortcut(.cancelAction).accessibilityIdentifier("confirm-cancel")431 Button(r.confirmLabel) {432 let action = r.action433 request = nil434 Task { await action() }435 }436 .buttonStyle(r.destructive ? .vaultDanger : .vaultPrimary)437 .disabled(r.typed != nil && typed != r.typed)438 .accessibilityIdentifier("confirm-ok")439 }440 }441 .padding(22)442 .frame(minWidth: 320, idealWidth: 440, maxWidth: 520)443 .background(Palette.s1)444 .presentationDetents([.medium])445 .onAppear { typed = "" }446 }447 }448}449450extension View {451 func confirmSheet(_ request: Binding<ConfirmRequest?>) -> some View { modifier(ConfirmSheet(request: request)) }452}453