Allow text file editing
This commit is contained in:
@ -8,31 +8,65 @@ struct TextFileContentView: View {
|
||||
@State
|
||||
private var fileContent: String = ""
|
||||
|
||||
@State
|
||||
private var loadedFile: String?
|
||||
|
||||
var body: some View {
|
||||
if fileContent != "" {
|
||||
TextEditor(text: $fileContent)
|
||||
.font(.body.monospaced())
|
||||
.textEditorStyle(.plain)
|
||||
//.background(.clear)
|
||||
} else {
|
||||
VStack {
|
||||
VStack {
|
||||
if fileContent != "" {
|
||||
HStack {
|
||||
Button("Reload", action: reload)
|
||||
Button("Save", action: save)
|
||||
Spacer()
|
||||
}
|
||||
TextEditor(text: $fileContent)
|
||||
.font(.body.monospaced())
|
||||
.textEditorStyle(.plain)
|
||||
.foregroundStyle(.primary)
|
||||
} else {
|
||||
Image(systemSymbol: .docText)
|
||||
.resizable()
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.frame(width: 150)
|
||||
Text("No preview available")
|
||||
Text("No preview available or empty file")
|
||||
.font(.title)
|
||||
}
|
||||
.foregroundStyle(.secondary)
|
||||
.onAppear(perform: loadFileContent)
|
||||
}
|
||||
.foregroundStyle(.secondary)
|
||||
.onAppear(perform: loadFileContent)
|
||||
.onDisappear(perform: save)
|
||||
}
|
||||
|
||||
private func loadFileContent() {
|
||||
guard fileContent == "" else {
|
||||
return
|
||||
}
|
||||
reload()
|
||||
}
|
||||
|
||||
private func reload() {
|
||||
fileContent = file.textContent()
|
||||
loadedFile = file.id
|
||||
print("Loaded content of file \(file.id)")
|
||||
}
|
||||
|
||||
private func save() {
|
||||
guard let loadedFile else {
|
||||
print("[ERROR] Text File View: No file loaded to save")
|
||||
return
|
||||
}
|
||||
guard loadedFile == file.id else {
|
||||
print("[ERROR] Text File View: Not saving since file changed")
|
||||
return
|
||||
}
|
||||
guard fileContent != "" else {
|
||||
print("Text File View: Not saving empty file \(file.id)")
|
||||
return
|
||||
}
|
||||
guard file.save(textContent: fileContent) else {
|
||||
print("[ERROR] Text File View: Failed to save file \(file.id)")
|
||||
return
|
||||
}
|
||||
print("Text File View: Saved file \(file.id)")
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user