fix: use execCommand insertText for contenteditable replace - fixes delete-without-paste bug
Some checks failed
CI — Test & Build / Test & Build (push) Failing after 43s
Some checks failed
CI — Test & Build / Test & Build (push) Failing after 43s
This commit is contained in:
@@ -496,19 +496,35 @@ 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 {
|
||||||
snapRange.deleteContents();
|
// Strategy: restore the selection from the cloned range, then use
|
||||||
const textNode = document.createTextNode(resultText);
|
// execCommand('insertText') which works reliably on contenteditable.
|
||||||
snapRange.insertNode(textNode);
|
// insertNode() on stale ranges often fails after async operations.
|
||||||
const sel = window.getSelection();
|
const sel = window.getSelection();
|
||||||
if (sel) {
|
if (sel) {
|
||||||
sel.removeAllRanges();
|
sel.removeAllRanges();
|
||||||
const newRange = document.createRange();
|
sel.addRange(snapRange); // restore original selection
|
||||||
newRange.setStartAfter(textNode);
|
}
|
||||||
newRange.collapse(true);
|
|
||||||
sel.addRange(newRange);
|
// Try execCommand first (works on most contenteditable editors)
|
||||||
|
const inserted = document.execCommand('insertText', false, resultText);
|
||||||
|
|
||||||
|
if (!inserted) {
|
||||||
|
// Fallback: direct DOM manipulation
|
||||||
|
snapRange.deleteContents();
|
||||||
|
const textNode = document.createTextNode(resultText);
|
||||||
|
snapRange.insertNode(textNode);
|
||||||
|
if (sel) {
|
||||||
|
sel.removeAllRanges();
|
||||||
|
const newRange = document.createRange();
|
||||||
|
newRange.setStartAfter(textNode);
|
||||||
|
newRange.collapse(true);
|
||||||
|
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.
Reference in New Issue
Block a user