Spaces:
Running
Running
| class FileUpload extends HTMLElement { | |
| connectedCallback() { | |
| this.attachShadow({ mode: 'open' }); | |
| this.shadowRoot.innerHTML = ` | |
| <style> | |
| .file-upload-container { | |
| display: flex; | |
| flex-direction: column; | |
| gap: 0.5rem; | |
| margin-bottom: 1rem; | |
| } | |
| .drop-area { | |
| border: 2px dashed #d1d5db; | |
| border-radius: 0.5rem; | |
| padding: 1rem; | |
| text-align: center; | |
| cursor: pointer; | |
| transition: all 0.2s; | |
| } | |
| .drop-area:hover, .drop-area.highlight { | |
| border-color: #7c3aed; | |
| background-color: #f5f3ff; | |
| } | |
| .file-input { | |
| display: none; | |
| } | |
| .file-info { | |
| font-size: 0.875rem; | |
| color: #6b7280; | |
| margin-top: 0.5rem; | |
| } | |
| </style> | |
| <div class="file-upload-container"> | |
| <label for="file-upload" class="drop-area" id="drop-area"> | |
| <p>Click to select or drag & drop a text file</p> | |
| <input type="file" id="file-upload" class="file-input" accept=".txt"> | |
| </label> | |
| <div class="file-info" id="file-info">No file selected</div> | |
| </div> | |
| `; | |
| const dropArea = this.shadowRoot.getElementById('drop-area'); | |
| const fileInput = this.shadowRoot.getElementById('file-upload'); | |
| const fileInfo = this.shadowRoot.getElementById('file-info'); | |
| ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { | |
| dropArea.addEventListener(eventName, preventDefaults, false); | |
| }); | |
| ['dragenter', 'dragover'].forEach(eventName => { | |
| dropArea.addEventListener(eventName, highlight, false); | |
| }); | |
| ['dragleave', 'drop'].forEach(eventName => { | |
| dropArea.addEventListener(eventName, unhighlight, false); | |
| }); | |
| dropArea.addEventListener('drop', handleDrop, false); | |
| fileInput.addEventListener('change', handleFiles, false); | |
| function preventDefaults(e) { | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| } | |
| function highlight() { | |
| dropArea.classList.add('highlight'); | |
| } | |
| function unhighlight() { | |
| dropArea.classList.remove('highlight'); | |
| } | |
| function handleDrop(e) { | |
| const dt = e.dataTransfer; | |
| const files = dt.files; | |
| fileInput.files = files; | |
| handleFiles({ target: fileInput }); | |
| } | |
| function handleFiles(e) { | |
| const file = e.target.files[0]; | |
| if (file) { | |
| fileInfo.textContent = `Selected: ${file.name} (${(file.size / 1024).toFixed(1)} KB)`; | |
| const reader = new FileReader(); | |
| reader.onload = function(e) { | |
| const textarea = document.getElementById('dataset'); | |
| textarea.value = e.target.result; | |
| }; | |
| reader.readAsText(file); | |
| } else { | |
| fileInfo.textContent = 'No file selected'; | |
| } | |
| } | |
| } | |
| } | |
| customElements.define('file-upload', FileUpload); |