Sources/OrgstarMobile/ReaderScreen.swift

3751eb733020e3cdc9832f98bc6720b65a1f2ecb
orgstar/Sources/OrgstarMobile/ReaderScreen.swift

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