fix: use execCommand insertText for contenteditable replace - fixes delete-without-paste bug
Some checks failed
CI — Test & Build / Test & Build (push) Failing after 43s

This commit is contained in:
Forge
2026-03-06 14:44:05 +08:00
parent 132e8790dc
commit 8d3887a0af
2 changed files with 23 additions and 7 deletions

View File

@@ -496,10 +496,23 @@ export default defineContentScript({
// contenteditable / DOM range path // contenteditable / DOM range path
console.log('[LexAI Replace] using DOM range'); console.log('[LexAI Replace] using DOM range');
try { try {
// Strategy: restore the selection from the cloned range, then use
// execCommand('insertText') which works reliably on contenteditable.
// insertNode() on stale ranges often fails after async operations.
const sel = window.getSelection();
if (sel) {
sel.removeAllRanges();
sel.addRange(snapRange); // restore original selection
}
// Try execCommand first (works on most contenteditable editors)
const inserted = document.execCommand('insertText', false, resultText);
if (!inserted) {
// Fallback: direct DOM manipulation
snapRange.deleteContents(); snapRange.deleteContents();
const textNode = document.createTextNode(resultText); const textNode = document.createTextNode(resultText);
snapRange.insertNode(textNode); snapRange.insertNode(textNode);
const sel = window.getSelection();
if (sel) { if (sel) {
sel.removeAllRanges(); sel.removeAllRanges();
const newRange = document.createRange(); const newRange = document.createRange();
@@ -507,8 +520,11 @@ export default defineContentScript({
newRange.collapse(true); newRange.collapse(true);
sel.addRange(newRange); sel.addRange(newRange);
} }
}
} catch (err) { } catch (err) {
console.warn('[LexAI Replace] range replace failed:', err); console.warn('[LexAI Replace] range replace failed:', err);
// Last resort: execCommand
try { document.execCommand('insertText', false, resultText); } catch (_) {}
} }
} else { } else {
console.warn('[LexAI Replace] NO VALID SNAP STATE — snapStart:', snapStart, 'snapEnd:', snapEnd, 'snapElement:', snapElement, 'snapRange:', snapRange); console.warn('[LexAI Replace] NO VALID SNAP STATE — snapStart:', snapStart, 'snapEnd:', snapEnd, 'snapElement:', snapElement, 'snapRange:', snapRange);

Binary file not shown.