Sources/OrgstarMobile/ReaderScreen.swift

15d73b1f0d2ee9cac84fe463bbeaf4b409d8f9fb
orgstar/Sources/OrgstarMobile/ReaderScreen.swift

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