Sources/OrgstarMobile/ReaderScreen.swift

a6efdda15d73f36320bc8a9004ecfbe07a6211f9
orgstar/Sources/OrgstarMobile/ReaderScreen.swift

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