fix(wysiwyg): Fix text selection detection for formatting menu in Shadow DOM
- Update selection detection to properly handle Shadow DOM boundaries - Use getComposedRanges API correctly according to MDN documentation - Add direct selection detection within block components - Dispatch custom events from blocks when text is selected - Fix formatting menu positioning using selection rect from events
This commit is contained in:
@@ -24,6 +24,7 @@ import {
|
||||
WysiwygDragDropHandler,
|
||||
WysiwygModalManager,
|
||||
WysiwygHistory,
|
||||
WysiwygSelection,
|
||||
DeesSlashMenu,
|
||||
DeesFormattingMenu
|
||||
} from './index.js';
|
||||
@@ -138,11 +139,38 @@ export class DeesInputWysiwyg extends DeesInputBase<string> {
|
||||
console.log('Adding selectionchange listener');
|
||||
document.addEventListener('selectionchange', this.selectionChangeHandler);
|
||||
|
||||
// Also add listener to our shadow root if supported
|
||||
if (this.shadowRoot && 'addEventListener' in this.shadowRoot) {
|
||||
this.shadowRoot.addEventListener('selectionchange', this.selectionChangeHandler);
|
||||
}
|
||||
|
||||
// Listen for custom selection events from blocks
|
||||
this.addEventListener('block-text-selected', (e: CustomEvent) => {
|
||||
console.log('Received block-text-selected event:', e.detail);
|
||||
|
||||
if (!this.slashMenu.visible) {
|
||||
this.selectedText = e.detail.text;
|
||||
this.updateFormattingMenuPosition();
|
||||
if (e.detail.hasSelection && e.detail.text.length > 0) {
|
||||
this.selectedText = e.detail.text;
|
||||
|
||||
// Use the rect from the event if available
|
||||
if (e.detail.rect) {
|
||||
const coords = {
|
||||
x: e.detail.rect.left + (e.detail.rect.width / 2),
|
||||
y: Math.max(45, e.detail.rect.top - 45)
|
||||
};
|
||||
|
||||
// Show the formatting menu at the calculated position
|
||||
this.formattingMenu.show(
|
||||
coords,
|
||||
async (command: string) => await this.applyFormat(command)
|
||||
);
|
||||
} else {
|
||||
this.updateFormattingMenuPosition();
|
||||
}
|
||||
} else {
|
||||
// Clear selection
|
||||
this.hideFormattingMenu();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -700,72 +728,157 @@ export class DeesInputWysiwyg extends DeesInputBase<string> {
|
||||
}
|
||||
|
||||
private handleSelectionChange(): void {
|
||||
// Try to get selection from shadow root first, then fall back to window
|
||||
const shadowSelection = (this.shadowRoot as any).getSelection ? (this.shadowRoot as any).getSelection() : null;
|
||||
const windowSelection = window.getSelection();
|
||||
const editorContent = this.shadowRoot?.querySelector('.editor-content') as HTMLElement;
|
||||
console.log('=== handleSelectionChange called ===');
|
||||
|
||||
// Check both shadow and window selections
|
||||
let selection = shadowSelection;
|
||||
let selectedText = shadowSelection?.toString() || '';
|
||||
|
||||
// If no shadow selection, check window selection
|
||||
if (!selectedText && windowSelection) {
|
||||
selection = windowSelection;
|
||||
selectedText = windowSelection.toString() || '';
|
||||
}
|
||||
|
||||
console.log('Selection change:', {
|
||||
hasText: selectedText.length > 0,
|
||||
selectedText: selectedText.substring(0, 50),
|
||||
shadowSelection: !!shadowSelection,
|
||||
windowSelection: !!windowSelection,
|
||||
rangeCount: selection?.rangeCount,
|
||||
editorContent: !!editorContent
|
||||
});
|
||||
|
||||
if (!selection || selection.rangeCount === 0 || !editorContent) {
|
||||
console.log('No selection or editor content');
|
||||
const selection = window.getSelection();
|
||||
if (!selection || selection.rangeCount === 0) {
|
||||
if (this.formattingMenu.visible) {
|
||||
console.log('No selection, hiding menu');
|
||||
this.hideFormattingMenu();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// If we have selected text, show the formatting menu
|
||||
if (selectedText.length > 0) {
|
||||
console.log('✅ Text selected:', selectedText);
|
||||
|
||||
if (selectedText !== this.selectedText) {
|
||||
this.selectedText = selectedText;
|
||||
this.updateFormattingMenuPosition();
|
||||
const selectedText = selection.toString().trim();
|
||||
console.log('Selected text:', selectedText);
|
||||
|
||||
if (selectedText.length === 0) {
|
||||
if (this.formattingMenu.visible) {
|
||||
console.log('No text selected, hiding menu');
|
||||
this.hideFormattingMenu();
|
||||
}
|
||||
} else if (this.formattingMenu.visible) {
|
||||
console.log('No text selected, hiding menu');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all shadow roots in our component tree
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (this.shadowRoot) shadowRoots.push(this.shadowRoot);
|
||||
|
||||
// Find all block shadow roots
|
||||
const blockWrappers = this.shadowRoot?.querySelectorAll('.block-wrapper');
|
||||
console.log('Found block wrappers:', blockWrappers?.length || 0);
|
||||
|
||||
blockWrappers?.forEach(wrapper => {
|
||||
const blockComponent = wrapper.querySelector('dees-wysiwyg-block');
|
||||
if (blockComponent?.shadowRoot) {
|
||||
shadowRoots.push(blockComponent.shadowRoot);
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Shadow roots collected:', shadowRoots.length);
|
||||
|
||||
// Try using getComposedRanges if available
|
||||
let ranges: Range[] | StaticRange[] = [];
|
||||
let selectionInEditor = false;
|
||||
|
||||
if ('getComposedRanges' in selection && typeof selection.getComposedRanges === 'function') {
|
||||
console.log('Using getComposedRanges with shadow roots');
|
||||
try {
|
||||
// According to MDN, pass shadow roots in options object
|
||||
ranges = selection.getComposedRanges({ shadowRoots });
|
||||
console.log('getComposedRanges returned', ranges.length, 'ranges');
|
||||
|
||||
if (ranges.length > 0) {
|
||||
const range = ranges[0];
|
||||
// Check if the range is within our editor
|
||||
selectionInEditor = this.isRangeInEditor(range);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('getComposedRanges failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to regular selection API
|
||||
if (ranges.length === 0 && selection.rangeCount > 0) {
|
||||
console.log('Falling back to getRangeAt');
|
||||
const range = selection.getRangeAt(0);
|
||||
ranges = [range];
|
||||
selectionInEditor = this.isRangeInEditor(range);
|
||||
}
|
||||
|
||||
console.log('Selection in editor:', selectionInEditor);
|
||||
|
||||
if (selectionInEditor && selectedText !== this.selectedText) {
|
||||
console.log('✅ Text selected in editor:', selectedText);
|
||||
this.selectedText = selectedText;
|
||||
this.updateFormattingMenuPosition();
|
||||
} else if (!selectionInEditor && this.formattingMenu.visible) {
|
||||
console.log('Selection not in editor, hiding menu');
|
||||
this.hideFormattingMenu();
|
||||
}
|
||||
}
|
||||
|
||||
private isRangeInEditor(range: Range | StaticRange): boolean {
|
||||
// Check if the selection is within one of our blocks
|
||||
const blockWrappers = this.shadowRoot?.querySelectorAll('.block-wrapper');
|
||||
if (!blockWrappers) return false;
|
||||
|
||||
// Check each block
|
||||
for (let i = 0; i < blockWrappers.length; i++) {
|
||||
const wrapper = blockWrappers[i];
|
||||
const blockComponent = wrapper.querySelector('dees-wysiwyg-block');
|
||||
if (blockComponent?.shadowRoot) {
|
||||
const editableElements = blockComponent.shadowRoot.querySelectorAll('.block, .block.code');
|
||||
for (let j = 0; j < editableElements.length; j++) {
|
||||
const elem = editableElements[j];
|
||||
if (elem) {
|
||||
// For StaticRange, we need to check differently
|
||||
if ('startContainer' in range) {
|
||||
// Check if the range nodes are within this element
|
||||
const startInElement = this.isNodeInElement(range.startContainer, elem);
|
||||
const endInElement = this.isNodeInElement(range.endContainer, elem);
|
||||
|
||||
if (startInElement || endInElement) {
|
||||
console.log('Selection found in block:', wrapper.getAttribute('data-block-id'));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Selection not in any block. Range:', range);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a node is within an element (handles shadow DOM)
|
||||
*/
|
||||
private isNodeInElement(node: Node, element: Element): boolean {
|
||||
let current: Node | null = node;
|
||||
while (current) {
|
||||
if (current === element) return true;
|
||||
// Walk up the tree, including shadow host if in shadow DOM
|
||||
current = current.parentNode || (current as any).host;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
private updateFormattingMenuPosition(): void {
|
||||
console.log('updateFormattingMenuPosition called');
|
||||
const coords = WysiwygFormatting.getSelectionCoordinates(this.shadowRoot as ShadowRoot);
|
||||
|
||||
// Get all shadow roots
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (this.shadowRoot) shadowRoots.push(this.shadowRoot);
|
||||
|
||||
// Find all block shadow roots
|
||||
const blockWrappers = this.shadowRoot?.querySelectorAll('.block-wrapper');
|
||||
blockWrappers?.forEach(wrapper => {
|
||||
const blockComponent = wrapper.querySelector('dees-wysiwyg-block');
|
||||
if (blockComponent?.shadowRoot) {
|
||||
shadowRoots.push(blockComponent.shadowRoot);
|
||||
}
|
||||
});
|
||||
|
||||
const coords = WysiwygFormatting.getSelectionCoordinates(...shadowRoots);
|
||||
console.log('Selection coordinates:', coords);
|
||||
|
||||
if (coords) {
|
||||
const container = this.shadowRoot!.querySelector('.wysiwyg-container');
|
||||
if (!container) {
|
||||
console.error('Container not found!');
|
||||
return;
|
||||
}
|
||||
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
const formattingMenuPosition = {
|
||||
x: coords.x - containerRect.left,
|
||||
y: coords.y - containerRect.top
|
||||
};
|
||||
|
||||
console.log('Setting menu position:', formattingMenuPosition);
|
||||
// Show the global formatting menu
|
||||
// Show the global formatting menu at absolute coordinates
|
||||
this.formattingMenu.show(
|
||||
{ x: coords.x, y: coords.y }, // Use absolute coordinates
|
||||
{ x: coords.x, y: coords.y },
|
||||
async (command: string) => await this.applyFormat(command)
|
||||
);
|
||||
} else {
|
||||
@@ -779,33 +892,56 @@ export class DeesInputWysiwyg extends DeesInputBase<string> {
|
||||
}
|
||||
|
||||
public async applyFormat(command: string): Promise<void> {
|
||||
// Save current selection before applying format
|
||||
const selection = window.getSelection();
|
||||
if (!selection || selection.rangeCount === 0) return;
|
||||
|
||||
// Get the current block
|
||||
const anchorNode = selection.anchorNode;
|
||||
const blockElement = anchorNode?.nodeType === Node.TEXT_NODE
|
||||
? anchorNode.parentElement?.closest('.block')
|
||||
: (anchorNode as Element)?.closest('.block');
|
||||
// Get all shadow roots
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (this.shadowRoot) shadowRoots.push(this.shadowRoot);
|
||||
|
||||
if (!blockElement) return;
|
||||
|
||||
const blockWrapper = blockElement.closest('.block-wrapper');
|
||||
const blockId = blockWrapper?.getAttribute('data-block-id');
|
||||
const block = this.blocks.find(b => b.id === blockId);
|
||||
const blockComponent = blockWrapper?.querySelector('dees-wysiwyg-block') as any;
|
||||
// Find all block shadow roots
|
||||
const blockWrappers = this.shadowRoot?.querySelectorAll('.block-wrapper');
|
||||
blockWrappers?.forEach(wrapper => {
|
||||
const blockComponent = wrapper.querySelector('dees-wysiwyg-block');
|
||||
if (blockComponent?.shadowRoot) {
|
||||
shadowRoots.push(blockComponent.shadowRoot);
|
||||
}
|
||||
});
|
||||
|
||||
if (!block || !blockComponent) return;
|
||||
// Get selection info using Shadow DOM-aware utilities
|
||||
const selectionInfo = WysiwygSelection.getSelectionInfo(...shadowRoots);
|
||||
if (!selectionInfo) return;
|
||||
|
||||
// Find which block contains the selection
|
||||
let targetBlock: IBlock | undefined;
|
||||
let targetBlockComponent: any;
|
||||
|
||||
const wrappers = this.shadowRoot!.querySelectorAll('.block-wrapper');
|
||||
for (let i = 0; i < wrappers.length; i++) {
|
||||
const wrapper = wrappers[i];
|
||||
const blockComponent = wrapper.querySelector('dees-wysiwyg-block') as any;
|
||||
if (blockComponent?.shadowRoot) {
|
||||
const block = blockComponent.shadowRoot.querySelector('.block');
|
||||
if (block && (
|
||||
block.contains(selectionInfo.startContainer) ||
|
||||
block.contains(selectionInfo.endContainer)
|
||||
)) {
|
||||
const blockId = wrapper.getAttribute('data-block-id');
|
||||
targetBlock = this.blocks.find(b => b.id === blockId);
|
||||
targetBlockComponent = blockComponent;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetBlock || !targetBlockComponent) return;
|
||||
|
||||
// Handle link command specially
|
||||
if (command === 'link') {
|
||||
const url = await this.showLinkDialog();
|
||||
if (!url) {
|
||||
// User cancelled - restore focus to block
|
||||
blockComponent.focus();
|
||||
targetBlockComponent.focus();
|
||||
return;
|
||||
}
|
||||
// Apply link format
|
||||
WysiwygFormatting.applyFormat(command, url);
|
||||
} else {
|
||||
// Apply the format
|
||||
@@ -813,10 +949,10 @@ export class DeesInputWysiwyg extends DeesInputBase<string> {
|
||||
}
|
||||
|
||||
// Update content after a microtask to ensure DOM is updated
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
// Force content update
|
||||
block.content = blockComponent.getContent();
|
||||
targetBlock.content = targetBlockComponent.getContent();
|
||||
|
||||
// Update value to persist changes
|
||||
this.updateValue();
|
||||
@@ -825,14 +961,9 @@ export class DeesInputWysiwyg extends DeesInputBase<string> {
|
||||
if (command === 'link') {
|
||||
this.hideFormattingMenu();
|
||||
} else if (this.formattingMenu.visible) {
|
||||
// Update menu position if still showing
|
||||
// Keep selection and update menu position
|
||||
this.updateFormattingMenuPosition();
|
||||
}
|
||||
|
||||
// Ensure block still has focus
|
||||
if (document.activeElement !== blockElement) {
|
||||
blockComponent.focus();
|
||||
}
|
||||
}
|
||||
|
||||
private async showLinkDialog(): Promise<string | null> {
|
||||
|
Reference in New Issue
Block a user