feat: Add WYSIWYG editor components and utilities
- Implemented WysiwygModalManager for managing modals related to code blocks and block settings. - Created WysiwygSelection for handling text selection across Shadow DOM boundaries. - Introduced WysiwygShortcuts for managing keyboard shortcuts and slash menu items. - Developed wysiwygStyles for consistent styling of the WYSIWYG editor. - Defined types for blocks, slash menu items, and shortcut patterns in wysiwyg.types.ts.
This commit is contained in:
716
ts_web/elements/dees-input-wysiwyg/blocks/text/code.block.ts
Normal file
716
ts_web/elements/dees-input-wysiwyg/blocks/text/code.block.ts
Normal file
@@ -0,0 +1,716 @@
|
||||
import { BaseBlockHandler, type IBlockEventHandlers } from '../block.base.js';
|
||||
import type { IBlock } from '../../wysiwyg.types.js';
|
||||
import { cssManager } from '@design.estate/dees-element';
|
||||
import { WysiwygSelection } from '../../wysiwyg.selection.js';
|
||||
import hlight from 'highlight.js';
|
||||
import { cssGeistFontFamily, cssMonoFontFamily } from '../../../00fonts.js';
|
||||
import { PROGRAMMING_LANGUAGES } from '../../wysiwyg.constants.js';
|
||||
|
||||
/**
|
||||
* CodeBlockHandler with improved architecture
|
||||
*
|
||||
* Key features:
|
||||
* 1. Simple DOM structure
|
||||
* 2. Line number handling
|
||||
* 3. Syntax highlighting only when not focused (grey text while editing)
|
||||
* 4. Clean event handling
|
||||
* 5. Copy button functionality
|
||||
*/
|
||||
export class CodeBlockHandler extends BaseBlockHandler {
|
||||
type = 'code';
|
||||
|
||||
private highlightTimer: any = null;
|
||||
|
||||
render(block: IBlock, isSelected: boolean): string {
|
||||
const language = block.metadata?.language || 'typescript';
|
||||
const content = block.content || '';
|
||||
const lineCount = content.split('\n').length;
|
||||
|
||||
// Generate line numbers
|
||||
let lineNumbersHtml = '';
|
||||
for (let i = 1; i <= lineCount; i++) {
|
||||
lineNumbersHtml += `<div class="line-number">${i}</div>`;
|
||||
}
|
||||
|
||||
// Generate language options
|
||||
const languageOptions = PROGRAMMING_LANGUAGES.map(lang => {
|
||||
const value = lang.toLowerCase();
|
||||
return `<option value="${value}" ${value === language ? 'selected' : ''}>${lang}</option>`;
|
||||
}).join('');
|
||||
|
||||
return `
|
||||
<div class="code-block-container${isSelected ? ' selected' : ''}" data-language="${language}">
|
||||
<div class="code-header">
|
||||
<select class="language-selector" data-block-id="${block.id}">
|
||||
${languageOptions}
|
||||
</select>
|
||||
<button class="copy-button" title="Copy code">
|
||||
<svg class="copy-icon" width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
||||
<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 010 1.5h-1.5a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-1.5a.75.75 0 011.5 0v1.5A1.75 1.75 0 019.25 16h-7.5A1.75 1.75 0 010 14.25v-7.5z"></path>
|
||||
<path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0114.25 11h-7.5A1.75 1.75 0 015 9.25v-7.5zm1.75-.25a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-7.5a.25.25 0 00-.25-.25h-7.5z"></path>
|
||||
</svg>
|
||||
<span class="copy-text">Copy</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="code-body">
|
||||
<div class="line-numbers">${lineNumbersHtml}</div>
|
||||
<div class="code-content">
|
||||
<pre class="code-pre"><code class="code-editor"
|
||||
contenteditable="true"
|
||||
data-block-id="${block.id}"
|
||||
data-block-type="${block.type}"
|
||||
spellcheck="false">${this.escapeHtml(content)}</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
setup(element: HTMLElement, block: IBlock, handlers: IBlockEventHandlers): void {
|
||||
const editor = element.querySelector('.code-editor') as HTMLElement;
|
||||
const container = element.querySelector('.code-block-container') as HTMLElement;
|
||||
const copyButton = element.querySelector('.copy-button') as HTMLButtonElement;
|
||||
const languageSelector = element.querySelector('.language-selector') as HTMLSelectElement;
|
||||
|
||||
if (!editor || !container) return;
|
||||
|
||||
// Setup language selector
|
||||
if (languageSelector) {
|
||||
languageSelector.addEventListener('change', (e) => {
|
||||
const newLanguage = (e.target as HTMLSelectElement).value;
|
||||
block.metadata = { ...block.metadata, language: newLanguage };
|
||||
container.setAttribute('data-language', newLanguage);
|
||||
|
||||
// Update the syntax highlighting if content exists and not focused
|
||||
if (block.content && document.activeElement !== editor) {
|
||||
this.applyHighlighting(element, block);
|
||||
}
|
||||
|
||||
// Notify about the change
|
||||
if (handlers.onInput) {
|
||||
handlers.onInput(new InputEvent('input'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Setup copy button
|
||||
if (copyButton) {
|
||||
copyButton.addEventListener('click', async () => {
|
||||
const content = editor.textContent || '';
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(content);
|
||||
|
||||
// Show feedback
|
||||
const copyText = copyButton.querySelector('.copy-text') as HTMLElement;
|
||||
const originalText = copyText.textContent;
|
||||
copyText.textContent = 'Copied!';
|
||||
copyButton.classList.add('copied');
|
||||
|
||||
// Reset after 2 seconds
|
||||
setTimeout(() => {
|
||||
copyText.textContent = originalText;
|
||||
copyButton.classList.remove('copied');
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
console.error('Failed to copy:', err);
|
||||
// Fallback for older browsers
|
||||
const textArea = document.createElement('textarea');
|
||||
textArea.value = content;
|
||||
textArea.style.position = 'fixed';
|
||||
textArea.style.opacity = '0';
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
try {
|
||||
// @ts-ignore - execCommand is deprecated but needed for fallback
|
||||
document.execCommand('copy');
|
||||
// Show feedback
|
||||
const copyText = copyButton.querySelector('.copy-text') as HTMLElement;
|
||||
const originalText = copyText.textContent;
|
||||
copyText.textContent = 'Copied!';
|
||||
copyButton.classList.add('copied');
|
||||
|
||||
setTimeout(() => {
|
||||
copyText.textContent = originalText;
|
||||
copyButton.classList.remove('copied');
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
console.error('Fallback copy failed:', err);
|
||||
}
|
||||
document.body.removeChild(textArea);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Track if we're currently editing
|
||||
let isEditing = false;
|
||||
|
||||
// Focus handler
|
||||
editor.addEventListener('focus', () => {
|
||||
isEditing = true;
|
||||
container.classList.add('editing');
|
||||
|
||||
// Remove all syntax highlighting when focused
|
||||
const content = editor.textContent || '';
|
||||
editor.textContent = content; // This removes all HTML formatting
|
||||
|
||||
// Restore cursor position after removing highlighting
|
||||
requestAnimationFrame(() => {
|
||||
const range = document.createRange();
|
||||
const selection = window.getSelection();
|
||||
if (editor.firstChild) {
|
||||
range.setStart(editor.firstChild, 0);
|
||||
range.collapse(true);
|
||||
selection?.removeAllRanges();
|
||||
selection?.addRange(range);
|
||||
}
|
||||
});
|
||||
|
||||
handlers.onFocus();
|
||||
});
|
||||
|
||||
// Blur handler
|
||||
editor.addEventListener('blur', () => {
|
||||
isEditing = false;
|
||||
container.classList.remove('editing');
|
||||
// Apply final highlighting on blur
|
||||
this.applyHighlighting(element, block);
|
||||
handlers.onBlur();
|
||||
});
|
||||
|
||||
// Input handler
|
||||
editor.addEventListener('input', (e) => {
|
||||
handlers.onInput(e as InputEvent);
|
||||
|
||||
// Update line numbers
|
||||
this.updateLineNumbers(element);
|
||||
|
||||
// Clear any pending highlight timer (no highlighting while editing)
|
||||
clearTimeout(this.highlightTimer);
|
||||
});
|
||||
|
||||
// Keydown handler
|
||||
editor.addEventListener('keydown', (e) => {
|
||||
// Handle Tab key for code blocks
|
||||
if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
const selection = window.getSelection();
|
||||
if (selection && selection.rangeCount > 0) {
|
||||
const range = selection.getRangeAt(0);
|
||||
const textNode = document.createTextNode(' ');
|
||||
range.insertNode(textNode);
|
||||
range.setStartAfter(textNode);
|
||||
range.setEndAfter(textNode);
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
handlers.onInput(new InputEvent('input'));
|
||||
this.updateLineNumbers(element);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Check cursor position for navigation keys
|
||||
if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) {
|
||||
const cursorPos = this.getCursorPosition(element);
|
||||
const textLength = editor.textContent?.length || 0;
|
||||
|
||||
// For ArrowLeft at position 0 or ArrowRight at end, let parent handle navigation
|
||||
if ((e.key === 'ArrowLeft' && cursorPos === 0) ||
|
||||
(e.key === 'ArrowRight' && cursorPos === textLength)) {
|
||||
// Pass to parent handler for inter-block navigation
|
||||
handlers.onKeyDown(e);
|
||||
return;
|
||||
}
|
||||
|
||||
// For ArrowUp/Down, check if we're at first/last line
|
||||
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
|
||||
const lines = (editor.textContent || '').split('\n');
|
||||
const currentLine = this.getCurrentLineIndex(editor);
|
||||
|
||||
if ((e.key === 'ArrowUp' && currentLine === 0) ||
|
||||
(e.key === 'ArrowDown' && currentLine === lines.length - 1)) {
|
||||
// Let parent handle navigation to prev/next block
|
||||
handlers.onKeyDown(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pass other keys to parent handler
|
||||
handlers.onKeyDown(e);
|
||||
});
|
||||
|
||||
// Paste handler - plain text only
|
||||
editor.addEventListener('paste', (e) => {
|
||||
e.preventDefault();
|
||||
const text = e.clipboardData?.getData('text/plain');
|
||||
if (text) {
|
||||
const selection = window.getSelection();
|
||||
if (selection && selection.rangeCount > 0) {
|
||||
const range = selection.getRangeAt(0);
|
||||
range.deleteContents();
|
||||
const textNode = document.createTextNode(text);
|
||||
range.insertNode(textNode);
|
||||
range.setStartAfter(textNode);
|
||||
range.setEndAfter(textNode);
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
handlers.onInput(new InputEvent('input'));
|
||||
this.updateLineNumbers(element);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Composition handlers
|
||||
editor.addEventListener('compositionstart', () => handlers.onCompositionStart());
|
||||
editor.addEventListener('compositionend', () => handlers.onCompositionEnd());
|
||||
|
||||
// Initial syntax highlighting if content exists and not focused
|
||||
if (block.content && document.activeElement !== editor) {
|
||||
requestAnimationFrame(() => {
|
||||
this.applyHighlighting(element, block);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private updateLineNumbers(element: HTMLElement): void {
|
||||
const editor = element.querySelector('.code-editor') as HTMLElement;
|
||||
const lineNumbersContainer = element.querySelector('.line-numbers') as HTMLElement;
|
||||
|
||||
if (!editor || !lineNumbersContainer) return;
|
||||
|
||||
const content = editor.textContent || '';
|
||||
const lines = content.split('\n');
|
||||
const lineCount = lines.length || 1;
|
||||
|
||||
let lineNumbersHtml = '';
|
||||
for (let i = 1; i <= lineCount; i++) {
|
||||
lineNumbersHtml += `<div class="line-number">${i}</div>`;
|
||||
}
|
||||
|
||||
lineNumbersContainer.innerHTML = lineNumbersHtml;
|
||||
}
|
||||
|
||||
private getCurrentLineIndex(editor: HTMLElement): number {
|
||||
const selection = window.getSelection();
|
||||
if (!selection || selection.rangeCount === 0) return 0;
|
||||
|
||||
const range = selection.getRangeAt(0);
|
||||
const preCaretRange = range.cloneRange();
|
||||
preCaretRange.selectNodeContents(editor);
|
||||
preCaretRange.setEnd(range.startContainer, range.startOffset);
|
||||
|
||||
const textBeforeCursor = preCaretRange.toString();
|
||||
const linesBeforeCursor = textBeforeCursor.split('\n');
|
||||
|
||||
return linesBeforeCursor.length - 1; // 0-indexed
|
||||
}
|
||||
|
||||
private applyHighlighting(element: HTMLElement, block: IBlock): void {
|
||||
const editor = element.querySelector('.code-editor') as HTMLElement;
|
||||
if (!editor) return;
|
||||
|
||||
// Store cursor position
|
||||
const cursorPos = this.getCursorPosition(element);
|
||||
|
||||
// Get plain text content
|
||||
const content = editor.textContent || '';
|
||||
const language = block.metadata?.language || 'typescript';
|
||||
|
||||
// Apply highlighting
|
||||
try {
|
||||
const result = hlight.highlight(content, {
|
||||
language: language,
|
||||
ignoreIllegals: true
|
||||
});
|
||||
|
||||
// Only update if we have valid highlighted content
|
||||
if (result.value) {
|
||||
editor.innerHTML = result.value;
|
||||
|
||||
// Restore cursor position if editor is focused
|
||||
if (document.activeElement === editor && cursorPos !== null) {
|
||||
requestAnimationFrame(() => {
|
||||
WysiwygSelection.setCursorPosition(editor, cursorPos);
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// If highlighting fails, keep plain text
|
||||
console.warn('Syntax highlighting failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private escapeHtml(text: string): string {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
getContent(element: HTMLElement): string {
|
||||
const editor = element.querySelector('.code-editor') as HTMLElement;
|
||||
return editor?.textContent || '';
|
||||
}
|
||||
|
||||
setContent(element: HTMLElement, content: string): void {
|
||||
const editor = element.querySelector('.code-editor') as HTMLElement;
|
||||
if (!editor) return;
|
||||
|
||||
editor.textContent = content;
|
||||
this.updateLineNumbers(element);
|
||||
|
||||
// Apply highlighting if not focused
|
||||
if (document.activeElement !== editor) {
|
||||
const block: IBlock = {
|
||||
id: editor.dataset.blockId || '',
|
||||
type: 'code',
|
||||
content: content,
|
||||
metadata: {
|
||||
language: element.querySelector('.code-block-container')?.getAttribute('data-language') || 'typescript'
|
||||
}
|
||||
};
|
||||
this.applyHighlighting(element, block);
|
||||
}
|
||||
}
|
||||
|
||||
getCursorPosition(element: HTMLElement): number | null {
|
||||
const editor = element.querySelector('.code-editor') as HTMLElement;
|
||||
if (!editor) return null;
|
||||
|
||||
const selection = window.getSelection();
|
||||
if (!selection || selection.rangeCount === 0) return null;
|
||||
|
||||
const range = selection.getRangeAt(0);
|
||||
if (!editor.contains(range.startContainer)) return null;
|
||||
|
||||
const preCaretRange = document.createRange();
|
||||
preCaretRange.selectNodeContents(editor);
|
||||
preCaretRange.setEnd(range.startContainer, range.startOffset);
|
||||
|
||||
return preCaretRange.toString().length;
|
||||
}
|
||||
|
||||
setCursorToStart(element: HTMLElement): void {
|
||||
const editor = element.querySelector('.code-editor') as HTMLElement;
|
||||
if (editor) {
|
||||
WysiwygSelection.setCursorPosition(editor, 0);
|
||||
}
|
||||
}
|
||||
|
||||
setCursorToEnd(element: HTMLElement): void {
|
||||
const editor = element.querySelector('.code-editor') as HTMLElement;
|
||||
if (editor) {
|
||||
const length = editor.textContent?.length || 0;
|
||||
WysiwygSelection.setCursorPosition(editor, length);
|
||||
}
|
||||
}
|
||||
|
||||
focus(element: HTMLElement): void {
|
||||
const editor = element.querySelector('.code-editor') as HTMLElement;
|
||||
editor?.focus();
|
||||
}
|
||||
|
||||
focusWithCursor(element: HTMLElement, position: 'start' | 'end' | number = 'end'): void {
|
||||
const editor = element.querySelector('.code-editor') as HTMLElement;
|
||||
if (!editor) return;
|
||||
|
||||
editor.focus();
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
if (position === 'start') {
|
||||
this.setCursorToStart(element);
|
||||
} else if (position === 'end') {
|
||||
this.setCursorToEnd(element);
|
||||
} else if (typeof position === 'number') {
|
||||
WysiwygSelection.setCursorPosition(editor, position);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
getSplitContent(element: HTMLElement): { before: string; after: string } | null {
|
||||
const position = this.getCursorPosition(element);
|
||||
if (position === null) return null;
|
||||
|
||||
const content = this.getContent(element);
|
||||
return {
|
||||
before: content.substring(0, position),
|
||||
after: content.substring(position)
|
||||
};
|
||||
}
|
||||
|
||||
getStyles(): string {
|
||||
return `
|
||||
/* Code Block Container - Minimalist shadcn style */
|
||||
.code-block-container {
|
||||
position: relative;
|
||||
margin: 12px 0;
|
||||
background: transparent;
|
||||
border: 1px solid ${cssManager.bdTheme('#e5e7eb', '#374151')};
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
.code-block-container.selected {
|
||||
border-color: ${cssManager.bdTheme('#9ca3af', '#6b7280')};
|
||||
}
|
||||
|
||||
.code-block-container.editing {
|
||||
border-color: ${cssManager.bdTheme('#6b7280', '#9ca3af')};
|
||||
background: ${cssManager.bdTheme('#fafafa', '#0a0a0a')};
|
||||
}
|
||||
|
||||
/* Header - Simplified */
|
||||
.code-header {
|
||||
background: transparent;
|
||||
border-bottom: 1px solid ${cssManager.bdTheme('#e5e7eb', '#374151')};
|
||||
padding: 8px 12px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.language-selector {
|
||||
font-size: 12px;
|
||||
color: ${cssManager.bdTheme('#6b7280', '#9ca3af')};
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
font-family: ${cssGeistFontFamily};
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 4px;
|
||||
padding: 4px 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.language-selector:hover {
|
||||
background: ${cssManager.bdTheme('#f9fafb', '#1f2937')};
|
||||
border-color: ${cssManager.bdTheme('#e5e7eb', '#374151')};
|
||||
color: ${cssManager.bdTheme('#374151', '#e5e7eb')};
|
||||
}
|
||||
|
||||
.language-selector:focus {
|
||||
border-color: ${cssManager.bdTheme('#9ca3af', '#6b7280')};
|
||||
}
|
||||
|
||||
/* Copy Button - Minimal */
|
||||
.copy-button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 4px 8px;
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 4px;
|
||||
color: ${cssManager.bdTheme('#6b7280', '#9ca3af')};
|
||||
font-size: 12px;
|
||||
font-family: ${cssGeistFontFamily};
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.copy-button:hover {
|
||||
background: ${cssManager.bdTheme('#f9fafb', '#1f2937')};
|
||||
border-color: ${cssManager.bdTheme('#e5e7eb', '#374151')};
|
||||
color: ${cssManager.bdTheme('#374151', '#e5e7eb')};
|
||||
}
|
||||
|
||||
.copy-button:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.copy-button.copied {
|
||||
color: ${cssManager.bdTheme('#059669', '#10b981')};
|
||||
}
|
||||
|
||||
.copy-icon {
|
||||
flex-shrink: 0;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.copy-button:hover .copy-icon {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.copy-text {
|
||||
min-width: 40px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Code Body */
|
||||
.code-body {
|
||||
display: flex;
|
||||
position: relative;
|
||||
background: ${cssManager.bdTheme('#fafafa', '#0a0a0a')};
|
||||
}
|
||||
|
||||
/* Line Numbers - Subtle */
|
||||
.line-numbers {
|
||||
flex-shrink: 0;
|
||||
padding: 12px 0;
|
||||
background: transparent;
|
||||
text-align: right;
|
||||
user-select: none;
|
||||
min-width: 40px;
|
||||
border-right: 1px solid ${cssManager.bdTheme('#e5e7eb', '#374151')};
|
||||
}
|
||||
|
||||
.line-number {
|
||||
padding: 0 12px 0 8px;
|
||||
color: ${cssManager.bdTheme('#9ca3af', '#4b5563')};
|
||||
font-family: ${cssMonoFontFamily};
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
/* Code Content */
|
||||
.code-content {
|
||||
flex: 1;
|
||||
overflow-x: auto;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.code-pre {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.code-editor {
|
||||
display: block;
|
||||
padding: 12px 16px;
|
||||
margin: 0;
|
||||
font-family: ${cssMonoFontFamily};
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
color: ${cssManager.bdTheme('#111827', '#f9fafb')};
|
||||
background: transparent;
|
||||
border: none;
|
||||
outline: none;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
min-height: 60px;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
/* Placeholder */
|
||||
.code-editor:empty::before {
|
||||
content: "// Type or paste code here...";
|
||||
color: ${cssManager.bdTheme('#9ca3af', '#4b5563')};
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* When editing (focused), show grey text without highlighting */
|
||||
.code-block-container.editing .code-editor {
|
||||
color: ${cssManager.bdTheme('#6b7280', '#9ca3af')} !important;
|
||||
}
|
||||
|
||||
.code-block-container.editing .code-editor * {
|
||||
color: inherit !important;
|
||||
}
|
||||
|
||||
/* Syntax Highlighting - Muted colors */
|
||||
.code-editor .hljs-keyword {
|
||||
color: ${cssManager.bdTheme('#dc2626', '#f87171')};
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.code-editor .hljs-string {
|
||||
color: ${cssManager.bdTheme('#059669', '#10b981')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-number {
|
||||
color: ${cssManager.bdTheme('#7c3aed', '#a78bfa')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-function {
|
||||
color: ${cssManager.bdTheme('#2563eb', '#60a5fa')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-comment {
|
||||
color: ${cssManager.bdTheme('#6b7280', '#6b7280')};
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.code-editor .hljs-variable,
|
||||
.code-editor .hljs-attr {
|
||||
color: ${cssManager.bdTheme('#ea580c', '#fb923c')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-class,
|
||||
.code-editor .hljs-title {
|
||||
color: ${cssManager.bdTheme('#2563eb', '#60a5fa')};
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.code-editor .hljs-params {
|
||||
color: ${cssManager.bdTheme('#374151', '#e5e7eb')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-built_in {
|
||||
color: ${cssManager.bdTheme('#7c3aed', '#a78bfa')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-literal {
|
||||
color: ${cssManager.bdTheme('#7c3aed', '#a78bfa')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-meta {
|
||||
color: ${cssManager.bdTheme('#6b7280', '#9ca3af')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-punctuation {
|
||||
color: ${cssManager.bdTheme('#374151', '#d1d5db')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-tag {
|
||||
color: ${cssManager.bdTheme('#dc2626', '#f87171')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-attribute {
|
||||
color: ${cssManager.bdTheme('#2563eb', '#60a5fa')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-selector-tag {
|
||||
color: ${cssManager.bdTheme('#dc2626', '#f87171')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-selector-class {
|
||||
color: ${cssManager.bdTheme('#2563eb', '#60a5fa')};
|
||||
}
|
||||
|
||||
.code-editor .hljs-selector-id {
|
||||
color: ${cssManager.bdTheme('#7c3aed', '#a78bfa')};
|
||||
}
|
||||
|
||||
/* Selection */
|
||||
.code-editor::selection,
|
||||
.code-editor *::selection {
|
||||
background: ${cssManager.bdTheme('rgba(99, 102, 241, 0.2)', 'rgba(99, 102, 241, 0.3)')};
|
||||
}
|
||||
|
||||
/* Scrollbar styling - Minimal */
|
||||
.code-content::-webkit-scrollbar {
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.code-content::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.code-content::-webkit-scrollbar-thumb {
|
||||
background: ${cssManager.bdTheme('#d1d5db', '#4b5563')};
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.code-content::-webkit-scrollbar-thumb:hover {
|
||||
background: ${cssManager.bdTheme('#9ca3af', '#6b7280')};
|
||||
}
|
||||
`;
|
||||
}
|
||||
}
|
533
ts_web/elements/dees-input-wysiwyg/blocks/text/heading.block.ts
Normal file
533
ts_web/elements/dees-input-wysiwyg/blocks/text/heading.block.ts
Normal file
@@ -0,0 +1,533 @@
|
||||
import { BaseBlockHandler, type IBlockEventHandlers } from '../block.base.js';
|
||||
import type { IBlock } from '../../wysiwyg.types.js';
|
||||
import { cssManager } from '@design.estate/dees-element';
|
||||
import { WysiwygBlocks } from '../../wysiwyg.blocks.js';
|
||||
import { WysiwygSelection } from '../../wysiwyg.selection.js';
|
||||
|
||||
export class HeadingBlockHandler extends BaseBlockHandler {
|
||||
type: string;
|
||||
private level: 1 | 2 | 3;
|
||||
|
||||
// Track cursor position
|
||||
private lastKnownCursorPosition: number = 0;
|
||||
private lastSelectedText: string = '';
|
||||
private selectionHandler: (() => void) | null = null;
|
||||
|
||||
constructor(type: 'heading-1' | 'heading-2' | 'heading-3') {
|
||||
super();
|
||||
this.type = type;
|
||||
this.level = parseInt(type.split('-')[1]) as 1 | 2 | 3;
|
||||
}
|
||||
|
||||
render(block: IBlock, isSelected: boolean): string {
|
||||
const selectedClass = isSelected ? ' selected' : '';
|
||||
const placeholder = this.getPlaceholder();
|
||||
|
||||
|
||||
return `
|
||||
<div
|
||||
class="block heading-${this.level}${selectedClass}"
|
||||
contenteditable="true"
|
||||
data-placeholder="${placeholder}"
|
||||
data-block-id="${block.id}"
|
||||
data-block-type="${block.type}"
|
||||
></div>
|
||||
`;
|
||||
}
|
||||
|
||||
setup(element: HTMLElement, block: IBlock, handlers: IBlockEventHandlers): void {
|
||||
const headingBlock = element.querySelector(`.block.heading-${this.level}`) as HTMLDivElement;
|
||||
if (!headingBlock) {
|
||||
console.error('HeadingBlockHandler.setup: No heading block element found');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Set initial content if needed
|
||||
if (block.content && !headingBlock.innerHTML) {
|
||||
headingBlock.innerHTML = block.content;
|
||||
}
|
||||
|
||||
// Input handler with cursor tracking
|
||||
headingBlock.addEventListener('input', (e) => {
|
||||
handlers.onInput(e as InputEvent);
|
||||
|
||||
// Track cursor position after input
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
});
|
||||
|
||||
// Keydown handler with cursor tracking
|
||||
headingBlock.addEventListener('keydown', (e) => {
|
||||
// Track cursor position before keydown
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
|
||||
handlers.onKeyDown(e);
|
||||
});
|
||||
|
||||
// Focus handler
|
||||
headingBlock.addEventListener('focus', () => {
|
||||
handlers.onFocus();
|
||||
});
|
||||
|
||||
// Blur handler
|
||||
headingBlock.addEventListener('blur', () => {
|
||||
handlers.onBlur();
|
||||
});
|
||||
|
||||
// Composition handlers for IME support
|
||||
headingBlock.addEventListener('compositionstart', () => {
|
||||
handlers.onCompositionStart();
|
||||
});
|
||||
|
||||
headingBlock.addEventListener('compositionend', () => {
|
||||
handlers.onCompositionEnd();
|
||||
});
|
||||
|
||||
// Mouse up handler
|
||||
headingBlock.addEventListener('mouseup', (e) => {
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
|
||||
// Selection will be handled by selectionchange event
|
||||
handlers.onMouseUp?.(e);
|
||||
});
|
||||
|
||||
// Click handler with delayed cursor tracking
|
||||
headingBlock.addEventListener('click', (e: MouseEvent) => {
|
||||
// Small delay to let browser set cursor position
|
||||
setTimeout(() => {
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
}, 0);
|
||||
});
|
||||
|
||||
// Keyup handler for additional cursor tracking
|
||||
headingBlock.addEventListener('keyup', (e) => {
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
});
|
||||
|
||||
// Set up selection change handler
|
||||
this.setupSelectionHandler(element, headingBlock, block);
|
||||
}
|
||||
|
||||
private setupSelectionHandler(element: HTMLElement, headingBlock: HTMLDivElement, block: IBlock): void {
|
||||
// Add selection change handler
|
||||
const checkSelection = () => {
|
||||
const selection = window.getSelection();
|
||||
if (!selection || selection.rangeCount === 0) return;
|
||||
|
||||
const selectedText = selection.toString();
|
||||
if (selectedText.length === 0) {
|
||||
// Clear selection if no text
|
||||
if (this.lastSelectedText) {
|
||||
this.lastSelectedText = '';
|
||||
this.dispatchSelectionEvent(element, {
|
||||
text: '',
|
||||
blockId: block.id,
|
||||
hasSelection: false
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Get parent wysiwyg component's shadow root - in setup, we need to traverse
|
||||
const wysiwygBlock = (headingBlock.getRootNode() as ShadowRoot).host as any;
|
||||
const parentComponent = wysiwygBlock?.closest('dees-input-wysiwyg');
|
||||
const parentShadowRoot = parentComponent?.shadowRoot;
|
||||
const blockShadowRoot = wysiwygBlock?.shadowRoot;
|
||||
|
||||
// Use getComposedRanges with shadow roots as per MDN docs
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (parentShadowRoot) shadowRoots.push(parentShadowRoot);
|
||||
if (blockShadowRoot) shadowRoots.push(blockShadowRoot);
|
||||
|
||||
// Get selection info using our Shadow DOM-aware utility
|
||||
const selectionInfo = WysiwygSelection.getSelectionInfo(...shadowRoots);
|
||||
if (!selectionInfo) return;
|
||||
|
||||
// Check if selection is within this block
|
||||
const startInBlock = WysiwygSelection.containsAcrossShadowDOM(headingBlock, selectionInfo.startContainer);
|
||||
const endInBlock = WysiwygSelection.containsAcrossShadowDOM(headingBlock, selectionInfo.endContainer);
|
||||
|
||||
if (startInBlock || endInBlock) {
|
||||
if (selectedText !== this.lastSelectedText) {
|
||||
this.lastSelectedText = selectedText;
|
||||
|
||||
// Create range and get rect
|
||||
const range = WysiwygSelection.createRangeFromInfo(selectionInfo);
|
||||
const rect = range.getBoundingClientRect();
|
||||
|
||||
// Dispatch event
|
||||
this.dispatchSelectionEvent(element, {
|
||||
text: selectedText.trim(),
|
||||
blockId: block.id,
|
||||
range: range,
|
||||
rect: rect,
|
||||
hasSelection: true
|
||||
});
|
||||
}
|
||||
} else if (this.lastSelectedText) {
|
||||
// Clear selection if no longer in this block
|
||||
this.lastSelectedText = '';
|
||||
this.dispatchSelectionEvent(element, {
|
||||
text: '',
|
||||
blockId: block.id,
|
||||
hasSelection: false
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Listen for selection changes
|
||||
document.addEventListener('selectionchange', checkSelection);
|
||||
|
||||
// Store the handler for cleanup
|
||||
this.selectionHandler = checkSelection;
|
||||
|
||||
// Clean up on disconnect (will be called by dees-wysiwyg-block)
|
||||
const wysiwygBlock = (headingBlock.getRootNode() as ShadowRoot).host as any;
|
||||
if (wysiwygBlock) {
|
||||
const originalDisconnectedCallback = (wysiwygBlock as any).disconnectedCallback;
|
||||
(wysiwygBlock as any).disconnectedCallback = async function() {
|
||||
if (this.selectionHandler) {
|
||||
document.removeEventListener('selectionchange', this.selectionHandler);
|
||||
this.selectionHandler = null;
|
||||
}
|
||||
if (originalDisconnectedCallback) {
|
||||
await originalDisconnectedCallback.call(wysiwygBlock);
|
||||
}
|
||||
}.bind(this);
|
||||
}
|
||||
}
|
||||
|
||||
private dispatchSelectionEvent(element: HTMLElement, detail: any): void {
|
||||
const event = new CustomEvent('block-text-selected', {
|
||||
detail,
|
||||
bubbles: true,
|
||||
composed: true
|
||||
});
|
||||
element.dispatchEvent(event);
|
||||
}
|
||||
|
||||
getStyles(): string {
|
||||
// Return styles for all heading levels
|
||||
return `
|
||||
.block.heading-1 {
|
||||
font-size: 32px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
margin: 24px 0 8px 0;
|
||||
color: ${cssManager.bdTheme('#000000', '#ffffff')};
|
||||
}
|
||||
|
||||
.block.heading-2 {
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
line-height: 1.3;
|
||||
margin: 20px 0 6px 0;
|
||||
color: ${cssManager.bdTheme('#000000', '#ffffff')};
|
||||
}
|
||||
|
||||
.block.heading-3 {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
margin: 16px 0 4px 0;
|
||||
color: ${cssManager.bdTheme('#000000', '#ffffff')};
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
getPlaceholder(): string {
|
||||
switch(this.level) {
|
||||
case 1:
|
||||
return 'Heading 1';
|
||||
case 2:
|
||||
return 'Heading 2';
|
||||
case 3:
|
||||
return 'Heading 3';
|
||||
default:
|
||||
return 'Heading';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to get the last text node in an element
|
||||
*/
|
||||
private getLastTextNode(element: Node): Text | null {
|
||||
if (element.nodeType === Node.TEXT_NODE) {
|
||||
return element as Text;
|
||||
}
|
||||
|
||||
for (let i = element.childNodes.length - 1; i >= 0; i--) {
|
||||
const lastText = this.getLastTextNode(element.childNodes[i]);
|
||||
if (lastText) return lastText;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Helper methods for heading functionality (mostly the same as paragraph)
|
||||
|
||||
getCursorPosition(element: HTMLElement, context?: any): number | null {
|
||||
// Get the actual heading element
|
||||
const headingBlock = element.querySelector(`.block.heading-${this.level}`) as HTMLDivElement;
|
||||
if (!headingBlock) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get shadow roots from context
|
||||
const wysiwygBlock = context?.component;
|
||||
const parentComponent = wysiwygBlock?.closest('dees-input-wysiwyg');
|
||||
const parentShadowRoot = parentComponent?.shadowRoot;
|
||||
const blockShadowRoot = context?.shadowRoot;
|
||||
|
||||
// Get selection info with both shadow roots for proper traversal
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (parentShadowRoot) shadowRoots.push(parentShadowRoot);
|
||||
if (blockShadowRoot) shadowRoots.push(blockShadowRoot);
|
||||
|
||||
const selectionInfo = WysiwygSelection.getSelectionInfo(...shadowRoots);
|
||||
|
||||
if (!selectionInfo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!WysiwygSelection.containsAcrossShadowDOM(headingBlock, selectionInfo.startContainer)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create a range from start of element to cursor position
|
||||
const preCaretRange = document.createRange();
|
||||
preCaretRange.selectNodeContents(headingBlock);
|
||||
preCaretRange.setEnd(selectionInfo.startContainer, selectionInfo.startOffset);
|
||||
|
||||
// Get the text content length up to cursor
|
||||
const position = preCaretRange.toString().length;
|
||||
|
||||
return position;
|
||||
}
|
||||
|
||||
getContent(element: HTMLElement, context?: any): string {
|
||||
const headingBlock = element.querySelector(`.block.heading-${this.level}`) as HTMLDivElement;
|
||||
if (!headingBlock) return '';
|
||||
|
||||
// For headings, get the innerHTML which includes formatting tags
|
||||
const content = headingBlock.innerHTML || '';
|
||||
return content;
|
||||
}
|
||||
|
||||
setContent(element: HTMLElement, content: string, context?: any): void {
|
||||
const headingBlock = element.querySelector(`.block.heading-${this.level}`) as HTMLDivElement;
|
||||
if (!headingBlock) return;
|
||||
|
||||
// Store if we have focus
|
||||
const hadFocus = document.activeElement === headingBlock ||
|
||||
element.shadowRoot?.activeElement === headingBlock;
|
||||
|
||||
headingBlock.innerHTML = content;
|
||||
|
||||
// Restore focus if we had it
|
||||
if (hadFocus) {
|
||||
headingBlock.focus();
|
||||
}
|
||||
}
|
||||
|
||||
setCursorToStart(element: HTMLElement, context?: any): void {
|
||||
const headingBlock = element.querySelector(`.block.heading-${this.level}`) as HTMLDivElement;
|
||||
if (headingBlock) {
|
||||
WysiwygBlocks.setCursorToStart(headingBlock);
|
||||
}
|
||||
}
|
||||
|
||||
setCursorToEnd(element: HTMLElement, context?: any): void {
|
||||
const headingBlock = element.querySelector(`.block.heading-${this.level}`) as HTMLDivElement;
|
||||
if (headingBlock) {
|
||||
WysiwygBlocks.setCursorToEnd(headingBlock);
|
||||
}
|
||||
}
|
||||
|
||||
focus(element: HTMLElement, context?: any): void {
|
||||
const headingBlock = element.querySelector(`.block.heading-${this.level}`) as HTMLDivElement;
|
||||
if (!headingBlock) return;
|
||||
|
||||
// Ensure the element is focusable
|
||||
if (!headingBlock.hasAttribute('contenteditable')) {
|
||||
headingBlock.setAttribute('contenteditable', 'true');
|
||||
}
|
||||
|
||||
headingBlock.focus();
|
||||
|
||||
// If focus failed, try again after a microtask
|
||||
if (document.activeElement !== headingBlock && element.shadowRoot?.activeElement !== headingBlock) {
|
||||
Promise.resolve().then(() => {
|
||||
headingBlock.focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
focusWithCursor(element: HTMLElement, position: 'start' | 'end' | number = 'end', context?: any): void {
|
||||
const headingBlock = element.querySelector(`.block.heading-${this.level}`) as HTMLDivElement;
|
||||
if (!headingBlock) return;
|
||||
|
||||
|
||||
// Ensure element is focusable first
|
||||
if (!headingBlock.hasAttribute('contenteditable')) {
|
||||
headingBlock.setAttribute('contenteditable', 'true');
|
||||
}
|
||||
|
||||
// For 'end' position, we need to set up selection before focus to prevent browser default
|
||||
if (position === 'end' && headingBlock.textContent && headingBlock.textContent.length > 0) {
|
||||
// Set up the selection first
|
||||
const sel = window.getSelection();
|
||||
if (sel) {
|
||||
const range = document.createRange();
|
||||
const lastNode = this.getLastTextNode(headingBlock) || headingBlock;
|
||||
if (lastNode.nodeType === Node.TEXT_NODE) {
|
||||
range.setStart(lastNode, lastNode.textContent?.length || 0);
|
||||
range.setEnd(lastNode, lastNode.textContent?.length || 0);
|
||||
} else {
|
||||
range.selectNodeContents(lastNode);
|
||||
range.collapse(false);
|
||||
}
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
}
|
||||
}
|
||||
|
||||
// Now focus the element
|
||||
headingBlock.focus();
|
||||
|
||||
// Set cursor position after focus is established (for non-end positions)
|
||||
const setCursor = () => {
|
||||
if (position === 'start') {
|
||||
this.setCursorToStart(element, context);
|
||||
} else if (position === 'end' && (!headingBlock.textContent || headingBlock.textContent.length === 0)) {
|
||||
// Only call setCursorToEnd for empty blocks
|
||||
this.setCursorToEnd(element, context);
|
||||
} else if (typeof position === 'number') {
|
||||
// Use the selection utility to set cursor position
|
||||
WysiwygSelection.setCursorPosition(headingBlock, position);
|
||||
}
|
||||
};
|
||||
|
||||
// Ensure cursor is set after focus
|
||||
if (document.activeElement === headingBlock || element.shadowRoot?.activeElement === headingBlock) {
|
||||
setCursor();
|
||||
} else {
|
||||
// Wait for focus to be established
|
||||
Promise.resolve().then(() => {
|
||||
if (document.activeElement === headingBlock || element.shadowRoot?.activeElement === headingBlock) {
|
||||
setCursor();
|
||||
} else {
|
||||
// Try again with a small delay - sometimes focus needs more time
|
||||
setTimeout(() => {
|
||||
if (document.activeElement === headingBlock || element.shadowRoot?.activeElement === headingBlock) {
|
||||
setCursor();
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
getSplitContent(element: HTMLElement, context?: any): { before: string; after: string } | null {
|
||||
const headingBlock = element.querySelector(`.block.heading-${this.level}`) as HTMLDivElement;
|
||||
if (!headingBlock) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get shadow roots from context
|
||||
const wysiwygBlock = context?.component;
|
||||
const parentComponent = wysiwygBlock?.closest('dees-input-wysiwyg');
|
||||
const parentShadowRoot = parentComponent?.shadowRoot;
|
||||
const blockShadowRoot = context?.shadowRoot;
|
||||
|
||||
// Get selection info with both shadow roots for proper traversal
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (parentShadowRoot) shadowRoots.push(parentShadowRoot);
|
||||
if (blockShadowRoot) shadowRoots.push(blockShadowRoot);
|
||||
|
||||
const selectionInfo = WysiwygSelection.getSelectionInfo(...shadowRoots);
|
||||
|
||||
if (!selectionInfo) {
|
||||
// Try using last known cursor position
|
||||
if (this.lastKnownCursorPosition !== null) {
|
||||
const fullText = headingBlock.textContent || '';
|
||||
const pos = Math.min(this.lastKnownCursorPosition, fullText.length);
|
||||
return {
|
||||
before: fullText.substring(0, pos),
|
||||
after: fullText.substring(pos)
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Make sure the selection is within this block
|
||||
if (!WysiwygSelection.containsAcrossShadowDOM(headingBlock, selectionInfo.startContainer)) {
|
||||
// Try using last known cursor position
|
||||
if (this.lastKnownCursorPosition !== null) {
|
||||
const fullText = headingBlock.textContent || '';
|
||||
const pos = Math.min(this.lastKnownCursorPosition, fullText.length);
|
||||
return {
|
||||
before: fullText.substring(0, pos),
|
||||
after: fullText.substring(pos)
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get cursor position first
|
||||
const cursorPos = this.getCursorPosition(element, context);
|
||||
|
||||
if (cursorPos === null || cursorPos === 0) {
|
||||
// If cursor is at start or can't determine position, move all content
|
||||
return {
|
||||
before: '',
|
||||
after: headingBlock.innerHTML
|
||||
};
|
||||
}
|
||||
|
||||
// For HTML content, split using ranges to preserve formatting
|
||||
const beforeRange = document.createRange();
|
||||
const afterRange = document.createRange();
|
||||
|
||||
// Before range: from start of element to cursor
|
||||
beforeRange.setStart(headingBlock, 0);
|
||||
beforeRange.setEnd(selectionInfo.startContainer, selectionInfo.startOffset);
|
||||
|
||||
// After range: from cursor to end of element
|
||||
afterRange.setStart(selectionInfo.startContainer, selectionInfo.startOffset);
|
||||
afterRange.setEnd(headingBlock, headingBlock.childNodes.length);
|
||||
|
||||
// Extract HTML content
|
||||
const beforeFragment = beforeRange.cloneContents();
|
||||
const afterFragment = afterRange.cloneContents();
|
||||
|
||||
// Convert to HTML strings
|
||||
const tempDiv = document.createElement('div');
|
||||
tempDiv.appendChild(beforeFragment);
|
||||
const beforeHtml = tempDiv.innerHTML;
|
||||
|
||||
tempDiv.innerHTML = '';
|
||||
tempDiv.appendChild(afterFragment);
|
||||
const afterHtml = tempDiv.innerHTML;
|
||||
|
||||
return {
|
||||
before: beforeHtml,
|
||||
after: afterHtml
|
||||
};
|
||||
}
|
||||
}
|
448
ts_web/elements/dees-input-wysiwyg/blocks/text/list.block.ts
Normal file
448
ts_web/elements/dees-input-wysiwyg/blocks/text/list.block.ts
Normal file
@@ -0,0 +1,448 @@
|
||||
import { BaseBlockHandler, type IBlockEventHandlers } from '../block.base.js';
|
||||
import type { IBlock } from '../../wysiwyg.types.js';
|
||||
import { cssManager } from '@design.estate/dees-element';
|
||||
import { WysiwygBlocks } from '../../wysiwyg.blocks.js';
|
||||
import { WysiwygSelection } from '../../wysiwyg.selection.js';
|
||||
|
||||
export class ListBlockHandler extends BaseBlockHandler {
|
||||
type = 'list';
|
||||
|
||||
// Track cursor position and list state
|
||||
private lastKnownCursorPosition: number = 0;
|
||||
private lastSelectedText: string = '';
|
||||
private selectionHandler: (() => void) | null = null;
|
||||
|
||||
render(block: IBlock, isSelected: boolean): string {
|
||||
const selectedClass = isSelected ? ' selected' : '';
|
||||
const listType = block.metadata?.listType || 'unordered';
|
||||
const listTag = listType === 'ordered' ? 'ol' : 'ul';
|
||||
|
||||
// Render list content
|
||||
const listContent = this.renderListContent(block.content, block.metadata);
|
||||
|
||||
return `
|
||||
<div
|
||||
class="block list${selectedClass}"
|
||||
contenteditable="true"
|
||||
data-block-id="${block.id}"
|
||||
data-block-type="${block.type}"
|
||||
>${listContent}</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderListContent(content: string | undefined, metadata: any): string {
|
||||
if (!content) return '<ul><li></li></ul>';
|
||||
|
||||
const listType = metadata?.listType || 'unordered';
|
||||
const listTag = listType === 'ordered' ? 'ol' : 'ul';
|
||||
|
||||
// Split content by newlines to create list items
|
||||
const lines = content.split('\n').filter(line => line.trim());
|
||||
if (lines.length === 0) {
|
||||
return `<${listTag}><li></li></${listTag}>`;
|
||||
}
|
||||
|
||||
const listItems = lines.map(line => `<li>${line}</li>`).join('');
|
||||
return `<${listTag}>${listItems}</${listTag}>`;
|
||||
}
|
||||
|
||||
setup(element: HTMLElement, block: IBlock, handlers: IBlockEventHandlers): void {
|
||||
const listBlock = element.querySelector('.block.list') as HTMLDivElement;
|
||||
if (!listBlock) {
|
||||
console.error('ListBlockHandler.setup: No list block element found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Set initial content if needed
|
||||
if (block.content && !listBlock.innerHTML) {
|
||||
listBlock.innerHTML = this.renderListContent(block.content, block.metadata);
|
||||
}
|
||||
|
||||
// Input handler
|
||||
listBlock.addEventListener('input', (e) => {
|
||||
handlers.onInput(e as InputEvent);
|
||||
|
||||
// Track cursor position after input
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
});
|
||||
|
||||
// Keydown handler
|
||||
listBlock.addEventListener('keydown', (e) => {
|
||||
// Track cursor position before keydown
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
|
||||
// Special handling for Enter key in lists
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
const selection = window.getSelection();
|
||||
if (selection && selection.rangeCount > 0) {
|
||||
const range = selection.getRangeAt(0);
|
||||
const currentLi = range.startContainer.parentElement?.closest('li');
|
||||
|
||||
if (currentLi && currentLi.textContent === '') {
|
||||
// Empty list item - exit list mode
|
||||
e.preventDefault();
|
||||
handlers.onKeyDown(e);
|
||||
return;
|
||||
}
|
||||
// Otherwise, let browser create new list item naturally
|
||||
}
|
||||
}
|
||||
|
||||
handlers.onKeyDown(e);
|
||||
});
|
||||
|
||||
// Focus handler
|
||||
listBlock.addEventListener('focus', () => {
|
||||
handlers.onFocus();
|
||||
});
|
||||
|
||||
// Blur handler
|
||||
listBlock.addEventListener('blur', () => {
|
||||
handlers.onBlur();
|
||||
});
|
||||
|
||||
// Composition handlers for IME support
|
||||
listBlock.addEventListener('compositionstart', () => {
|
||||
handlers.onCompositionStart();
|
||||
});
|
||||
|
||||
listBlock.addEventListener('compositionend', () => {
|
||||
handlers.onCompositionEnd();
|
||||
});
|
||||
|
||||
// Mouse up handler
|
||||
listBlock.addEventListener('mouseup', (e) => {
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
handlers.onMouseUp?.(e);
|
||||
});
|
||||
|
||||
// Click handler
|
||||
listBlock.addEventListener('click', (e: MouseEvent) => {
|
||||
setTimeout(() => {
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
}, 0);
|
||||
});
|
||||
|
||||
// Keyup handler
|
||||
listBlock.addEventListener('keyup', (e) => {
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
});
|
||||
|
||||
// Set up selection handler
|
||||
this.setupSelectionHandler(element, listBlock, block);
|
||||
}
|
||||
|
||||
private setupSelectionHandler(element: HTMLElement, listBlock: HTMLDivElement, block: IBlock): void {
|
||||
const checkSelection = () => {
|
||||
const selection = window.getSelection();
|
||||
if (!selection || selection.rangeCount === 0) return;
|
||||
|
||||
const selectedText = selection.toString();
|
||||
if (selectedText.length === 0) {
|
||||
if (this.lastSelectedText) {
|
||||
this.lastSelectedText = '';
|
||||
this.dispatchSelectionEvent(element, {
|
||||
text: '',
|
||||
blockId: block.id,
|
||||
hasSelection: false
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Get parent wysiwyg component's shadow root
|
||||
const wysiwygBlock = (listBlock.getRootNode() as ShadowRoot).host as any;
|
||||
const parentComponent = wysiwygBlock?.closest('dees-input-wysiwyg');
|
||||
const parentShadowRoot = parentComponent?.shadowRoot;
|
||||
const blockShadowRoot = wysiwygBlock?.shadowRoot;
|
||||
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (parentShadowRoot) shadowRoots.push(parentShadowRoot);
|
||||
if (blockShadowRoot) shadowRoots.push(blockShadowRoot);
|
||||
|
||||
const selectionInfo = WysiwygSelection.getSelectionInfo(...shadowRoots);
|
||||
if (!selectionInfo) return;
|
||||
|
||||
const startInBlock = WysiwygSelection.containsAcrossShadowDOM(listBlock, selectionInfo.startContainer);
|
||||
const endInBlock = WysiwygSelection.containsAcrossShadowDOM(listBlock, selectionInfo.endContainer);
|
||||
|
||||
if (startInBlock || endInBlock) {
|
||||
if (selectedText !== this.lastSelectedText) {
|
||||
this.lastSelectedText = selectedText;
|
||||
|
||||
const range = WysiwygSelection.createRangeFromInfo(selectionInfo);
|
||||
const rect = range.getBoundingClientRect();
|
||||
|
||||
this.dispatchSelectionEvent(element, {
|
||||
text: selectedText.trim(),
|
||||
blockId: block.id,
|
||||
range: range,
|
||||
rect: rect,
|
||||
hasSelection: true
|
||||
});
|
||||
}
|
||||
} else if (this.lastSelectedText) {
|
||||
this.lastSelectedText = '';
|
||||
this.dispatchSelectionEvent(element, {
|
||||
text: '',
|
||||
blockId: block.id,
|
||||
hasSelection: false
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('selectionchange', checkSelection);
|
||||
this.selectionHandler = checkSelection;
|
||||
|
||||
// Cleanup on disconnect
|
||||
const wysiwygBlock = (listBlock.getRootNode() as ShadowRoot).host as any;
|
||||
if (wysiwygBlock) {
|
||||
const originalDisconnectedCallback = (wysiwygBlock as any).disconnectedCallback;
|
||||
(wysiwygBlock as any).disconnectedCallback = async function() {
|
||||
if (this.selectionHandler) {
|
||||
document.removeEventListener('selectionchange', this.selectionHandler);
|
||||
this.selectionHandler = null;
|
||||
}
|
||||
if (originalDisconnectedCallback) {
|
||||
await originalDisconnectedCallback.call(wysiwygBlock);
|
||||
}
|
||||
}.bind(this);
|
||||
}
|
||||
}
|
||||
|
||||
private dispatchSelectionEvent(element: HTMLElement, detail: any): void {
|
||||
const event = new CustomEvent('block-text-selected', {
|
||||
detail,
|
||||
bubbles: true,
|
||||
composed: true
|
||||
});
|
||||
element.dispatchEvent(event);
|
||||
}
|
||||
|
||||
getStyles(): string {
|
||||
return `
|
||||
/* List specific styles */
|
||||
.block.list {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.block.list ul,
|
||||
.block.list ol {
|
||||
margin: 0;
|
||||
padding-left: 24px;
|
||||
}
|
||||
|
||||
.block.list li {
|
||||
margin: 4px 0;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.block.list li:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
getPlaceholder(): string {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Helper methods for list functionality
|
||||
|
||||
getCursorPosition(element: HTMLElement, context?: any): number | null {
|
||||
const listBlock = element.querySelector('.block.list') as HTMLDivElement;
|
||||
if (!listBlock) return null;
|
||||
|
||||
const wysiwygBlock = context?.component;
|
||||
const parentComponent = wysiwygBlock?.closest('dees-input-wysiwyg');
|
||||
const parentShadowRoot = parentComponent?.shadowRoot;
|
||||
const blockShadowRoot = context?.shadowRoot;
|
||||
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (parentShadowRoot) shadowRoots.push(parentShadowRoot);
|
||||
if (blockShadowRoot) shadowRoots.push(blockShadowRoot);
|
||||
|
||||
const selectionInfo = WysiwygSelection.getSelectionInfo(...shadowRoots);
|
||||
if (!selectionInfo) return null;
|
||||
|
||||
if (!WysiwygSelection.containsAcrossShadowDOM(listBlock, selectionInfo.startContainer)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// For lists, calculate position based on text content
|
||||
const preCaretRange = document.createRange();
|
||||
preCaretRange.selectNodeContents(listBlock);
|
||||
preCaretRange.setEnd(selectionInfo.startContainer, selectionInfo.startOffset);
|
||||
|
||||
return preCaretRange.toString().length;
|
||||
}
|
||||
|
||||
getContent(element: HTMLElement, context?: any): string {
|
||||
const listBlock = element.querySelector('.block.list') as HTMLDivElement;
|
||||
if (!listBlock) return '';
|
||||
|
||||
// Extract text content from list items
|
||||
const listItems = listBlock.querySelectorAll('li');
|
||||
const content = Array.from(listItems)
|
||||
.map(li => li.textContent || '')
|
||||
.join('\n');
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
setContent(element: HTMLElement, content: string, context?: any): void {
|
||||
const listBlock = element.querySelector('.block.list') as HTMLDivElement;
|
||||
if (!listBlock) return;
|
||||
|
||||
const hadFocus = document.activeElement === listBlock ||
|
||||
element.shadowRoot?.activeElement === listBlock;
|
||||
|
||||
// Get current metadata to preserve list type
|
||||
const listElement = listBlock.querySelector('ul, ol');
|
||||
const isOrdered = listElement?.tagName === 'OL';
|
||||
|
||||
// Update content
|
||||
listBlock.innerHTML = this.renderListContent(content, { listType: isOrdered ? 'ordered' : 'unordered' });
|
||||
|
||||
if (hadFocus) {
|
||||
listBlock.focus();
|
||||
}
|
||||
}
|
||||
|
||||
setCursorToStart(element: HTMLElement, context?: any): void {
|
||||
const listBlock = element.querySelector('.block.list') as HTMLDivElement;
|
||||
if (!listBlock) return;
|
||||
|
||||
const firstLi = listBlock.querySelector('li');
|
||||
if (firstLi) {
|
||||
const textNode = this.getFirstTextNode(firstLi);
|
||||
if (textNode) {
|
||||
const range = document.createRange();
|
||||
const selection = window.getSelection();
|
||||
range.setStart(textNode, 0);
|
||||
range.setEnd(textNode, 0);
|
||||
selection?.removeAllRanges();
|
||||
selection?.addRange(range);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setCursorToEnd(element: HTMLElement, context?: any): void {
|
||||
const listBlock = element.querySelector('.block.list') as HTMLDivElement;
|
||||
if (!listBlock) return;
|
||||
|
||||
const lastLi = listBlock.querySelector('li:last-child');
|
||||
if (lastLi) {
|
||||
const textNode = this.getLastTextNode(lastLi);
|
||||
if (textNode) {
|
||||
const range = document.createRange();
|
||||
const selection = window.getSelection();
|
||||
const textLength = textNode.textContent?.length || 0;
|
||||
range.setStart(textNode, textLength);
|
||||
range.setEnd(textNode, textLength);
|
||||
selection?.removeAllRanges();
|
||||
selection?.addRange(range);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getFirstTextNode(element: Node): Text | null {
|
||||
if (element.nodeType === Node.TEXT_NODE) {
|
||||
return element as Text;
|
||||
}
|
||||
|
||||
for (let i = 0; i < element.childNodes.length; i++) {
|
||||
const firstText = this.getFirstTextNode(element.childNodes[i]);
|
||||
if (firstText) return firstText;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private getLastTextNode(element: Node): Text | null {
|
||||
if (element.nodeType === Node.TEXT_NODE) {
|
||||
return element as Text;
|
||||
}
|
||||
|
||||
for (let i = element.childNodes.length - 1; i >= 0; i--) {
|
||||
const lastText = this.getLastTextNode(element.childNodes[i]);
|
||||
if (lastText) return lastText;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
focus(element: HTMLElement, context?: any): void {
|
||||
const listBlock = element.querySelector('.block.list') as HTMLDivElement;
|
||||
if (!listBlock) return;
|
||||
|
||||
if (!listBlock.hasAttribute('contenteditable')) {
|
||||
listBlock.setAttribute('contenteditable', 'true');
|
||||
}
|
||||
|
||||
listBlock.focus();
|
||||
|
||||
if (document.activeElement !== listBlock && element.shadowRoot?.activeElement !== listBlock) {
|
||||
Promise.resolve().then(() => {
|
||||
listBlock.focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
focusWithCursor(element: HTMLElement, position: 'start' | 'end' | number = 'end', context?: any): void {
|
||||
const listBlock = element.querySelector('.block.list') as HTMLDivElement;
|
||||
if (!listBlock) return;
|
||||
|
||||
if (!listBlock.hasAttribute('contenteditable')) {
|
||||
listBlock.setAttribute('contenteditable', 'true');
|
||||
}
|
||||
|
||||
listBlock.focus();
|
||||
|
||||
const setCursor = () => {
|
||||
if (position === 'start') {
|
||||
this.setCursorToStart(element, context);
|
||||
} else if (position === 'end') {
|
||||
this.setCursorToEnd(element, context);
|
||||
} else if (typeof position === 'number') {
|
||||
// For numeric positions in lists, we need custom logic
|
||||
// This is complex due to list structure, so default to end
|
||||
this.setCursorToEnd(element, context);
|
||||
}
|
||||
};
|
||||
|
||||
if (document.activeElement === listBlock || element.shadowRoot?.activeElement === listBlock) {
|
||||
setCursor();
|
||||
} else {
|
||||
Promise.resolve().then(() => {
|
||||
if (document.activeElement === listBlock || element.shadowRoot?.activeElement === listBlock) {
|
||||
setCursor();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
getSplitContent(element: HTMLElement, context?: any): { before: string; after: string } | null {
|
||||
const listBlock = element.querySelector('.block.list') as HTMLDivElement;
|
||||
if (!listBlock) return null;
|
||||
|
||||
// For lists, we don't split content - instead let the keyboard handler
|
||||
// create a new paragraph block when Enter is pressed on empty list item
|
||||
return null;
|
||||
}
|
||||
}
|
@@ -0,0 +1,499 @@
|
||||
import { BaseBlockHandler, type IBlockEventHandlers } from '../block.base.js';
|
||||
import type { IBlock } from '../../wysiwyg.types.js';
|
||||
import { cssManager } from '@design.estate/dees-element';
|
||||
import { WysiwygBlocks } from '../../wysiwyg.blocks.js';
|
||||
import { WysiwygSelection } from '../../wysiwyg.selection.js';
|
||||
|
||||
export class ParagraphBlockHandler extends BaseBlockHandler {
|
||||
type = 'paragraph';
|
||||
|
||||
// Track cursor position
|
||||
private lastKnownCursorPosition: number = 0;
|
||||
private lastSelectedText: string = '';
|
||||
private selectionHandler: (() => void) | null = null;
|
||||
|
||||
render(block: IBlock, isSelected: boolean): string {
|
||||
const selectedClass = isSelected ? ' selected' : '';
|
||||
const placeholder = this.getPlaceholder();
|
||||
|
||||
|
||||
return `
|
||||
<div
|
||||
class="block paragraph${selectedClass}"
|
||||
contenteditable="true"
|
||||
data-placeholder="${placeholder}"
|
||||
data-block-id="${block.id}"
|
||||
data-block-type="${block.type}"
|
||||
></div>
|
||||
`;
|
||||
}
|
||||
|
||||
setup(element: HTMLElement, block: IBlock, handlers: IBlockEventHandlers): void {
|
||||
const paragraphBlock = element.querySelector('.block.paragraph') as HTMLDivElement;
|
||||
if (!paragraphBlock) {
|
||||
console.error('ParagraphBlockHandler.setup: No paragraph block element found');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Set initial content if needed
|
||||
if (block.content && !paragraphBlock.innerHTML) {
|
||||
paragraphBlock.innerHTML = block.content;
|
||||
}
|
||||
|
||||
// Input handler with cursor tracking
|
||||
paragraphBlock.addEventListener('input', (e) => {
|
||||
handlers.onInput(e as InputEvent);
|
||||
|
||||
// Track cursor position after input
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
});
|
||||
|
||||
// Keydown handler with cursor tracking
|
||||
paragraphBlock.addEventListener('keydown', (e) => {
|
||||
// Track cursor position before keydown
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
|
||||
handlers.onKeyDown(e);
|
||||
});
|
||||
|
||||
// Focus handler
|
||||
paragraphBlock.addEventListener('focus', () => {
|
||||
handlers.onFocus();
|
||||
});
|
||||
|
||||
// Blur handler
|
||||
paragraphBlock.addEventListener('blur', () => {
|
||||
handlers.onBlur();
|
||||
});
|
||||
|
||||
// Composition handlers for IME support
|
||||
paragraphBlock.addEventListener('compositionstart', () => {
|
||||
handlers.onCompositionStart();
|
||||
});
|
||||
|
||||
paragraphBlock.addEventListener('compositionend', () => {
|
||||
handlers.onCompositionEnd();
|
||||
});
|
||||
|
||||
// Mouse up handler
|
||||
paragraphBlock.addEventListener('mouseup', (e) => {
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
|
||||
// Selection will be handled by selectionchange event
|
||||
handlers.onMouseUp?.(e);
|
||||
});
|
||||
|
||||
// Click handler with delayed cursor tracking
|
||||
paragraphBlock.addEventListener('click', (e: MouseEvent) => {
|
||||
// Small delay to let browser set cursor position
|
||||
setTimeout(() => {
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
}, 0);
|
||||
});
|
||||
|
||||
// Keyup handler for additional cursor tracking
|
||||
paragraphBlock.addEventListener('keyup', (e) => {
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
});
|
||||
|
||||
// Set up selection change handler
|
||||
this.setupSelectionHandler(element, paragraphBlock, block);
|
||||
}
|
||||
|
||||
private setupSelectionHandler(element: HTMLElement, paragraphBlock: HTMLDivElement, block: IBlock): void {
|
||||
// Add selection change handler
|
||||
const checkSelection = () => {
|
||||
const selection = window.getSelection();
|
||||
if (!selection || selection.rangeCount === 0) return;
|
||||
|
||||
const selectedText = selection.toString();
|
||||
if (selectedText.length === 0) {
|
||||
// Clear selection if no text
|
||||
if (this.lastSelectedText) {
|
||||
this.lastSelectedText = '';
|
||||
this.dispatchSelectionEvent(element, {
|
||||
text: '',
|
||||
blockId: block.id,
|
||||
hasSelection: false
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Get parent wysiwyg component's shadow root - traverse from shadow root
|
||||
const wysiwygBlock = (paragraphBlock.getRootNode() as ShadowRoot).host as any;
|
||||
const parentComponent = wysiwygBlock?.closest('dees-input-wysiwyg');
|
||||
const parentShadowRoot = parentComponent?.shadowRoot;
|
||||
const blockShadowRoot = wysiwygBlock?.shadowRoot;
|
||||
|
||||
// Use getComposedRanges with shadow roots as per MDN docs
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (parentShadowRoot) shadowRoots.push(parentShadowRoot);
|
||||
if (blockShadowRoot) shadowRoots.push(blockShadowRoot);
|
||||
|
||||
// Get selection info using our Shadow DOM-aware utility
|
||||
const selectionInfo = WysiwygSelection.getSelectionInfo(...shadowRoots);
|
||||
if (!selectionInfo) return;
|
||||
|
||||
// Check if selection is within this block
|
||||
const startInBlock = WysiwygSelection.containsAcrossShadowDOM(paragraphBlock, selectionInfo.startContainer);
|
||||
const endInBlock = WysiwygSelection.containsAcrossShadowDOM(paragraphBlock, selectionInfo.endContainer);
|
||||
|
||||
if (startInBlock || endInBlock) {
|
||||
if (selectedText !== this.lastSelectedText) {
|
||||
this.lastSelectedText = selectedText;
|
||||
|
||||
// Create range and get rect
|
||||
const range = WysiwygSelection.createRangeFromInfo(selectionInfo);
|
||||
const rect = range.getBoundingClientRect();
|
||||
|
||||
// Dispatch event
|
||||
this.dispatchSelectionEvent(element, {
|
||||
text: selectedText.trim(),
|
||||
blockId: block.id,
|
||||
range: range,
|
||||
rect: rect,
|
||||
hasSelection: true
|
||||
});
|
||||
}
|
||||
} else if (this.lastSelectedText) {
|
||||
// Clear selection if no longer in this block
|
||||
this.lastSelectedText = '';
|
||||
this.dispatchSelectionEvent(element, {
|
||||
text: '',
|
||||
blockId: block.id,
|
||||
hasSelection: false
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Listen for selection changes
|
||||
document.addEventListener('selectionchange', checkSelection);
|
||||
|
||||
// Store the handler for cleanup
|
||||
this.selectionHandler = checkSelection;
|
||||
|
||||
// Clean up on disconnect (will be called by dees-wysiwyg-block)
|
||||
const wysiwygBlock = element.closest('dees-wysiwyg-block');
|
||||
if (wysiwygBlock) {
|
||||
const originalDisconnectedCallback = (wysiwygBlock as any).disconnectedCallback;
|
||||
(wysiwygBlock as any).disconnectedCallback = async function() {
|
||||
if (this.selectionHandler) {
|
||||
document.removeEventListener('selectionchange', this.selectionHandler);
|
||||
this.selectionHandler = null;
|
||||
}
|
||||
if (originalDisconnectedCallback) {
|
||||
await originalDisconnectedCallback.call(wysiwygBlock);
|
||||
}
|
||||
}.bind(this);
|
||||
}
|
||||
}
|
||||
|
||||
private dispatchSelectionEvent(element: HTMLElement, detail: any): void {
|
||||
const event = new CustomEvent('block-text-selected', {
|
||||
detail,
|
||||
bubbles: true,
|
||||
composed: true
|
||||
});
|
||||
element.dispatchEvent(event);
|
||||
}
|
||||
|
||||
getStyles(): string {
|
||||
return `
|
||||
/* Paragraph specific styles */
|
||||
.block.paragraph {
|
||||
font-size: 16px;
|
||||
line-height: 1.6;
|
||||
font-weight: 400;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
getPlaceholder(): string {
|
||||
return "Type '/' for commands...";
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to get the last text node in an element
|
||||
*/
|
||||
private getLastTextNode(element: Node): Text | null {
|
||||
if (element.nodeType === Node.TEXT_NODE) {
|
||||
return element as Text;
|
||||
}
|
||||
|
||||
for (let i = element.childNodes.length - 1; i >= 0; i--) {
|
||||
const lastText = this.getLastTextNode(element.childNodes[i]);
|
||||
if (lastText) return lastText;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Helper methods for paragraph functionality
|
||||
|
||||
getCursorPosition(element: HTMLElement, context?: any): number | null {
|
||||
// Get the actual paragraph element
|
||||
const paragraphBlock = element.querySelector('.block.paragraph') as HTMLDivElement;
|
||||
if (!paragraphBlock) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get shadow roots from context
|
||||
const wysiwygBlock = context?.component;
|
||||
const parentComponent = wysiwygBlock?.closest('dees-input-wysiwyg');
|
||||
const parentShadowRoot = parentComponent?.shadowRoot;
|
||||
const blockShadowRoot = context?.shadowRoot;
|
||||
|
||||
// Get selection info with both shadow roots for proper traversal
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (parentShadowRoot) shadowRoots.push(parentShadowRoot);
|
||||
if (blockShadowRoot) shadowRoots.push(blockShadowRoot);
|
||||
|
||||
const selectionInfo = WysiwygSelection.getSelectionInfo(...shadowRoots);
|
||||
|
||||
if (!selectionInfo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!WysiwygSelection.containsAcrossShadowDOM(paragraphBlock, selectionInfo.startContainer)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create a range from start of element to cursor position
|
||||
const preCaretRange = document.createRange();
|
||||
preCaretRange.selectNodeContents(paragraphBlock);
|
||||
preCaretRange.setEnd(selectionInfo.startContainer, selectionInfo.startOffset);
|
||||
|
||||
// Get the text content length up to cursor
|
||||
const position = preCaretRange.toString().length;
|
||||
|
||||
return position;
|
||||
}
|
||||
|
||||
getContent(element: HTMLElement, context?: any): string {
|
||||
const paragraphBlock = element.querySelector('.block.paragraph') as HTMLDivElement;
|
||||
if (!paragraphBlock) return '';
|
||||
|
||||
// For paragraphs, get the innerHTML which includes formatting tags
|
||||
const content = paragraphBlock.innerHTML || '';
|
||||
return content;
|
||||
}
|
||||
|
||||
setContent(element: HTMLElement, content: string, context?: any): void {
|
||||
const paragraphBlock = element.querySelector('.block.paragraph') as HTMLDivElement;
|
||||
if (!paragraphBlock) return;
|
||||
|
||||
// Store if we have focus
|
||||
const hadFocus = document.activeElement === paragraphBlock ||
|
||||
element.shadowRoot?.activeElement === paragraphBlock;
|
||||
|
||||
paragraphBlock.innerHTML = content;
|
||||
|
||||
// Restore focus if we had it
|
||||
if (hadFocus) {
|
||||
paragraphBlock.focus();
|
||||
}
|
||||
}
|
||||
|
||||
setCursorToStart(element: HTMLElement, context?: any): void {
|
||||
const paragraphBlock = element.querySelector('.block.paragraph') as HTMLDivElement;
|
||||
if (paragraphBlock) {
|
||||
WysiwygBlocks.setCursorToStart(paragraphBlock);
|
||||
}
|
||||
}
|
||||
|
||||
setCursorToEnd(element: HTMLElement, context?: any): void {
|
||||
const paragraphBlock = element.querySelector('.block.paragraph') as HTMLDivElement;
|
||||
if (paragraphBlock) {
|
||||
WysiwygBlocks.setCursorToEnd(paragraphBlock);
|
||||
}
|
||||
}
|
||||
|
||||
focus(element: HTMLElement, context?: any): void {
|
||||
const paragraphBlock = element.querySelector('.block.paragraph') as HTMLDivElement;
|
||||
if (!paragraphBlock) return;
|
||||
|
||||
// Ensure the element is focusable
|
||||
if (!paragraphBlock.hasAttribute('contenteditable')) {
|
||||
paragraphBlock.setAttribute('contenteditable', 'true');
|
||||
}
|
||||
|
||||
paragraphBlock.focus();
|
||||
|
||||
// If focus failed, try again after a microtask
|
||||
if (document.activeElement !== paragraphBlock && element.shadowRoot?.activeElement !== paragraphBlock) {
|
||||
Promise.resolve().then(() => {
|
||||
paragraphBlock.focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
focusWithCursor(element: HTMLElement, position: 'start' | 'end' | number = 'end', context?: any): void {
|
||||
const paragraphBlock = element.querySelector('.block.paragraph') as HTMLDivElement;
|
||||
if (!paragraphBlock) return;
|
||||
|
||||
|
||||
// Ensure element is focusable first
|
||||
if (!paragraphBlock.hasAttribute('contenteditable')) {
|
||||
paragraphBlock.setAttribute('contenteditable', 'true');
|
||||
}
|
||||
|
||||
// For 'end' position, we need to set up selection before focus to prevent browser default
|
||||
if (position === 'end' && paragraphBlock.textContent && paragraphBlock.textContent.length > 0) {
|
||||
// Set up the selection first
|
||||
const sel = window.getSelection();
|
||||
if (sel) {
|
||||
const range = document.createRange();
|
||||
const lastNode = this.getLastTextNode(paragraphBlock) || paragraphBlock;
|
||||
if (lastNode.nodeType === Node.TEXT_NODE) {
|
||||
range.setStart(lastNode, lastNode.textContent?.length || 0);
|
||||
range.setEnd(lastNode, lastNode.textContent?.length || 0);
|
||||
} else {
|
||||
range.selectNodeContents(lastNode);
|
||||
range.collapse(false);
|
||||
}
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
}
|
||||
}
|
||||
|
||||
// Now focus the element
|
||||
paragraphBlock.focus();
|
||||
|
||||
// Set cursor position after focus is established (for non-end positions)
|
||||
const setCursor = () => {
|
||||
if (position === 'start') {
|
||||
this.setCursorToStart(element, context);
|
||||
} else if (position === 'end' && (!paragraphBlock.textContent || paragraphBlock.textContent.length === 0)) {
|
||||
// Only call setCursorToEnd for empty blocks
|
||||
this.setCursorToEnd(element, context);
|
||||
} else if (typeof position === 'number') {
|
||||
// Use the selection utility to set cursor position
|
||||
WysiwygSelection.setCursorPosition(paragraphBlock, position);
|
||||
}
|
||||
};
|
||||
|
||||
// Ensure cursor is set after focus
|
||||
if (document.activeElement === paragraphBlock || element.shadowRoot?.activeElement === paragraphBlock) {
|
||||
setCursor();
|
||||
} else {
|
||||
// Wait for focus to be established
|
||||
Promise.resolve().then(() => {
|
||||
if (document.activeElement === paragraphBlock || element.shadowRoot?.activeElement === paragraphBlock) {
|
||||
setCursor();
|
||||
} else {
|
||||
// Try again with a small delay - sometimes focus needs more time
|
||||
setTimeout(() => {
|
||||
if (document.activeElement === paragraphBlock || element.shadowRoot?.activeElement === paragraphBlock) {
|
||||
setCursor();
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
getSplitContent(element: HTMLElement, context?: any): { before: string; after: string } | null {
|
||||
const paragraphBlock = element.querySelector('.block.paragraph') as HTMLDivElement;
|
||||
if (!paragraphBlock) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get shadow roots from context
|
||||
const wysiwygBlock = context?.component;
|
||||
const parentComponent = wysiwygBlock?.closest('dees-input-wysiwyg');
|
||||
const parentShadowRoot = parentComponent?.shadowRoot;
|
||||
const blockShadowRoot = context?.shadowRoot;
|
||||
|
||||
// Get selection info with both shadow roots for proper traversal
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (parentShadowRoot) shadowRoots.push(parentShadowRoot);
|
||||
if (blockShadowRoot) shadowRoots.push(blockShadowRoot);
|
||||
|
||||
const selectionInfo = WysiwygSelection.getSelectionInfo(...shadowRoots);
|
||||
|
||||
if (!selectionInfo) {
|
||||
// Try using last known cursor position
|
||||
if (this.lastKnownCursorPosition !== null) {
|
||||
const fullText = paragraphBlock.textContent || '';
|
||||
const pos = Math.min(this.lastKnownCursorPosition, fullText.length);
|
||||
return {
|
||||
before: fullText.substring(0, pos),
|
||||
after: fullText.substring(pos)
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Make sure the selection is within this block
|
||||
if (!WysiwygSelection.containsAcrossShadowDOM(paragraphBlock, selectionInfo.startContainer)) {
|
||||
// Try using last known cursor position
|
||||
if (this.lastKnownCursorPosition !== null) {
|
||||
const fullText = paragraphBlock.textContent || '';
|
||||
const pos = Math.min(this.lastKnownCursorPosition, fullText.length);
|
||||
return {
|
||||
before: fullText.substring(0, pos),
|
||||
after: fullText.substring(pos)
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get cursor position first
|
||||
const cursorPos = this.getCursorPosition(element, context);
|
||||
|
||||
if (cursorPos === null || cursorPos === 0) {
|
||||
// If cursor is at start or can't determine position, move all content
|
||||
return {
|
||||
before: '',
|
||||
after: paragraphBlock.innerHTML
|
||||
};
|
||||
}
|
||||
|
||||
// For HTML content, split using ranges to preserve formatting
|
||||
const beforeRange = document.createRange();
|
||||
const afterRange = document.createRange();
|
||||
|
||||
// Before range: from start of element to cursor
|
||||
beforeRange.setStart(paragraphBlock, 0);
|
||||
beforeRange.setEnd(selectionInfo.startContainer, selectionInfo.startOffset);
|
||||
|
||||
// After range: from cursor to end of element
|
||||
afterRange.setStart(selectionInfo.startContainer, selectionInfo.startOffset);
|
||||
afterRange.setEnd(paragraphBlock, paragraphBlock.childNodes.length);
|
||||
|
||||
// Extract HTML content
|
||||
const beforeFragment = beforeRange.cloneContents();
|
||||
const afterFragment = afterRange.cloneContents();
|
||||
|
||||
// Convert to HTML strings
|
||||
const tempDiv = document.createElement('div');
|
||||
tempDiv.appendChild(beforeFragment);
|
||||
const beforeHtml = tempDiv.innerHTML;
|
||||
|
||||
tempDiv.innerHTML = '';
|
||||
tempDiv.appendChild(afterFragment);
|
||||
const afterHtml = tempDiv.innerHTML;
|
||||
|
||||
return {
|
||||
before: beforeHtml,
|
||||
after: afterHtml
|
||||
};
|
||||
}
|
||||
}
|
457
ts_web/elements/dees-input-wysiwyg/blocks/text/quote.block.ts
Normal file
457
ts_web/elements/dees-input-wysiwyg/blocks/text/quote.block.ts
Normal file
@@ -0,0 +1,457 @@
|
||||
import { BaseBlockHandler, type IBlockEventHandlers } from '../block.base.js';
|
||||
import type { IBlock } from '../../wysiwyg.types.js';
|
||||
import { cssManager } from '@design.estate/dees-element';
|
||||
import { WysiwygBlocks } from '../../wysiwyg.blocks.js';
|
||||
import { WysiwygSelection } from '../../wysiwyg.selection.js';
|
||||
|
||||
export class QuoteBlockHandler extends BaseBlockHandler {
|
||||
type = 'quote';
|
||||
|
||||
// Track cursor position
|
||||
private lastKnownCursorPosition: number = 0;
|
||||
private lastSelectedText: string = '';
|
||||
private selectionHandler: (() => void) | null = null;
|
||||
|
||||
render(block: IBlock, isSelected: boolean): string {
|
||||
const selectedClass = isSelected ? ' selected' : '';
|
||||
const placeholder = this.getPlaceholder();
|
||||
|
||||
|
||||
return `
|
||||
<div
|
||||
class="block quote${selectedClass}"
|
||||
contenteditable="true"
|
||||
data-placeholder="${placeholder}"
|
||||
data-block-id="${block.id}"
|
||||
data-block-type="${block.type}"
|
||||
></div>
|
||||
`;
|
||||
}
|
||||
|
||||
setup(element: HTMLElement, block: IBlock, handlers: IBlockEventHandlers): void {
|
||||
const quoteBlock = element.querySelector('.block.quote') as HTMLDivElement;
|
||||
if (!quoteBlock) {
|
||||
console.error('QuoteBlockHandler.setup: No quote block element found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Set initial content if needed
|
||||
if (block.content && !quoteBlock.innerHTML) {
|
||||
quoteBlock.innerHTML = block.content;
|
||||
}
|
||||
|
||||
// Input handler with cursor tracking
|
||||
quoteBlock.addEventListener('input', (e) => {
|
||||
handlers.onInput(e as InputEvent);
|
||||
|
||||
// Track cursor position after input
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
});
|
||||
|
||||
// Keydown handler with cursor tracking
|
||||
quoteBlock.addEventListener('keydown', (e) => {
|
||||
// Track cursor position before keydown
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
|
||||
handlers.onKeyDown(e);
|
||||
});
|
||||
|
||||
// Focus handler
|
||||
quoteBlock.addEventListener('focus', () => {
|
||||
handlers.onFocus();
|
||||
});
|
||||
|
||||
// Blur handler
|
||||
quoteBlock.addEventListener('blur', () => {
|
||||
handlers.onBlur();
|
||||
});
|
||||
|
||||
// Composition handlers for IME support
|
||||
quoteBlock.addEventListener('compositionstart', () => {
|
||||
handlers.onCompositionStart();
|
||||
});
|
||||
|
||||
quoteBlock.addEventListener('compositionend', () => {
|
||||
handlers.onCompositionEnd();
|
||||
});
|
||||
|
||||
// Mouse up handler
|
||||
quoteBlock.addEventListener('mouseup', (e) => {
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
|
||||
// Selection will be handled by selectionchange event
|
||||
handlers.onMouseUp?.(e);
|
||||
});
|
||||
|
||||
// Click handler with delayed cursor tracking
|
||||
quoteBlock.addEventListener('click', (e: MouseEvent) => {
|
||||
// Small delay to let browser set cursor position
|
||||
setTimeout(() => {
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
}, 0);
|
||||
});
|
||||
|
||||
// Keyup handler for additional cursor tracking
|
||||
quoteBlock.addEventListener('keyup', (e) => {
|
||||
const pos = this.getCursorPosition(element);
|
||||
if (pos !== null) {
|
||||
this.lastKnownCursorPosition = pos;
|
||||
}
|
||||
});
|
||||
|
||||
// Set up selection change handler
|
||||
this.setupSelectionHandler(element, quoteBlock, block);
|
||||
}
|
||||
|
||||
private setupSelectionHandler(element: HTMLElement, quoteBlock: HTMLDivElement, block: IBlock): void {
|
||||
// Add selection change handler
|
||||
const checkSelection = () => {
|
||||
const selection = window.getSelection();
|
||||
if (!selection || selection.rangeCount === 0) return;
|
||||
|
||||
const selectedText = selection.toString();
|
||||
if (selectedText.length === 0) {
|
||||
// Clear selection if no text
|
||||
if (this.lastSelectedText) {
|
||||
this.lastSelectedText = '';
|
||||
this.dispatchSelectionEvent(element, {
|
||||
text: '',
|
||||
blockId: block.id,
|
||||
hasSelection: false
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Get parent wysiwyg component's shadow root - traverse from shadow root
|
||||
const wysiwygBlock = (quoteBlock.getRootNode() as ShadowRoot).host as any;
|
||||
const parentComponent = wysiwygBlock?.closest('dees-input-wysiwyg');
|
||||
const parentShadowRoot = parentComponent?.shadowRoot;
|
||||
const blockShadowRoot = wysiwygBlock?.shadowRoot;
|
||||
|
||||
// Use getComposedRanges with shadow roots as per MDN docs
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (parentShadowRoot) shadowRoots.push(parentShadowRoot);
|
||||
if (blockShadowRoot) shadowRoots.push(blockShadowRoot);
|
||||
|
||||
// Get selection info using our Shadow DOM-aware utility
|
||||
const selectionInfo = WysiwygSelection.getSelectionInfo(...shadowRoots);
|
||||
if (!selectionInfo) return;
|
||||
|
||||
// Check if selection is within this block
|
||||
const startInBlock = WysiwygSelection.containsAcrossShadowDOM(quoteBlock, selectionInfo.startContainer);
|
||||
const endInBlock = WysiwygSelection.containsAcrossShadowDOM(quoteBlock, selectionInfo.endContainer);
|
||||
|
||||
if (startInBlock || endInBlock) {
|
||||
if (selectedText !== this.lastSelectedText) {
|
||||
this.lastSelectedText = selectedText;
|
||||
|
||||
// Create range and get rect
|
||||
const range = WysiwygSelection.createRangeFromInfo(selectionInfo);
|
||||
const rect = range.getBoundingClientRect();
|
||||
|
||||
// Dispatch event
|
||||
this.dispatchSelectionEvent(element, {
|
||||
text: selectedText.trim(),
|
||||
blockId: block.id,
|
||||
range: range,
|
||||
rect: rect,
|
||||
hasSelection: true
|
||||
});
|
||||
}
|
||||
} else if (this.lastSelectedText) {
|
||||
// Clear selection if no longer in this block
|
||||
this.lastSelectedText = '';
|
||||
this.dispatchSelectionEvent(element, {
|
||||
text: '',
|
||||
blockId: block.id,
|
||||
hasSelection: false
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Listen for selection changes
|
||||
document.addEventListener('selectionchange', checkSelection);
|
||||
|
||||
// Store the handler for cleanup
|
||||
this.selectionHandler = checkSelection;
|
||||
|
||||
// Clean up on disconnect (will be called by dees-wysiwyg-block)
|
||||
const wysiwygBlock = (quoteBlock.getRootNode() as ShadowRoot).host as any;
|
||||
if (wysiwygBlock) {
|
||||
const originalDisconnectedCallback = (wysiwygBlock as any).disconnectedCallback;
|
||||
(wysiwygBlock as any).disconnectedCallback = async function() {
|
||||
if (this.selectionHandler) {
|
||||
document.removeEventListener('selectionchange', this.selectionHandler);
|
||||
this.selectionHandler = null;
|
||||
}
|
||||
if (originalDisconnectedCallback) {
|
||||
await originalDisconnectedCallback.call(wysiwygBlock);
|
||||
}
|
||||
}.bind(this);
|
||||
}
|
||||
}
|
||||
|
||||
private dispatchSelectionEvent(element: HTMLElement, detail: any): void {
|
||||
const event = new CustomEvent('block-text-selected', {
|
||||
detail,
|
||||
bubbles: true,
|
||||
composed: true
|
||||
});
|
||||
element.dispatchEvent(event);
|
||||
}
|
||||
|
||||
getStyles(): string {
|
||||
return `
|
||||
/* Quote specific styles */
|
||||
.block.quote {
|
||||
border-left: 3px solid ${cssManager.bdTheme('#0066cc', '#4d94ff')};
|
||||
padding-left: 20px;
|
||||
color: ${cssManager.bdTheme('#555', '#b0b0b0')};
|
||||
font-style: italic;
|
||||
line-height: 1.6;
|
||||
margin: 16px 0;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
getPlaceholder(): string {
|
||||
return 'Add a quote...';
|
||||
}
|
||||
|
||||
// Helper methods for quote functionality
|
||||
|
||||
getCursorPosition(element: HTMLElement, context?: any): number | null {
|
||||
// Get the actual quote element
|
||||
const quoteBlock = element.querySelector('.block.quote') as HTMLDivElement;
|
||||
if (!quoteBlock) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get shadow roots from context
|
||||
const wysiwygBlock = context?.component;
|
||||
const parentComponent = wysiwygBlock?.closest('dees-input-wysiwyg');
|
||||
const parentShadowRoot = parentComponent?.shadowRoot;
|
||||
const blockShadowRoot = context?.shadowRoot;
|
||||
|
||||
// Get selection info with both shadow roots for proper traversal
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (parentShadowRoot) shadowRoots.push(parentShadowRoot);
|
||||
if (blockShadowRoot) shadowRoots.push(blockShadowRoot);
|
||||
|
||||
const selectionInfo = WysiwygSelection.getSelectionInfo(...shadowRoots);
|
||||
|
||||
if (!selectionInfo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!WysiwygSelection.containsAcrossShadowDOM(quoteBlock, selectionInfo.startContainer)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create a range from start of element to cursor position
|
||||
const preCaretRange = document.createRange();
|
||||
preCaretRange.selectNodeContents(quoteBlock);
|
||||
preCaretRange.setEnd(selectionInfo.startContainer, selectionInfo.startOffset);
|
||||
|
||||
// Get the text content length up to cursor
|
||||
const position = preCaretRange.toString().length;
|
||||
|
||||
return position;
|
||||
}
|
||||
|
||||
getContent(element: HTMLElement, context?: any): string {
|
||||
const quoteBlock = element.querySelector('.block.quote') as HTMLDivElement;
|
||||
if (!quoteBlock) return '';
|
||||
|
||||
// For quotes, get the innerHTML which includes formatting tags
|
||||
const content = quoteBlock.innerHTML || '';
|
||||
return content;
|
||||
}
|
||||
|
||||
setContent(element: HTMLElement, content: string, context?: any): void {
|
||||
const quoteBlock = element.querySelector('.block.quote') as HTMLDivElement;
|
||||
if (!quoteBlock) return;
|
||||
|
||||
// Store if we have focus
|
||||
const hadFocus = document.activeElement === quoteBlock ||
|
||||
element.shadowRoot?.activeElement === quoteBlock;
|
||||
|
||||
quoteBlock.innerHTML = content;
|
||||
|
||||
// Restore focus if we had it
|
||||
if (hadFocus) {
|
||||
quoteBlock.focus();
|
||||
}
|
||||
}
|
||||
|
||||
setCursorToStart(element: HTMLElement, context?: any): void {
|
||||
const quoteBlock = element.querySelector('.block.quote') as HTMLDivElement;
|
||||
if (quoteBlock) {
|
||||
WysiwygBlocks.setCursorToStart(quoteBlock);
|
||||
}
|
||||
}
|
||||
|
||||
setCursorToEnd(element: HTMLElement, context?: any): void {
|
||||
const quoteBlock = element.querySelector('.block.quote') as HTMLDivElement;
|
||||
if (quoteBlock) {
|
||||
WysiwygBlocks.setCursorToEnd(quoteBlock);
|
||||
}
|
||||
}
|
||||
|
||||
focus(element: HTMLElement, context?: any): void {
|
||||
const quoteBlock = element.querySelector('.block.quote') as HTMLDivElement;
|
||||
if (!quoteBlock) return;
|
||||
|
||||
// Ensure the element is focusable
|
||||
if (!quoteBlock.hasAttribute('contenteditable')) {
|
||||
quoteBlock.setAttribute('contenteditable', 'true');
|
||||
}
|
||||
|
||||
quoteBlock.focus();
|
||||
|
||||
// If focus failed, try again after a microtask
|
||||
if (document.activeElement !== quoteBlock && element.shadowRoot?.activeElement !== quoteBlock) {
|
||||
Promise.resolve().then(() => {
|
||||
quoteBlock.focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
focusWithCursor(element: HTMLElement, position: 'start' | 'end' | number = 'end', context?: any): void {
|
||||
const quoteBlock = element.querySelector('.block.quote') as HTMLDivElement;
|
||||
if (!quoteBlock) return;
|
||||
|
||||
// Ensure element is focusable first
|
||||
if (!quoteBlock.hasAttribute('contenteditable')) {
|
||||
quoteBlock.setAttribute('contenteditable', 'true');
|
||||
}
|
||||
|
||||
// Focus the element
|
||||
quoteBlock.focus();
|
||||
|
||||
// Set cursor position after focus is established
|
||||
const setCursor = () => {
|
||||
if (position === 'start') {
|
||||
this.setCursorToStart(element, context);
|
||||
} else if (position === 'end') {
|
||||
this.setCursorToEnd(element, context);
|
||||
} else if (typeof position === 'number') {
|
||||
// Use the selection utility to set cursor position
|
||||
WysiwygSelection.setCursorPosition(quoteBlock, position);
|
||||
}
|
||||
};
|
||||
|
||||
// Ensure cursor is set after focus
|
||||
if (document.activeElement === quoteBlock || element.shadowRoot?.activeElement === quoteBlock) {
|
||||
setCursor();
|
||||
} else {
|
||||
// Wait for focus to be established
|
||||
Promise.resolve().then(() => {
|
||||
if (document.activeElement === quoteBlock || element.shadowRoot?.activeElement === quoteBlock) {
|
||||
setCursor();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
getSplitContent(element: HTMLElement, context?: any): { before: string; after: string } | null {
|
||||
const quoteBlock = element.querySelector('.block.quote') as HTMLDivElement;
|
||||
if (!quoteBlock) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get shadow roots from context
|
||||
const wysiwygBlock = context?.component;
|
||||
const parentComponent = wysiwygBlock?.closest('dees-input-wysiwyg');
|
||||
const parentShadowRoot = parentComponent?.shadowRoot;
|
||||
const blockShadowRoot = context?.shadowRoot;
|
||||
|
||||
// Get selection info with both shadow roots for proper traversal
|
||||
const shadowRoots: ShadowRoot[] = [];
|
||||
if (parentShadowRoot) shadowRoots.push(parentShadowRoot);
|
||||
if (blockShadowRoot) shadowRoots.push(blockShadowRoot);
|
||||
|
||||
const selectionInfo = WysiwygSelection.getSelectionInfo(...shadowRoots);
|
||||
|
||||
if (!selectionInfo) {
|
||||
// Try using last known cursor position
|
||||
if (this.lastKnownCursorPosition !== null) {
|
||||
const fullText = quoteBlock.textContent || '';
|
||||
const pos = Math.min(this.lastKnownCursorPosition, fullText.length);
|
||||
return {
|
||||
before: fullText.substring(0, pos),
|
||||
after: fullText.substring(pos)
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Make sure the selection is within this block
|
||||
if (!WysiwygSelection.containsAcrossShadowDOM(quoteBlock, selectionInfo.startContainer)) {
|
||||
// Try using last known cursor position
|
||||
if (this.lastKnownCursorPosition !== null) {
|
||||
const fullText = quoteBlock.textContent || '';
|
||||
const pos = Math.min(this.lastKnownCursorPosition, fullText.length);
|
||||
return {
|
||||
before: fullText.substring(0, pos),
|
||||
after: fullText.substring(pos)
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get cursor position first
|
||||
const cursorPos = this.getCursorPosition(element, context);
|
||||
|
||||
if (cursorPos === null || cursorPos === 0) {
|
||||
// If cursor is at start or can't determine position, move all content
|
||||
return {
|
||||
before: '',
|
||||
after: quoteBlock.innerHTML
|
||||
};
|
||||
}
|
||||
|
||||
// For HTML content, split using ranges to preserve formatting
|
||||
const beforeRange = document.createRange();
|
||||
const afterRange = document.createRange();
|
||||
|
||||
// Before range: from start of element to cursor
|
||||
beforeRange.setStart(quoteBlock, 0);
|
||||
beforeRange.setEnd(selectionInfo.startContainer, selectionInfo.startOffset);
|
||||
|
||||
// After range: from cursor to end of element
|
||||
afterRange.setStart(selectionInfo.startContainer, selectionInfo.startOffset);
|
||||
afterRange.setEnd(quoteBlock, quoteBlock.childNodes.length);
|
||||
|
||||
// Extract HTML content
|
||||
const beforeFragment = beforeRange.cloneContents();
|
||||
const afterFragment = afterRange.cloneContents();
|
||||
|
||||
// Convert to HTML strings
|
||||
const tempDiv = document.createElement('div');
|
||||
tempDiv.appendChild(beforeFragment);
|
||||
const beforeHtml = tempDiv.innerHTML;
|
||||
|
||||
tempDiv.innerHTML = '';
|
||||
tempDiv.appendChild(afterFragment);
|
||||
const afterHtml = tempDiv.innerHTML;
|
||||
|
||||
return {
|
||||
before: beforeHtml,
|
||||
after: afterHtml
|
||||
};
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user