Sources/OrgstarMobile/ReaderScreen.swift

46d6a046f519e5ab5a9338ff643341bd53e7788f
orgstar/Sources/OrgstarMobile/ReaderScreen.swift history · blame · raw

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