fix(web): JinjaRender's form bugfix

This commit is contained in:
zhaoying
2026-01-22 15:15:54 +08:00
parent cd3b4d8dde
commit e3110d2f48
2 changed files with 55 additions and 41 deletions

View File

@@ -1,6 +1,6 @@
import { useEffect } from 'react';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { TextNode, $createTextNode } from 'lexical';
import { TextNode, $createTextNode, $getSelection, $isRangeSelection } from 'lexical';
const Jinja2HighlightPlugin = () => {
const [editor] = useLexicalComposerContext();
@@ -18,6 +18,16 @@ const Jinja2HighlightPlugin = () => {
const parent = textNode.getParent();
if (!parent) return;
// Preserve selection
const selection = $getSelection();
let selectionOffset = null;
if ($isRangeSelection(selection)) {
const anchor = selection.anchor;
if (anchor.getNode() === textNode) {
selectionOffset = anchor.offset;
}
}
const tokens = tokenizeJinja2(text);
// Skip if no meaningful tokenization (only one text token)
@@ -85,6 +95,19 @@ const Jinja2HighlightPlugin = () => {
for (let i = 1; i < newNodes.length; i++) {
newNodes[i - 1].insertAfter(newNodes[i]);
}
// Restore selection
if (selectionOffset !== null && $isRangeSelection(selection)) {
let currentOffset = 0;
for (const node of newNodes) {
const nodeLength = node.getTextContent().length;
if (currentOffset + nodeLength >= selectionOffset) {
node.select(selectionOffset - currentOffset, selectionOffset - currentOffset);
break;
}
currentOffset += nodeLength;
}
}
}
});
}, [editor]);