Sources/Orgstar/ContentView.swift
276 lines · 11345 bytes
1import OrgApp
2import OrgCore
3import OrgEditorAppKit
4import OrgIndex
5import SwiftUI
6
7struct ContentView: View {
8 let workspace: WorkspaceModel
9 let session: DocumentSession
10 @Bindable var commands: AppCommands
11 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
12 @AppStorage("keymap") private var preset = KeymapPreset.emacs
13 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
14 @State private var keymap = KeymapPreset.emacs.keymap
15 @AppStorage("tagsColumn") private var tagsColumn = -77
16 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
17 @AppStorage("splitLine") private var splitLine = false
18 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
19
20 private var options: EditingOptions {
21 Preferences.options(tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists)
22 }
23 @State private var selectedFile: String?
24 @State private var query = ""
25 @FocusState private var searchFocused: Bool
26
27 var body: some View {
28 NavigationSplitView {
29 Sidebar(workspace: workspace, selection: $selectedFile)
30 .navigationSplitViewColumnWidth(min: 200, ideal: 260)
31 } content: {
32 Group {
33 if query.isEmpty {
34 OutlineColumn(session: session)
35 } else {
36 SearchResults(results: workspace.search(query, overlay: workspace.overlay(path: session.path, document: session.document))) { location in
37 guard location.path == session.path || UnsavedChanges.resolve(session) else { return }
38 selectedFile = location.path
39 session.show(location)
40 }
41 }
42 }
43 .navigationSplitViewColumnWidth(min: 160, ideal: 220, max: 360)
44 } detail: {
45 if session.path != nil {
46 EditorView(session: session, commands: commands, keymap: keymap, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, onAppCommand: perform)
47 .safeAreaInset(edge: .bottom, spacing: 0) { EchoArea(commands: commands) }
48 } else {
49 ContentUnavailableView(
50 workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
51 systemImage: "doc.text",
52 description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
53 )
54 }
55 }
56 .navigationTitle(session.path.map { ($0 as NSString).lastPathComponent } ?? "Orgstar")
57 .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
58 .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
59 .searchFocused($searchFocused)
60 .toolbar {
61 if workspace.isIndexing { ProgressView().controlSize(.small) }
62 if session.conflict != nil {
63 Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
64 .help("The file changed on disk, and the changes conflict with yours")
65 }
66 }
67 .onChange(of: selectedFile) { old, path in
68 guard let path, path != session.path else { return }
69 if UnsavedChanges.resolve(session) {
70 session.open(path)
71 } else {
72 selectedFile = old
73 }
74 }
75 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
76 .onChange(of: options, initial: true) { _, options in session.options = options }
77 .onChange(of: preset, initial: true) { loadKeymap() }
78 .sheet(isPresented: $commands.showingPalette) {
79 PaletteView(keymap: keymap) { id in
80 commands.showingPalette = false
81 // After the sheet closes, so app commands can present their own.
82 DispatchQueue.main.async { perform(id) }
83 }
84 }
85 .onChange(of: session.conflict) { _, conflict in
86 if conflict != nil { commands.showingConflict = true }
87 }
88 .alert("Conflicting changes", isPresented: $commands.showingConflict) {
89 Button("Keep Mine") { session.keepMine() }
90 Button("Use Disk Version") { session.useDiskVersion() }
91 Button("Decide Later", role: .cancel) {}
92 } message: {
93 Text((session.conflict ?? "") + " The version you don't keep is saved in the recovery folder.")
94 }
95 .onChange(of: workspace.changedFile?.version) {
96 if let path = workspace.changedFile?.path { session.fileChanged(path) }
97 }
98 .onChange(of: commands.focusSearch) { _, focus in
99 if focus {
100 searchFocused = true
101 commands.focusSearch = false
102 }
103 }
104 .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
105 guard case .success(let url) = result else { return }
106 Task {
107 do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
108 }
109 }
110 .sheet(isPresented: $commands.showingQuickOpen) {
111 QuickOpenView(workspace: workspace) { entry in
112 selectedFile = entry.path
113 commands.showingQuickOpen = false
114 }
115 }
116 .alert("Orgstar", isPresented: errorShown) {
117 Button("OK") {
118 workspace.lastError = nil
119 session.lastError = nil
120 }
121 } message: {
122 Text(workspace.lastError ?? session.lastError ?? "")
123 }
124 .task {
125 DevelopmentHooks.scheduleSnapshot()
126 if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
127 await workspace.refresh()
128 workspace.startWatching()
129 }
130 }
131
132 private func loadKeymap() {
133 let loaded = KeymapLoader.load(preset)
134 keymap = loaded.keymap
135 if let first = loaded.problems.first {
136 let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
137 commands.show("keymap.toml: \(first)\(more)")
138 }
139 }
140
141 /// Runs a command from a key, the palette or the Org menu.
142 private func perform(_ id: String) {
143 switch id {
144 case "app.save":
145 if !session.save(), session.conflict != nil { commands.showingConflict = true }
146 case "app.quick-open": commands.showingQuickOpen = true
147 case "app.palette": commands.showingPalette = true
148 case "app.search": commands.focusSearch = true
149 case "app.reload-keymap":
150 loadKeymap()
151 commands.show("Keymap reloaded")
152 case "app.refile":
153 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
154 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
155 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
156 if let message = session.refile(to: target) { commands.show(message) }
157 }
158 case "app.archive":
159 if let message = session.archive() { commands.show(message) }
160 default:
161 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
162 }
163 }
164
165 private var errorShown: Binding<Bool> {
166 Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
167 }
168}
169
170struct Sidebar: View {
171 let workspace: WorkspaceModel
172 @Binding var selection: String?
173
174 var body: some View {
175 List(selection: $selection) {
176 ForEach(workspace.rootPaths, id: \.self) { root in
177 Section((root as NSString).lastPathComponent) {
178 OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
179 Label(node.name, systemImage: icon(node))
180 .foregroundStyle(node.file?.kind == .conflict ? .orange : .primary)
181 .tag(node.file?.path)
182 }
183 }
184 .contextMenu {
185 Button("Remove Folder") { try? workspace.removeRoot(path: root) }
186 }
187 }
188 }
189 .listStyle(.sidebar)
190 }
191
192 private func icon(_ node: FileTreeNode) -> String {
193 guard let file = node.file else { return "folder" }
194 switch file.kind {
195 case .org: return "doc.text"
196 case .archive: return "archivebox"
197 case .conflict: return "exclamationmark.triangle"
198 }
199 }
200}
201
202struct OutlineColumn: View {
203 let session: DocumentSession
204
205 var body: some View {
206 List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
207 Button {
208 session.reveal(entry.start)
209 } label: {
210 Text(entry.title.isEmpty ? "(untitled)" : entry.title)
211 .lineLimit(1)
212 .padding(.leading, CGFloat(entry.level - 1) * 12)
213 }
214 .buttonStyle(.plain)
215 }
216 .overlay {
217 if session.path != nil, session.outline.isEmpty {
218 ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
219 }
220 }
221 }
222}
223
224struct SearchResults: View {
225 let results: [HeadingLocation]
226 let open: (HeadingLocation) -> Void
227
228 var body: some View {
229 List(results, id: \.self) { location in
230 Button {
231 open(location)
232 } label: {
233 VStack(alignment: .leading, spacing: 2) {
234 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
235 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
236 }
237 }
238 .buttonStyle(.plain)
239 }
240 .overlay {
241 if results.isEmpty { ContentUnavailableView.search }
242 }
243 }
244}
245
246struct QuickOpenView: View {
247 let workspace: WorkspaceModel
248 let open: (FileEntry) -> Void
249 @State private var query = ""
250 @Environment(\.dismiss) private var dismiss
251
252 var body: some View {
253 let matches = workspace.quickOpen(query)
254 VStack(spacing: 0) {
255 TextField("Open file", text: $query)
256 .textFieldStyle(.plain)
257 .font(.title3)
258 .padding(12)
259 .onSubmit { if let first = matches.first { open(first) } }
260 Divider()
261 List(matches) { entry in
262 Button {
263 open(entry)
264 } label: {
265 VStack(alignment: .leading, spacing: 2) {
266 Text(entry.name)
267 Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
268 }
269 }
270 .buttonStyle(.plain)
271 }
272 }
273 .frame(width: 520, height: 360)
274 .onExitCommand { dismiss() }
275 }
276}