| @@ -43,6 +43,12 @@ struct ReaderScreen: View { |
| 43 | @State private var previewed: URL? |
43 | @State private var previewed: URL? |
| 44 | /// The pane the reader shows its file in, closed with the reader. |
44 | /// The pane the reader shows its file in, closed with the reader. |
| 45 | @State private var holder = PaneHolder() |
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? |
| 46 | @Environment(\.openURL) private var openURL |
52 | @Environment(\.openURL) private var openURL |
| 47 | @Environment(MobileModel.self) private var model |
53 | @Environment(MobileModel.self) private var model |
| 48 | |
54 | |
| @@ -103,11 +109,21 @@ struct ReaderScreen: View { |
| 103 | guard let offset = pane?.revealRequest?.offset else { return } |
109 | guard let offset = pane?.revealRequest?.offset else { return } |
| 104 | reveal(offset, proxy) |
110 | reveal(offset, proxy) |
| 105 | } |
111 | } |
| |
112 | .onChange(of: findTarget) { |
| |
113 | guard let offset = findTarget else { return } |
| |
114 | findTarget = nil |
| |
115 | showFound(offset, proxy) |
| |
116 | } |
| 106 | } |
117 | } |
| 107 | .navigationTitle(((shownPath ?? "") as NSString).lastPathComponent) |
118 | .navigationTitle(((shownPath ?? "") as NSString).lastPathComponent) |
| 108 | .navigationBarTitleDisplayMode(.inline) |
119 | .navigationBarTitleDisplayMode(.inline) |
| 109 | .toolbar { |
120 | .toolbar { |
| 110 | ToolbarItemGroup(placement: .primaryAction) { |
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) |
| 111 | Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty) |
127 | Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty) |
| 112 | if let path = shownPath { |
128 | if let path = shownPath { |
| 113 | if let tree = document?.tree { ExportMenu(path: path, tree: tree) { message = $0 } } |
129 | if let tree = document?.tree { ExportMenu(path: path, tree: tree) { message = $0 } } |
| @@ -119,6 +135,7 @@ struct ReaderScreen: View { |
| 119 | .sheet(isPresented: $showingOutline) { outlineSheet } |
135 | .sheet(isPresented: $showingOutline) { outlineSheet } |
| 120 | .message($message) |
136 | .message($message) |
| 121 | .environment(\.openURL, OpenURLAction { url in follow(url) }) |
137 | .environment(\.openURL, OpenURLAction { url in follow(url) }) |
| |
138 | .background { FindHost(find: find, request: findRequest) } |
| 122 | .onAppear(perform: open) |
139 | .onAppear(perform: open) |
| 123 | .onChange(of: pane?.path) { loadFolds() } |
140 | .onChange(of: pane?.path) { loadFolds() } |
| 124 | .onChange(of: pane?.editVersion) { loadFolds() } |
141 | .onChange(of: pane?.editVersion) { loadFolds() } |
| @@ -325,11 +342,45 @@ struct ReaderScreen: View { |
| 325 | } |
342 | } |
| 326 | part.font = Font(font as CTFont) |
343 | part.font = Font(font as CTFont) |
| 327 | part.foregroundColor = Color(uiColor: color) |
344 | part.foregroundColor = Color(uiColor: color) |
| |
345 | if !found.isEmpty { markFound(&part, segment) } |
| 328 | result += part |
346 | result += part |
| 329 | } |
347 | } |
| 330 | return result |
348 | return result |
| 331 | } |
349 | } |
| 332 | |
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 | |
| 333 | /// How deep a role's text usually nests: elements, then objects, then their parts. |
384 | /// How deep a role's text usually nests: elements, then objects, then their parts. |
| 334 | private static func depth(_ role: StyleRole) -> Int { |
385 | private static func depth(_ role: StyleRole) -> Int { |
| 335 | switch role { |
386 | switch role { |
| @@ -343,6 +394,8 @@ struct ReaderScreen: View { |
| 343 | // MARK: - Actions |
394 | // MARK: - Actions |
| 344 | |
395 | |
| 345 | private func open() { |
396 | private func open() { |
| |
397 | find.onChange = { found = $0 } |
| |
398 | find.onShow = { findTarget = $0 } |
| 346 | let pane = holder.pane ?? { |
399 | let pane = holder.pane ?? { |
| 347 | let made = session.makePane() |
400 | let made = session.makePane() |
| 348 | holder.pane = made |
401 | holder.pane = made |
| @@ -438,6 +491,102 @@ struct ReaderScreen: View { |
| 438 | } |
491 | } |
| 439 | } |
492 | } |
| 440 | |
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 |
| |
497 | final 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. |
| |
561 | private 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 | |
| 441 | private extension AttributedString { |
590 | private extension AttributedString { |
| 442 | /// Without the final newline, which `Text` would show as an empty line. |
591 | /// Without the final newline, which `Text` would show as an empty line. |
| 443 | func trimmingTrailingNewlines() -> AttributedString { |
592 | func trimmingTrailingNewlines() -> AttributedString { |