Repository Public
1// ORIX Docs2// File: App/Sources/Sidebar/FindPanel.swift3// Description: The find and replace panel: query and options, result list with context and location, navigation,4// and undoable Replace / Replace All through the editing engine.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel1011struct FindPanel: View {12 @Bindable var session: DocumentSession13 @State private var replacement = ""14 @State private var searchTask: Task<Void, Never>?15 @FocusState private var focus: Field?1617 private enum Field { case query, replacement }1819 var body: some View {20 let _ = session.revision21 let _ = session.selectionRevision22 let matches = session.findMatches23 let current = currentIndex(in: matches)24 let regexError = regexProblem25 VStack(spacing: 0) {26 VStack(alignment: .leading, spacing: ORIX.Space.s) {27 SidebarSectionHeader(title: "Find and Replace") {28 Text(countText(matches.count, current: current)).monospacedDigit().lineLimit(1).fixedSize()29 .accessibilityIdentifier("find-count")30 }31 .frame(height: 14)32 HStack(spacing: 6) {33 Image(systemName: "magnifyingglass").font(.system(size: 11, weight: .medium)).foregroundStyle(ORIX.Palette.textTertiary)34 TextField("Find in document", text: $session.findQuery)35 .textFieldStyle(.plain).font(ORIX.Font.body)36 .focused($focus, equals: .query)37 .onSubmit { step(forward: true); focus = .query }38 .accessibilityIdentifier("find-query")39 if !session.findQuery.isEmpty {40 Button { session.findQuery = ""; focus = .query } label: { Image(systemName: "xmark.circle.fill").font(.system(size: 11)) }41 .buttonStyle(.plain).foregroundStyle(ORIX.Palette.textTertiary)42 .help("Clear").accessibilityLabel(Text("Clear search"))43 }44 }45 .padding(.horizontal, 7).padding(.vertical, 5)46 .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(ORIX.Palette.surface))47 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(regexError != nil ? ORIX.Palette.critical : (focus == .query ? ORIX.Palette.accent : ORIX.Palette.hairline)))4849 if let regexError {50 Label { Text("Invalid regular expression: \(regexError)") } icon: { Image(systemName: "exclamationmark.triangle.fill") }51 .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.critical)52 .fixedSize(horizontal: false, vertical: true)53 .accessibilityIdentifier("find-regex-error")54 }5556 HStack(spacing: 4) {57 FindOptionChip(text: "Aa", help: "Match Case", isOn: $session.findOptions.caseSensitive).accessibilityIdentifier("find-option-case")58 FindOptionChip(text: "W", help: "Whole Words", isOn: $session.findOptions.wholeWord, isEnabled: !session.findOptions.regularExpression)59 .accessibilityIdentifier("find-option-word")60 FindOptionChip(text: ".*", help: "Regular Expression", isOn: $session.findOptions.regularExpression).accessibilityIdentifier("find-option-regex")61 FindOptionChip(text: "é", help: "Match Accents and Diacritics", isOn: $session.findOptions.diacriticSensitive, isEnabled: !session.findOptions.regularExpression)62 .accessibilityIdentifier("find-option-diacritics")63 Spacer(minLength: 0)64 BarButton(symbol: "chevron.up", help: "Previous Result", isEnabled: !matches.isEmpty) { step(forward: false) }65 .accessibilityIdentifier("find-previous")66 BarButton(symbol: "chevron.down", help: "Next Result", isEnabled: !matches.isEmpty) { step(forward: true) }67 .accessibilityIdentifier("find-next")68 }6970 TextField(session.findOptions.regularExpression ? "Replace with ($1 inserts a group)" : "Replace with", text: $replacement)71 .focused($focus, equals: .replacement)72 .modifier(SidebarFieldChrome(focused: focus == .replacement))73 .onSubmit { replaceCurrent() }74 .accessibilityIdentifier("find-replacement")75 HStack(spacing: ORIX.Space.s) {76 Button { replaceCurrent() } label: { Text("Replace").frame(maxWidth: .infinity) }77 .buttonStyle(ORIXButtonStyle(prominent: false))78 .accessibilityIdentifier("find-replace")79 Button { replaceAll() } label: { Text("Replace All").frame(maxWidth: .infinity) }80 .buttonStyle(ORIXButtonStyle(prominent: false))81 .accessibilityIdentifier("find-replace-all")82 }83 .disabled(matches.isEmpty)84 .opacity(matches.isEmpty ? 0.45 : 1)85 }86 .padding(.horizontal, ORIX.Space.m).padding(.top, ORIX.Space.s).padding(.bottom, ORIX.Space.m)87 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)8889 if session.findQuery.isEmpty {90 EmptyState(symbol: "text.magnifyingglass", title: "Search the whole document",91 message: "Body text, tables, headers, footers and notes are searched. Press Return for the next result.")92 } else if matches.isEmpty {93 EmptyState(symbol: "magnifyingglass", title: "No results",94 message: regexError == nil ? "Nothing in this document matches. Check the options above." : "Correct the regular expression to search.")95 } else {96 ScrollViewReader { proxy in97 ScrollView {98 LazyVStack(alignment: .leading, spacing: 1) {99 ForEach(Array(matches.enumerated()), id: \.element.id) { index, match in100 FindResultRow(session: session, match: match, isCurrent: index == current) { session.selectMatch(match) }101 .id(match.id)102 }103 }104 .padding(ORIX.Space.s)105 }106 .onChange(of: current) { _, index in107 if let index, matches.indices.contains(index) { proxy.scrollTo(matches[index].id) }108 }109 }110 }111 }112 .onAppear { takeFocus() }113 .onChange(of: session.focusFindField) { _, _ in takeFocus() }114 .onChange(of: session.findQuery) { _, _ in scheduleSearch() }115 .onChange(of: session.findOptions) { _, _ in session.runFind() }116 .onExitCommand { session.canvas?.window?.makeFirstResponder(session.canvas) }117 .accessibilityIdentifier("find-panel")118 }119120 private func takeFocus() { DispatchQueue.main.async { focus = .query } }121122 /// Searches shortly after the last keystroke so a long document is not scanned for every character typed.123 private func scheduleSearch() {124 searchTask?.cancel()125 searchTask = Task {126 try? await Task.sleep(for: .milliseconds(120))127 guard !Task.isCancelled else { return }128 session.runFind()129 }130 }131132 private var regexProblem: String? {133 guard session.findOptions.regularExpression, !session.findQuery.isEmpty else { return nil }134 do { _ = try NSRegularExpression(pattern: session.findQuery); return nil } catch { return error.localizedDescription }135 }136137 private func countText(_ count: Int, current: Int?) -> String {138 if session.findQuery.isEmpty { return "" }139 if count == 0 { return String(localized: "No results") }140 if let current { return String(localized: "\(current + 1) of \(count)") }141 return String(localized: "\(count) results")142 }143144 /// Index of the match that is exactly the selection.145 private func currentIndex(in matches: [TextMatch]) -> Int? {146 let sel = session.selection147 guard !sel.isCaret, sel.start.path == sel.end.path else { return nil }148 let range = sel.start.offset..<sel.end.offset149 return matches.firstIndex { $0.story == sel.story && $0.path == sel.start.path && $0.range == range }150 }151152 /// Moves to the next or previous result, keeping the keyboard in the panel.153 private func step(forward: Bool) {154 searchTask?.cancel()155 session.runFind()156 let matches = session.findMatches157 guard !matches.isEmpty else { return }158 let sel = session.selection159 let same = matches.filter { $0.story == sel.story }160 let pool = same.isEmpty ? matches : same161 let next: TextMatch162 if forward {163 let here = sel.end164 next = pool.first { Position(path: $0.path, offset: $0.range.lowerBound) >= here } ?? (same.isEmpty ? pool[0] : following(pool, in: matches, forward: true))165 } else {166 let here = sel.start167 next = pool.last { Position(path: $0.path, offset: $0.range.upperBound) <= here } ?? (same.isEmpty ? pool[pool.count - 1] : following(pool, in: matches, forward: false))168 }169 session.showRange(story: next.story, path: next.path, range: next.range)170 }171172 /// Past the last result of the current story: continue in the next story (results are in reading order), wrapping around.173 private func following(_ pool: [TextMatch], in matches: [TextMatch], forward: Bool) -> TextMatch {174 guard let edge = forward ? pool.last : pool.first, let i = matches.firstIndex(of: edge) else { return matches[0] }175 return matches[(i + (forward ? 1 : matches.count - 1)) % matches.count]176 }177178 private func expanded(_ match: TextMatch) -> String {179 guard session.findOptions.regularExpression,180 let re = try? NSRegularExpression(pattern: session.findQuery, options: session.findOptions.caseSensitive ? [] : [.caseInsensitive]),181 let p = session.doc.blocks(in: match.story).paragraph(at: match.path), match.range.upperBound <= p.length else { return replacement }182 let source = (p.plainText as NSString).substring(with: NSRange(location: match.range.lowerBound, length: match.range.count))183 return re.stringByReplacingMatches(in: source, range: NSRange(location: 0, length: (source as NSString).length), withTemplate: replacement)184 }185186 /// Replaces the selected result, then moves to the next one. With no result selected it only selects the next one.187 private func replaceCurrent() {188 searchTask?.cancel()189 session.runFind()190 let matches = session.findMatches191 guard let index = currentIndex(in: matches) else { step(forward: true); return }192 let match = matches[index], text = expanded(match)193 session.perform(String(localized: "Replace")) { $0.replace(match, with: text) }194 step(forward: true)195 }196197 private func replaceAll() {198 searchTask?.cancel()199 let query = session.findQuery, options = session.findOptions, text = replacement200 guard !query.isEmpty else { return }201 var count = 0202 session.perform(String(localized: "Replace All")) { count = $0.replaceAll(query, with: text, options: options) }203 session.statusMessage = String(localized: "\(count) replacements made")204 }205}206207/// A two-state option button whose glyph is text ("Aa", ".*"): the state is also exposed as a trait and drawn as a filled chip.208private struct FindOptionChip: View {209 let text: String210 let help: LocalizedStringKey211 @Binding var isOn: Bool212 var isEnabled = true213214 var body: some View {215 let on = isOn && isEnabled216 Button { isOn.toggle() } label: {217 Text(text)218 .font(.system(size: 11, weight: .semibold, design: .rounded))219 .frame(width: 26, height: 22)220 .foregroundStyle(on ? Color.white : ORIX.Palette.textSecondary.opacity(isEnabled ? 1 : 0.4))221 .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(on ? AnyShapeStyle(ORIX.Palette.accent) : AnyShapeStyle(ORIX.Palette.text.opacity(0.06))))222 .contentShape(Rectangle())223 }224 .buttonStyle(.plain)225 .disabled(!isEnabled)226 .help(help)227 .accessibilityLabel(Text(help))228 .accessibilityValue(on ? Text("On") : Text("Off"))229 .accessibilityAddTraits(on ? .isSelected : [])230 }231}232233private struct FindResultRow: View {234 let session: DocumentSession235 let match: TextMatch236 let isCurrent: Bool237 let action: () -> Void238 @State private var hover = false239240 var body: some View {241 Button(action: action) {242 VStack(alignment: .leading, spacing: 2) {243 Text(context).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2).multilineTextAlignment(.leading)244 Text(location).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)245 }246 .padding(.horizontal, 8).padding(.vertical, 5)247 .frame(maxWidth: .infinity, alignment: .leading)248 .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(isCurrent ? ORIX.Palette.accent.opacity(0.13) : (hover ? ORIX.Palette.text.opacity(0.06) : .clear)))249 .overlay(alignment: .leading) {250 if isCurrent { RoundedRectangle(cornerRadius: 1).fill(ORIX.Palette.accent).frame(width: 2.5).padding(.vertical, 4) }251 }252 .contentShape(Rectangle())253 }254 .buttonStyle(.plain)255 .onHover { hover = $0 }256 .accessibilityAddTraits(isCurrent ? .isSelected : [])257 }258259 private var location: String {260 let story = SidebarFormat.story(match.story, cell: match.path.cell != nil)261 guard let page = session.pageLabel(story: match.story, path: match.path, offset: match.range.lowerBound) else { return story }262 return String(localized: "\(story) · Page \(page)")263 }264265 /// The paragraph text around the match, with the match itself emphasised (weight and tint, not colour alone).266 private var context: AttributedString {267 guard let p = session.doc.blocks(in: match.story).paragraph(at: match.path), match.range.upperBound <= p.length else {268 return AttributedString(SidebarFormat.excerpt(match.context))269 }270 let ns = p.plainText as NSString271 let lo = max(0, match.range.lowerBound - 28), hi = min(ns.length, match.range.upperBound + 60)272 let before = ns.rangeOfComposedCharacterSequences(for: NSRange(location: lo, length: match.range.lowerBound - lo))273 let after = ns.rangeOfComposedCharacterSequences(for: NSRange(location: match.range.upperBound, length: hi - match.range.upperBound))274 func clean(_ s: String) -> String {275 s.replacingOccurrences(of: "\u{FFFC}", with: " ").replacingOccurrences(of: "\u{2028}", with: " ").replacingOccurrences(of: "\t", with: " ")276 }277 var out = AttributedString((before.location > 0 ? "…" : "") + clean(ns.substring(with: before)))278 var hit = AttributedString(clean(ns.substring(with: NSRange(location: match.range.lowerBound, length: match.range.count))))279 hit.font = .system(size: 11.5, weight: .bold)280 hit.foregroundColor = ORIX.Palette.text281 hit.backgroundColor = ORIX.Palette.secondary.opacity(0.28)282 out.append(hit)283 out.append(AttributedString(clean(ns.substring(with: after)) + (NSMaxRange(after) < ns.length ? "…" : "")))284 return out285 }286}287