Sources/OrgstarMobile/ReaderScreen.swift

97747b094d086278e81ed74839087570090a5691
orgstar/Sources/OrgstarMobile/ReaderScreen.swift

665 lines · 32593 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import OrgDocument
  5import OrgIndex
  6import OrgPresentation
  7import QuickLook
  8import SwiftUI
  9import UIKit
 10
 11/// What to read: a file, and where in it.
 12enum ReaderRoute: Hashable {
 13    case file(String)
 14    case offset(String, Int)
 15    /// A search result, found again if the file changed since it was indexed.
 16    case heading(HeadingLocation)
 17}
 18
 19/// Editing a file, from the reader.
 20struct EditorRoute: Hashable {
 21    let path: String
 22    let offset: Int?
 23}
 24
 25/// A file to read: headings that fold and unfold with a tap, as TAB cycles them, text styled as
 26/// in the editor, and links to follow.
 27struct ReaderScreen: View {
 28    let route: ReaderRoute
 29    let workspace: WorkspaceModel
 30    let session: DocumentSession
 31    @State private var fold = FoldState()
 32    @State private var folded: [Range<Int>] = []
 33    /// Drawers and blocks the file opens with folded, which fold and unfold from their first line.
 34    @State private var foldable: [Range<Int>] = []
 35    @State private var loadedPath: String?
 36    /// The file's display: indentation, leading stars, inline images, truncation.
 37    @State private var startup: StartupDisplay?
 38    /// Headings' padded tags, by the heading's start.
 39    @State private var tagGaps: [Int: TagGap] = [:]
 40    /// The view's width, which images in a line's text are no wider than.
 41    @State private var width: CGFloat = 0
 42    @State private var showingOutline = false
 43    @State private var showingCommands = false
 44    /// The command chosen in Commands, run once the list is gone.
 45    @State private var chosenCommand: String?
 46    @State private var message: String?
 47    /// A file a link opened, shown in Quick Look.
 48    @State private var previewed: URL?
 49    /// The pane the reader shows its file in, closed with the reader.
 50    @State private var holder = PaneHolder()
 51    /// The system find bar over the file's text, shown each time `findRequest` changes.
 52    @State private var find = ReaderFind()
 53    @State private var findRequest = 0
 54    /// Find's results, true for the one shown, and the offset to scroll to.
 55    @State private var found: [Range<Int>: Bool] = [:]
 56    @State private var findTarget: Int?
 57    @Environment(\.openURL) private var openURL
 58    @Environment(MobileModel.self) private var model
 59
 60    private var pane: EditorPane? { holder.pane }
 61    private var outline: [OutlineEntry] { pane?.outline ?? [] }
 62    /// The file the reader's pane shows.
 63    private var shownPath: String? { pane?.path }
 64    private var document: DocumentState? { shownPath.flatMap(session.document(of:)) }
 65
 66    /// The file this reader shows.
 67    private var path: String {
 68        switch route {
 69        case .file(let path), .offset(let path, _): path
 70        case .heading(let location): location.path
 71        }
 72    }
 73
 74    /// The pane shows this reader's file; the session opens files by their resolved paths.
 75    private var showsOwnFile: Bool {
 76        guard let current = shownPath else { return false }
 77        return current == path || current == URL(fileURLWithPath: path).resolvingSymlinksInPath().path
 78    }
 79
 80    var body: some View {
 81        let _ = pane?.editVersion
 82        // Read again when settings or the Dynamic Type size change.
 83        let _ = model.settingsVersion
 84        let theme = MobileTheme(model.theme)
 85        let truncated = startup?.truncated ?? false
 86        ScrollViewReader { proxy in
 87            ScrollView(truncated ? [.vertical, .horizontal] : .vertical) {
 88                LazyVStack(alignment: .leading, spacing: 8) {
 89                    if let tree = document?.tree, showsOwnFile {
 90                        let length = (tree.text as NSString).length
 91                        let preambleEnd = min(outline.first?.start ?? length, length)
 92                        if preambleEnd > 0 { textView(tree, 0..<preambleEnd, theme) }
 93                        ForEach(Array(outline.enumerated()), id: \.element.start) { index, entry in
 94                            // While another file opens, rows can update with the last file's
 95                            // entries for a moment; those don't fit this text.
 96                            if index < outline.count, outline[index] == entry, entry.end <= length, isShown(index) {
 97                                heading(tree, entry, theme).id(entry.start)
 98                                if !fold.folds.contains(entry.start), !fold.bodyFolds.contains(entry.start) {
 99                                    let body = bodyRange(index, tree)
100                                    if !body.isEmpty { textView(tree, body, theme).padding(.leading, bodyIndent(entry, theme)) }
101                                }
102                            }
103                        }
104                    }
105                }
106                .padding()
107                .frame(maxWidth: truncated ? nil : .infinity, alignment: .leading)
108            }
109            // Narrower than the view while truncated, the text still starts at the top left.
110            .defaultScrollAnchor(truncated ? .topLeading : nil)
111            .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 }
112            .background(theme.swiftColor("background") ?? Color(uiColor: .systemBackground))
113            .onChange(of: pane?.revealRequest?.id) {
114                guard let offset = pane?.revealRequest?.offset else { return }
115                reveal(offset, proxy)
116            }
117            .onChange(of: findTarget) {
118                guard let offset = findTarget else { return }
119                findTarget = nil
120                showFound(offset, proxy)
121            }
122        }
123        .navigationTitle(((shownPath ?? "") as NSString).lastPathComponent)
124        .navigationBarTitleDisplayMode(.inline)
125        .toolbar {
126            ToolbarItemGroup(placement: .primaryAction) {
127                Button("Find", systemImage: "magnifyingglass") {
128                    find.text = (document?.tree.text ?? "") as NSString
129                    findRequest += 1
130                }
131                .disabled(document == nil)
132                Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty)
133                if let path = shownPath {
134                    if let tree = document?.tree { ExportMenu(path: path, tree: tree) { message = $0 } }
135                    NavigationLink(value: EditorRoute(path: path, offset: nil)) { Label("Edit", systemImage: "pencil") }
136                }
137                Button("Commands", systemImage: "command") { showingCommands = true }
138            }
139        }
140        .sheet(isPresented: $showingCommands, onDismiss: {
141            // After the list has gone, so the command's own sheet can show.
142            if let id = chosenCommand {
143                chosenCommand = nil
144                runCommand(id)
145            }
146        }) {
147            CommandList(rows: commandRows) { chosenCommand = $0 }
148        }
149        .quickLookPreview($previewed)
150        .sheet(isPresented: $showingOutline) { outlineSheet }
151        .message($message)
152        .environment(\.openURL, OpenURLAction { url in follow(url) })
153        .background { FindHost(find: find, request: findRequest) }
154        .onAppear(perform: open)
155        .onChange(of: pane?.path) { loadFolds() }
156        .onChange(of: pane?.editVersion) { loadFolds() }
157        .onChange(of: model.settingsVersion) { loadFolds() }
158        .onReceive(NotificationCenter.default.publisher(for: OrgExport.refused)) { message = $0.object as? String }
159    }
160
161    // MARK: - Commands
162
163    /// The reader's commands: its own, capture, and the clock's that need no caret.
164    private var commandRows: [CommandRow] {
165        [
166            CommandRow(id: "reader.find", title: String(localized: "Find"), reason: document == nil ? String(localized: "Nothing to do here") : nil),
167            CommandRow(id: "reader.outline", title: String(localized: "Outline"), reason: outline.isEmpty ? String(localized: "Nothing to do here") : nil),
168            CommandRow(id: "app.toggle-markup", title: CommandTitle.localized("Show or Hide Markup")),
169            CommandRow(id: "app.capture", title: CommandTitle.localized("Capture…")),
170        ] + MobileClock.screenCommands.map { CommandRow(id: $0.id, title: CommandTitle.localized($0.title)) }
171    }
172
173    private func runCommand(_ id: String) {
174        switch id {
175        case "reader.find":
176            find.text = (document?.tree.text ?? "") as NSString
177            findRequest += 1
178        case "reader.outline": showingOutline = true
179        case "app.toggle-markup": model.showMarkup.toggle()
180        case "app.capture": model.captureRequest = CaptureRequest()
181        default: _ = MobileClock.run(id, model: model, workspace: workspace) { message = $0 }
182        }
183    }
184
185    // MARK: - Content
186
187    private func indent(_ entry: OutlineEntry) -> CGFloat { CGFloat(entry.level - 1) * 14 }
188
189    private var indented: Bool { startup?.indented ?? true }
190
191    /// The text as the editor's display settings show it.
192    private var display: ReadingText.Display {
193        ReadingText.Display(showMarkup: model.showMarkup, options: session.options, highlighter: MobileEditor.highlighter)
194    }
195
196    /// org-indent: a heading's text and its body start past its stars, at level + 1 columns,
197    /// the fold mark standing where the last star and its space would. Without it nothing is
198    /// indented and the stars show.
199    private func headingIndent(_ entry: OutlineEntry, _ theme: MobileTheme) -> CGFloat {
200        indented ? CGFloat(entry.level - 1) * theme.column : 0
201    }
202
203    private func bodyIndent(_ entry: OutlineEntry, _ theme: MobileTheme) -> CGFloat {
204        indented ? CGFloat(entry.level + 1) * theme.column : 0
205    }
206
207    /// Hidden under a folded ancestor.
208    private func isShown(_ index: Int) -> Bool {
209        var parent = outline[index].parent
210        while let p = parent {
211            if fold.folds.contains(outline[p].start) { return false }
212            parent = outline[p].parent
213        }
214        return true
215    }
216
217    /// From after the heading line to the first child, or the section's end.
218    private func bodyRange(_ index: Int, _ tree: OrgTree) -> Range<Int> {
219        let entry = outline[index]
220        let ns = tree.text as NSString
221        let lineEnd = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0)))
222        let firstChild = outline[(index + 1)...].first { $0.parent == index }?.start ?? entry.end
223        return min(lineEnd, firstChild)..<firstChild
224    }
225
226    private func heading(_ tree: OrgTree, _ entry: OutlineEntry, _ theme: MobileTheme) -> some View {
227        let ns = tree.text as NSString
228        let line = ns.lineRange(for: NSRange(location: entry.start, length: 0))
229        let start = indented ? min(entry.start + entry.level + 1, NSMaxRange(line)) : entry.start
230        let tags = tagGaps[entry.start].flatMap { $0.tags.upperBound <= NSMaxRange(line) ? $0 : nil }
231        func styled(_ range: Range<Int>) -> AttributedString {
232            attributed(ReadingText.segments(tree, in: range, display: display), heading: entry.level, theme)
233        }
234        let hasContent = entry.end > NSMaxRange(line)
235        let foldedMark = fold.folds.contains(entry.start) && hasContent
236        return HStack(alignment: .firstTextBaseline, spacing: 0) {
237            Image(systemName: foldedMark ? "chevron.right" : "chevron.down")
238                .font(.caption.weight(.semibold)).foregroundStyle(theme.swiftColor("markup") ?? Color(uiColor: .tertiaryLabel))
239                .opacity(hasContent ? 1 : 0)
240                .frame(width: 2 * theme.column, alignment: .leading)
241            if let tags, tags.gap.lowerBound >= start {
242                headingWithTags(title: styled(start..<tags.gap.lowerBound), gap: styled(tags.gap),
243                                tags: styled(tags.tags.lowerBound..<NSMaxRange(line)).trimmingTrailingNewlines(), theme)
244            } else {
245                lineText(Text(styled(start..<NSMaxRange(line)).trimmingTrailingNewlines()), theme)
246            }
247        }
248        .padding(.leading, headingIndent(entry, theme))
249        .padding(.top, entry.level == 1 ? 6 : 0)
250        .contentShape(Rectangle())
251        .onTapGesture { fold = Presentation.cycle(entry.start, in: tree, fold) }
252        .accessibilityAddTraits(.isButton)
253        .accessibilityHint(foldedMark ? "Unfolds the heading" : "Folds the heading")
254    }
255
256    /// A heading whose tags are padded: as written when the line fits, the tags at the right
257    /// edge when they fit after one space, else the tags on a line of their own at the right.
258    private func headingWithTags(title: AttributedString, gap: AttributedString, tags: AttributedString, _ theme: MobileTheme) -> some View {
259        ViewThatFits(in: .horizontal) {
260            Text(title + gap + tags).fixedSize()
261            HStack(alignment: .firstTextBaseline, spacing: 0) {
262                Text(title).fixedSize()
263                Spacer(minLength: theme.column)
264                Text(tags).fixedSize()
265            }
266            VStack(alignment: .trailing, spacing: 0) {
267                lineText(Text(title), theme)
268                Text(tags).fixedSize()
269            }
270        }
271        .lineSpacing(CGFloat(max(0, theme.spec.lineSpacing)))
272    }
273
274    private func textView(_ tree: OrgTree, _ range: Range<Int>, _ theme: MobileTheme) -> some View {
275        VStack(alignment: .leading, spacing: 4) {
276            ForEach(parts(tree, range), id: \.range.lowerBound) { part in
277                if let image = part.image {
278                    Image(uiImage: image.picture).resizable().scaledToFit()
279                        .frame(maxWidth: image.width.map { CGFloat($0) } ?? image.picture.size.width, alignment: .leading)
280                        .accessibilityLabel((image.path as NSString).lastPathComponent)
281                } else {
282                    lineText(text(tree, part, theme), theme)
283                        .textSelection(.enabled)
284                }
285            }
286        }
287    }
288
289    /// A part's text, with each image in it standing where its link is.
290    private func text(_ tree: OrgTree, _ part: Part, _ theme: MobileTheme) -> Text {
291        func styled(_ range: Range<Int>) -> AttributedString {
292            attributed(ReadingText.segments(tree, in: range, folded: folded, open: foldable.filter { !folded.contains($0) }, display: display), heading: nil, theme)
293        }
294        var text = Text("")
295        var start = part.range.lowerBound
296        for image in part.inText {
297            text = Text("\(text)\(Text(styled(start..<image.range.lowerBound)))\(Image(uiImage: image.picture))")
298            start = image.range.upperBound
299        }
300        return Text("\(text)\(Text(styled(start..<part.range.upperBound).trimmingTrailingNewlines()))")
301    }
302
303    /// Wrapped to the view's width, or on one line each, scrolling sideways, while truncated.
304    private func lineText(_ text: Text, _ theme: MobileTheme) -> some View {
305        text
306            .lineSpacing(CGFloat(max(0, theme.spec.lineSpacing)))
307            .fixedSize(horizontal: startup?.truncated ?? false, vertical: false)
308            .frame(maxWidth: startup?.truncated == true ? nil : .infinity, alignment: .leading)
309    }
310
311    private struct Part {
312        let range: Range<Int>
313        /// The image of a link that is all its line holds.
314        var image: (picture: UIImage, path: String, width: Int?)?
315        /// Images in the text, at their size, and the links they stand for.
316        var inText: [(range: Range<Int>, picture: UIImage)] = []
317    }
318
319    /// Text, and with inline images on, image links shown as their images: a link that is all
320    /// its line holds as a part of its own, others in their part's text.
321    private func parts(_ tree: OrgTree, _ range: Range<Int>) -> [Part] {
322        guard startup?.inlineImages == true, let path = shownPath else { return [Part(range: range)] }
323        // Read so that the view draws again when a remote image arrives.
324        _ = RemoteImages.shared.version
325        let remote = RemoteImages.Mode(rawValue: session.options.remoteInlineImages) ?? .skip
326        let base = URL(fileURLWithPath: path).deletingLastPathComponent()
327        let ns = tree.text as NSString
328        let maxWidth = width > 0 ? max(80, width - 72) : .greatestFiniteMagnitude
329        var parts: [Part] = []
330        var pending = Part(range: range.lowerBound..<range.lowerBound)
331        let links = InlineImages.links(tree, in: range, remote: remote != .skip, attachment: { DocumentSession.attachmentPath($0, at: $1, tree: tree, path: path) })
332        for placement in Presentation.imagePlacements(links, in: ns) {
333            let link = placement.link
334            guard link.range.lowerBound >= pending.range.lowerBound, link.range.upperBound <= range.upperBound,
335                  folded.allSatisfy({ !$0.contains(link.range.lowerBound) }),
336                  let picture = MobileEditor.loadImage(link.image.path, relativeTo: base, remote: remote) else { continue }
337            guard placement.ownLine else {
338                let size = Presentation.imageSize(natural: picture.size, width: link.image.width, maxWidth: maxWidth)
339                let sized = picture.cgImage.map { UIImage(cgImage: $0, scale: picture.size.width * picture.scale / max(1, size.width), orientation: picture.imageOrientation) }
340                pending.inText.append((link.range, sized ?? picture))
341                continue
342            }
343            let line = ns.lineRange(for: NSRange(location: link.range.lowerBound, length: 0))
344            if pending.range.lowerBound < line.location {
345                parts.append(Part(range: pending.range.lowerBound..<line.location, inText: pending.inText))
346            }
347            let end = min(NSMaxRange(line), range.upperBound)
348            parts.append(Part(range: line.location..<end, image: (picture, link.image.path, link.image.width)))
349            pending = Part(range: end..<end)
350        }
351        if pending.range.lowerBound < range.upperBound { parts.append(Part(range: pending.range.lowerBound..<range.upperBound, inText: pending.inText)) }
352        return parts
353    }
354
355    /// Segments as styled text in the theme's font and colors, as the editor styles them;
356    /// links get `orgstar-link:` URLs to follow.
357    private func attributed(_ segments: [ReadingText.Segment], heading level: Int?, _ theme: MobileTheme) -> AttributedString {
358        var result = AttributedString()
359        for segment in segments {
360            var part = AttributedString(segment.text)
361            var font = level.map(theme.headingFont) ?? theme.body
362            if theme.mixedPitch, segment.roles.contains(where: Presentation.isFixedPitch) { font = theme.fixedPitch(font) }
363            var color = level.flatMap { theme.color("heading-\(min(max($0, 1), 8))") } ?? theme.foreground
364            func fg(_ key: String) { if let c = theme.color(key) { color = c } }
365            // Outer roles first, so inner ones win.
366            for role in segment.roles.sorted(by: { Self.depth($0) < Self.depth($1) }) {
367                switch role {
368                case .todo, .done:
369                    font = MobileTheme.adding(.traitBold, to: font)
370                    if let c = theme.keywordColor(segment.text, done: role == .done) { color = c }
371                case .priority: fg("priority")
372                case .tags: fg("tags")
373                case .bold: font = MobileTheme.adding(.traitBold, to: font)
374                case .italic: font = MobileTheme.adding(.traitItalic, to: font)
375                case .underline: part.underlineStyle = .single
376                case .strikeThrough: part.strikethroughStyle = .single
377                case .verbatim, .code, .inlineSource:
378                    if let background = theme.color("inline-background") { part.backgroundColor = Color(uiColor: background) }
379                    fg(role == .verbatim ? "verbatim" : "code")
380                case .markup, .linkMarkup: fg("markup")
381                case .leadingStars:
382                    // As the editor hides them; shown in the heading's color unless hidden.
383                    if !Presentation.skipsLeadingStars(role, indented: indented, hideStars: startup?.hideStars ?? false) { color = .clear }
384                case .syntax(let category): if let key = category.themeKey { fg(key) }
385                case .timestamp: fg("timestamp")
386                case .comment: fg("comment")
387                case .keyword: fg("keyword")
388                case .metadata: fg("metadata")
389                case .blockDelimiter: fg("block-delimiter")
390                case .footnote, .cookie, .target, .macro, .latex: fg("special")
391                case .table, .rule: fg("table")
392                case .link:
393                    part.underlineStyle = .single
394                    fg("link")
395                case .heading, .block: break
396                }
397            }
398            if segment.link != nil {
399                // Found again by position when followed.
400                part.link = URL(string: "orgstar-link:\(segment.offset)")
401            }
402            if let start = segment.toggles { part.link = URL(string: "orgstar-fold:\(start)") }
403            if let superscript = segment.superscript {
404                // Raised or lowered as the editor draws `org-pretty-entities` scripts.
405                part.baselineOffset = (superscript ? 0.3 : -0.3) * font.pointSize
406                font = font.withSize(font.pointSize * 0.7)
407            }
408            part.font = Font(font as CTFont)
409            part.foregroundColor = Color(uiColor: color)
410            if !found.isEmpty { markFound(&part, segment) }
411            result += part
412        }
413        return result
414    }
415
416    /// Find's results in a segment's text: exactly where the segment shows the file as written,
417    /// otherwise the whole segment.
418    private func markFound(_ part: inout AttributedString, _ segment: ReadingText.Segment) {
419        let length = (segment.text as NSString).length
420        let span = segment.offset..<(segment.offset + length)
421        let source = (document?.tree.text ?? "") as NSString
422        let asWritten = span.upperBound <= source.length && source.substring(with: NSRange(span)) == segment.text
423        for (range, shown) in found where range.overlaps(span) || (span.isEmpty && range.contains(span.lowerBound)) {
424            let color = Color(uiColor: shown ? .systemYellow : .systemYellow.withAlphaComponent(0.35))
425            guard asWritten else {
426                part.backgroundColor = color
427                continue
428            }
429            let text = segment.text
430            func index(_ offset: Int) -> AttributedString.Index {
431                let utf16 = text.utf16.index(text.startIndex, offsetBy: min(max(0, offset - span.lowerBound), length))
432                return part.index(part.startIndex, offsetByCharacters: text.distance(from: text.startIndex, to: utf16))
433            }
434            let lower = index(range.lowerBound), upper = index(range.upperBound)
435            if lower < upper { part[lower..<upper].backgroundColor = color }
436        }
437    }
438
439    /// Unfolds the way to a find result, its heading and a drawer it's in, and scrolls to its heading.
440    private func showFound(_ offset: Int, _ proxy: ScrollViewProxy) {
441        folded.removeAll { $0.contains(offset) }
442        // Before the first heading, the text shows already.
443        guard let index = outline.lastIndex(where: { $0.start <= offset }) else { return }
444        fold.folds.remove(outline[index].start)
445        fold.bodyFolds.remove(outline[index].start)
446        reveal(offset, proxy)
447    }
448
449    /// How deep a role's text usually nests: elements, then objects, then their parts.
450    private static func depth(_ role: StyleRole) -> Int {
451        switch role {
452        case .heading: 0
453        case .metadata, .keyword, .comment, .block, .table, .rule: 1
454        case .blockDelimiter, .link, .bold, .italic, .underline, .strikeThrough, .timestamp, .footnote, .target, .macro, .latex: 2
455        default: 3
456        }
457    }
458
459    // MARK: - Actions
460
461    private func open() {
462        find.onChange = { found = $0 }
463        find.onShow = { findTarget = $0 }
464        let pane = holder.pane ?? {
465            let made = session.makePane()
466            holder.pane = made
467            holder.release = { [weak session] in session?.closePane(made) }
468            return made
469        }()
470        // What the reader opens and follows goes to its pane.
471        session.focused = pane
472        if loadedPath == nil {
473            switch route {
474            case .file(let path): session.open(path, in: pane)
475            case .offset(let path, let offset):
476                session.open(path, in: pane)
477                session.reveal(offset, in: pane)
478            case .heading(let location): session.show(location)
479            }
480        }
481        loadFolds()
482    }
483
484    /// The file's startup display, as the editor opens it; its heading folds are kept while
485    /// the same file is open.
486    private func loadFolds() {
487        guard let tree = document?.tree, showsOwnFile else { return }
488        let display = Presentation.startupDisplay(tree, options: session.options)
489        startup = display
490        let text = tree.text as NSString
491        tagGaps = Dictionary(Presentation.tagGaps(tree).map { (text.lineRange(for: NSRange(location: $0.gap.lowerBound, length: 0)).location, $0) }) { a, _ in a }
492        folded = display.wrappers.map(\.hidden)
493        foldable = folded
494        guard loadedPath != shownPath else { return }
495        loadedPath = shownPath
496        fold = display.folds
497    }
498
499    /// Unfolds the way to the heading containing `offset` and scrolls to it.
500    private func reveal(_ offset: Int, _ proxy: ScrollViewProxy) {
501        guard let index = outline.lastIndex(where: { $0.start <= offset }) else { return }
502        var parent = outline[index].parent
503        while let p = parent {
504            fold.folds.remove(outline[p].start)
505            parent = outline[p].parent
506        }
507        let start = outline[index].start
508        DispatchQueue.main.async { withAnimation { proxy.scrollTo(start, anchor: .top) } }
509    }
510
511    private func follow(_ url: URL) -> OpenURLAction.Result {
512        if url.scheme == "orgstar-fold", let start = Int(url.absoluteString.dropFirst("orgstar-fold:".count)) {
513            if folded.contains(where: { $0.lowerBound == start }) {
514                folded.removeAll { $0.lowerBound == start }
515            } else if let range = foldable.first(where: { $0.lowerBound == start }) {
516                folded.append(range)
517            }
518            return .handled
519        }
520        guard url.scheme == "orgstar-link", let offset = Int(url.absoluteString.dropFirst("orgstar-link:".count)),
521              let tree = document?.tree, let link = Links.link(at: offset, text: tree.text, tree: tree)?.link else {
522            return .systemAction
523        }
524        if let pane { session.focused = pane }
525        switch session.follow(link, workspace: workspace, isText: { _ in false }) {
526        case .shown:
527            message = nil
528            // A link to another file shows it on its own screen; this pane keeps its file.
529            if let pane, let target = pane.path, target != path, !showsOwnFile {
530                let caret = session.caret(of: target) ?? 0
531                session.open(path, in: pane)
532                model.openRequest = .offset(target, caret)
533            }
534        case .openExternally(let target): if target.isFileURL { previewed = target } else { openURL(target) }
535        case .message(let text): message = text
536        case .choose(let question, let paths): message = question + paths.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
537        case .elisp: message = "Open the file in the editor to run elisp links."
538        }
539        return .handled
540    }
541
542    private var outlineSheet: some View {
543        NavigationStack {
544            List(outline, id: \.start) { entry in
545                Button {
546                    showingOutline = false
547                    if let pane { session.reveal(entry.start, in: pane) }
548                } label: {
549                    Text(entry.title.isEmpty ? "(untitled)" : entry.title)
550                        .padding(.leading, indent(entry))
551                        .foregroundStyle(.primary)
552                }
553            }
554            .navigationTitle("Outline")
555            .navigationBarTitleDisplayMode(.inline)
556            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { showingOutline = false } } }
557        }
558    }
559}
560
561/// The reader's find, for the system find bar: it searches the file as written and tells the
562/// reader which results to mark and which one to show.
563@MainActor
564final class ReaderFind: NSObject, @preconcurrency UITextSearching, UIFindInteractionDelegate {
565    /// The file's text, set when the find bar opens.
566    nonisolated(unsafe) var text: NSString = ""
567    /// Each result marked, true for the one shown.
568    var onChange: ([Range<Int>: Bool]) -> Void = { _ in }
569    /// The result to show, by its offset.
570    var onShow: (Int) -> Void = { _ in }
571    private var marked: [Range<Int>: Bool] = [:]
572
573    final class Position: UITextPosition {
574        let offset: Int
575        init(_ offset: Int) { self.offset = offset }
576    }
577
578    final class TextRange: UITextRange {
579        let range: Range<Int>
580        init(_ range: Range<Int>) { self.range = range }
581        override var start: UITextPosition { Position(range.lowerBound) }
582        override var end: UITextPosition { Position(range.upperBound) }
583        override var isEmpty: Bool { range.isEmpty }
584    }
585
586    func findInteraction(_ interaction: UIFindInteraction, sessionFor view: UIView) -> UIFindSession? {
587        UITextSearchingFindSession(searchableObject: self)
588    }
589
590    var selectedTextRange: UITextRange? { nil }
591
592    func compare(_ foundRange: UITextRange, toRange: UITextRange, document: AnyHashable??) -> ComparisonResult {
593        let a = (foundRange as? TextRange)?.range.lowerBound ?? 0, b = (toRange as? TextRange)?.range.lowerBound ?? 0
594        return a < b ? .orderedAscending : a > b ? .orderedDescending : .orderedSame
595    }
596
597    /// May be called off the main thread; reads only `text`, an immutable string.
598    nonisolated func performTextSearch(queryString: String, options: UITextSearchOptions, resultAggregator: UITextSearchAggregator<AnyHashable?>) {
599        for found in EditorFind.matches(of: queryString, in: text, options: options) {
600            resultAggregator.foundRange(TextRange(found), searchString: queryString, document: nil)
601        }
602        resultAggregator.finishedSearching()
603    }
604
605    func decorate(foundTextRange: UITextRange, document: AnyHashable??, usingStyle style: UITextSearchFoundTextStyle) {
606        guard let range = (foundTextRange as? TextRange)?.range else { return }
607        switch style {
608        case .normal: marked[range] = nil
609        case .highlighted:
610            marked[range] = true
611            onShow(range.lowerBound)
612        default: marked[range] = false
613        }
614        onChange(marked)
615    }
616
617    func clearAllDecoratedFoundText() {
618        marked = [:]
619        onChange(marked)
620    }
621
622    func scrollRangeToVisible(_ range: UITextRange, inDocument: AnyHashable??) {
623        if let range = (range as? TextRange)?.range { onShow(range.lowerBound) }
624    }
625}
626
627/// Holds the find interaction for a SwiftUI screen, and shows its find bar when `request` changes.
628private struct FindHost: UIViewRepresentable {
629    let find: ReaderFind
630    let request: Int
631
632    /// The find bar shows for the first responder's interaction.
633    final class Host: UIView {
634        override var canBecomeFirstResponder: Bool { true }
635    }
636
637    func makeUIView(context: Context) -> Host {
638        let view = Host()
639        view.addInteraction(UIFindInteraction(sessionDelegate: find))
640        return view
641    }
642
643    func updateUIView(_ view: Host, context: Context) {
644        guard request != context.coordinator.shown else { return }
645        context.coordinator.shown = request
646        view.becomeFirstResponder()
647        view.interactions.lazy.compactMap { $0 as? UIFindInteraction }.first?.presentFindNavigator(showingReplace: false)
648    }
649
650    func makeCoordinator() -> Coordinator { Coordinator() }
651
652    final class Coordinator {
653        var shown = 0
654    }
655}
656
657private extension AttributedString {
658    /// Without the final newline, which `Text` would show as an empty line.
659    func trimmingTrailingNewlines() -> AttributedString {
660        var copy = self
661        while let last = copy.characters.last, last.isNewline { copy.characters.removeLast() }
662        return copy
663    }
664}
665#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