(function() {
'use strict';
class WikipediaClaudeProofreader {
constructor() {
this.apiKey = localStorage.getItem('claude_api_key');
this.sidebarWidth = localStorage.getItem('claude_sidebar_width') || '350px';
this.isVisible = localStorage.getItem('claude_sidebar_visible') !== 'false';
this.currentResults = localStorage.getItem('claude_current_results') || '';
this.init();
}
init() {
this.createUI();
this.attachEventListeners();
this.adjustMainContent();
}
createUI() {
// Create sidebar container
const sidebar = document.createElement('div');
sidebar.id = 'claude-proofreader-sidebar';
sidebar.innerHTML = `
<div id="claude-sidebar-header">
<h3>Claude Proofreader</h3>
<div id="claude-sidebar-controls">
<button id="claude-close-btn" title="Close">×</button>
</div>
</div>
<div id="claude-sidebar-content">
<div id="claude-controls">
<button id="claude-set-key-btn" ${this.apiKey ? 'style="display:none"' : ''}>Set API Key</button>
<button id="claude-proofread-btn" ${!this.apiKey ? 'style="display:none"' : ''}>Proofread Article</button>
<button id="claude-change-key-btn" ${!this.apiKey ? 'style="display:none"' : ''}>Change Key</button>
</div>
<div id="claude-results">
<div id="claude-status">Ready to proofread</div>
<div id="claude-output">${this.currentResults}</div>
</div>
</div>
<div id="claude-resize-handle"></div>
`;
// Create Claude tab for when sidebar is closed
this.createClaudeTab();
// Add CSS styles
const style = document.createElement('style');
style.textContent = `
#claude-proofreader-sidebar {
position: fixed;
top: 0;
right: 0;
width: ${this.sidebarWidth};
height: 100vh;
background: #fff;
border-left: 2px solid #0645ad;
box-shadow: -2px 0 8px rgba(0,0,0,0.1);
z-index: 10000;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
font-size: 14px;
display: flex;
flex-direction: column;
transition: all 0.3s ease;
}
#claude-sidebar-header {
background: #0645ad;
color: white;
padding: 12px 15px;
display: flex;
justify-content: space-between;
align-items: center;
flex-shrink: 0;
}
#claude-sidebar-header h3 {
margin: 0;
font-size: 16px;
}
#claude-sidebar-controls {
display: flex;
gap: 8px;
}
#claude-sidebar-controls button {
background: rgba(255,255,255,0.2);
border: none;
color: white;
font-size: 16px;
cursor: pointer;
padding: 4px 8px;
border-radius: 3px;
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
}
#claude-sidebar-controls button:hover {
background: rgba(255,255,255,0.3);
}
#claude-sidebar-content {
padding: 15px;
flex: 1;
overflow-y: auto;
display: flex;
flex-direction: column;
}
#claude-controls {
margin-bottom: 15px;
flex-shrink: 0;
}
#claude-controls button {
background: #0645ad;
color: white;
border: none;
padding: 8px 12px;
border-radius: 4px;
cursor: pointer;
margin-right: 8px;
margin-bottom: 8px;
font-size: 12px;
}
#claude-controls button:hover {
background: #0a5bb3;
}
#claude-controls button:disabled {
background: #ccc;
cursor: not-allowed;
}
#claude-results {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
}
#claude-status {
font-weight: bold;
margin-bottom: 10px;
padding: 8px;
background: #f8f9fa;
border-radius: 4px;
flex-shrink: 0;
}
#claude-output {
line-height: 1.5;
flex: 1;
overflow-y: auto;
border: 1px solid #ddd;
padding: 12px;
border-radius: 4px;
background: #fafafa;
font-size: 13px;
}
#claude-output h1, #claude-output h2, #claude-output h3 {
color: #0645ad;
margin-top: 16px;
margin-bottom: 8px;
}
#claude-output h1 { font-size: 1.3em; }
#claude-output h2 { font-size: 1.2em; }
#claude-output h3 { font-size: 1.1em; }
#claude-output ul, #claude-output ol {
padding-left: 18px;
}
#claude-output p {
margin-bottom: 10px;
}
#claude-output strong {
color: #d33;
}
#claude-resize-handle {
position: absolute;
left: 0;
top: 0;
width: 4px;
height: 100%;
background: transparent;
cursor: ew-resize;
z-index: 10001;
}
#claude-resize-handle:hover {
background: #0645ad;
opacity: 0.5;
}
#ca-claude {
display: none;
}
#ca-claude a {
color: #0645ad !important;
text-decoration: none !important;
padding: 0.5em !important;
}
#ca-claude a:hover {
text-decoration: underline !important;
}
.claude-error {
color: #d33;
background: #fef2f2;
border: 1px solid #fecaca;
padding: 8px;
border-radius: 4px;
}
/* Hidden state styles */
body.claude-sidebar-hidden #claude-proofreader-sidebar {
display: none;
}
body.claude-sidebar-hidden #ca-claude {
display: list-item !important;
}
`;
document.head.appendChild(style);
document.body.appendChild(sidebar);
// Set initial state
if (!this.isVisible) {
this.hideSidebar();
} else {
this.showSidebar();
}
// Make sidebar resizable
this.makeResizable();
}
createClaudeTab() {
// Only create tab if we're in the main article namespace (namespace 0)
if (typeof mw !== 'undefined' && mw.config.get('wgNamespaceNumber') === 0) {
// Create the Claude tab
const claudeTab = document.createElement('li');
claudeTab.id = 'ca-claude';
claudeTab.className = 'mw-list-item';
const claudeLink = document.createElement('a');
claudeLink.href = '#';
claudeLink.title = 'Proofread with Claude AI';
claudeLink.addEventListener('click', (e) => {
e.preventDefault();
this.showSidebar();
});
const claudeSpan = document.createElement('span');
claudeSpan.textContent = 'Claude';
claudeLink.appendChild(claudeSpan);
claudeTab.appendChild(claudeLink);
// Find the talk tab and add Claude tab after it
const talkTab = document.getElementById('ca-talk') || document.querySelector('.ca-talk');
if (talkTab && talkTab.parentNode) {
talkTab.parentNode.insertBefore(claudeTab, talkTab.nextSibling);
}
// Fallback: add to any tabs container we can find
else {
const tabsContainer = document.querySelector('#p-namespaces ul') ||
document.querySelector('.vector-menu-tabs ul') ||
document.querySelector('#p-views ul');
if (tabsContainer) {
tabsContainer.appendChild(claudeTab);
}
}
}
}
makeResizable() {
const handle = document.getElementById('claude-resize-handle');
const sidebar = document.getElementById('claude-proofreader-sidebar');
if (!handle || !sidebar) return;
let isResizing = false;
handle.addEventListener('mousedown', (e) => {
isResizing = true;
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
e.preventDefault();
});
const handleMouseMove = (e) => {
if (!isResizing) return;
const newWidth = window.innerWidth - e.clientX;
const minWidth = 250;
const maxWidth = window.innerWidth * 0.7;
if (newWidth >= minWidth && newWidth <= maxWidth) {
const widthPx = newWidth + 'px';
sidebar.style.width = widthPx;
this.sidebarWidth = widthPx;
localStorage.setItem('claude_sidebar_width', widthPx);
// Update the CSS rules for the new width
this.updateWidthCSS();
}
};
const handleMouseUp = () => {
isResizing = false;
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
}
updateWidthCSS() {
// Update the CSS rules with the new width
const existingStyle = document.querySelector('style[data-claude-proofreader]');
if (existingStyle) {
existingStyle.remove();
}
const style = document.createElement('style');
style.setAttribute('data-claude-proofreader', 'true');
style.textContent = `
/* Vector 2022 theme - comprehensive approach */
body.claude-sidebar-visible .mw-page-container {
margin-right: ${this.sidebarWidth} !important;
box-sizing: border-box !important;
}
/* Vector 2022 - main content wrapper */
body.claude-sidebar-visible .mw-page-container-inner {
margin-right: 0 !important;
padding-right: 0 !important;
max-width: none !important;
}
/* Vector 2022 - content area */
body.claude-sidebar-visible .mw-content-container {
max-width: none !important;
margin-right: 0 !important;
}
/* Vector 2022 - article content */
body.claude-sidebar-visible .mw-body {
margin-right: 0 !important;
max-width: none !important;
}
/* Vector 2022 - main content */
body.claude-sidebar-visible #content {
margin-right: 0 !important;
max-width: none !important;
}
/* Legacy Vector and other themes */
body.claude-sidebar-visible #globalWrapper {
margin-right: ${this.sidebarWidth} !important;
box-sizing: border-box;
}
/* Header adjustments */
body.claude-sidebar-visible .vector-header,
body.claude-sidebar-visible .vector-sticky-header,
body.claude-sidebar-visible #mw-head {
right: ${this.sidebarWidth} !important;
width: calc(100% - ${this.sidebarWidth}) !important;
box-sizing: border-box;
}
`;
document.head.appendChild(style);
}
showSidebar() {
const claudeTab = document.getElementById('ca-claude');
document.body.classList.remove('claude-sidebar-hidden');
document.body.classList.add('claude-sidebar-visible');
if (claudeTab) claudeTab.style.display = 'none';
this.isVisible = true;
localStorage.setItem('claude_sidebar_visible', 'true');
}
hideSidebar() {
const claudeTab = document.getElementById('ca-claude');
document.body.classList.add('claude-sidebar-hidden');
document.body.classList.remove('claude-sidebar-visible');
if (claudeTab) claudeTab.style.display = 'list-item';
this.isVisible = false;
localStorage.setItem('claude_sidebar_visible', 'false');
}
adjustMainContent() {
// Only apply layout changes when sidebar is actually visible
if (this.isVisible) {
document.body.classList.add('claude-sidebar-visible');
document.body.classList.remove('claude-sidebar-hidden');
} else {
document.body.classList.add('claude-sidebar-hidden');
document.body.classList.remove('claude-sidebar-visible');
}
}
attachEventListeners() {
document.getElementById('claude-close-btn').addEventListener('click', () => {
this.hideSidebar();
});
document.getElementById('claude-set-key-btn').addEventListener('click', () => {
this.setApiKey();
});
document.getElementById('claude-change-key-btn').addEventListener('click', () => {
this.setApiKey();
});
document.getElementById('claude-proofread-btn').addEventListener('click', () => {
this.proofreadArticle();
});
}
setApiKey() {
const key = prompt('Enter your Claude API Key:');
if (key && key.trim()) {
this.apiKey = key.trim();
localStorage.setItem('claude_api_key', this.apiKey);
// Update UI
document.getElementById('claude-set-key-btn').style.display = 'none';
document.getElementById('claude-proofread-btn').style.display = 'inline-block';
document.getElementById('claude-change-key-btn').style.display = 'inline-block';
this.updateStatus('API key set successfully!');
}
}
clearResults() {
this.currentResults = '';
localStorage.removeItem('claude_current_results');
this.updateOutput('');
this.updateStatus('Results cleared. Ready to proofread.');
}
updateStatus(message, isError = false) {
const statusEl = document.getElementById('claude-status');
statusEl.textContent = message;
statusEl.className = isError ? 'claude-error' : '';
}
updateOutput(content, isMarkdown = false) {
const outputEl = document.getElementById('claude-output');
if (isMarkdown) {
content = this.markdownToHtml(content);
outputEl.innerHTML = content;
} else {
outputEl.textContent = content;
}
// Store results
if (content) {
this.currentResults = content;
localStorage.setItem('claude_current_results', content);
}
}
markdownToHtml(markdown) {
return markdown
// Headers
.replace(/^### (.*$)/gim, '<h3>$1</h3>')
.replace(/^## (.*$)/gim, '<h2>$1</h2>')
.replace(/^# (.*$)/gim, '<h1>$1</h1>')
// Bold
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
// Italic
.replace(/\*(.*?)\*/g, '<em>$1</em>')
// Lists
.replace(/^\* (.*$)/gim, '<li>$1</li>')
.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>')
.replace(/^\d+\. (.*$)/gim, '<li>$1</li>')
// Line breaks
.replace(/\n\n/g, '</p><p>')
.replace(/\n/g, '<br>')
// Wrap in paragraphs
.replace(/^(?!<[hul])/gm, '<p>')
.replace(/(?<!>)$/gm, '</p>')
// Clean up
.replace(/<p><\/p>/g, '')
.replace(/<p>(<[hul])/g, '$1')
.replace(/(<\/[hul]>)<\/p>/g, '$1');
}
async proofreadArticle() {
if (!this.apiKey) {
this.updateStatus('Please set your API key first!', true);
return;
}
try {
this.updateStatus('Fetching article content...', false);
const proofreadBtn = document.getElementById('claude-proofread-btn');
proofreadBtn.disabled = true;
// Get current article title
const articleTitle = this.getArticleTitle();
if (!articleTitle) {
throw new Error('Could not extract article title from current page');
}
// Fetch wikicode
const wikicode = await this.fetchWikicode(articleTitle);
if (!wikicode) {
throw new Error('Could not fetch article wikicode');
}
// Check length and warn user
if (wikicode.length > 100000) {
if (!confirm(`This article is quite long (${wikicode.length} characters). Processing may take a while and use significant API credits. Continue?`)) {
this.updateStatus('Operation cancelled by user.');
proofreadBtn.disabled = false;
return;
}
}
this.updateStatus('Processing with Claude... Please wait...');
// Call Claude API
const result = await this.callClaudeAPI(wikicode);
this.updateStatus('Proofreading complete!');
this.updateOutput(result, true);
} catch (error) {
console.error('Proofreading error:', error);
this.updateStatus(`Error: ${error.message}`, true);
this.updateOutput('');
} finally {
document.getElementById('claude-proofread-btn').disabled = false;
}
}
getArticleTitle() {
// Extract title from URL
const url = window.___location.href;
let match = url.match(/\/wiki\/(.+)$/);
if (match) {
return decodeURIComponent(match[1]);
}
// Check if we're on an edit page
match = url.match(/[?&]title=([^&]+)/);
if (match) {
return decodeURIComponent(match[1]);
}
return null;
}
async fetchWikicode(articleTitle) {
// Get language from current URL
const language = window.___location.hostname.split('.')[0] || 'en';
const apiUrl = `https://${language}.wikipedia.org/w/api.php?` +
`action=query&titles=${encodeURIComponent(articleTitle)}&` +
`prop=revisions&rvprop=content&format=json&formatversion=2&origin=*`;
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`Wikipedia API request failed: ${response.status}`);
}
const data = await response.json();
if (!data.query || !data.query.pages || data.query.pages.length === 0) {
throw new Error('No pages found in API response');
}
const page = data.query.pages[0];
if (page.missing) {
throw new Error('Wikipedia page not found');
}
if (!page.revisions || page.revisions.length === 0) {
throw new Error('No revisions found');
}
const content = page.revisions[0].content;
if (!content || content.length < 50) {
throw new Error('Retrieved content is too short');
}
return content;
} catch (error) {
console.error('Error fetching wikicode:', error);
throw error;
}
}
async callClaudeAPI(wikicode) {
const requestBody = {
model: "claude-sonnet-4-20250514",
max_tokens: 4000,
messages: [{
role: "user",
content: `It is currently June 2025. Please proofread this Wikipedia article and identify any typos, grammatical errors and factual inconsistencies. Ignore formatting issues and date inconsistencies. Focus on the actual article content. Format your response as a detailed analysis with specific issues found:\n\n${wikicode}`
}]
};
try {
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': this.apiKey,
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`API request failed (${response.status}): ${errorText}`);
}
const data = await response.json();
if (!data.content || !data.content[0] || !data.content[0].text) {
throw new Error('Invalid API response format');
}
return data.content[0].text;
} catch (error) {
console.error('Claude API error:', error);
throw error;
}
}
}
// Initialize the proofreader when page loads
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
new WikipediaClaudeProofreader();
});
} else {
new WikipediaClaudeProofreader();
}
})();