refactor: notifications and settings view models; enhance login and registration UI

This commit is contained in:
2026-03-15 21:40:20 +07:00
parent 0947c048c1
commit 37b87ececd
45 changed files with 985 additions and 680 deletions
+88 -61
View File
@@ -6,74 +6,101 @@ struct LoginView: View {
@State private var password = ""
@State private var showRegister = false
private var isFormInvalid: Bool {
email.isEmpty || password.isEmpty || authViewModel.isLoading
}
var body: some View {
NavigationStack {
VStack(spacing: 24) {
Spacer()
VStack(spacing: 8) {
Image(systemName: "bell.badge.fill")
.font(.system(size: 60))
.foregroundStyle(.red)
Text("Mayday")
.font(.largeTitle.bold())
Text("login_subtitle")
.font(.subheadline)
ZStack {
ScrollView {
VStack(spacing: 24) {
Spacer(minLength: 24)
VStack(spacing: 10) {
Image("Logo")
.resizable()
.scaledToFit()
.frame(width: 84, height: 84)
.clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))
.shadow(color: .red.opacity(0.25), radius: 12, y: 6)
Text("Mayday")
.font(.largeTitle.bold())
Text("login_subtitle")
.font(.subheadline)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
}
.padding(.top, 8)
VStack(spacing: 14) {
AppTextField(
title: "Email",
icon: "envelope.fill",
text: $email
)
.textContentType(.emailAddress)
.keyboardType(.emailAddress)
.autocorrectionDisabled()
.textInputAutocapitalization(.never)
AppSecureField(
title: "password",
icon: "lock.fill",
text: $password
)
.textContentType(.password)
}
if let error = authViewModel.error {
Text(error)
.foregroundStyle(.red)
.font(.footnote)
.multilineTextAlignment(.center)
.frame(maxWidth: .infinity, alignment: .leading)
}
Button {
Task { await authViewModel.login(email: email, password: password) }
} label: {
ZStack {
RoundedRectangle(cornerRadius: 14, style: .continuous)
.fill(
LinearGradient(
colors: [Color.red, Color.red.opacity(0.82)],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
)
.frame(height: 52)
if authViewModel.isLoading {
ProgressView()
.tint(.white)
} else {
Text("login_button")
.font(.headline)
.foregroundStyle(.white)
}
}
}
.disabled(isFormInvalid)
.opacity(isFormInvalid ? 0.6 : 1)
Button("login_no_account") {
showRegister = true
}
.font(.footnote.weight(.semibold))
.foregroundStyle(.secondary)
}
VStack(spacing: 16) {
TextField("Email", text: $email)
.textFieldStyle(.roundedBorder)
.textContentType(.emailAddress)
.keyboardType(.emailAddress)
.autocorrectionDisabled()
.textInputAutocapitalization(.never)
SecureField("password", text: $password)
.textFieldStyle(.roundedBorder)
.textContentType(.password)
}
if let error = authViewModel.error {
Text(error)
.foregroundStyle(.red)
.font(.footnote)
.multilineTextAlignment(.center)
}
Button {
Task { await authViewModel.login(email: email, password: password) }
} label: {
if authViewModel.isLoading {
ProgressView()
.frame(maxWidth: .infinity)
} else {
Text("login_button")
.frame(maxWidth: .infinity)
Spacer(minLength: 8)
}
.cardContainer()
}
.buttonStyle(.borderedProminent)
.disabled(email.isEmpty || password.isEmpty || authViewModel.isLoading)
Button("login_no_account") {
showRegister = true
}
.font(.footnote)
#if DEBUG
Button {
Task { await authViewModel.enterPreviewMode() }
} label: {
Label("demo_mode", systemImage: "play.circle.fill")
.font(.footnote)
.foregroundStyle(.secondary)
}
.padding(.top, 8)
#endif
Spacer()
}
.padding()
.appBackground()
.navigationDestination(isPresented: $showRegister) {
RegisterView()
}
+97 -63
View File
@@ -10,76 +10,110 @@ struct RegisterView: View {
@State private var showVerify = false
@State private var registeredEmail = ""
private var isFormInvalid: Bool {
!isFormValid || authViewModel.isLoading
}
var body: some View {
VStack(spacing: 24) {
Spacer()
ZStack {
ScrollView {
VStack(spacing: 24) {
Spacer(minLength: 24)
Text("register_title")
.font(.largeTitle.bold())
VStack(spacing: 10) {
Image("Logo")
.resizable()
.scaledToFit()
.frame(width: 76, height: 76)
.clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))
.shadow(color: .red.opacity(0.22), radius: 12, y: 6)
VStack(spacing: 16) {
TextField("Email", text: $email)
.textFieldStyle(.roundedBorder)
.textContentType(.emailAddress)
.keyboardType(.emailAddress)
.autocorrectionDisabled()
.textInputAutocapitalization(.never)
SecureField("password", text: $password)
.textFieldStyle(.roundedBorder)
.textContentType(.newPassword)
SecureField("confirm_password", text: $confirmPassword)
.textFieldStyle(.roundedBorder)
.textContentType(.newPassword)
}
if password.count > 0 && password.count < 8 {
Text("password_min_length")
.foregroundStyle(.red)
.font(.footnote)
}
if confirmPassword.count > 0 && password != confirmPassword {
Text("passwords_mismatch")
.foregroundStyle(.red)
.font(.footnote)
}
if let error = authViewModel.error {
Text(error)
.foregroundStyle(.red)
.font(.footnote)
.multilineTextAlignment(.center)
}
Button {
Task {
let success = await authViewModel.register(email: email, password: password)
if success {
registeredEmail = email
showVerify = true
Text("register_title")
.font(.largeTitle.bold())
}
VStack(spacing: 14) {
AppTextField(title: "Email", icon: "envelope.fill", text: $email)
.textContentType(.emailAddress)
.keyboardType(.emailAddress)
.autocorrectionDisabled()
.textInputAutocapitalization(.never)
AppSecureField(title: "password", icon: "lock.fill", text: $password)
.textContentType(.newPassword)
AppSecureField(title: "confirm_password", icon: "lock.rotation", text: $confirmPassword)
.textContentType(.newPassword)
}
if password.count > 0 && password.count < 8 {
Text("password_min_length")
.foregroundStyle(.red)
.font(.footnote)
.frame(maxWidth: .infinity, alignment: .leading)
}
if confirmPassword.count > 0 && password != confirmPassword {
Text("passwords_mismatch")
.foregroundStyle(.red)
.font(.footnote)
.frame(maxWidth: .infinity, alignment: .leading)
}
if let error = authViewModel.error {
Text(error)
.foregroundStyle(.red)
.font(.footnote)
.multilineTextAlignment(.leading)
.frame(maxWidth: .infinity, alignment: .leading)
}
Button {
Task {
let success = await authViewModel.register(email: email, password: password)
if success {
registeredEmail = email
showVerify = true
}
}
} label: {
ZStack {
RoundedRectangle(cornerRadius: 14, style: .continuous)
.fill(
LinearGradient(
colors: [Color.red, Color.red.opacity(0.82)],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
)
.frame(height: 52)
if authViewModel.isLoading {
ProgressView()
.tint(.white)
} else {
Text("register_button")
.font(.headline)
.foregroundStyle(.white)
}
}
}
.disabled(isFormInvalid)
.opacity(isFormInvalid ? 0.6 : 1)
Button("register_has_account") { dismiss() }
.font(.footnote.weight(.semibold))
.foregroundStyle(.secondary)
Spacer(minLength: 8)
}
} label: {
if authViewModel.isLoading {
ProgressView().frame(maxWidth: .infinity)
} else {
Text("register_button").frame(maxWidth: .infinity)
}
.cardContainer()
}
.navigationDestination(isPresented: $showVerify) {
VerifyEmailView(email: registeredEmail, password: password)
}
.buttonStyle(.borderedProminent)
.disabled(!isFormValid || authViewModel.isLoading)
Button("register_has_account") { dismiss() }
.font(.footnote)
Spacer()
}
.padding()
.navigationDestination(isPresented: $showVerify) {
VerifyEmailView(email: registeredEmail)
}
.appBackground()
.navigationTitle("register_title")
.navigationBarTitleDisplayMode(.inline)
}
+128 -59
View File
@@ -2,98 +2,167 @@ import SwiftUI
struct VerifyEmailView: View {
let email: String
let password: String
@EnvironmentObject var authViewModel: AuthViewModel
@State private var codeDigits: [String] = Array(repeating: "", count: 6)
@State private var resendCooldown = 0
@FocusState private var focusedIndex: Int?
@State private var focusedIndex: Int?
@State private var cooldownTask: Task<Void, Never>?
private var code: String {
codeDigits.joined()
}
var body: some View {
VStack(spacing: 32) {
Spacer()
VStack(spacing: 8) {
Text("verify_email_title")
.font(.largeTitle.bold())
Text("verify_code_sent_to")
.foregroundStyle(.secondary)
Text(email)
.fontWeight(.semibold)
ScrollView {
contentCard
}
.appBackground()
.navigationTitle("verify_nav_title")
.navigationBarTitleDisplayMode(.inline)
.onAppear { focusedIndex = 0 }
.onDisappear { cooldownTask?.cancel() }
.onChange(of: code) { _, newValue in
if newValue.count == 6 {
Task { await submitCode(newValue) }
}
}
}
HStack(spacing: 12) {
ForEach(0..<6, id: \.self) { index in
TextField("", text: $codeDigits[index])
.frame(width: 44, height: 52)
.multilineTextAlignment(.center)
.font(.title2.bold())
.keyboardType(.numberPad)
.textContentType(.oneTimeCode)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(focusedIndex == index ? Color.accentColor : Color.secondary, lineWidth: 2)
)
.focused($focusedIndex, equals: index)
.onChange(of: codeDigits[index]) { _, newValue in
handleDigitChange(index: index, value: newValue)
}
}
}
private var contentCard: some View {
VStack(spacing: 28) {
Spacer(minLength: 24)
headerView
otpFieldsView
if let error = authViewModel.error {
Text(error)
.foregroundStyle(.red)
.font(.footnote)
.multilineTextAlignment(.leading)
.frame(maxWidth: .infinity, alignment: .leading)
}
Button {
Task { await resendCode() }
} label: {
if code.count == 6 {
ProgressView()
.padding(.top, 2)
}
resendButton
Spacer(minLength: 8)
}
.cardContainer()
}
private var headerView: some View {
VStack(spacing: 8) {
Image("Logo")
.resizable()
.scaledToFit()
.frame(width: 72, height: 72)
.clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
.shadow(color: .red.opacity(0.22), radius: 12, y: 6)
Text("verify_email_title")
.font(.largeTitle.bold())
Text("verify_code_sent_to")
.font(.subheadline)
.foregroundStyle(.secondary)
Text(email)
.font(.subheadline.weight(.semibold))
.foregroundStyle(.primary)
.lineLimit(1)
.minimumScaleFactor(0.8)
}
}
private var otpFieldsView: some View {
HStack(spacing: 10) {
ForEach(0..<6, id: \.self) { index in
otpField(at: index)
}
}
}
private var resendButton: some View {
Button {
Task { await resendCode() }
} label: {
Group {
if resendCooldown > 0 {
Text("verify_resend_cooldown \(resendCooldown)")
} else {
Text("verify_resend")
}
}
.disabled(resendCooldown > 0)
Spacer()
.font(.footnote.weight(.semibold))
.foregroundStyle(resendCooldown > 0 ? Color.secondary : Color.red)
.padding(.horizontal, 14)
.padding(.vertical, 8)
.background(Color(.tertiarySystemFill))
.clipShape(Capsule())
}
.padding()
.navigationTitle("verify_nav_title")
.navigationBarTitleDisplayMode(.inline)
.onAppear { focusedIndex = 0 }
.onDisappear { cooldownTask?.cancel() }
.disabled(resendCooldown > 0)
}
private func handleDigitChange(index: Int, value: String) {
let filtered = value.filter { $0.isNumber }
if filtered.count > 1 {
// Paste handling
let digits = Array(filtered.prefix(6))
for (i, d) in digits.enumerated() where i < 6 {
codeDigits[i] = String(d)
@ViewBuilder
private func otpField(at index: Int) -> some View {
OTPDigitField(
text: $codeDigits[index],
isFocused: focusedIndex == index,
onFocus: { focusedIndex = index },
onInsert: {
if index < 5 {
focusedIndex = index + 1
}
},
onDeleteWhenEmpty: {
handleDeleteOnEmpty(at: index)
},
onPaste: { digits in
handlePaste(digits, startingAt: index)
}
focusedIndex = min(digits.count, 5)
} else {
codeDigits[index] = filtered.isEmpty ? "" : String(filtered.last!)
if !filtered.isEmpty && index < 5 {
focusedIndex = index + 1
}
}
)
.frame(width: 46, height: 56)
.background(Color(.secondarySystemBackground))
.clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: 12, style: .continuous)
.stroke(
focusedIndex == index
? Color.red.opacity(0.9)
: Color.primary.opacity(0.10),
lineWidth: focusedIndex == index ? 2 : 1
)
)
}
let code = codeDigits.joined()
if code.count == 6 {
Task { await submitCode(code) }
private func handleDeleteOnEmpty(at index: Int) {
guard index > 0 else { return }
codeDigits[index - 1] = ""
focusedIndex = index - 1
}
private func handlePaste(_ digits: [String], startingAt startIndex: Int) {
guard !digits.isEmpty else { return }
for (offset, digit) in digits.enumerated() {
let target = startIndex + offset
guard target < codeDigits.count else { break }
codeDigits[target] = String(digit.prefix(1))
}
focusedIndex = min(startIndex + digits.count, codeDigits.count - 1)
}
private func submitCode(_ code: String) async {
await authViewModel.verifyEmail(email: email, code: code)
if authViewModel.error == nil {
// Auto-login after verification - in a real flow we'd re-login here
// since verify doesn't return tokens
await authViewModel.login(email: email, password: password)
}
}
@@ -1,24 +1,49 @@
import SwiftUI
struct NotificationDetailView: View {
let notification: AppNotification
let viewModel: NotificationsViewModel
let notificationId: UUID
@ObservedObject var viewModel: NotificationsViewModel
private var notification: AppNotification? {
viewModel.notifications.first { $0.id == notificationId }
}
init(notification: AppNotification, viewModel: NotificationsViewModel) {
self.notificationId = notification.id
self.viewModel = viewModel
}
var body: some View {
Group {
if let notification {
scrollContent(notification)
}
}
.background(Color(.systemGroupedBackground))
.navigationTitle("details_section")
.navigationBarTitleDisplayMode(.inline)
.task {
if let notification, !notification.isRead {
await viewModel.markAsRead(notification)
}
}
}
private func scrollContent(_ notification: AppNotification) -> some View {
ScrollView {
VStack(spacing: 0) {
// Hero header
headerSection
headerSection(notification)
// Info cards
VStack(spacing: 16) {
detailsCard
detailsCard(notification)
if let metadata = notification.metadata, !metadata.isEmpty {
metadataCard(metadata)
}
statusCard
statusCard(notification)
}
.padding(.horizontal, 16)
.padding(.top, 24)
@@ -44,29 +69,24 @@ struct NotificationDetailView: View {
}
}
}
.background(Color(.systemGroupedBackground))
.navigationTitle("details_section")
.navigationBarTitleDisplayMode(.inline)
.task {
await viewModel.markAsRead(notification)
}
}
// MARK: - Hero Header
private var headerSection: some View {
VStack(spacing: 16) {
private func headerSection(_ notification: AppNotification) -> some View {
let severity = NotificationSeverity(from: notification.metadata)
return VStack(spacing: 16) {
ZStack {
Circle()
.fill(Color(.secondarySystemGroupedBackground))
.frame(width: 88, height: 88)
.shadow(color: topicColor.opacity(0.3), radius: 12, y: 4)
.shadow(color: severity.color.opacity(0.3), radius: 12, y: 4)
Circle()
.fill(topicColor.opacity(0.15))
.fill(severity.color.opacity(0.15))
.frame(width: 80, height: 80)
Image(systemName: topicIcon)
Image(systemName: severity.icon)
.font(.system(size: 32))
.foregroundStyle(topicColor)
.foregroundStyle(severity.color)
}
VStack(spacing: 6) {
@@ -79,7 +99,7 @@ struct NotificationDetailView: View {
.foregroundStyle(.secondary)
}
statusBadge
statusBadge(for: notification)
}
.padding(.vertical, 28)
.frame(maxWidth: .infinity)
@@ -87,7 +107,7 @@ struct NotificationDetailView: View {
// MARK: - Status Badge
private var statusBadge: some View {
private func statusBadge(for notification: AppNotification) -> some View {
let (text, color): (String, Color) = notification.isRead
? (String(localized: "status_read"), .green)
: (String(localized: "status_new"), .red)
@@ -102,7 +122,7 @@ struct NotificationDetailView: View {
// MARK: - Details Card
private var detailsCard: some View {
private func detailsCard(_ notification: AppNotification) -> some View {
VStack(alignment: .leading, spacing: 12) {
Label("details_section", systemImage: "doc.text.fill")
.font(.subheadline.bold())
@@ -168,14 +188,14 @@ struct NotificationDetailView: View {
// MARK: - Status Card
private var statusCard: some View {
private func statusCard(_ notification: AppNotification) -> some View {
VStack(alignment: .leading, spacing: 12) {
Label("status_section", systemImage: "clock.fill")
.font(.subheadline.bold())
.foregroundStyle(.primary)
VStack(spacing: 8) {
infoRow(icon: "paperplane.fill", label: String(localized: "channel_label"), value: channelLabel)
infoRow(icon: "paperplane.fill", label: String(localized: "channel_label"), value: channelLabel(for: notification))
Divider()
infoRow(icon: "clock", label: String(localized: "received_label"), value: notification.createdAt.formatted(date: .abbreviated, time: .shortened))
if let readAt = notification.readAt {
@@ -209,7 +229,7 @@ struct NotificationDetailView: View {
// MARK: - Helpers
private var channelLabel: String {
private func channelLabel(for notification: AppNotification) -> String {
switch notification.channel {
case .inApp: return String(localized: "channel_in_app")
case .apns: return "Push"
@@ -218,34 +238,4 @@ struct NotificationDetailView: View {
case .webhook: return "Webhook"
}
}
private var topicIcon: String {
let lowered = (notification.source ?? "").lowercased()
if lowered.contains("fire") || lowered.contains("пожар") || lowered.contains("огонь") {
return "flame.fill"
} else if lowered.contains("medical") || lowered.contains("медиц") || lowered.contains("здоров") {
return "heart.fill"
} else if lowered.contains("security") || lowered.contains("безопас") {
return "shield.fill"
} else if lowered.contains("water") || lowered.contains("вод") || lowered.contains("затоп") {
return "drop.fill"
} else {
return "exclamationmark.triangle.fill"
}
}
private var topicColor: Color {
let lowered = (notification.source ?? "").lowercased()
if lowered.contains("fire") || lowered.contains("пожар") || lowered.contains("огонь") {
return .red
} else if lowered.contains("medical") || lowered.contains("медиц") || lowered.contains("здоров") {
return .green
} else if lowered.contains("security") || lowered.contains("безопас") {
return .blue
} else if lowered.contains("water") || lowered.contains("вод") || lowered.contains("затоп") {
return .cyan
} else {
return .orange
}
}
}
@@ -36,21 +36,8 @@ struct NotificationsView: View {
}
.background(Color(.systemGroupedBackground))
.navigationTitle("notifications_title")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
#if DEBUG
if PreviewData.isPreviewMode {
ToolbarItem(placement: .topBarLeading) {
Button(action: {}) {
Text("demo_badge")
.font(.caption2.bold())
}
.buttonStyle(.borderedProminent)
.tint(.orange)
.controlSize(.mini)
.allowsHitTesting(false)
}
}
#endif
ToolbarItem(placement: .topBarTrailing) {
Button {
showSettings = true
@@ -86,6 +73,7 @@ struct NotificationsView: View {
NavigationLink(destination: NotificationDetailView(notification: notification, viewModel: viewModel)) {
ActiveNotificationCard(notification: notification)
}
.id("\(notification.id)-\(notification.isRead)")
.buttonStyle(.plain)
.padding(.horizontal, 16)
.padding(.bottom, 12)
@@ -103,6 +91,7 @@ struct NotificationsView: View {
NavigationLink(destination: NotificationDetailView(notification: notification, viewModel: viewModel)) {
ResolvedNotificationCard(notification: notification)
}
.id("\(notification.id)-\(notification.isRead)")
.buttonStyle(.plain)
.padding(.horizontal, 16)
.padding(.bottom, 12)
@@ -146,7 +135,7 @@ struct ActiveNotificationCard: View {
var body: some View {
VStack(alignment: .leading, spacing: 12) {
HStack(alignment: .top) {
NotificationIconView(source: notification.source, isActive: true)
NotificationIconView(severity: NotificationSeverity(from: notification.metadata), isActive: true)
VStack(alignment: .leading, spacing: 2) {
Text(notification.subject ?? "")
@@ -206,7 +195,7 @@ struct ResolvedNotificationCard: View {
var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .top) {
NotificationIconView(source: notification.source, isActive: false)
NotificationIconView(severity: NotificationSeverity(from: notification.metadata), isActive: false)
VStack(alignment: .leading, spacing: 2) {
Text(notification.subject ?? "")
@@ -255,51 +244,3 @@ struct ResolvedNotificationCard: View {
.shadow(color: .black.opacity(0.06), radius: 8, y: 2)
}
}
// MARK: - Notification Icon
struct NotificationIconView: View {
let source: String?
let isActive: Bool
private var iconName: String {
let lowered = (source ?? "").lowercased()
if lowered.contains("fire") || lowered.contains("пожар") || lowered.contains("огонь") {
return "flame.fill"
} else if lowered.contains("medical") || lowered.contains("медиц") || lowered.contains("здоров") {
return "heart.fill"
} else if lowered.contains("security") || lowered.contains("безопас") {
return "shield.fill"
} else if lowered.contains("water") || lowered.contains("вод") || lowered.contains("затоп") {
return "drop.fill"
} else {
return "exclamationmark.triangle.fill"
}
}
private var iconColor: Color {
let lowered = (source ?? "").lowercased()
if lowered.contains("fire") || lowered.contains("пожар") || lowered.contains("огонь") {
return .red
} else if lowered.contains("medical") || lowered.contains("медиц") || lowered.contains("здоров") {
return .green
} else if lowered.contains("security") || lowered.contains("безопас") {
return .blue
} else if lowered.contains("water") || lowered.contains("вод") || lowered.contains("затоп") {
return .cyan
} else {
return .orange
}
}
var body: some View {
ZStack {
Circle()
.fill(isActive ? .white.opacity(0.25) : iconColor.opacity(0.12))
.frame(width: 40, height: 40)
Image(systemName: iconName)
.font(.body)
.foregroundStyle(isActive ? .white : iconColor)
}
}
}
+17 -17
View File
@@ -59,6 +59,23 @@ struct SettingsView: View {
Button("logout_all_button", role: .destructive) {
showLogoutAllConfirm = true
}
.confirmationDialog(
"logout_all_confirm",
isPresented: $showLogoutAllConfirm,
titleVisibility: .visible
) {
Button("logout_all_action", role: .destructive) {
Task {
do {
_ = try await NotificationsAPIService.shared.logoutAll()
await authViewModel.logout()
} catch {
logoutAllError = error.localizedDescription
}
}
}
Button("cancel", role: .cancel) {}
}
}
}
.navigationTitle("settings_title")
@@ -75,23 +92,6 @@ struct SettingsView: View {
SessionsView()
.environmentObject(viewModel)
}
.confirmationDialog(
"logout_all_confirm",
isPresented: $showLogoutAllConfirm,
titleVisibility: .visible
) {
Button("logout_all_action", role: .destructive) {
Task {
do {
_ = try await NotificationsAPIService.shared.logoutAll()
await authViewModel.logout()
} catch {
logoutAllError = error.localizedDescription
}
}
}
Button("cancel", role: .cancel) {}
}
.alert(
"error_title",
isPresented: Binding(
+20
View File
@@ -0,0 +1,20 @@
import SwiftUI
struct AppBackgroundModifier: ViewModifier {
func body(content: Content) -> some View {
content.background(
LinearGradient(
colors: [Color(.systemGroupedBackground), Color.red.opacity(0.08)],
startPoint: .top,
endPoint: .bottom
)
.ignoresSafeArea()
)
}
}
extension View {
func appBackground() -> some View {
modifier(AppBackgroundModifier())
}
}
+25
View File
@@ -0,0 +1,25 @@
import SwiftUI
struct AppSecureField: View {
let title: LocalizedStringKey
let icon: String
@Binding var text: String
var body: some View {
HStack(spacing: 10) {
Image(systemName: icon)
.foregroundStyle(.secondary)
.frame(width: 18)
SecureField(title, text: $text)
}
.padding(.horizontal, 14)
.padding(.vertical, 14)
.background(Color(.secondarySystemBackground))
.clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: 14, style: .continuous)
.stroke(Color.primary.opacity(0.08), lineWidth: 1)
)
}
}
+25
View File
@@ -0,0 +1,25 @@
import SwiftUI
struct AppTextField: View {
let title: LocalizedStringKey
let icon: String
@Binding var text: String
var body: some View {
HStack(spacing: 10) {
Image(systemName: icon)
.foregroundStyle(.secondary)
.frame(width: 18)
TextField(title, text: $text)
}
.padding(.horizontal, 14)
.padding(.vertical, 14)
.background(Color(.secondarySystemBackground))
.clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: 14, style: .continuous)
.stroke(Color.primary.opacity(0.08), lineWidth: 1)
)
}
}
+22
View File
@@ -0,0 +1,22 @@
import SwiftUI
struct CardContainerModifier: ViewModifier {
func body(content: Content) -> some View {
content
.padding(.horizontal, 20)
.padding(.vertical, 24)
.background(Color(.systemBackground).opacity(0.8))
.clipShape(RoundedRectangle(cornerRadius: 28, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: 28, style: .continuous)
.stroke(Color.primary.opacity(0.06), lineWidth: 1)
)
.padding(16)
}
}
extension View {
func cardContainer() -> some View {
modifier(CardContainerModifier())
}
}
@@ -0,0 +1,47 @@
import SwiftUI
enum NotificationSeverity: String {
case critical
case warning
case info
case success
var icon: String {
switch self {
case .critical: return "exclamationmark.triangle.fill"
case .warning: return "exclamationmark.circle.fill"
case .info: return "info.circle.fill"
case .success: return "checkmark.seal.fill"
}
}
var color: Color {
switch self {
case .critical: return .red
case .warning: return .orange
case .info: return .blue
case .success: return .green
}
}
init(from metadata: [String: String]?) {
let raw = metadata?["severity"]?.lowercased() ?? ""
self = NotificationSeverity(rawValue: raw) ?? .info
}
}
struct NotificationIconView: View {
let severity: NotificationSeverity
let isActive: Bool
var body: some View {
ZStack {
Circle()
.fill(isActive ? .white.opacity(0.25) : severity.color.opacity(0.12))
.frame(width: 40, height: 40)
Image(systemName: severity.icon)
.font(.body)
.foregroundStyle(isActive ? .white : severity.color)
}
}
}
+100
View File
@@ -0,0 +1,100 @@
import SwiftUI
import UIKit
struct OTPDigitField: UIViewRepresentable {
@Binding var text: String
let isFocused: Bool
let onFocus: () -> Void
let onInsert: () -> Void
let onDeleteWhenEmpty: () -> Void
let onPaste: ([String]) -> Void
func makeUIView(context: Context) -> BackspaceAwareTextField {
let textField = BackspaceAwareTextField()
textField.delegate = context.coordinator
textField.keyboardType = .numberPad
textField.textAlignment = .center
textField.font = UIFont.systemFont(ofSize: 24, weight: .bold)
textField.textContentType = .oneTimeCode
textField.onDeleteWhenEmpty = {
onDeleteWhenEmpty()
}
textField.addTarget(context.coordinator, action: #selector(Coordinator.editingChanged(_:)), for: .editingChanged)
return textField
}
func updateUIView(_ uiView: BackspaceAwareTextField, context: Context) {
if uiView.text != text {
uiView.text = text
}
if isFocused && !uiView.isFirstResponder {
DispatchQueue.main.async {
uiView.becomeFirstResponder()
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}
final class Coordinator: NSObject, UITextFieldDelegate {
var parent: OTPDigitField
init(parent: OTPDigitField) {
self.parent = parent
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
parent.onFocus()
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
parent.onFocus()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.isEmpty {
return true
}
let digits = string.filter { $0.isNumber }
guard !digits.isEmpty else {
return false
}
if digits.count > 1 {
parent.onPaste(digits.map(String.init))
return false
}
parent.text = String(digits.prefix(1))
parent.onInsert()
return false
}
@objc
func editingChanged(_ textField: UITextField) {
let digitsOnly = (textField.text ?? "").filter { $0.isNumber }
let single = String(digitsOnly.prefix(1))
if textField.text != single {
textField.text = single
}
parent.text = single
}
}
}
final class BackspaceAwareTextField: UITextField {
var onDeleteWhenEmpty: (() -> Void)?
override func deleteBackward() {
let wasEmpty = (text ?? "").isEmpty
super.deleteBackward()
if wasEmpty {
onDeleteWhenEmpty?()
}
}
}