| 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() |
| } |
| }); |
|
|
| |
| this.editor.on('cursorActivity', () => { |
| this.updateStatusBar(); |
| }); |
|
|
| |
| this.editor.on('change', () => { |
| this.updateStatusBar(); |
| this.files[this.currentFile] = this.editor.getValue(); |
| }); |
| } |
|
|
| bindEvents() { |
| |
| document.getElementById('languageSelect').addEventListener('change', (e) => { |
| this.changeLanguage(e.target.value); |
| }); |
|
|
| |
| document.getElementById('themeSelect').addEventListener('change', (e) => { |
| this.changeTheme(e.target.value); |
| }); |
|
|
| |
| 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)); |
|
|
| |
| document.getElementById('undoBtn').addEventListener('click', () => this.editor.undo()); |
| document.getElementById('redoBtn').addEventListener('click', () => this.editor.redo()); |
|
|
| |
| document.getElementById('findBtn').addEventListener('click', () => this.editor.execCommand('findPersistent')); |
| document.getElementById('replaceBtn').addEventListener('click', () => this.editor.execCommand('replace')); |
|
|
| |
| document.getElementById('runCode').addEventListener('click', () => this.runCode()); |
| document.getElementById('formatCode').addEventListener('click', () => this.formatCode()); |
|
|
| |
| document.getElementById('clearOutput').addEventListener('click', () => this.clearOutput()); |
|
|
| |
| document.getElementById('addTab').addEventListener('click', () => this.addNewTab()); |
|
|
| |
| 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) { |
| |
| this.files[this.currentFile] = this.editor.getValue(); |
| |
| |
| this.currentFile = fileName; |
| this.editor.setValue(this.files[fileName]); |
| |
| |
| document.querySelectorAll('.tab').forEach(tab => { |
| tab.classList.remove('active'); |
| if (tab.getAttribute('data-file') === fileName) { |
| tab.classList.add('active'); |
| } |
| }); |
| |
| |
| 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'); |
| |
| |
| 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) { |
| |
| 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 { |
| |
| const originalLog = console.log; |
| const outputs = []; |
| console.log = (...args) => { |
| outputs.push(args.join(' ')); |
| }; |
|
|
| |
| eval(code); |
|
|
| |
| console.log = originalLog; |
|
|
| |
| 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(); |
| |
| const formatted = code.replace(/\t/g, ' '); |
| 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`; |
| } |
| } |
|
|
| |
| document.addEventListener('DOMContentLoaded', () => { |
| window.codeEditor = new CodeEditor(); |
| |
| |
| 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); |
| }); |
|
|
| |
| document.addEventListener('keydown', (e) => { |
| if ((e.ctrlKey || e.metaKey) && (e.key === 's' || e.key === 'f')) { |
| e.preventDefault(); |
| } |
| if (e.key === 'F5') { |
| e.preventDefault(); |
| } |
| }); |