Sources/OrgApp/ReplacePreview.swift
143 lines · 7133 bytes
6 symbols in this file
1import OrgCore
2import SwiftUI
3
4/// Which of the commands over files a sheet runs.
5public enum ReplaceKind: String, Identifiable, Sendable {
6 case replace, renameTag, renameKeyword
7 public var id: String { rawValue }
8
9 /// The command that opens it.
10 public init?(command: String) {
11 switch command {
12 case "app.replace-in-files": self = .replace
13 case "app.rename-tag": self = .renameTag
14 case "app.rename-todo-keyword": self = .renameKeyword
15 default: return nil
16 }
17 }
18
19 public var title: String {
20 switch self {
21 case .replace: String(localized: "Replace in Files", comment: "Window title")
22 case .renameTag: String(localized: "Rename Tag", comment: "Window title")
23 case .renameKeyword: String(localized: "Rename TODO Keyword", comment: "Window title")
24 }
25 }
26
27 /// What the sheet starts with for a heading line at `caret`: its tag under the caret or
28 /// first tag, or its TODO keyword.
29 public func initial(text: String, caret: Int, keywords: Set<String>) -> String {
30 guard self != .replace else { return "" }
31 let ns = text as NSString
32 let lineRange = ns.lineRange(for: NSRange(location: min(caret, ns.length), length: 0))
33 let line = ns.substring(with: lineRange).trimmingCharacters(in: .newlines)
34 guard line.hasPrefix("*") else { return "" }
35 let words = line.drop { $0 == "*" }.split(whereSeparator: { $0 == " " || $0 == "\t" })
36 if self == .renameKeyword {
37 return words.first.map(String.init).flatMap { keywords.contains($0) ? $0 : nil } ?? ""
38 }
39 guard let tags = line.firstMatch(of: /[ \t]:([\p{L}\p{N}_@#%:]+):[ \t]*$/) else { return "" }
40 let start = line.utf16.distance(from: line.startIndex, to: tags.1.startIndex)
41 var at = start
42 for tag in tags.1.split(separator: ":") {
43 let end = at + tag.utf16.count
44 if (lineRange.location + at...lineRange.location + end).contains(caret) { return String(tag) }
45 at = end + 1
46 }
47 return tags.1.split(separator: ":").first.map(String.init) ?? ""
48 }
49
50 /// The button that applies the ticked changes.
51 public var applyTitle: String {
52 switch self {
53 case .replace: String(localized: "Replace", comment: "Replace in Files: applies the ticked changes")
54 case .renameTag, .renameKeyword: String(localized: "Rename", comment: "Rename Tag or TODO Keyword: applies the ticked changes")
55 }
56 }
57}
58
59/// The changes a search found, by file and line, each with a checkbox: the line with the part
60/// that goes struck through in `removed` and what replaces it in `added`.
61public struct ReplacePreview: View {
62 let model: ReplaceInFiles
63 let removed: Color
64 let added: Color
65 @Environment(\.accessibilityDifferentiateWithoutColor) private var withoutColor
66
67 public init(model: ReplaceInFiles, removed: Color = .red, added: Color = .green) {
68 self.model = model
69 self.removed = removed
70 self.added = added
71 }
72
73 public var body: some View {
74 List {
75 if let change = model.configChange, model.changesConfig {
76 Section {
77 VStack(alignment: .leading, spacing: 2) {
78 Text(verbatim: "\(change.key) = \"\(change.new.replacingOccurrences(of: "\n", with: "\\n"))\"")
79 .font(.system(.callout, design: .monospaced))
80 Text("Was \"\(change.old.replacingOccurrences(of: "\n", with: "\\n"))\"", comment: "Rename: the config.toml setting before the change")
81 .font(.caption).foregroundStyle(.secondary)
82 }
83 } header: {
84 Text(verbatim: "config.toml")
85 }
86 }
87 ForEach(model.files) { file in
88 Section {
89 // Ids unique across files: a List reuses rows by id across its sections.
90 ForEach(file.changes.map { (key: file.path + "#\($0.id)", change: $0) }, id: \.key) { item in
91 let change = item.change
92 Toggle(isOn: Binding(get: { !file.unticked.contains(change.id) }, set: { model.setTicked($0, change: change.id, in: file.path) })) {
93 row(change)
94 }
95 }
96 } header: {
97 Toggle(isOn: Binding(get: { file.isIncluded }, set: { model.setTicked($0, file: file.path) })) {
98 HStack(spacing: 6) {
99 Text(verbatim: file.name).bold()
100 Text(verbatim: file.relativePath).foregroundStyle(.secondary).lineLimit(1).truncationMode(.head)
101 Spacer()
102 Text("\(file.changes.count - file.unticked.count) of \(file.changes.count)", comment: "Replace in Files: ticked changes of the file's changes")
103 .foregroundStyle(.secondary).monospacedDigit()
104 }
105 }
106 }
107 }
108 }
109 #if os(macOS)
110 .toggleStyle(.checkbox)
111 #endif
112 }
113
114 private func row(_ change: ProposedChange) -> some View {
115 let line = change.lineText as NSString
116 let start = min(change.changed.lowerBound, line.length), end = min(change.changed.upperBound, line.length)
117 var old = AttributedString(Self.collapsed(line.substring(with: NSRange(location: start, length: end - start))))
118 old.strikethroughStyle = .single
119 old.foregroundColor = removed
120 var new = AttributedString(Self.collapsed(change.replacement.replacingOccurrences(of: "\n", with: "⏎")))
121 new.foregroundColor = added
122 if withoutColor { new.underlineStyle = .single }
123 let text = AttributedString(Self.trimmedStart(Self.collapsed(line.substring(to: start)))) + old + new
124 + AttributedString(Self.collapsed(line.substring(from: end)))
125 return HStack(alignment: .firstTextBaseline, spacing: 8) {
126 Text(verbatim: "\(change.line)").foregroundStyle(.secondary).monospacedDigit()
127 Text(text).lineLimit(2).font(.system(.callout, design: .monospaced))
128 }
129 .accessibilityElement(children: .ignore)
130 .accessibilityLabel(Text("Line \(change.line): \(change.lineText)", comment: "Replace in Files: a change, for VoiceOver"))
131 .accessibilityValue(Text("Becomes \(line.substring(to: start) + change.replacement + line.substring(from: end))", comment: "Replace in Files: the line after the change, for VoiceOver"))
132 }
133
134 /// Runs of blanks as one space, so the spaces that align tags don't fill the row.
135 static func collapsed(_ text: String) -> String {
136 text.replacingOccurrences(of: "[ \t]{2,}", with: " ", options: .regularExpression)
137 }
138
139 /// A long start of a line, cut to its last 40 characters so the change shows.
140 static func trimmedStart(_ text: String) -> String {
141 text.count > 40 ? "…" + text.suffix(40) : text
142 }
143}