Looking at your script, I can see you're trying to replicate Sider's functionality. Here are the key issues and improvements to make it more robust:
Key Issues & Solutions
1. Event Handling Conflicts
Your current approach might conflict with modern web apps (React, Vue, etc.). Here's an improved version:
private readonly string enableCopyScript = @"
(function() {
// Create isolated scope to avoid conflicts
const SIDER_NAMESPACE = {
aiBtn: null,
aiPanel: null,
lastSelection: '',
selectionTimeout: null,
isProcessing: false,
lastMousePos: { x: 0, y: 0 }
};
// --- Helper: Detect input/editor elements ---
function isInputOrEditor(el) {
if (!el) return false;
const tagName = el.tagName?.toUpperCase();
if (tagName === 'INPUT' || tagName === 'TEXTAREA' || el.isContentEditable) return true;
// Check for common editor classes
const editorSelectors = [
'.ql-editor', '.CodeMirror', '.monaco-editor',
'[role=""textbox""]', '[contenteditable=""true""]',
'.ace_editor', '.cm-editor', '.ProseMirror'
];
return editorSelectors.some(selector => el.closest(selector));
}
// --- Enhanced selection enabler ---
function enableTextSelection() {
// Create style with higher specificity
const styleId = 'sider-enable-selection';
let style = document.getElementById(styleId);
if (!style) {
style = document.createElement('style');
style.id = styleId;
style.innerHTML = `
*:not(input):not(textarea):not([contenteditable=""true""]):not(.ql-editor):not(.CodeMirror):not(.monaco-editor) {
user-select: text !important;
-webkit-user-select: text !important;
-ms-user-select: text !important;
-moz-user-select: text !important;
pointer-events: auto !important;
}
/* Override common blocking classes */
.no-select, .noselect, .unselectable, .disable-select {
user-select: text !important;
-webkit-user-select: text !important;
}
/* Ensure our UI stays on top */
.sider-ai-btn, .sider-ai-panel {
z-index: 2147483647 !important;
}
`;
document.head.appendChild(style);
}
// Remove inline styles blocking selection
const elements = document.querySelectorAll('[style*=""user-select""], [style*=""pointer-events""]');
elements.forEach(el => {
if (isInputOrEditor(el)) return;
const computedStyle = window.getComputedStyle(el);
if (computedStyle.userSelect === 'none') {
el.style.setProperty('user-select', 'text', 'important');
el.style.setProperty('-webkit-user-select', 'text', 'important');
}
if (computedStyle.pointerEvents === 'none' && !el.classList.contains('sider-ai-btn')) {
el.style.setProperty('pointer-events', 'auto', 'important');
}
});
}
// --- Create AI Button ---
function createAIButton(rect, text) {
removeAIElements();
const btn = document.createElement('button');
btn.className = 'sider-ai-btn';
btn.innerHTML = `
<svg width=""16"" height=""16"" viewBox=""0 0 24 24"" fill=""none"" style=""margin-right: 4px; vertical-align: middle;"">
<path d=""M12 2L2 7L12 12L22 7L12 2Z"" stroke=""currentColor"" stroke-width=""2""/>
<path d=""M2 17L12 22L22 17"" stroke=""currentColor"" stroke-width=""2""/>
<path d=""M2 12L12 17L22 12"" stroke=""currentColor"" stroke-width=""2""/>
</svg>
Ask AI
`;
// Calculate position with viewport bounds check
const btnWidth = 100;
const btnHeight = 36;
let left = rect.right + 8;
let top = rect.top - 4;
// Adjust if button would go off screen
if (left + btnWidth > window.innerWidth - 10) {
left = rect.left - btnWidth - 8;
}
if (top + btnHeight > window.innerHeight - 10) {
top = rect.bottom - btnHeight - 4;
}
Object.assign(btn.style, {
position: 'fixed',
left: left + 'px',
top: top + 'px',
padding: '6px 12px',
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
color: 'white',
border: 'none',
borderRadius: '20px',
boxShadow: '0 4px 12px rgba(102, 126, 234, 0.4)',
fontSize: '14px',
fontWeight: '500',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
transition: 'all 0.2s ease',
opacity: '0',
transform: 'scale(0.9)',
zIndex: '2147483647'
});
// Animate in
setTimeout(() => {
btn.style.opacity = '1';
btn.style.transform = 'scale(1)';
}, 10);
// Hover effect
btn.onmouseenter = () => {
btn.style.transform = 'scale(1.05)';
btn.style.boxShadow = '0 6px 16px rgba(102, 126, 234, 0.5)';
};
btn.onmouseleave = () => {
btn.style.transform = 'scale(1)';
btn.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.4)';
};
// Click handler with event capture
btn.addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
showAIPanel(text, btn);
}, true);
document.body.appendChild(btn);
SIDER_NAMESPACE.aiBtn = btn;
}
// --- Create AI Panel ---
function showAIPanel(text, anchorBtn) {
if (SIDER_NAMESPACE.aiPanel) return;
const panel = document.createElement('div');
panel.className = 'sider-ai-panel';
const btnRect = anchorBtn.getBoundingClientRect();
const panelWidth = 360;
const panelMaxHeight = 500;
// Smart positioning
let left = btnRect.right + 16;
let top = btnRect.top;
if (left + panelWidth > window.innerWidth - 20) {
left = btnRect.left - panelWidth - 16;
}
if (top + panelMaxHeight > window.innerHeight - 20) {
top = window.innerHeight - panelMaxHeight - 20;
}
panel.innerHTML = `
<div class=""sider-panel-header"">
<h3 style=""margin: 0; font-size: 16px; color: #333;"">AI Assistant</h3>
<button class=""sider-close-btn"" style=""
position: absolute;
right: 12px;
top: 12px;
background: none;
border: none;
font-size: 20px;
cursor: pointer;
color: #666;
padding: 4px 8px;
"">×</button>
</div>
<div class=""sider-panel-content"" style=""padding: 16px;"">
<div style=""color: #666; font-size: 14px; margin-bottom: 12px;"">Selected text:</div>
<div style=""
background: #f5f5f5;
padding: 12px;
border-radius: 8px;
margin-bottom: 16px;
font-size: 14px;
max-height: 100px;
overflow-y: auto;
"">${escapeHtml(text.slice(0, 500))}</div>
<div class=""sider-ai-response"" style=""
min-height: 60px;
display: flex;
align-items: center;
justify-content: center;
color: #666;
"">
<div class=""sider-loading"">
<div style=""
width: 40px;
height: 40px;
border: 3px solid #f3f3f3;
border-top: 3px solid #667eea;
border-radius: 50%;
animation: sider-spin 1s linear infinite;
""></div>
</div>
</div>
</div>
`;
Object.assign(panel.style, {
position: 'fixed',
left: left + 'px',
top: top + 'px',
width: panelWidth + 'px',
maxHeight: panelMaxHeight + 'px',
background: 'white',
borderRadius: '12px',
boxShadow: '0 8px 32px rgba(0, 0, 0, 0.12)',
overflow: 'hidden',
opacity: '0',
transform: 'translateY(10px)',
transition: 'all 0.3s ease',
zIndex: '2147483647'
});
// Add animation keyframes
if (!document.getElementById('sider-animations')) {
const animStyle = document.createElement('style');
animStyle.id = 'sider-animations';
animStyle.innerHTML = `
@keyframes sider-spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`;
document.head.appendChild(animStyle);
}
document.body.appendChild(panel);
SIDER_NAMESPACE.aiPanel = panel;
// Animate in
setTimeout(() => {
panel.style.opacity = '1';
panel.style.transform = 'translateY(0)';
}, 10);
// Close button handler
panel.querySelector('.sider-close-btn').onclick = removeAIElements;
// Simulate AI response (replace with actual API call)
setTimeout(() => {
const responseDiv = panel.querySelector('.sider-ai-response');
responseDiv.innerHTML = `
<div style=""color: #333; line-height: 1.6;"">
<p style=""margin: 0 0 12px 0;"">Here's what I found about your selection:</p>
<p style=""margin: 0; color: #555;"">${generateMockResponse(text)}</p>
</div>
`;
}, 1500);
}
// --- Helper Functions ---
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function generateMockResponse(text) {
// Replace with actual AI API call
return `This is a mock AI response for the selected text. In production, this would call your AI service with the text: ""${text.slice(0, 50)}...""`;
}
function removeAIElements() {
if (SIDER_NAMESPACE.aiBtn) {
SIDER_NAMESPACE.aiBtn.style.opacity = '0';
SIDER_NAMESPACE.aiBtn.style.transform = 'scale(0.9)';
setTimeout(() => {
SIDER_NAMESPACE.aiBtn?.remove();
SIDER_NAMESPACE.aiBtn = null;
}, 200);
}
if (SIDER_NAMESPACE.aiPanel) {
SIDER_NAMESPACE.aiPanel.style.opacity = '0';
SIDER_NAMESPACE.aiPanel.style.transform = 'translateY(10px)';
setTimeout(() => {
SIDER_NAMESPACE.aiPanel?.remove();
SIDER_NAMESPACE.aiPanel = null;
}, 300);
}
}
// --- Enhanced Selection Detection ---
function handleSelection() {
if (SIDER_NAMESPACE.isProcessing) return;
clearTimeout(SIDER_NAMESPACE.selectionTimeout);
SIDER_NAMESPACE.selectionTimeout = setTimeout(() => {
const selection = window.getSelection();
if (!selection || selection.isCollapsed) {
removeAIElements();
SIDER_NAMESPACE.lastSelection = '';
return;
}
const text = selection.toString().trim();
if (!text || text.length < 3) {
removeAIElements();
SIDER_NAMESPACE.lastSelection = '';
return;
}
// Check if selection is in input/editor
const anchorNode = selection.anchorNode;
const element = anchorNode?.nodeType === Node.TEXT_NODE
? anchorNode.parentElement
: anchorNode;
if (isInputOrEditor(element)) {
removeAIElements();
return;
}
// Get selection rectangle
try {
const range = selection.getRangeAt(0);
const rect = range.getBoundingClientRect();
if (rect.width > 0 && rect.height > 0) {
if (text !== SIDER_NAMESPACE.lastSelection) {
SIDER_NAMESPACE.lastSelection = text;
createAIButton(rect, text);
}
}
} catch (e) {
console.error('Selection error:', e);
}
}, 200);
}
// --- Event Listeners ---
// Primary selection detection
document.addEventListener('selectionchange', handleSelection);
// Backup selection detection for mouseup
document.addEventListener('mouseup', function(e) {
// Store mouse position for later use
SIDER_NAMESPACE.lastMousePos = { x: e.clientX, y: e.clientY };
// Don't trigger if clicking on our elements
if (e.target.closest('.sider-ai-btn, .sider-ai-panel')) return;
setTimeout(handleSelection, 50);
});
// Remove on outside click
document.addEventListener('mousedown', function(e) {
if (!e.target.closest('.sider-ai-btn, .sider-ai-panel')) {
removeAIElements();
}
}, true);
// Remove on scroll
let scrollTimeout;
document.addEventListener('scroll', function() {
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(removeAIElements, 100);
}, true);
// Remove on escape key
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') removeAIElements();
});
// Initial setup
enableTextSelection();
// Reapply selection enabling periodically for dynamic content
setInterval(enableTextSelection, 2000);