Spaces:
Running
Running
File size: 9,870 Bytes
31e1a75 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | // Theme handling: "undefined mode" defaults to system unless explicitly toggled
(function initTheme() {
const root = document.documentElement;
const saved = localStorage.getItem('theme-mode'); // 'light' | 'dark'
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
const apply = (mode) => {
root.classList.toggle('dark', mode === 'dark');
};
if (saved === 'light' || saved === 'dark') {
apply(saved);
} else {
apply(prefersDark ? 'dark' : 'light');
}
})();
const themeToggle = document.getElementById('themeToggle');
if (themeToggle) {
themeToggle.addEventListener('click', () => {
const root = document.documentElement;
const isDark = root.classList.toggle('dark');
localStorage.setItem('theme-mode', isDark ? 'dark' : 'light');
});
}
// Elements
const chatBox = document.getElementById('chatBox');
const composerForm = document.getElementById('composerForm');
const messageInput = document.getElementById('messageInput');
const sendBtn = document.getElementById('sendBtn');
const imageInput = document.getElementById('imageInput');
const codeInput = document.getElementById('codeInput');
const uploadImageBtn = document.getElementById('uploadImageBtn');
const uploadCodeBtn = document.getElementById('uploadCodeBtn');
const connectGitHubBtn = document.getElementById('connectGitHubBtn');
const githubConnectHeaderBtn = document.getElementById('githubConnectBtn');
const attachmentPreview = document.getElementById('attachmentPreview');
const modeIndicator = document.getElementById('modeIndicator');
const modeButtons = document.querySelectorAll('.mode-btn');
let currentMode = 'code';
updateModeIndicator();
// Helpers
function formatTime(date = new Date()) {
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
function scrollToBottom() {
chatBox.scrollTop = chatBox.scrollHeight;
}
function createAvatar(initials, seed = 0) {
const palette = ['bg-undefined-500', 'bg-blue-500', 'bg-teal-500', 'bg-violet-500', 'bg-rose-500'];
const color = palette[seed % palette.length];
return `<div class="h-10 w-10 rounded-full ${color} grid place-items-center text-white font-bold">${initials}</div>`;
}
function agentBubble({ name = 'Agent', message = '', attachments = [] }) {
const idx = Math.floor(Math.random() * 5);
return `
<div class="flex items-start gap-3">
${createAvatar(name.slice(0,1).toUpperCase(), idx)}
<div class="max-w-[85%] sm:max-w-[80%]">
<div class="text-xs text-zinc-600 dark:text-zinc-400 mb-1">${name}</div>
<div class="prose prose-sm dark:prose-invert max-w-none bg-zinc-100 dark:bg-zinc-800 rounded-2xl rounded-tl-sm px-4 py-2">
${message ? `<p class="m-0">${escapeHtml(message)}</p>` : ''}
${attachments.length ? `<div class="mt-2 grid gap-2">${attachments.join('')}</div>` : ''}
</div>
<div class="text-[10px] text-zinc-500 mt-1">${formatTime()}</div>
</div>
</div>
`;
}
function userBubble({ message = '', attachments = [] }) {
return `
<div class="flex items-start gap-3 justify-end">
<div class="max-w-[85%] sm:max-w-[80%]">
<div class="text-xs text-right text-zinc-600 dark:text-zinc-400 mb-1">You</div>
<div class="bg-undefined-500 text-white rounded-2xl rounded-tr-sm px-4 py-2">
${message ? `<p class="m-0">${escapeHtml(message)}</p>` : ''}
${attachments.length ? `<div class="mt-2 grid gap-2">${attachments.join('')}</div>` : ''}
</div>
<div class="text-[10px] text-right text-zinc-500 mt-1">${formatTime()}</div>
</div>
${createAvatar('Y')}
</div>
`;
}
function escapeHtml(str) {
return str
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>');
}
// Attachments UI
function showAttachmentPreview(items) {
if (!items.length) {
attachmentPreview.classList.add('hidden');
attachmentPreview.innerHTML = '';
return;
}
attachmentPreview.classList.remove('hidden');
attachmentPreview.innerHTML = items.map((item) => {
if (item.type.startsWith('image/')) {
return `<div class="rounded-lg border border-zinc-200 dark:border-zinc-700 p-2 bg-zinc-50 dark:bg-zinc-900">
<div class="flex items-center gap-3">
<img src="${item.url}" alt="preview" class="h-12 w-12 object-cover rounded-md"/>
<div class="text-xs"><div class="font-medium truncate">${item.file?.name || 'image'}</div><div class="text-zinc-600 dark:text-zinc-400">${(item.file?.size / 1024).toFixed(1)} KB</div></div>
<button class="ml-auto text-sm text-red-600 hover:underline" data-remove>Remove</button>
</div>
</div>`;
}
// code file preview
return `<div class="rounded-lg border border-zinc-200 dark:border-zinc-700 p-2 bg-zinc-50 dark:bg-zinc-900">
<div class="flex items-center gap-2">
<span class="text-sm">📄</span>
<div class="text-xs">
<div class="font-medium truncate">${item.file?.name || 'code'}</div>
<div class="text-zinc-600 dark:text-zinc-400">${(item.file?.size / 1024).toFixed(1)} KB</div>
</div>
<button class="ml-auto text-sm text-red-600 hover:underline" data-remove>Remove</button>
</div>
</div>`;
}).join('');
// Remove handler
attachmentPreview.querySelectorAll('[data-remove]').forEach(btn => {
btn.addEventListener('click', () => {
const card = btn.closest('[class*=rounded-lg]');
const index = Array.from(attachmentPreview.children).indexOf(card);
pendingAttachments.splice(index, 1);
showAttachmentPreview(pendingAttachments);
});
});
}
const pendingAttachments = [];
// Mode handling
function updateModeIndicator() {
if (modeIndicator) modeIndicator.textContent = `Mode: ${currentMode}`;
modeButtons.forEach(b => {
const isActive = b.dataset.mode === currentMode;
b.classList.toggle('bg-undefined-500', isActive);
b.classList.toggle('text-white', isActive);
b.classList.toggle('hover:opacity-90', isActive);
});
}
modeButtons.forEach(btn => {
btn.addEventListener('click', () => {
currentMode = btn.dataset.mode;
updateModeIndicator();
// Post a small status message
const statusMsg = `Mode switched to: ${currentMode}`;
chatBox.insertAdjacentHTML('beforeend', agentBubble({ name: 'System', message: statusMsg }));
scrollToBottom();
});
});
// Composer events
composerForm.addEventListener('submit', (e) => {
e.preventDefault();
const message = messageInput.value.trim();
const attachments = pendingAttachments.slice();
if (!message && !attachments.length) return;
chatBox.insertAdjacentHTML('beforeend', userBubble({ message, attachments }));
scrollToBottom();
// Simulate agent response
setTimeout(() => {
const reply = agentReply(message, currentMode, attachments);
chatBox.insertAdjacentHTML('beforeend', reply);
scrollToBottom();
}, 600);
// Reset composer
messageInput.value = '';
pendingAttachments.length = 0;
showAttachmentPreview(pendingAttachments);
messageInput.focus();
});
function agentReply(text, mode, attachments) {
let message = '';
if (attachments.some(a => a.type.startsWith('image/'))) {
message += 'Got your image(s). ';
}
if (attachments.some(a => !a.type.startsWith('image/'))) {
message += 'I also see code/file attachments. ';
}
const modeHints = {
design: 'I can suggest UI/UX and styling tweaks.',
architect: 'I can outline components, data flow, and constraints.',
plan: 'I can draft a plan with milestones and tasks.',
debug: 'I can help triage issues and propose fixes.',
code: 'I can produce and refine code based on your input.'
};
message += `${modeHints[mode] || ''}${text ? ` Regarding "${escapeHtml(text)}"` : ''} — what would you like to do next?`;
return agentBubble({ name: 'Agent', message });
}
// Input attachments
uploadImageBtn.addEventListener('click', () => imageInput.click());
uploadCodeBtn.addEventListener('click', () => codeInput.click());
imageInput.addEventListener('change', async (e) => {
const files = Array.from(e.target.files || []);
files.forEach(file => {
if (!file.type.startsWith('image/')) return;
const url = URL.createObjectURL(file);
pendingAttachments.push({ type: file.type, file, url });
});
showAttachmentPreview(pendingAttachments);
imageInput.value = '';
});
codeInput.addEventListener('change', async (e) => {
const files = Array.from(e.target.files || []);
files.forEach(file => {
// accept text-based files
const isText = /(\.|\/)(txt|md|json|js|ts|jsx|tsx|html|css|scss|py|rb|go|rs|java|c|cpp|cs|yml|yaml|ini|env)$/i.test(file.name);
if (!isText) return;
const url = URL.createObjectURL(file);
pendingAttachments.push({ type: 'text/x-code', file, url });
});
showAttachmentPreview(pendingAttachments);
codeInput.value = '';
});
// GitHub connect
function connectGitHub() {
// In a real app, redirect to your backend OAuth route
const token = prompt('Paste a personal access token (classic or fine-grained) to simulate GitHub connection:');
if (!token) return;
const shortToken = token.slice(0, 6) + '...' + token.slice(-4);
const msg = `Connected to GitHub (token: ${shortToken}). You can now fetch repos, issues, and PRs.`;
chatBox.insertAdjacentHTML('beforeend', agentBubble({ name: 'GitHub', message: msg }));
scrollToBottom();
}
connectGitHubBtn?.addEventListener('click', connectGitHub);
githubConnectHeaderBtn?.addEventListener('click', connectGitHub);
// Auto-resize textarea
messageInput.addEventListener('input', () => {
messageInput.style.height = 'auto';
messageInput.style.height = Math.min(messageInput.scrollHeight, 160) + 'px';
});
// Accessibility: focus input on load
messageInput.focus(); |