Source code for the WriteFreely SwiftUI app for iOS, iPadOS, and macOS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

82 lines
2.8 KiB

  1. import SwiftUI
  2. struct AccountLogoutView: View {
  3. @EnvironmentObject var model: WriteFreelyModel
  4. @EnvironmentObject var errorHandling: ErrorHandling
  5. @State private var isPresentingLogoutConfirmation: Bool = false
  6. @State private var editedPostsWarningString: String = ""
  7. var body: some View {
  8. #if os(iOS)
  9. VStack {
  10. Spacer()
  11. VStack {
  12. Text("Logged in as \(model.account.username)")
  13. Text("on \(model.account.server)")
  14. }
  15. Spacer()
  16. Button(action: logoutHandler, label: {
  17. Text("Log Out")
  18. })
  19. }
  20. .actionSheet(isPresented: $isPresentingLogoutConfirmation, content: {
  21. ActionSheet(
  22. title: Text("Log Out?"),
  23. message: Text("\(editedPostsWarningString)You won't lose any local posts. Are you sure?"),
  24. buttons: [
  25. .destructive(Text("Log Out"), action: {
  26. model.logout()
  27. }),
  28. .cancel()
  29. ]
  30. )
  31. })
  32. #else
  33. VStack {
  34. Spacer()
  35. VStack {
  36. Text("Logged in as \(model.account.username)")
  37. Text("on \(model.account.server)")
  38. }
  39. Spacer()
  40. Button(action: logoutHandler, label: {
  41. Text("Log Out")
  42. })
  43. }
  44. .alert(isPresented: $isPresentingLogoutConfirmation) {
  45. Alert(
  46. title: Text("Log Out?"),
  47. message: Text("\(editedPostsWarningString)You won't lose any local posts. Are you sure?"),
  48. primaryButton: .cancel(Text("Cancel"), action: { self.isPresentingLogoutConfirmation = false }),
  49. secondaryButton: .destructive(Text("Log Out"), action: model.logout )
  50. )
  51. }
  52. #endif
  53. }
  54. func logoutHandler() {
  55. let request = WFAPost.createFetchRequest()
  56. request.predicate = NSPredicate(format: "status == %i", 1)
  57. do {
  58. let editedPosts = try LocalStorageManager.standard.container.viewContext.fetch(request)
  59. if editedPosts.count == 1 {
  60. editedPostsWarningString = "You'll lose unpublished changes to \(editedPosts.count) edited post. "
  61. }
  62. if editedPosts.count > 1 {
  63. editedPostsWarningString = "You'll lose unpublished changes to \(editedPosts.count) edited posts. "
  64. }
  65. } catch {
  66. self.errorHandling.handle(error: LocalStoreError.couldNotFetchPosts("cached"))
  67. }
  68. self.isPresentingLogoutConfirmation = true
  69. }
  70. }
  71. struct AccountLogoutView_Previews: PreviewProvider {
  72. static var previews: some View {
  73. AccountLogoutView()
  74. .environmentObject(WriteFreelyModel())
  75. }
  76. }