Sources/OrgstarMobile/ReaderScreen.swift

71cfd8421de8b3d3c1fbdc9f394e56b267ec23e1
orgstar/Sources/OrgstarMobile/ReaderScreen.swift

419 lines · 20642 bytes

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form