Sources/OrgstarMobile/ReaderScreen.swift
387 lines · 18761 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgIndex
5import OrgPresentation
6import SwiftUI
7import UIKit
8
9/// What to read: a file, and where in it.
10enum ReaderRoute: Hashable {
11 case file(String)
12 case offset(String, Int)
13 /// A search result, found again if the file changed since it was indexed.
14 case heading(HeadingLocation)
15}
16
17/// Editing a file, from the reader.
18struct EditorRoute: Hashable {
19 let path: String
20 let offset: Int?
21}
22
23/// A file to read: headings that fold and unfold with a tap, as TAB cycles them, text styled as
24/// in the editor, and links to follow.
25struct ReaderScreen: View {
26 let route: ReaderRoute
27 let workspace: WorkspaceModel
28 let session: DocumentSession
29 @State private var fold = FoldState()
30 @State private var folded: [Range<Int>] = []
31 /// Drawers and blocks the file opens with folded, which fold and unfold from their first line.
32 @State private var foldable: [Range<Int>] = []
33 @State private var loadedPath: String?
34 /// The file's display: indentation, leading stars, inline images, truncation.
35 @State private var startup: StartupDisplay?
36 @State private var showingOutline = false
37 @State private var message: String?
38 @Environment(\.openURL) private var openURL
39 @Environment(MobileModel.self) private var model
40
41 private var outline: [OutlineEntry] { session.outline }
42
43 /// The file this reader shows. Readers lower in the stack stay alive while the session
44 /// shows another file, and draw nothing then.
45 private var path: String {
46 switch route {
47 case .file(let path), .offset(let path, _): path
48 case .heading(let location): location.path
49 }
50 }
51
52 /// The session shows this reader's file; it opens files by their resolved paths.
53 private var showsOwnFile: Bool {
54 guard let current = session.path else { return false }
55 return current == path || current == URL(fileURLWithPath: path).resolvingSymlinksInPath().path
56 }
57
58 var body: some View {
59 let _ = session.editVersion
60 // Read again when settings or the Dynamic Type size change.
61 let _ = model.settingsVersion
62 let theme = MobileTheme(model.theme)
63 let truncated = startup?.truncated ?? false
64 ScrollViewReader { proxy in
65 ScrollView(truncated ? [.vertical, .horizontal] : .vertical) {
66 LazyVStack(alignment: .leading, spacing: 8) {
67 if let tree = session.document?.tree, showsOwnFile {
68 let length = (tree.text as NSString).length
69 let preambleEnd = min(outline.first?.start ?? length, length)
70 if preambleEnd > 0 { textView(tree, 0..<preambleEnd, theme) }
71 ForEach(Array(outline.enumerated()), id: \.element.start) { index, entry in
72 // While another file opens, rows can update with the last file's
73 // entries for a moment; those don't fit this text.
74 if index < outline.count, outline[index] == entry, entry.end <= length, isShown(index) {
75 heading(tree, entry, theme).id(entry.start)
76 if !fold.folds.contains(entry.start), !fold.bodyFolds.contains(entry.start) {
77 let body = bodyRange(index, tree)
78 if !body.isEmpty { textView(tree, body, theme).padding(.leading, bodyIndent(entry, theme)) }
79 }
80 }
81 }
82 }
83 }
84 .padding()
85 .frame(maxWidth: truncated ? nil : .infinity, alignment: .leading)
86 }
87 // Narrower than the view while truncated, the text still starts at the top left.
88 .defaultScrollAnchor(truncated ? .topLeading : nil)
89 .background(theme.swiftColor("background") ?? Color(uiColor: .systemBackground))
90 .onChange(of: session.revealRequest?.id) {
91 guard let offset = session.revealRequest?.offset else { return }
92 reveal(offset, proxy)
93 }
94 }
95 .navigationTitle(((session.path ?? "") as NSString).lastPathComponent)
96 .navigationBarTitleDisplayMode(.inline)
97 .toolbar {
98 ToolbarItemGroup(placement: .primaryAction) {
99 Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty)
100 if let path = session.path {
101 if let text = session.document?.text { ExportMenu(path: path, text: text) { message = $0 } }
102 NavigationLink(value: EditorRoute(path: path, offset: nil)) { Label("Edit", systemImage: "square.and.pencil") }
103 }
104 }
105 }
106 .sheet(isPresented: $showingOutline) { outlineSheet }
107 .safeAreaInset(edge: .bottom) {
108 if let message {
109 Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
110 .onTapGesture { self.message = nil }
111 }
112 }
113 .environment(\.openURL, OpenURLAction { url in follow(url) })
114 .onAppear(perform: open)
115 .onChange(of: session.path) { loadFolds() }
116 .onChange(of: session.editVersion) { loadFolds() }
117 .onChange(of: model.settingsVersion) { loadFolds() }
118 }
119
120 // MARK: - Content
121
122 private func indent(_ entry: OutlineEntry) -> CGFloat { CGFloat(entry.level - 1) * 14 }
123
124 private var indented: Bool { startup?.indented ?? true }
125
126 /// The text as the editor's display settings show it.
127 private var display: ReadingText.Display {
128 ReadingText.Display(showMarkup: model.showMarkup, options: session.options, highlighter: MobileEditor.highlighter)
129 }
130
131 /// org-indent: a heading's text and its body start past its stars, at level + 1 columns,
132 /// the fold mark standing where the last star and its space would. Without it nothing is
133 /// indented and the stars show.
134 private func headingIndent(_ entry: OutlineEntry, _ theme: MobileTheme) -> CGFloat {
135 indented ? CGFloat(entry.level - 1) * theme.column : 0
136 }
137
138 private func bodyIndent(_ entry: OutlineEntry, _ theme: MobileTheme) -> CGFloat {
139 indented ? CGFloat(entry.level + 1) * theme.column : 0
140 }
141
142 /// Hidden under a folded ancestor.
143 private func isShown(_ index: Int) -> Bool {
144 var parent = outline[index].parent
145 while let p = parent {
146 if fold.folds.contains(outline[p].start) { return false }
147 parent = outline[p].parent
148 }
149 return true
150 }
151
152 /// From after the heading line to the first child, or the section's end.
153 private func bodyRange(_ index: Int, _ tree: OrgTree) -> Range<Int> {
154 let entry = outline[index]
155 let ns = tree.text as NSString
156 let lineEnd = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
157 let firstChild = outline[(index + 1)...].first { $0.parent == index }?.start ?? entry.end
158 return min(lineEnd, firstChild)..<firstChild
159 }
160
161 private func heading(_ tree: OrgTree, _ entry: OutlineEntry, _ theme: MobileTheme) -> some View {
162 let ns = tree.text as NSString
163 let line = ns.lineRange(for: NSRange(location: entry.start, length: 0))
164 let start = indented ? min(entry.start + entry.level + 1, NSMaxRange(line)) : entry.start
165 let text = attributed(ReadingText.segments(tree, in: start..<NSMaxRange(line), display: display), heading: entry.level, theme)
166 let hasContent = entry.end > NSMaxRange(line)
167 let foldedMark = fold.folds.contains(entry.start) && hasContent
168 return HStack(alignment: .firstTextBaseline, spacing: 0) {
169 Image(systemName: foldedMark ? "chevron.right" : "chevron.down")
170 .font(.caption.weight(.semibold)).foregroundStyle(theme.swiftColor("markup") ?? Color(uiColor: .tertiaryLabel))
171 .opacity(hasContent ? 1 : 0)
172 .frame(width: 2 * theme.column, alignment: .leading)
173 lineText(text.trimmingTrailingNewlines(), theme)
174 }
175 .padding(.leading, headingIndent(entry, theme))
176 .padding(.top, entry.level == 1 ? 6 : 0)
177 .contentShape(Rectangle())
178 .onTapGesture { fold = Presentation.cycle(entry.start, in: tree, fold) }
179 .accessibilityAddTraits(.isButton)
180 .accessibilityHint(foldedMark ? "Unfolds the heading" : "Folds the heading")
181 }
182
183 private func textView(_ tree: OrgTree, _ range: Range<Int>, _ theme: MobileTheme) -> some View {
184 VStack(alignment: .leading, spacing: 4) {
185 ForEach(parts(tree, range), id: \.range.lowerBound) { part in
186 if let image = part.image {
187 Image(uiImage: image.picture).resizable().scaledToFit()
188 .frame(maxWidth: image.width.map { CGFloat($0) } ?? image.picture.size.width, alignment: .leading)
189 .accessibilityLabel((image.path as NSString).lastPathComponent)
190 } else {
191 lineText(attributed(ReadingText.segments(tree, in: part.range, folded: folded, open: foldable.filter { !folded.contains($0) }, display: display), heading: nil, theme).trimmingTrailingNewlines(), theme)
192 .textSelection(.enabled)
193 }
194 }
195 }
196 }
197
198 /// Wrapped to the view's width, or on one line each, scrolling sideways, while truncated.
199 private func lineText(_ text: AttributedString, _ theme: MobileTheme) -> some View {
200 Text(text)
201 .lineSpacing(CGFloat(max(0, theme.spec.lineSpacing)))
202 .fixedSize(horizontal: startup?.truncated ?? false, vertical: false)
203 .frame(maxWidth: startup?.truncated == true ? nil : .infinity, alignment: .leading)
204 }
205
206 private struct Part {
207 let range: Range<Int>
208 var image: (picture: UIImage, path: String, width: Int?)?
209 }
210
211 /// Text, and with inline images on, lines that are only an image link shown as the image.
212 private func parts(_ tree: OrgTree, _ range: Range<Int>) -> [Part] {
213 guard startup?.inlineImages == true, let path = session.path else { return [Part(range: range)] }
214 let base = URL(fileURLWithPath: path).deletingLastPathComponent()
215 let ns = tree.text as NSString
216 var parts: [Part] = []
217 var textStart = range.lowerBound
218 var location = range.lowerBound
219 while location < range.upperBound {
220 let line = ns.lineRange(for: NSRange(location: location, length: 0))
221 location = NSMaxRange(line)
222 guard folded.allSatisfy({ !$0.contains(line.location) }), let image = InlineImages.image(atLine: line.location, in: ns),
223 let picture = MobileEditor.loadImage(image.path, relativeTo: base) else { continue }
224 if textStart < line.location { parts.append(Part(range: textStart..<line.location)) }
225 parts.append(Part(range: line.location..<min(NSMaxRange(line), range.upperBound), image: (picture, image.path, image.width)))
226 textStart = min(NSMaxRange(line), range.upperBound)
227 }
228 if textStart < range.upperBound { parts.append(Part(range: textStart..<range.upperBound)) }
229 return parts
230 }
231
232 /// Segments as styled text in the theme's font and colors, as the editor styles them;
233 /// links get `orgstar-link:` URLs to follow.
234 private func attributed(_ segments: [ReadingText.Segment], heading level: Int?, _ theme: MobileTheme) -> AttributedString {
235 var result = AttributedString()
236 for segment in segments {
237 var part = AttributedString(segment.text)
238 var font = level.map(theme.headingFont) ?? theme.font
239 var color = level.flatMap { theme.color("heading-\(min(max($0, 1), 8))") } ?? theme.foreground
240 func fg(_ key: String) { if let c = theme.color(key) { color = c } }
241 // Outer roles first, so inner ones win.
242 for role in segment.roles.sorted(by: { Self.depth($0) < Self.depth($1) }) {
243 switch role {
244 case .todo, .done:
245 font = MobileTheme.adding(.traitBold, to: font)
246 if let c = theme.keywordColor(segment.text, done: role == .done) { color = c }
247 case .priority: fg("priority")
248 case .tags: fg("tags")
249 case .bold: font = MobileTheme.adding(.traitBold, to: font)
250 case .italic: font = MobileTheme.adding(.traitItalic, to: font)
251 case .underline: part.underlineStyle = .single
252 case .strikeThrough: part.strikethroughStyle = .single
253 case .verbatim, .code, .inlineSource:
254 if let background = theme.color("inline-background") { part.backgroundColor = Color(uiColor: background) }
255 fg(role == .verbatim ? "verbatim" : "code")
256 case .markup, .linkMarkup: fg("markup")
257 case .leadingStars:
258 // As the editor hides them; shown in the heading's color unless hidden.
259 if !Presentation.skipsLeadingStars(role, indented: indented, hideStars: startup?.hideStars ?? false) { color = .clear }
260 case .syntax(let category): if let key = category.themeKey { fg(key) }
261 case .timestamp: fg("timestamp")
262 case .comment: fg("comment")
263 case .keyword: fg("keyword")
264 case .metadata: fg("metadata")
265 case .blockDelimiter: fg("block-delimiter")
266 case .footnote, .cookie, .target, .macro, .latex: fg("special")
267 case .table, .rule: fg("table")
268 case .link:
269 part.underlineStyle = .single
270 fg("link")
271 case .heading, .block: break
272 }
273 }
274 if segment.link != nil {
275 // Found again by position when followed.
276 part.link = URL(string: "orgstar-link:\(segment.offset)")
277 }
278 if let start = segment.toggles { part.link = URL(string: "orgstar-fold:\(start)") }
279 if let superscript = segment.superscript {
280 // Raised or lowered as the editor draws `org-pretty-entities` scripts.
281 part.baselineOffset = (superscript ? 0.3 : -0.3) * font.pointSize
282 font = font.withSize(font.pointSize * 0.7)
283 }
284 part.font = Font(font as CTFont)
285 part.foregroundColor = Color(uiColor: color)
286 result += part
287 }
288 return result
289 }
290
291 /// How deep a role's text usually nests: elements, then objects, then their parts.
292 private static func depth(_ role: StyleRole) -> Int {
293 switch role {
294 case .heading: 0
295 case .metadata, .keyword, .comment, .block, .table, .rule: 1
296 case .blockDelimiter, .link, .bold, .italic, .underline, .strikeThrough, .timestamp, .footnote, .target, .macro, .latex: 2
297 default: 3
298 }
299 }
300
301 // MARK: - Actions
302
303 private func open() {
304 switch route {
305 case .file(let path): if session.path != path { session.open(path) }
306 case .offset(let path, let offset):
307 if session.path != path { session.open(path) }
308 session.reveal(offset)
309 case .heading(let location): session.show(location)
310 }
311 loadFolds()
312 }
313
314 /// The file's startup display, as the editor opens it; its heading folds are kept while
315 /// the same file is open.
316 private func loadFolds() {
317 guard let tree = session.document?.tree, showsOwnFile else { return }
318 let display = Presentation.startupDisplay(tree, options: session.options)
319 startup = display
320 folded = display.wrappers.map(\.hidden)
321 foldable = folded
322 guard loadedPath != session.path else { return }
323 loadedPath = session.path
324 fold = display.folds
325 }
326
327 /// Unfolds the way to the heading containing `offset` and scrolls to it.
328 private func reveal(_ offset: Int, _ proxy: ScrollViewProxy) {
329 guard let index = outline.lastIndex(where: { $0.start <= offset }) else { return }
330 var parent = outline[index].parent
331 while let p = parent {
332 fold.folds.remove(outline[p].start)
333 parent = outline[p].parent
334 }
335 let start = outline[index].start
336 DispatchQueue.main.async { withAnimation { proxy.scrollTo(start, anchor: .top) } }
337 }
338
339 private func follow(_ url: URL) -> OpenURLAction.Result {
340 if url.scheme == "orgstar-fold", let start = Int(url.absoluteString.dropFirst("orgstar-fold:".count)) {
341 if folded.contains(where: { $0.lowerBound == start }) {
342 folded.removeAll { $0.lowerBound == start }
343 } else if let range = foldable.first(where: { $0.lowerBound == start }) {
344 folded.append(range)
345 }
346 return .handled
347 }
348 guard url.scheme == "orgstar-link", let offset = Int(url.absoluteString.dropFirst("orgstar-link:".count)),
349 let tree = session.document?.tree, let link = Links.link(at: offset, text: tree.text, tree: tree)?.link else {
350 return .systemAction
351 }
352 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
353 case .shown: message = nil
354 case .openExternally(let target): openURL(target)
355 case .message(let text): message = text
356 }
357 return .handled
358 }
359
360 private var outlineSheet: some View {
361 NavigationStack {
362 List(outline, id: \.start) { entry in
363 Button {
364 showingOutline = false
365 session.reveal(entry.start)
366 } label: {
367 Text(entry.title.isEmpty ? "(untitled)" : entry.title)
368 .padding(.leading, indent(entry))
369 .foregroundStyle(.primary)
370 }
371 }
372 .navigationTitle("Outline")
373 .navigationBarTitleDisplayMode(.inline)
374 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { showingOutline = false } } }
375 }
376 }
377}
378
379private extension AttributedString {
380 /// Without the final newline, which `Text` would show as an empty line.
381 func trimmingTrailingNewlines() -> AttributedString {
382 var copy = self
383 while let last = copy.characters.last, last.isNewline { copy.characters.removeLast() }
384 return copy
385 }
386}
387#endif