File size: 12,909 Bytes
6987311 | 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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | class CodeEditor {
constructor() {
this.editor = null;
this.currentFile = 'main.py';
this.files = {
'main.py': 'import torch\nimport transformers\nfrom transformers import AutoTokenizer, AutoModel\n\n# Load pre-trained model and tokenizer\nmodel_name = "bert-base-uncased"\ntokenizer = AutoTokenizer.from_pretrained(model_name)\nmodel = AutoModel.from_pretrained(model_name)\n\n# Example text\ntext = "Hello, this is a sample text for processing."\n\n# Tokenize input\ninputs = tokenizer(text, return_tensors="pt")\n\n# Get model outputs\nwith torch.no_grad():\n outputs = model(**inputs)\n \n# Extract embeddings\nlast_hidden_states = outputs.last_hidden_state\nprint(f"Shape of embeddings: {last_hidden_states.shape}")\nprint("Model loaded and text processed successfully!")'
};
this.init();
}
init() {
this.initEditor();
this.bindEvents();
this.updateStatusBar();
}
initEditor() {
this.editor = CodeMirror.fromTextArea(document.getElementById('codeEditor'), {
mode: 'python',
theme: 'default',
lineNumbers: true,
autoCloseBrackets: true,
matchBrackets: true,
indentUnit: 4,
tabSize: 4,
lineWrapping: true,
foldGutter: true,
gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
extraKeys: {
"Ctrl-Space": "autocomplete",
"Ctrl-F": "findPersistent",
"Ctrl-H": "replace",
"Ctrl-S": () => this.saveFile(),
"Ctrl-Z": () => this.editor.undo(),
"Ctrl-Y": () => this.editor.redo(),
"F5": () => this.runCode()
}
});
// Update status bar on cursor activity
this.editor.on('cursorActivity', () => {
this.updateStatusBar();
});
// Update status bar on content change
this.editor.on('change', () => {
this.updateStatusBar();
this.files[this.currentFile] = this.editor.getValue();
});
}
bindEvents() {
// Language selector
document.getElementById('languageSelect').addEventListener('change', (e) => {
this.changeLanguage(e.target.value);
});
// Theme selector
document.getElementById('themeSelect').addEventListener('change', (e) => {
this.changeTheme(e.target.value);
});
// File operations
document.getElementById('newFile').addEventListener('click', () => this.newFile());
document.getElementById('openFile').addEventListener('click', () => this.openFile());
document.getElementById('saveFile').addEventListener('click', () => this.saveFile());
document.getElementById('fileInput').addEventListener('change', (e) => this.handleFileOpen(e));
// Edit operations
document.getElementById('undoBtn').addEventListener('click', () => this.editor.undo());
document.getElementById('redoBtn').addEventListener('click', () => this.editor.redo());
// Search operations
document.getElementById('findBtn').addEventListener('click', () => this.editor.execCommand('findPersistent'));
document.getElementById('replaceBtn').addEventListener('click', () => this.editor.execCommand('replace'));
// Code operations
document.getElementById('runCode').addEventListener('click', () => this.runCode());
document.getElementById('formatCode').addEventListener('click', () => this.formatCode());
// Output panel
document.getElementById('clearOutput').addEventListener('click', () => this.clearOutput());
// Tab operations
document.getElementById('addTab').addEventListener('click', () => this.addNewTab());
// Tab clicks
document.addEventListener('click', (e) => {
if (e.target.closest('.tab') && !e.target.classList.contains('tab-close')) {
const tab = e.target.closest('.tab');
const fileName = tab.getAttribute('data-file');
this.switchToFile(fileName);
}
if (e.target.classList.contains('tab-close')) {
const fileName = e.target.getAttribute('data-file');
this.closeTab(fileName);
}
});
}
changeLanguage(language) {
const modeMap = {
'python': 'python',
'javascript': 'javascript',
'html': 'xml',
'css': 'css',
'json': { name: 'javascript', json: true },
'markdown': 'markdown',
'sql': 'sql',
'yaml': 'yaml'
};
this.editor.setOption('mode', modeMap[language] || 'text');
document.getElementById('currentLanguage').textContent = language.charAt(0).toUpperCase() + language.slice(1);
}
changeTheme(theme) {
this.editor.setOption('theme', theme);
}
newFile() {
const fileName = prompt('Enter file name:', 'untitled.py');
if (fileName && !this.files[fileName]) {
this.files[fileName] = '';
this.addTab(fileName);
this.switchToFile(fileName);
}
}
openFile() {
document.getElementById('fileInput').click();
}
handleFileOpen(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target.result;
const fileName = file.name;
this.files[fileName] = content;
this.addTab(fileName);
this.switchToFile(fileName);
this.addOutput(`File '${fileName}' loaded successfully`, 'success');
};
reader.readAsText(file);
}
}
saveFile() {
const content = this.editor.getValue();
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = this.currentFile;
a.click();
URL.revokeObjectURL(url);
this.addOutput(`File '${this.currentFile}' saved successfully`, 'success');
}
addTab(fileName) {
const tabsContainer = document.getElementById('fileTabs');
const existingTab = tabsContainer.querySelector(`[data-file="${fileName}"]`);
if (!existingTab) {
const tab = document.createElement('div');
tab.className = 'tab';
tab.setAttribute('data-file', fileName);
tab.innerHTML = `
<span>${fileName}</span>
<span class="tab-close" data-file="${fileName}">×</span>
`;
tabsContainer.appendChild(tab);
}
}
addNewTab() {
this.newFile();
}
switchToFile(fileName) {
if (this.files[fileName] !== undefined) {
// Save current file content
this.files[this.currentFile] = this.editor.getValue();
// Switch to new file
this.currentFile = fileName;
this.editor.setValue(this.files[fileName]);
// Update active tab
document.querySelectorAll('.tab').forEach(tab => {
tab.classList.remove('active');
if (tab.getAttribute('data-file') === fileName) {
tab.classList.add('active');
}
});
// Auto-detect language
this.autoDetectLanguage(fileName);
this.updateStatusBar();
}
}
closeTab(fileName) {
if (Object.keys(this.files).length === 1) {
this.addOutput('Cannot close the last tab', 'error');
return;
}
delete this.files[fileName];
const tab = document.querySelector(`[data-file="${fileName}"]`);
if (tab) {
tab.remove();
}
if (this.currentFile === fileName) {
const remainingFiles = Object.keys(this.files);
this.switchToFile(remainingFiles[0]);
}
}
autoDetectLanguage(fileName) {
const extension = fileName.split('.').pop().toLowerCase();
const languageMap = {
'py': 'python',
'js': 'javascript',
'html': 'html',
'css': 'css',
'json': 'json',
'md': 'markdown',
'sql': 'sql',
'yaml': 'yaml',
'yml': 'yaml'
};
const language = languageMap[extension] || 'python';
document.getElementById('languageSelect').value = language;
this.changeLanguage(language);
}
runCode() {
const code = this.editor.getValue();
const language = document.getElementById('languageSelect').value;
this.addOutput(`Running ${language} code...`, 'info');
// Simulate code execution
setTimeout(() => {
if (language === 'python') {
this.simulatePythonExecution(code);
} else if (language === 'javascript') {
this.executeJavaScript(code);
} else {
this.addOutput(`Code execution for ${language} is not implemented yet`, 'info');
}
}, 1000);
}
simulatePythonExecution(code) {
// Simple simulation for demonstration
if (code.includes('print(')) {
const printMatches = code.match(/print\(([^)]*)\)/g);
if (printMatches) {
printMatches.forEach(match => {
const content = match.match(/print\(([^)]*)\)/)[1];
this.addOutput(content.replace(/["\']/g, ''), 'success');
});
}
} else {
this.addOutput('Code executed successfully (simulated)', 'success');
}
}
executeJavaScript(code) {
try {
// Capture console.log
const originalLog = console.log;
const outputs = [];
console.log = (...args) => {
outputs.push(args.join(' '));
};
// Execute code
eval(code);
// Restore console.log
console.log = originalLog;
// Display outputs
if (outputs.length > 0) {
outputs.forEach(output => this.addOutput(output, 'success'));
} else {
this.addOutput('Code executed successfully', 'success');
}
} catch (error) {
this.addOutput(`Error: ${error.message}`, 'error');
}
}
formatCode() {
const code = this.editor.getValue();
// Simple formatting for demonstration
const formatted = code.replace(/\t/g, ' '); // Convert tabs to spaces
this.editor.setValue(formatted);
this.addOutput('Code formatted', 'success');
}
addOutput(message, type = 'info') {
const outputContent = document.getElementById('outputContent');
const outputLine = document.createElement('div');
outputLine.className = `output-line ${type}`;
outputLine.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
outputContent.appendChild(outputLine);
outputContent.scrollTop = outputContent.scrollHeight;
}
clearOutput() {
document.getElementById('outputContent').innerHTML = '';
this.addOutput('Output cleared', 'info');
}
updateStatusBar() {
const cursor = this.editor.getCursor();
const content = this.editor.getValue();
document.getElementById('currentLine').textContent = cursor.line + 1;
document.getElementById('currentColumn').textContent = cursor.ch + 1;
document.getElementById('fileSize').textContent = `${new Blob([content]).size} bytes`;
document.getElementById('charCount').textContent = `${content.length} characters`;
}
}
// Initialize the code editor when the page loads
document.addEventListener('DOMContentLoaded', () => {
window.codeEditor = new CodeEditor();
// Add welcome message
setTimeout(() => {
window.codeEditor.addOutput('Welcome to HuggingFace Code Editor!', 'success');
window.codeEditor.addOutput('Features: Syntax highlighting, multiple tabs, themes, and more!', 'info');
window.codeEditor.addOutput('Press F5 to run code, Ctrl+S to save, Ctrl+F to find', 'info');
}, 500);
});
// Prevent default browser shortcuts
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && (e.key === 's' || e.key === 'f')) {
e.preventDefault();
}
if (e.key === 'F5') {
e.preventDefault();
}
}); |