diff --git a/Shared/Models/PostStore.swift b/Shared/Models/PostStore.swift index 907272a..31cedbf 100644 --- a/Shared/Models/PostStore.swift +++ b/Shared/Models/PostStore.swift @@ -1,17 +1,28 @@ import Foundation struct PostStore { var posts: [Post] init(posts: [Post] = []) { self.posts = posts } mutating func add(_ post: Post) { posts.append(post) } mutating func purgeAllPosts() { posts = [] } -} + + mutating func update(_ post: Post) { + // Find the local copy in the store + let localCopy = posts.first(where: { $0.id == post.id }) + + // If there's a local copy, update the updatedDate property of its WFPost + if let localCopy = localCopy { + localCopy.wfPost.updatedDate = Date() + } else { + print("local copy not found") + } + } diff --git a/Shared/PostEditor/PostEditorView.swift b/Shared/PostEditor/PostEditorView.swift index 51608c2..a9ba9b7 100644 --- a/Shared/PostEditor/PostEditorView.swift +++ b/Shared/PostEditor/PostEditorView.swift @@ -1,79 +1,83 @@ import SwiftUI struct PostEditorView: View { @EnvironmentObject var model: WriteFreelyModel @ObservedObject var post: Post @State private var isNewPost = false @State private var title = "" var body: some View { VStack { TextEditor(text: $title) .font(.title) .frame(height: 100) .onChange(of: title) { _ in if post.status == .published && post.wfPost.title != title { post.status = .edited } post.wfPost.title = title } TextEditor(text: $post.wfPost.body) .font(.body) .onChange(of: post.wfPost.body) { _ in if post.status == .published { post.status = .edited } } } .padding() .toolbar { ToolbarItem(placement: .status) { PostStatusBadgeView(post: post) } ToolbarItem(placement: .primaryAction) { Button(action: { model.publish(post: post) post.status = .published }, label: { Image(systemName: "paperplane") }) } } .onAppear(perform: { title = post.wfPost.title ?? "" checkIfNewPost() if self.isNewPost { addNewPostToStore() } }) .onDisappear(perform: { - post.wfPost.updatedDate = Date() + if post.status == .edited { + DispatchQueue.main.async { + model.store.update(post) + } + } }) } private func checkIfNewPost() { self.isNewPost = !model.store.posts.contains(where: { $0.id == post.id }) } private func addNewPostToStore() { withAnimation { model.store.add(post) self.isNewPost = false } } } struct PostEditorView_NewDraftPreviews: PreviewProvider { static var previews: some View { PostEditorView(post: Post()) .environmentObject(WriteFreelyModel()) } } struct PostEditorView_ExistingPostPreviews: PreviewProvider { static var previews: some View { PostEditorView(post: testPostData[0]) .environmentObject(WriteFreelyModel()) } }