Skip to content

Commit

Permalink
Mark Autosave Changes Immediately (#1865)
Browse files Browse the repository at this point in the history
- Modifies `CodeFileView` to mark the document as changed immediately when changes occur rather than debounced. This fixes a small issue where the "Edited" marker would appear after the file was saved, because the change notification was debounced.
- Adds some error logging to `CodeFileDocument`.
  • Loading branch information
thecoolwinter authored Aug 31, 2024
1 parent 4bc7548 commit 02b6919
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import CodeEditSourceEditor
import CodeEditTextView
import CodeEditLanguages
import Combine
import OSLog

enum CodeFileError: Error {
case failedToDecode
Expand All @@ -26,6 +27,8 @@ final class CodeFileDocument: NSDocument, ObservableObject {
let cursorPositions: [CursorPosition]
}

static let logger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "", category: "CodeFileDocument")

/// The text content of the document, stored as a text storage
///
/// This is intentionally not a `@Published` variable. If it were published, SwiftUI would do a string
Expand Down Expand Up @@ -121,6 +124,7 @@ final class CodeFileDocument: NSDocument, ObservableObject {

override func data(ofType _: String) throws -> Data {
guard let sourceEncoding, let data = (content?.string as NSString?)?.data(using: sourceEncoding.nsValue) else {
Self.logger.error("Failed to encode contents to \(self.sourceEncoding.debugDescription)")
throw CodeFileError.failedToEncode
}
return data
Expand All @@ -143,6 +147,8 @@ final class CodeFileDocument: NSDocument, ObservableObject {
if let validEncoding = FileEncoding(rawEncoding), let nsString {
self.sourceEncoding = validEncoding
self.content = NSTextStorage(string: nsString as String)
} else {
Self.logger.error("Failed to read file from data using encoding: \(rawEncoding)")
}
}

Expand Down
17 changes: 15 additions & 2 deletions CodeEdit/Features/Editor/Views/CodeFileView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,23 @@ struct CodeFileView: View {
codeFile
.contentCoordinator
.textUpdatePublisher
.debounce(for: 1.0, scheduler: DispatchQueue.main)
.sink { _ in
codeFile.updateChangeCount(.changeDone)
codeFile.autosave(withImplicitCancellability: false) { _ in }
}
.store(in: &cancellables)

codeFile
.contentCoordinator
.textUpdatePublisher
.debounce(for: 1.0, scheduler: DispatchQueue.main)
.sink { _ in
codeFile.autosave(withImplicitCancellability: false) { error in
if let error {
CodeFileDocument.logger.error("Failed to autosave document, error: \(error)")
} else {
codeFile.updateChangeCount(.changeCleared)
}
}
}
.store(in: &cancellables)

Expand Down

0 comments on commit 02b6919

Please sign in to comment.