Sources/OrgstarMobile/ReaderScreen.swift
250 lines · 11026 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgIndex
5import OrgPresentation
6import SwiftUI
7
8/// What to read: a file, and where in it.
9enum ReaderRoute: Hashable {
10 case file(String)
11 case offset(String, Int)
12 /// A search result, found again if the file changed since it was indexed.
13 case heading(HeadingLocation)
14}
15
16/// Editing a file, from the reader.
17struct EditorRoute: Hashable {
18 let path: String
19 let offset: Int?
20}
21
22/// A file to read: headings that fold and unfold with a tap, as TAB cycles them, text styled as
23/// in the editor, and links to follow.
24struct ReaderScreen: View {
25 let route: ReaderRoute
26 let workspace: WorkspaceModel
27 let session: DocumentSession
28 @State private var fold = FoldState()
29 @State private var folded: [Range<Int>] = []
30 @State private var loadedPath: String?
31 @State private var showingOutline = false
32 @State private var message: String?
33 @Environment(\.openURL) private var openURL
34
35 private var outline: [OutlineEntry] { session.outline }
36
37 var body: some View {
38 let _ = session.editVersion
39 ScrollViewReader { proxy in
40 ScrollView {
41 LazyVStack(alignment: .leading, spacing: 8) {
42 if let tree = session.document?.tree {
43 let preambleEnd = outline.first?.start ?? (tree.text as NSString).length
44 if preambleEnd > 0 { textView(tree, 0..<preambleEnd) }
45 ForEach(Array(outline.enumerated()), id: \.element.start) { index, entry in
46 if isShown(index) {
47 heading(tree, entry).id(entry.start)
48 if !fold.folds.contains(entry.start), !fold.bodyFolds.contains(entry.start) {
49 let body = bodyRange(index, tree)
50 if !body.isEmpty { textView(tree, body).padding(.leading, indent(entry)) }
51 }
52 }
53 }
54 }
55 }
56 .padding()
57 .frame(maxWidth: .infinity, alignment: .leading)
58 }
59 .onChange(of: session.revealRequest?.id) {
60 guard let offset = session.revealRequest?.offset else { return }
61 reveal(offset, proxy)
62 }
63 }
64 .navigationTitle(((session.path ?? "") as NSString).lastPathComponent)
65 .navigationBarTitleDisplayMode(.inline)
66 .toolbar {
67 ToolbarItemGroup(placement: .primaryAction) {
68 Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty)
69 if let path = session.path {
70 NavigationLink(value: EditorRoute(path: path, offset: nil)) { Label("Edit", systemImage: "square.and.pencil") }
71 }
72 }
73 }
74 .sheet(isPresented: $showingOutline) { outlineSheet }
75 .safeAreaInset(edge: .bottom) {
76 if let message {
77 Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
78 .onTapGesture { self.message = nil }
79 }
80 }
81 .environment(\.openURL, OpenURLAction { url in follow(url) })
82 .onAppear(perform: open)
83 .onChange(of: session.path) { loadFolds() }
84 .onChange(of: session.editVersion) { loadFolds() }
85 }
86
87 // MARK: - Content
88
89 private func indent(_ entry: OutlineEntry) -> CGFloat { CGFloat(entry.level - 1) * 14 }
90
91 /// Hidden under a folded ancestor.
92 private func isShown(_ index: Int) -> Bool {
93 var parent = outline[index].parent
94 while let p = parent {
95 if fold.folds.contains(outline[p].start) { return false }
96 parent = outline[p].parent
97 }
98 return true
99 }
100
101 /// From after the heading line to the first child, or the section's end.
102 private func bodyRange(_ index: Int, _ tree: OrgTree) -> Range<Int> {
103 let entry = outline[index]
104 let ns = tree.text as NSString
105 let lineEnd = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
106 let firstChild = outline[(index + 1)...].first { $0.parent == index }?.start ?? entry.end
107 return min(lineEnd, firstChild)..<firstChild
108 }
109
110 private func heading(_ tree: OrgTree, _ entry: OutlineEntry) -> some View {
111 let ns = tree.text as NSString
112 var line = ns.lineRange(for: NSRange(location: entry.start, length: 0))
113 let title = min(entry.start + entry.level + 1, NSMaxRange(line))
114 line.length = NSMaxRange(line) - title
115 let text = attributed(ReadingText.segments(tree, in: title..<(title + line.length)), heading: entry.level)
116 let hasContent = entry.end > NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
117 let foldedMark = fold.folds.contains(entry.start) && hasContent
118 return HStack(alignment: .firstTextBaseline, spacing: 6) {
119 Image(systemName: foldedMark ? "chevron.right" : "chevron.down")
120 .font(.caption.weight(.semibold)).foregroundStyle(.tertiary)
121 .opacity(hasContent ? 1 : 0)
122 Text(text.trimmingTrailingNewlines()).frame(maxWidth: .infinity, alignment: .leading)
123 }
124 .padding(.leading, indent(entry))
125 .padding(.top, entry.level == 1 ? 6 : 0)
126 .contentShape(Rectangle())
127 .onTapGesture { fold = Presentation.cycle(entry.start, in: tree, fold) }
128 .accessibilityAddTraits(.isButton)
129 .accessibilityHint(foldedMark ? "Unfolds the heading" : "Folds the heading")
130 }
131
132 private func textView(_ tree: OrgTree, _ range: Range<Int>) -> some View {
133 Text(attributed(ReadingText.segments(tree, in: range, folded: folded), heading: nil).trimmingTrailingNewlines())
134 .textSelection(.enabled)
135 .frame(maxWidth: .infinity, alignment: .leading)
136 }
137
138 /// Segments as styled text; links get `orgstar-link:` URLs to follow.
139 private func attributed(_ segments: [ReadingText.Segment], heading level: Int?) -> AttributedString {
140 var result = AttributedString()
141 for segment in segments {
142 var part = AttributedString(segment.text)
143 if let level {
144 part.font = level == 1 ? .title3.weight(.semibold) : level == 2 ? .headline : .body.weight(.semibold)
145 }
146 for role in segment.roles {
147 switch role {
148 case .todo: part.foregroundColor = .red; part.font = (part.font ?? .body).weight(.semibold)
149 case .done: part.foregroundColor = .green
150 case .priority: part.foregroundColor = .orange
151 case .tags: part.foregroundColor = .secondary; part.font = .caption
152 case .bold: part.inlinePresentationIntent = .stronglyEmphasized
153 case .italic: part.inlinePresentationIntent = .emphasized
154 case .underline: part.underlineStyle = .single
155 case .strikeThrough: part.strikethroughStyle = .single
156 case .verbatim, .code, .inlineSource: part.font = .body.monospaced()
157 case .markup, .leadingStars: part.foregroundColor = .secondary
158 case .timestamp: part.foregroundColor = .purple
159 case .metadata, .keyword, .comment, .blockDelimiter:
160 part.foregroundColor = .secondary
161 part.font = .footnote.monospaced()
162 case .block, .table, .syntax: part.font = .callout.monospaced()
163 default: break
164 }
165 }
166 if segment.link != nil {
167 // Found again by position when followed.
168 part.link = URL(string: "orgstar-link:\(segment.offset)")
169 part.foregroundColor = .accentColor
170 }
171 result += part
172 }
173 return result
174 }
175
176 // MARK: - Actions
177
178 private func open() {
179 switch route {
180 case .file(let path): if session.path != path { session.open(path) }
181 case .offset(let path, let offset):
182 if session.path != path { session.open(path) }
183 session.reveal(offset)
184 case .heading(let location): session.show(location)
185 }
186 loadFolds()
187 }
188
189 /// The file's startup visibility, kept while the same file is open.
190 private func loadFolds() {
191 guard let tree = session.document?.tree else { return }
192 folded = Presentation.startupWrappers(tree).map(\.hidden)
193 guard loadedPath != session.path else { return }
194 loadedPath = session.path
195 fold = Presentation.applyVisibilityProperties(Presentation.startupFoldState(tree) ?? FoldState(), in: tree)
196 }
197
198 /// Unfolds the way to the heading containing `offset` and scrolls to it.
199 private func reveal(_ offset: Int, _ proxy: ScrollViewProxy) {
200 guard let index = outline.lastIndex(where: { $0.start <= offset }) else { return }
201 var parent = outline[index].parent
202 while let p = parent {
203 fold.folds.remove(outline[p].start)
204 parent = outline[p].parent
205 }
206 let start = outline[index].start
207 DispatchQueue.main.async { withAnimation { proxy.scrollTo(start, anchor: .top) } }
208 }
209
210 private func follow(_ url: URL) -> OpenURLAction.Result {
211 guard url.scheme == "orgstar-link", let offset = Int(url.absoluteString.dropFirst("orgstar-link:".count)),
212 let tree = session.document?.tree, let link = Links.link(at: offset, text: tree.text, tree: tree)?.link else {
213 return .systemAction
214 }
215 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
216 case .shown: message = nil
217 case .openExternally(let target): openURL(target)
218 case .message(let text): message = text
219 }
220 return .handled
221 }
222
223 private var outlineSheet: some View {
224 NavigationStack {
225 List(outline, id: \.start) { entry in
226 Button {
227 showingOutline = false
228 session.reveal(entry.start)
229 } label: {
230 Text(entry.title.isEmpty ? "(untitled)" : entry.title)
231 .padding(.leading, indent(entry))
232 .foregroundStyle(.primary)
233 }
234 }
235 .navigationTitle("Outline")
236 .navigationBarTitleDisplayMode(.inline)
237 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { showingOutline = false } } }
238 }
239 }
240}
241
242private extension AttributedString {
243 /// Without the final newline, which `Text` would show as an empty line.
244 func trimmingTrailingNewlines() -> AttributedString {
245 var copy = self
246 while let last = copy.characters.last, last.isNewline { copy.characters.removeLast() }
247 return copy
248 }
249}
250#endif