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