fix(search): 修复搜索/替换功能三个严重Bug

根因: 直接操作ProseMirror控制的DOM导致内容复制、高亮失效、导航无效

修复方案: 改用ProseMirror Decoration API (Decoration.inline)
- useMilkdown: 新增searchPlugin + getView()暴露EditorView
- SearchReplace: 完全重写,DOM操作→ProseMirror原生事务
- Editor: 传递getView替代editorContainer

Bug详情:
1. parent.children[0]只含Element不含Text → 内容被复制/乱序
2. <mark>不在ProseMirror schema中 → 被reconciliation剥离
3. mark已被移除 → ref指向分离节点 → 导航无效

验证: TypeScript零错误, 78/78测试通过, build成功
This commit is contained in:
thzxx
2026-06-04 11:08:07 +08:00
parent b34cbb5de3
commit ef697c5bcf
3 changed files with 235 additions and 145 deletions
@@ -1,101 +1,67 @@
import React, { useState, useCallback, useRef, useEffect, memo } from 'react'
import type { EditorView } from '@milkdown/prose/view'
import { TextSelection } from '@milkdown/prose/state'
import type { Node as ProseMirrorNode } from '@milkdown/prose/model'
import { searchPluginKey, type SearchMatch, type SearchPluginState } from '../Editor/useMilkdown'
interface SearchReplaceProps {
/** 获取 Milkdown 编辑器容器 DOM(用于遍历文本节点) */
editorContainer: HTMLDivElement | null
/** 获取 ProseMirror EditorView 实例 */
getView: () => EditorView | null
/** 关闭面板 */
onClose: () => void
}
const HIGHLIGHT_CLASS = 'search-match-highlight'
const ACTIVE_HIGHLIGHT_CLASS = 'search-match-active'
/**
* 清除所有搜索高亮
* 在 ProseMirror 文档中查找所有匹配位置
*/
function clearHighlights(root: HTMLElement) {
const highlighted = root.querySelectorAll(`.${HIGHLIGHT_CLASS}, .${ACTIVE_HIGHLIGHT_CLASS}`)
highlighted.forEach(el => {
const parent = el.parentNode
if (!parent) return
while (el.firstChild) parent.insertBefore(el.firstChild, el)
parent.removeChild(el)
})
// 合并相邻文本节点
root.normalize()
}
function findMatches(doc: ProseMirrorNode, query: string, caseSensitive: boolean): SearchMatch[] {
const matches: SearchMatch[] = []
if (!query) return matches
/**
* 高亮所有匹配项
* 返回高亮后的元素列表(用于导航)
*/
function highlightMatches(root: HTMLElement, query: string, caseSensitive: boolean): HTMLElement[] {
clearHighlights(root)
if (!query) return []
const matchElements: HTMLElement[] = []
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null)
const normalizedQuery = caseSensitive ? query : query.toLowerCase()
const textNodes: Text[] = []
let node: Node | null
while ((node = walker.nextNode())) {
textNodes.push(node as Text)
}
// 从后往前处理,避免偏移量变化
for (let i = textNodes.length - 1; i >= 0; i--) {
const textNode = textNodes[i]
const text = textNode.textContent || ''
doc.descendants((node, pos) => {
if (!node.isText) return true
const text = node.text || ''
const searchText = caseSensitive ? text : text.toLowerCase()
// 收集该文本节点中的所有匹配位置
const positions: number[] = []
let offset = 0
let idx: number
while ((idx = searchText.indexOf(normalizedQuery, offset)) !== -1) {
positions.push(idx)
matches.push({ from: pos + idx, to: pos + idx + query.length })
offset = idx + 1
}
return true
})
if (positions.length === 0) continue
return matches
}
// 从后往前拆分文本节点并插入高亮
const parent = textNode.parentNode
if (!parent) continue
for (let j = positions.length - 1; j >= 0; j--) {
const pos = positions[j]
const afterText = text.substring(pos + query.length)
const matchText = text.substring(pos, pos + query.length)
const beforeText = text.substring(0, pos)
// 移除原始文本节点
if (j === positions.length - 1) {
parent.removeChild(textNode)
}
// 插入后续文本
if (afterText) {
parent.insertBefore(document.createTextNode(afterText), parent.children[0] || null)
}
// 插入高亮标记
const mark = document.createElement('mark')
mark.className = HIGHLIGHT_CLASS
mark.textContent = matchText
mark.setAttribute('data-match-index', String(matchElements.length))
parent.insertBefore(mark, parent.children[0] || null)
matchElements.unshift(mark)
// 插入前面文本(仅第一个匹配时)
if (j === 0 && beforeText) {
parent.insertBefore(document.createTextNode(beforeText), parent.children[0] || null)
}
}
/**
* 滚动到指定文档位置
*/
function scrollToPos(view: EditorView, pos: number) {
try {
const { node } = view.domAtPos(pos)
const el = node.nodeType === Node.TEXT_NODE ? node.parentElement : (node as HTMLElement)
el?.scrollIntoView({ behavior: 'smooth', block: 'center' })
} catch {
// Position may be out of range
}
}
return matchElements
/**
* 更新 ProseMirror plugin state(触发 decorations 重绘)
*/
function dispatchSearchState(view: EditorView, state: SearchPluginState) {
const tr = view.state.tr.setMeta(searchPluginKey, state)
view.dispatch(tr)
}
/**
* 清除搜索高亮(dispatch 空状态)
*/
function clearSearchDecorations(view: EditorView) {
dispatchSearchState(view, { matches: [], currentIndex: -1, query: '' })
}
/**
@@ -109,7 +75,7 @@ function highlightMatches(root: HTMLElement, query: string, caseSensitive: boole
* - ESC 关闭面板
*/
export const SearchReplace = memo(function SearchReplace({
editorContainer,
getView,
onClose
}: SearchReplaceProps) {
const [query, setQuery] = useState('')
@@ -120,104 +86,147 @@ export const SearchReplace = memo(function SearchReplace({
const [currentMatch, setCurrentMatch] = useState(-1)
const searchInputRef = useRef<HTMLInputElement>(null)
const matchElementsRef = useRef<HTMLElement[]>([])
const panelRef = useRef<HTMLDivElement>(null)
// Keep latest state in refs for use in callbacks without stale closures
const matchesRef = useRef<SearchMatch[]>([])
const currentIndexRef = useRef(-1)
const caseSensitiveRef = useRef(false)
const queryRef = useRef('')
// Sync refs
caseSensitiveRef.current = caseSensitive
queryRef.current = query
// 执行搜索
const doSearch = useCallback((searchQuery: string, cs: boolean) => {
if (!editorContainer) return
const view = getView()
if (!view) return
if (!searchQuery.trim()) {
clearHighlights(editorContainer)
matchElementsRef.current = []
clearSearchDecorations(view)
matchesRef.current = []
currentIndexRef.current = -1
setMatchCount(0)
setCurrentMatch(-1)
return
}
const elements = highlightMatches(editorContainer, searchQuery, cs)
matchElementsRef.current = elements
setMatchCount(elements.length)
const matches = findMatches(view.state.doc, searchQuery, cs)
matchesRef.current = matches
const newIdx = matches.length > 0 ? 0 : -1
currentIndexRef.current = newIdx
if (elements.length > 0) {
setCurrentMatch(0)
elements[0].classList.add(ACTIVE_HIGHLIGHT_CLASS)
elements[0].scrollIntoView({ behavior: 'smooth', block: 'center' })
} else {
setCurrentMatch(-1)
setMatchCount(matches.length)
setCurrentMatch(newIdx)
// Dispatch to ProseMirror plugin to render decorations
dispatchSearchState(view, { matches, currentIndex: newIdx, query: searchQuery })
// Scroll to first match
if (matches.length > 0) {
scrollToPos(view, matches[0].from)
}
}, [editorContainer])
}, [getView])
// 搜索框输入变化
const handleQueryChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
setQuery(value)
doSearch(value, caseSensitive)
}, [doSearch, caseSensitive])
doSearch(value, caseSensitiveRef.current)
}, [doSearch])
// 大小写切换
const toggleCaseSensitive = useCallback(() => {
const newCS = !caseSensitive
const newCS = !caseSensitiveRef.current
setCaseSensitive(newCS)
doSearch(query, newCS)
}, [caseSensitive, query, doSearch])
doSearch(queryRef.current, newCS)
}, [doSearch])
// 导航到下一个/上一个匹配
const navigateMatch = useCallback((direction: 1 | -1) => {
const elements = matchElementsRef.current
if (elements.length === 0) return
const view = getView()
if (!view) return
// 移除当前高亮
if (currentMatch >= 0 && currentMatch < elements.length) {
elements[currentMatch].classList.remove(ACTIVE_HIGHLIGHT_CLASS)
}
const matches = matchesRef.current
if (matches.length === 0) return
let next = currentMatch + direction
if (next >= elements.length) next = 0
if (next < 0) next = elements.length - 1
let next = currentIndexRef.current + direction
if (next >= matches.length) next = 0
if (next < 0) next = matches.length - 1
currentIndexRef.current = next
setCurrentMatch(next)
elements[next].classList.add(ACTIVE_HIGHLIGHT_CLASS)
elements[next].scrollIntoView({ behavior: 'smooth', block: 'center' })
}, [currentMatch])
// Update plugin state to move the active highlight
dispatchSearchState(view, {
matches,
currentIndex: next,
query: queryRef.current
})
// Scroll to match and select it
const match = matches[next]
try {
const tr = view.state.tr.setSelection(
TextSelection.create(view.state.doc, match.from, match.to)
)
view.dispatch(tr)
} catch {
// Selection range might be invalid
}
scrollToPos(view, match.from)
}, [getView])
// 替换当前匹配
const replaceCurrent = useCallback(() => {
if (currentMatch < 0 || !editorContainer) return
const view = getView()
if (!view) return
const elements = matchElementsRef.current
const el = elements[currentMatch]
if (!el || !el.parentNode) return
const matches = matchesRef.current
const idx = currentIndexRef.current
if (idx < 0 || idx >= matches.length) return
// 替换文本
const textNode = document.createTextNode(replacement)
el.parentNode.replaceChild(textNode, el)
editorContainer.normalize()
const match = matches[idx]
// 重新搜索
doSearch(query, caseSensitive)
}, [currentMatch, replacement, editorContainer, query, caseSensitive, doSearch])
// Replace text in ProseMirror document
const tr = view.state.tr.insertText(replacement, match.from, match.to)
view.dispatch(tr)
// Re-search after replacement (document changed)
// Use requestAnimationFrame to let ProseMirror process the transaction
requestAnimationFrame(() => {
doSearch(queryRef.current, caseSensitiveRef.current)
})
}, [getView, replacement, doSearch])
// 全部替换
const replaceAll = useCallback(() => {
if (!editorContainer || matchCount === 0) return
const view = getView()
if (!view) return
const elements = [...matchElementsRef.current]
elements.forEach(el => {
if (el.parentNode) {
el.parentNode.replaceChild(document.createTextNode(replacement), el)
}
const matches = matchesRef.current
if (matches.length === 0) return
// Process matches in reverse order to preserve positions
const tr = view.state.tr
for (let i = matches.length - 1; i >= 0; i--) {
tr.insertText(replacement, matches[i].from, matches[i].to)
}
view.dispatch(tr)
// Re-search after replacement
requestAnimationFrame(() => {
doSearch(queryRef.current, caseSensitiveRef.current)
})
editorContainer.normalize()
doSearch(query, caseSensitive)
}, [editorContainer, matchCount, replacement, query, caseSensitive, doSearch])
}, [getView, replacement, doSearch])
// 键盘事件
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault()
if (editorContainer) clearHighlights(editorContainer)
const view = getView()
if (view) clearSearchDecorations(view)
onClose()
return
}
@@ -229,7 +238,7 @@ export const SearchReplace = memo(function SearchReplace({
navigateMatch(1)
}
}
}, [onClose, navigateMatch, editorContainer])
}, [onClose, navigateMatch, getView])
// 全局 Ctrl+F / Ctrl+H 拦截
useEffect(() => {
@@ -258,12 +267,14 @@ export const SearchReplace = memo(function SearchReplace({
searchInputRef.current?.select()
}, [])
// 清理高亮
// 清理高亮(组件卸载时)
useEffect(() => {
return () => {
if (editorContainer) clearHighlights(editorContainer)
const view = getView()
if (view) clearSearchDecorations(view)
}
}, [editorContainer])
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return (
<div
@@ -327,7 +338,8 @@ export const SearchReplace = memo(function SearchReplace({
<button
className="search-btn search-close"
onClick={() => {
if (editorContainer) clearHighlights(editorContainer)
const view = getView()
if (view) clearSearchDecorations(view)
onClose()
}}
title="关闭 (Esc)"