krz/libre-edit
A free and private text editor for iOS.
clone: git clone https://gitbay.org/krz/libre-edit.git
main: LibreEdit/ContentView.swift · raw
1//
2// ContentView.swift
3// LibreEdit
4//
5// Created by Christian Cleberg on 2024-01-13.
6//
7
8import SwiftUI
9import UniformTypeIdentifiers
10
11struct TextFile: FileDocument {
12 static var readableContentTypes = [UTType.plainText]
13 var text = ""
14
15 // Initialize a new document
16 init(initialText: String = "") {
17 text = initialText
18 }
19
20 // Load an existing document
21 init(configuration: ReadConfiguration) throws {
22 if let data = configuration.file.regularFileContents {
23 text = String(decoding: data, as: UTF8.self)
24 } else {
25 throw CocoaError(.fileReadCorruptFile)
26 }
27 }
28
29 // Save document data to file
30 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
31 let data = Data(text.utf8)
32 return FileWrapper(regularFileWithContents: data)
33 }
34}
35
36// Counts all words in the opened file
37func countWords(text: String) -> Int {
38 let words = text.split { $0 == " " || $0.isNewline }
39 return words.count
40}
41
42struct ContentView: View {
43 @Binding var document: TextFile
44 @State private var showingPopover = false
45 @State private var wordCount: Int = 0
46
47 var body: some View {
48 NavigationView {
49 VStack {
50 Text("\(wordCount) words")
51 .foregroundColor(Color.white)
52 .font(.headline)
53 .padding(.trailing)
54 .frame(maxWidth: .infinity, maxHeight: 50)
55 .background(Color.gray.opacity(0.3))
56 .padding(.top, 20)
57 TextEditor(text: $document.text)
58 .onAppear {
59 self.wordCount = countWords(text: document.text)
60 }
61 .onChange(of: document.text) {
62 self.wordCount = countWords(text: document.text)
63 }
64 .toolbar {
65 ToolbarItemGroup(placement: .secondaryAction) {
66 NavigationLink(destination: MarkdownView(document: $document)) {
67 Text("Show Rendered Markdown")
68 }
69 Button {
70 showingPopover = true
71 } label: {
72 Text("More Info")
73 }.popover(isPresented: $showingPopover) {
74 VStack(alignment: .leading) {
75 Text("More Info")
76 .font(.largeTitle)
77 Text("")
78 Text("Instructions")
79 .font(.title)
80 Text("")
81 Text("LibreEdit provides a direct interface with the Apple Files app on your iPhone. Simply navigate to your preferred directory, edit existing files, or create new files!")
82 Text("")
83 Text("Developer")
84 .font(.title)
85 Text("")
86 Text("LibreEdit is a free and open source text editor for iOS built by [Christian Cleberg](https://cmc.pub).")
87 Text("")
88 Text("Visit the [GitHub Repository](https://git.cleberg.net/libre-edit.git) to view the source code.")
89 Text("")
90 Text("This project was developed under the [GNU GPL v3 license](https://git.cleberg.net/libre-edit.git/tree/LICENSE).")
91 Spacer()
92 }
93 .padding()
94 }
95 }
96 }
97 }
98 }
99 }
100}