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