fix(wysiwyg): cursor position

This commit is contained in:
2025-06-24 13:53:47 +00:00
parent 4b2178cedd
commit e0a125c9bd
2 changed files with 165 additions and 62 deletions

View File

@@ -100,9 +100,9 @@ export class WysiwygSelection {
/**
* Gets cursor position relative to a specific element
*/
static getCursorPositionInElement(element: Element, shadowRoot?: ShadowRoot): number | null {
const selectionInfo = shadowRoot
? this.getSelectionInfo(shadowRoot)
static getCursorPositionInElement(element: Element, ...shadowRoots: ShadowRoot[]): number | null {
const selectionInfo = shadowRoots.length > 0
? this.getSelectionInfo(...shadowRoots)
: this.getSelectionInfo();
if (!selectionInfo || !selectionInfo.collapsed) return null;
@@ -111,9 +111,28 @@ export class WysiwygSelection {
try {
const range = document.createRange();
range.selectNodeContents(element);
range.setEnd(selectionInfo.startContainer, selectionInfo.startOffset);
return range.toString().length;
// Handle case where selection is in a text node that's a child of the element
if (element.contains(selectionInfo.startContainer)) {
range.setEnd(selectionInfo.startContainer, selectionInfo.startOffset);
return range.toString().length;
} else {
// Selection might be in shadow DOM or different context
// Try to find the equivalent position in the element
const text = element.textContent || '';
const selectionText = selectionInfo.startContainer.textContent || '';
// If the selection is at the beginning or end, handle those cases
if (selectionInfo.startOffset === 0) {
return 0;
} else if (selectionInfo.startOffset === selectionText.length) {
return text.length;
}
// For other cases, try to match based on text content
console.warn('Selection container not within element, using text matching fallback');
return selectionInfo.startOffset;
}
} catch (error) {
console.warn('Failed to get cursor position:', error);
return null;