ai factory

This commit is contained in:
Zylan
2025-02-03 14:49:18 +08:00
parent ab4f208e48
commit 597d6353b4
22 changed files with 1868 additions and 736 deletions

391
static/js/main.js Normal file
View File

@@ -0,0 +1,391 @@
class SnapSolver {
constructor() {
this.initializeElements();
this.initializeState();
this.setupEventListeners();
this.initializeConnection();
// Initialize managers
window.uiManager = new UIManager();
window.settingsManager = new SettingsManager();
}
initializeElements() {
// Capture elements
this.captureBtn = document.getElementById('captureBtn');
this.cropBtn = document.getElementById('cropBtn');
this.connectionStatus = document.getElementById('connectionStatus');
this.screenshotImg = document.getElementById('screenshotImg');
this.cropContainer = document.getElementById('cropContainer');
this.imagePreview = document.getElementById('imagePreview');
this.sendToClaudeBtn = document.getElementById('sendToClaude');
this.responseContent = document.getElementById('responseContent');
this.claudePanel = document.getElementById('claudePanel');
}
initializeState() {
this.socket = null;
this.cropper = null;
this.croppedImage = null;
this.history = JSON.parse(localStorage.getItem('snapHistory') || '[]');
}
updateConnectionStatus(connected) {
this.connectionStatus.textContent = connected ? 'Connected' : 'Disconnected';
this.connectionStatus.className = `status ${connected ? 'connected' : 'disconnected'}`;
this.captureBtn.disabled = !connected;
if (!connected) {
this.imagePreview.classList.add('hidden');
this.cropBtn.classList.add('hidden');
this.sendToClaudeBtn.classList.add('hidden');
}
}
initializeConnection() {
try {
this.socket = io(window.location.origin);
this.socket.on('connect', () => {
console.log('Connected to server');
this.updateConnectionStatus(true);
});
this.socket.on('disconnect', () => {
console.log('Disconnected from server');
this.updateConnectionStatus(false);
this.socket = null;
setTimeout(() => this.initializeConnection(), 5000);
});
this.setupSocketEventHandlers();
} catch (error) {
console.error('Connection error:', error);
this.updateConnectionStatus(false);
setTimeout(() => this.initializeConnection(), 5000);
}
}
setupSocketEventHandlers() {
this.socket.on('screenshot_response', (data) => {
if (data.success) {
this.screenshotImg.src = `data:image/png;base64,${data.image}`;
this.imagePreview.classList.remove('hidden');
this.cropBtn.classList.remove('hidden');
this.captureBtn.disabled = false;
this.captureBtn.innerHTML = '<i class="fas fa-camera"></i><span>Capture</span>';
this.sendToClaudeBtn.classList.add('hidden');
window.showToast('Screenshot captured successfully');
} else {
window.showToast('Failed to capture screenshot: ' + data.error, 'error');
this.captureBtn.disabled = false;
this.captureBtn.innerHTML = '<i class="fas fa-camera"></i><span>Capture</span>';
}
});
this.socket.on('claude_response', (data) => {
console.log('Received claude_response:', data);
switch (data.status) {
case 'started':
console.log('Analysis started');
this.responseContent.textContent = 'Starting analysis...\n';
this.sendToClaudeBtn.disabled = true;
break;
case 'streaming':
if (data.content) {
console.log('Received content:', data.content);
if (this.responseContent.textContent === 'Starting analysis...\n') {
this.responseContent.textContent = data.content;
} else {
this.responseContent.textContent += data.content;
}
this.responseContent.scrollTo({
top: this.responseContent.scrollHeight,
behavior: 'smooth'
});
}
break;
case 'completed':
console.log('Analysis completed');
this.responseContent.textContent += '\n\nAnalysis complete.';
this.sendToClaudeBtn.disabled = false;
this.addToHistory(this.croppedImage, this.responseContent.textContent);
window.showToast('Analysis completed successfully');
this.responseContent.scrollTo({
top: this.responseContent.scrollHeight,
behavior: 'smooth'
});
break;
case 'error':
console.error('Claude analysis error:', data.error);
const errorMessage = data.error || 'Unknown error occurred';
this.responseContent.textContent += '\n\nError: ' + errorMessage;
this.sendToClaudeBtn.disabled = false;
this.responseContent.scrollTop = this.responseContent.scrollHeight;
window.showToast('Analysis failed: ' + errorMessage, 'error');
break;
default:
console.warn('Unknown response status:', data.status);
if (data.error) {
this.responseContent.textContent += '\n\nError: ' + data.error;
this.sendToClaudeBtn.disabled = false;
this.responseContent.scrollTop = this.responseContent.scrollHeight;
window.showToast('Unknown error occurred', 'error');
}
}
});
this.socket.on('connect_error', (error) => {
console.error('Connection error:', error);
this.updateConnectionStatus(false);
this.socket = null;
setTimeout(() => this.initializeConnection(), 5000);
});
}
initializeCropper() {
if (this.cropper) {
this.cropper.destroy();
this.cropper = null;
}
const cropArea = document.querySelector('.crop-area');
cropArea.innerHTML = '';
const clonedImage = this.screenshotImg.cloneNode(true);
clonedImage.style.display = 'block';
cropArea.appendChild(clonedImage);
this.cropContainer.classList.remove('hidden');
this.cropper = new Cropper(clonedImage, {
viewMode: 1,
dragMode: 'move',
autoCropArea: 1,
restore: false,
modal: true,
guides: true,
highlight: true,
cropBoxMovable: true,
cropBoxResizable: true,
toggleDragModeOnDblclick: false,
minContainerWidth: window.innerWidth,
minContainerHeight: window.innerHeight - 100,
minCropBoxWidth: 100,
minCropBoxHeight: 100,
background: true,
responsive: true,
checkOrientation: true,
ready: function() {
this.cropper.crop();
}
});
}
addToHistory(imageData, response) {
const historyItem = {
id: Date.now(),
timestamp: new Date().toISOString(),
image: imageData,
response: response
};
this.history.unshift(historyItem);
if (this.history.length > 10) this.history.pop();
localStorage.setItem('snapHistory', JSON.stringify(this.history));
window.renderHistory();
}
setupEventListeners() {
// Capture button
this.captureBtn.addEventListener('click', async () => {
if (!this.socket || !this.socket.connected) {
window.showToast('Not connected to server', 'error');
return;
}
try {
this.captureBtn.disabled = true;
this.captureBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i><span>Capturing...</span>';
this.socket.emit('request_screenshot');
} catch (error) {
window.showToast('Error requesting screenshot: ' + error.message, 'error');
this.captureBtn.disabled = false;
this.captureBtn.innerHTML = '<i class="fas fa-camera"></i><span>Capture</span>';
}
});
// Crop button
this.cropBtn.addEventListener('click', () => {
if (this.screenshotImg.src) {
this.initializeCropper();
}
});
// Crop confirm button
document.getElementById('cropConfirm').addEventListener('click', () => {
if (this.cropper) {
try {
const canvas = this.cropper.getCroppedCanvas({
maxWidth: 4096,
maxHeight: 4096,
fillColor: '#fff',
imageSmoothingEnabled: true,
imageSmoothingQuality: 'high',
});
if (!canvas) {
throw new Error('Failed to create cropped canvas');
}
this.croppedImage = canvas.toDataURL('image/png');
this.cropper.destroy();
this.cropper = null;
this.cropContainer.classList.add('hidden');
document.querySelector('.crop-area').innerHTML = '';
this.settingsPanel.classList.add('hidden');
this.screenshotImg.src = this.croppedImage;
this.imagePreview.classList.remove('hidden');
this.cropBtn.classList.remove('hidden');
this.sendToClaudeBtn.classList.remove('hidden');
window.showToast('Image cropped successfully');
} catch (error) {
console.error('Cropping error:', error);
window.showToast('Error while cropping image', 'error');
}
}
});
// Crop cancel button
document.getElementById('cropCancel').addEventListener('click', () => {
if (this.cropper) {
this.cropper.destroy();
this.cropper = null;
}
this.cropContainer.classList.add('hidden');
this.sendToClaudeBtn.classList.add('hidden');
document.querySelector('.crop-area').innerHTML = '';
});
// Send to Claude button
this.sendToClaudeBtn.addEventListener('click', () => {
if (!this.croppedImage) {
window.showToast('Please crop the image first', 'error');
return;
}
const settings = window.settingsManager.getSettings();
if (!settings.apiKey) {
window.showToast('Please enter your API key in settings', 'error');
this.settingsPanel.classList.remove('hidden');
return;
}
this.claudePanel.classList.remove('hidden');
this.responseContent.textContent = 'Preparing to analyze image...\n';
this.sendToClaudeBtn.disabled = true;
try {
this.socket.emit('analyze_image', {
image: this.croppedImage.split(',')[1],
settings: {
apiKey: settings.apiKey,
model: settings.model || 'claude-3-5-sonnet-20241022',
temperature: parseFloat(settings.temperature) || 0.7,
systemPrompt: settings.systemPrompt || 'You are an expert at analyzing questions and providing detailed solutions.',
proxyEnabled: settings.proxyEnabled || false,
proxyHost: settings.proxyHost || '127.0.0.1',
proxyPort: settings.proxyPort || '4780'
}
});
} catch (error) {
this.responseContent.textContent += '\nError: Failed to send image for analysis - ' + error.message;
this.sendToClaudeBtn.disabled = false;
window.showToast('Failed to send image for analysis', 'error');
}
});
// Keyboard shortcuts for capture and crop
document.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey) {
switch(e.key) {
case 'c':
if (!this.captureBtn.disabled) this.captureBtn.click();
break;
case 'x':
if (!this.cropBtn.disabled) this.cropBtn.click();
break;
}
}
});
}
}
// Initialize the application when the DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
window.app = new SnapSolver();
});
// Global function for history rendering
window.renderHistory = function() {
const content = document.querySelector('.history-content');
const history = JSON.parse(localStorage.getItem('snapHistory') || '[]');
if (history.length === 0) {
content.innerHTML = `
<div class="history-empty">
<i class="fas fa-history"></i>
<p>No history yet</p>
</div>
`;
return;
}
content.innerHTML = history.map(item => `
<div class="history-item" data-id="${item.id}">
<div class="history-item-header">
<span>${new Date(item.timestamp).toLocaleString()}</span>
<button class="btn-icon delete-history" data-id="${item.id}">
<i class="fas fa-trash"></i>
</button>
</div>
<img src="${item.image}" alt="Historical screenshot" class="history-image">
</div>
`).join('');
// Add click handlers for history items
content.querySelectorAll('.delete-history').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const id = parseInt(btn.dataset.id);
const updatedHistory = history.filter(item => item.id !== id);
localStorage.setItem('snapHistory', JSON.stringify(updatedHistory));
window.renderHistory();
window.showToast('History item deleted');
});
});
content.querySelectorAll('.history-item').forEach(item => {
item.addEventListener('click', () => {
const historyItem = history.find(h => h.id === parseInt(item.dataset.id));
if (historyItem) {
window.app.screenshotImg.src = historyItem.image;
window.app.imagePreview.classList.remove('hidden');
document.getElementById('historyPanel').classList.add('hidden');
window.app.cropBtn.classList.add('hidden');
window.app.captureBtn.classList.add('hidden');
window.app.sendToClaudeBtn.classList.add('hidden');
if (historyItem.response) {
window.app.claudePanel.classList.remove('hidden');
window.app.responseContent.textContent = historyItem.response;
}
}
});
});
};

100
static/js/settings.js Normal file
View File

@@ -0,0 +1,100 @@
class SettingsManager {
constructor() {
this.initializeElements();
this.loadSettings();
this.setupEventListeners();
}
initializeElements() {
// Settings panel elements
this.settingsPanel = document.getElementById('settingsPanel');
this.apiKeyInput = document.getElementById('apiKey');
this.modelSelect = document.getElementById('modelSelect');
this.temperatureInput = document.getElementById('temperature');
this.temperatureValue = document.getElementById('temperatureValue');
this.systemPromptInput = document.getElementById('systemPrompt');
this.proxyEnabledInput = document.getElementById('proxyEnabled');
this.proxyHostInput = document.getElementById('proxyHost');
this.proxyPortInput = document.getElementById('proxyPort');
this.proxySettings = document.getElementById('proxySettings');
// Settings toggle elements
this.settingsToggle = document.getElementById('settingsToggle');
this.closeSettings = document.getElementById('closeSettings');
this.toggleApiKey = document.getElementById('toggleApiKey');
}
loadSettings() {
const settings = JSON.parse(localStorage.getItem('aiSettings') || '{}');
if (settings.apiKey) this.apiKeyInput.value = settings.apiKey;
if (settings.model) this.modelSelect.value = settings.model;
if (settings.temperature) {
this.temperatureInput.value = settings.temperature;
this.temperatureValue.textContent = settings.temperature;
}
if (settings.systemPrompt) this.systemPromptInput.value = settings.systemPrompt;
if (settings.proxyEnabled !== undefined) {
this.proxyEnabledInput.checked = settings.proxyEnabled;
}
if (settings.proxyHost) this.proxyHostInput.value = settings.proxyHost;
if (settings.proxyPort) this.proxyPortInput.value = settings.proxyPort;
this.proxySettings.style.display = this.proxyEnabledInput.checked ? 'block' : 'none';
}
saveSettings() {
const settings = {
apiKey: this.apiKeyInput.value,
model: this.modelSelect.value,
temperature: this.temperatureInput.value,
systemPrompt: this.systemPromptInput.value,
proxyEnabled: this.proxyEnabledInput.checked,
proxyHost: this.proxyHostInput.value,
proxyPort: this.proxyPortInput.value
};
localStorage.setItem('aiSettings', JSON.stringify(settings));
window.showToast('Settings saved successfully');
}
getSettings() {
return JSON.parse(localStorage.getItem('aiSettings') || '{}');
}
setupEventListeners() {
// Save settings on change
this.apiKeyInput.addEventListener('change', () => this.saveSettings());
this.modelSelect.addEventListener('change', () => this.saveSettings());
this.temperatureInput.addEventListener('input', (e) => {
this.temperatureValue.textContent = e.target.value;
this.saveSettings();
});
this.systemPromptInput.addEventListener('change', () => this.saveSettings());
this.proxyEnabledInput.addEventListener('change', (e) => {
this.proxySettings.style.display = e.target.checked ? 'block' : 'none';
this.saveSettings();
});
this.proxyHostInput.addEventListener('change', () => this.saveSettings());
this.proxyPortInput.addEventListener('change', () => this.saveSettings());
// Toggle API key visibility
this.toggleApiKey.addEventListener('click', () => {
const type = this.apiKeyInput.type === 'password' ? 'text' : 'password';
this.apiKeyInput.type = type;
this.toggleApiKey.innerHTML = `<i class="fas fa-${type === 'password' ? 'eye' : 'eye-slash'}"></i>`;
});
// Panel visibility
this.settingsToggle.addEventListener('click', () => {
window.closeAllPanels();
this.settingsPanel.classList.toggle('hidden');
});
this.closeSettings.addEventListener('click', () => {
this.settingsPanel.classList.add('hidden');
});
}
}
// Export for use in other modules
window.SettingsManager = SettingsManager;

140
static/js/ui.js Normal file
View File

@@ -0,0 +1,140 @@
class UIManager {
constructor() {
this.initializeElements();
this.setupTheme();
this.setupEventListeners();
}
initializeElements() {
// Theme elements
this.themeToggle = document.getElementById('themeToggle');
// Panel elements
this.settingsPanel = document.getElementById('settingsPanel');
this.historyPanel = document.getElementById('historyPanel');
this.claudePanel = document.getElementById('claudePanel');
// History elements
this.historyToggle = document.getElementById('historyToggle');
this.closeHistory = document.getElementById('closeHistory');
// Claude panel elements
this.closeClaudePanel = document.getElementById('closeClaudePanel');
// Toast container
this.toastContainer = document.getElementById('toastContainer');
}
setupTheme() {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
// Initialize theme
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
this.setTheme(savedTheme === 'dark');
} else {
this.setTheme(prefersDark.matches);
}
// Listen for system theme changes
prefersDark.addEventListener('change', (e) => this.setTheme(e.matches));
}
setTheme(isDark) {
document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');
this.themeToggle.innerHTML = `<i class="fas fa-${isDark ? 'sun' : 'moon'}"></i>`;
localStorage.setItem('theme', isDark ? 'dark' : 'light');
}
showToast(message, type = 'success') {
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.innerHTML = `
<i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
<span>${message}</span>
`;
this.toastContainer.appendChild(toast);
setTimeout(() => {
toast.style.opacity = '0';
setTimeout(() => toast.remove(), 300);
}, 3000);
}
closeAllPanels() {
this.settingsPanel.classList.add('hidden');
this.historyPanel.classList.add('hidden');
}
setupEventListeners() {
// Theme toggle
this.themeToggle.addEventListener('click', () => {
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
this.setTheme(!isDark);
});
// History panel
this.historyToggle.addEventListener('click', () => {
this.closeAllPanels();
this.historyPanel.classList.toggle('hidden');
window.renderHistory(); // Call global renderHistory function
});
this.closeHistory.addEventListener('click', () => {
this.historyPanel.classList.add('hidden');
});
// Claude panel
this.closeClaudePanel.addEventListener('click', () => {
this.claudePanel.classList.add('hidden');
});
// Mobile touch events
let touchStartX = 0;
let touchEndX = 0;
document.addEventListener('touchstart', (e) => {
touchStartX = e.changedTouches[0].screenX;
});
document.addEventListener('touchend', (e) => {
touchEndX = e.changedTouches[0].screenX;
this.handleSwipe(touchStartX, touchEndX);
});
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey) {
switch(e.key) {
case ',':
this.settingsPanel.classList.toggle('hidden');
break;
case 'h':
this.historyPanel.classList.toggle('hidden');
window.renderHistory();
break;
}
} else if (e.key === 'Escape') {
this.closeAllPanels();
}
});
}
handleSwipe(startX, endX) {
const swipeThreshold = 50;
const diff = endX - startX;
if (Math.abs(diff) > swipeThreshold) {
if (diff > 0) {
this.closeAllPanels();
} else {
this.settingsPanel.classList.remove('hidden');
}
}
}
}
// Export for use in other modules
window.UIManager = UIManager;
window.showToast = (message, type) => window.uiManager.showToast(message, type);
window.closeAllPanels = () => window.uiManager.closeAllPanels();