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