// SPDX-License-Identifier: GPL-3.0-or-later import SwiftUI import WebKit /// Find within the displayed HTML, including words split by inline formatting. /// DOM Ranges preserve links, source listings and the page's original markup. @MainActor final class ManualPageFind: ObservableObject { private weak var webView: WKWebView? @Published private(set) var visible = false @Published private(set) var focusRequest = 0 @Published var query = "" { didSet { if query != oldValue { refresh() } } } @Published private(set) var count = 0 @Published private(set) var position = 0 @Published private(set) var searching = false private var revision = 0 private var requested = 0 init(webView: WKWebView) { self.webView = webView } func show() { if !visible { visible = true refresh() } focusRequest += 1 } func close() { guard visible else { return } visible = false clear() if let webView { webView.window?.makeFirstResponder(webView) } } func pageChanged() { // An in-flight reply belongs to the document which produced it. visible = false clear() } private func clear() { revision += 1 requested = 0 count = 0 position = 0 searching = false webView?.callAsyncJavaScript(Self.script, arguments: ["query": "", "index": 0], in: nil, in: .defaultClient, completionHandler: nil) } func move(backward: Bool = false) { guard visible else { show(); return } guard count > 0 else { return } requested = (requested + (backward ? count - 1 : 1)) % count run() } private func refresh() { requested = 0 count = 0 position = 0 if visible { run() } } private func run() { guard let webView else { return } revision += 1 let expected = revision searching = true webView.callAsyncJavaScript(Self.script, arguments: ["query": query, "index": requested], in: nil, in: .defaultClient) { [weak self] result in guard let self, revision == expected else { return } let values = (try? result.get()) as? [Int] count = values?.first ?? 0 position = values?.last ?? 0 searching = false } } // Each WebKit document owns its match ranges in an isolated content world. // Group adjacent inline nodes so a phrase can span a link or a bold word, // while keeping headings, paragraphs, table cells and code blocks distinct. private static let script = #""" const term = query.trim(); let state = globalThis.vccPageFind; if (!term) { CSS.highlights?.delete('vcc-page-find'); if (state?.selected) getSelection()?.removeAllRanges(); delete globalThis.vccPageFind; return [0, 0]; } if (state?.term !== term) { CSS.highlights?.delete('vcc-page-find'); if (state?.selected) getSelection()?.removeAllRanges(); state = {term, ranges: []}; globalThis.vccPageFind = state; const root = document.querySelector('article.lesson') || document.querySelector('main') || document.body; const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); const pattern = term.split(/\s+/).map(word => word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('\\s+'); const re = new RegExp(pattern, 'giu'); let group, text = '', nodes = []; function collect() { let start = 0; for (const match of text.matchAll(re)) { const last = match.index + match[0].length; while (start + 1 < nodes.length && nodes[start + 1].offset <= match.index) start++; let end = start; while (end + 1 < nodes.length && nodes[end + 1].offset < last) end++; const range = document.createRange(); range.setStart(nodes[start].node, match.index - nodes[start].offset); range.setEnd(nodes[end].node, last - nodes[end].offset); state.ranges.push(range); } nodes = []; text = ''; } while (walker.nextNode()) { const node = walker.currentNode, parent = node.parentElement; if (!parent || parent.closest('script, style, noscript, [hidden], [aria-hidden="true"]')) continue; const block = parent.closest('p, h1, h2, h3, h4, li, dt, dd, td, th, pre, figcaption, summary, nav, label, button, section, article, div') || root; if (block !== group) { collect(); group = block; } nodes.push({node, offset:text.length}); text += node.data; } collect(); } if (!state.ranges.length) return [0, 0]; const active = index % state.ranges.length; const range = state.ranges[active]; const element = range.startContainer.parentElement; for (let p = element; p; p = p.parentElement) { if (p.tagName === 'DETAILS') p.open = true; } if (CSS.highlights && typeof Highlight === 'function') { CSS.highlights.set('vcc-page-find', new Highlight(range)); } else { const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); state.selected = true; } element.scrollIntoView({block:'nearest', inline:'nearest'}); const rect = range.getBoundingClientRect(); if (rect.top < 72 || rect.bottom > innerHeight) scrollBy(0, rect.top - innerHeight / 2); return [state.ranges.length, active + 1]; """# } private struct ManualPageFindKey: FocusedValueKey { typealias Value = ManualPageFind } extension FocusedValues { var manualPageFind: ManualPageFind? { get { self[ManualPageFindKey.self] } set { self[ManualPageFindKey.self] = newValue } } } struct ManualPageFindBar: View { @ObservedObject var finder: ManualPageFind @FocusState private var focused: Bool var body: some View { if finder.visible { HStack(spacing: 8) { TextField("Find on This Page", text: $finder.query) .textFieldStyle(.roundedBorder) .focused($focused) .onSubmit { finder.move() } .accessibilityIdentifier("manual.find.field") if !finder.query.isEmpty && !finder.searching { Text(finder.count == 0 ? "No matches" : "\(finder.position) of \(finder.count)") .font(.caption).foregroundStyle(.secondary).monospacedDigit() .accessibilityIdentifier("manual.find.status") } Button { finder.move(backward: true) } label: { Image(systemName: "chevron.up") } .disabled(finder.count == 0).accessibilityLabel("Find Previous") .help("Find previous occurrence (⇧⌘G)") Button { finder.move() } label: { Image(systemName: "chevron.down") } .disabled(finder.count == 0).accessibilityLabel("Find Next") .help("Find next occurrence (⌘G)") Button("Done") { finder.close() }.keyboardShortcut(.escape, modifiers: []) } .padding(.horizontal, 10).padding(.vertical, 5).background(.bar) .onAppear { focused = true } .onChange(of: finder.focusRequest) { focused = true } .onExitCommand { finder.close() } } } }