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.
 
 
 

81 lines
2.7 KiB

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