JavaRunner / index.html
parthmax's picture
Update index.html
9c580f0 verified
raw
history blame
20.6 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Java Learner — Mini IDE</title>
<!-- Font (modern, clean) -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap" rel="stylesheet">
<!-- Font Awesome (free icons) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" integrity="sha512-t9f6b...." crossorigin="anonymous" referrerpolicy="no-referrer" />
<!-- CodeMirror 5 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/codemirror.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/mode/clike/clike.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/edit/closebrackets.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/edit/matchbrackets.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/edit/indentation.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/format/formatting.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.13/addon/indent/auto-indent.min.js"></script>
<!-- Note: some addons are bundled differently across versions; the code uses indent/auto features -->
<style>
:root{
--bg:#0f1720;
--glass: rgba(255,255,255,0.04);
--glass-2: rgba(255,255,255,0.025);
--accent: #6c8cff;
--accent-2: #8be5d0;
--muted: #9aa4b2;
--card-shadow: 0 8px 30px rgba(2,6,23,0.6);
--radius: 14px;
}
*{box-sizing:border-box}
html,body{height:100%}
body{
margin:0;
font-family:Inter,system-ui,Segoe UI,Roboto,"Helvetica Neue",Arial;
background: linear-gradient(180deg, #071227 0%, #0d1a2b 100%);
color:#e6eef8;
-webkit-font-smoothing:antialiased;
-moz-osx-font-smoothing:grayscale;
padding:20px;
display:flex;
flex-direction:column;
gap:14px;
min-height:100vh;
}
/* App container */
.app {
display:grid;
grid-template-columns: 260px 1fr;
gap:18px;
align-items:stretch;
width:100%;
max-width:1200px;
margin:0 auto;
flex:1 1 auto;
}
/* Glass panel */
.panel {
background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0.01));
border-radius:var(--radius);
backdrop-filter: blur(8px) saturate(1.05);
box-shadow: var(--card-shadow);
border: 1px solid rgba(255,255,255,0.04);
padding:14px;
transition: transform .18s ease, box-shadow .2s ease;
}
.panel:hover{ transform: translateY(-4px); box-shadow: 0 16px 40px rgba(8,14,40,0.6); }
/* File sidebar */
.files {
display:flex;
flex-direction:column;
gap:12px;
min-height:200px;
}
.files .top {
display:flex; gap:8px; align-items:center; justify-content:space-between;
}
.brand {
display:flex; gap:12px; align-items:center;
font-weight:600; font-size:16px; color:var(--accent);
}
.brand i { font-size:20px; opacity:0.95; transform:translateY(-1px) }
.file-actions { display:flex; gap:8px; align-items:center; }
.btn {
background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0.01));
border: 1px solid rgba(255,255,255,0.04);
color:var(--muted);
padding:8px 10px;
border-radius:10px;
font-weight:600;
display:inline-flex; gap:8px; align-items:center;
cursor:pointer;
transition: all .14s ease;
white-space:nowrap;
}
.btn:hover{ transform: translateY(-3px); color:#fff; box-shadow: 0 8px 20px rgba(0,0,0,0.4); }
/* File list */
.file-list { display:flex; flex-direction:column; gap:8px; overflow:auto; padding-right:6px; }
.file-item {
display:flex; align-items:center; gap:10px; justify-content:space-between;
padding:8px; border-radius:9px; cursor:pointer; color:#dbe8ff; font-weight:600;
transition: background .12s ease, transform .12s ease;
background: linear-gradient(180deg, rgba(255,255,255,0.01), rgba(255,255,255,0.005));
border:1px solid rgba(255,255,255,0.02);
}
.file-item:hover{ transform: translateY(-3px); box-shadow: 0 6px 18px rgba(8,12,32,0.45); }
.file-item.active { background: linear-gradient(90deg, rgba(108,140,255,0.12), rgba(139,229,208,0.03)); color:#fff; }
.file-meta { display:flex; gap:8px; align-items:center; }
/* Editor area */
.editor-area { display:flex; flex-direction:column; gap:10px; min-height:400px; }
.topbar {
display:flex; align-items:center; justify-content:space-between; gap:6px;
}
.title {
font-size:14px; color:var(--muted);
}
.controls { display:flex; gap:8px; align-items:center; flex-wrap:wrap; }
.primary {
background: linear-gradient(90deg,var(--accent), #7bd0ff);
color:#04253b; padding:10px 14px; border-radius:10px; font-weight:700; border:none; cursor:pointer;
box-shadow: 0 8px 30px rgba(108,140,255,0.14);
display:inline-flex; gap:8px; align-items:center;
}
.secondary { background: transparent; border:1px solid rgba(255,255,255,0.05); color:var(--muted); padding:8px 12px; border-radius:10px; cursor:pointer; }
/* CodeMirror container */
.cm-wrap { border-radius:12px; overflow:hidden; border:1px solid rgba(255,255,255,0.02); }
.CodeMirror { height: calc(100vh - 360px); min-height:240px; background: linear-gradient(180deg, rgba(2,6,23,0.6), rgba(2,6,23,0.55)); color:#e8f1ff; font-size:13px; }
/* Output console */
.console {
margin-top:6px;
background: linear-gradient(180deg, rgba(0,0,0,0.5), rgba(2,6,23,0.6));
border-radius:10px; padding:12px; font-family:monospace; color:#cfe7ff; height:140px; overflow:auto;
border:1px solid rgba(255,255,255,0.02);
}
/* Footer */
footer { text-align:center; color:var(--muted); font-size:13px; padding:10px 0; }
.note { color:#c7d7ff; font-weight:600; }
/* Responsive */
@media (max-width:900px) {
.app { grid-template-columns: 1fr; padding-bottom:8px; }
.files { order:2; }
.editor-area { order:1; }
.CodeMirror { height: calc(100vh - 420px); }
}
@media (max-width:480px) {
body{padding:12px}
.brand { font-size:14px }
.btn { padding:6px 8px; font-size:13px }
.primary { padding:8px 10px; font-size:14px }
.CodeMirror { font-size:12px }
}
</style>
</head>
<body>
<div class="app">
<!-- Files Sidebar -->
<div class="panel files" id="sidebar">
<div class="top">
<div class="brand"><i class="fa-solid fa-flask"></i> Java Learner</div>
<div style="display:flex;gap:8px;align-items:center">
<button class="btn" id="toggleSidebar" title="Hide files"><i class="fa-solid fa-bars"></i></button>
<button class="btn" id="newBtn" title="New file"><i class="fa-solid fa-file-circle-plus"></i> New</button>
</div>
</div>
<div style="display:flex;gap:8px;align-items:center;">
<input id="searchFile" placeholder="Search files..." style="flex:1;background:transparent;border:1px solid rgba(255,255,255,0.03);padding:8px;border-radius:8px;color:var(--muted)" />
<button class="btn" id="importBtn" title="Import .java"><i class="fa-solid fa-file-import"></i></button>
</div>
<div class="file-list" id="fileList" aria-live="polite" style="margin-top:8px;"></div>
<div style="margin-top:auto;font-size:13px;color:var(--muted);padding-top:10px">
<div style="display:flex;gap:8px;align-items:center">
<i class="fa-solid fa-circle-notch fa-spin" style="opacity:0.18"></i>
<div>Local-only — your files stay on your device</div>
</div>
</div>
</div>
<!-- Editor area -->
<div class="panel editor-area">
<div class="topbar">
<div class="title">Interactive Java editor • Friendly for mobile & desktop</div>
<div class="controls">
<button class="primary" id="runBtn"><i class="fa-solid fa-play"></i> Run</button>
<button class="secondary" id="saveBtn" title="Save to device"><i class="fa-solid fa-floppy-disk"></i> Save</button>
<button class="secondary" id="downloadBtn" title="Download file"><i class="fa-solid fa-download"></i> Download</button>
<button class="secondary" id="formatBtn" title="Auto-indent / format"><i class="fa-solid fa-align-left"></i> Format</button>
<button class="secondary" id="cutBtn" title="Cut selection"><i class="fa-solid fa-cut"></i></button>
<button class="secondary" id="copyBtn" title="Copy selection"><i class="fa-solid fa-copy"></i></button>
<button class="secondary" id="pasteBtn" title="Paste"><i class="fa-solid fa-clipboard"></i></button>
<button class="secondary" id="deleteBtn" title="Delete file"><i class="fa-solid fa-trash"></i></button>
</div>
</div>
<div class="cm-wrap" id="cmWrap">
<div id="editor"></div>
</div>
<div style="display:flex;gap:10px;align-items:center;justify-content:space-between;">
<div style="display:flex;gap:8px;align-items:center">
<div style="font-size:13px;color:var(--muted)">Active file: <span id="activeFile" style="color:#eafbff;font-weight:700"></span></div>
</div>
<div style="font-size:13px;color:var(--muted)">Execution timeout: <strong>5s</strong></div>
</div>
<div class="console" id="console">Console output will appear here.</div>
</div>
</div>
<footer>
<div>Made with care for <span class="note">Ragini didi — happy learning!</span></div>
</footer>
<!-- Hidden file input for import -->
<input type="file" id="fileInput" accept=".java" style="display:none" />
<script>
// ---------- Editor setup ----------
const editor = CodeMirror(document.getElementById('editor'), {
mode: "text/x-java",
lineNumbers: true,
tabSize: 4,
indentUnit: 4,
autoCloseBrackets: true,
matchBrackets: true,
theme: "default",
value: "// Start here\nclass Main {\n public static void main(String[] args) {\n System.out.println(\"Hello from Java Learner\");\n }\n}\n"
});
// Keep editor responsive height
function resizeEditor(){
const wrap = document.querySelector('.CodeMirror');
if(wrap) {
// compute available height
let vh = window.innerHeight;
// set a comfortable height based on screen
const base = Math.max(240, vh - 360);
wrap.style.height = base + 'px';
editor.refresh();
}
}
window.addEventListener('resize', resizeEditor);
setTimeout(resizeEditor,300);
// ---------- Local file storage ----------
let files = JSON.parse(localStorage.getItem('java_learner_files') || '{}');
let active = localStorage.getItem('java_learner_active') || null;
const fileListEl = document.getElementById('fileList');
const activeFileEl = document.getElementById('activeFile');
const consoleEl = document.getElementById('console');
// Utilities
function saveToStorage(){
localStorage.setItem('java_learner_files', JSON.stringify(files));
}
function setActive(name){
active = name;
localStorage.setItem('java_learner_active', active);
activeFileEl.innerText = active || '—';
renderFiles();
if(active) editor.setValue(files[active]);
}
function renderFiles(filter=''){
fileListEl.innerHTML = '';
const names = Object.keys(files).filter(n => n.toLowerCase().includes(filter.toLowerCase())).sort();
if(names.length===0){
fileListEl.innerHTML = `<div style="color:var(--muted);padding:10px;font-size:13px">No files yet. Create one.</div>`;
return;
}
names.forEach(name=>{
const div = document.createElement('div');
div.className = 'file-item' + (name===active ? ' active':'');
div.innerHTML = `<div class="file-meta"><i class="fa-solid fa-file-code"></i><div style="margin-left:8px">${name}</div></div>
<div style="display:flex;gap:8px;align-items:center">
<button class="btn" title="Rename" style="padding:6px 8px" onclick="renameFile(event,'${encodeURIComponent(name)}')"><i class="fa-solid fa-pen"></i></button>
<button class="btn" title="Duplicate" style="padding:6px 8px" onclick="duplicateFile(event,'${encodeURIComponent(name)}')"><i class="fa-solid fa-clone"></i></button>
<button class="btn" title="Open" style="padding:6px 8px" onclick="openFile(event,'${encodeURIComponent(name)}')"><i class="fa-solid fa-folder-open"></i></button>
</div>`;
fileListEl.appendChild(div);
});
}
// Actions
function newFile(){
let name = prompt('Filename (end with .java):','Main.java');
if(!name) return;
if(!name.endsWith('.java')) { alert('Filename must end with .java'); return; }
if(files[name]) { alert('File exists'); return; }
const classname = name.replace('.java','').replace(/[^A-Za-z0-9_]/g,'') || 'Main';
files[name] = `class ${classname} {\n public static void main(String[] args) {\n System.out.println("Hello ${classname}!");\n }\n}\n`;
saveToStorage();
setActive(name);
}
function openFile(e, nameEnc){
e.stopPropagation();
const name = decodeURIComponent(nameEnc);
setActive(name);
}
function renameFile(e,nameEnc){
e.stopPropagation();
const oldName = decodeURIComponent(nameEnc);
const newName = prompt('Rename file to:', oldName);
if(!newName || newName===oldName) return;
if(!newName.endsWith('.java')) { alert('Filename must end with .java'); return; }
if(files[newName]) { alert('A file with this name exists'); return; }
files[newName] = files[oldName];
delete files[oldName];
saveToStorage();
setActive(newName);
}
function duplicateFile(e,nameEnc){
e.stopPropagation();
const name = decodeURIComponent(nameEnc);
let copyName = name.replace('.java','') + '_copy.java';
let i=1;
while(files[copyName]) { copyName = name.replace('.java','') + `_copy${i}.java`; i++; }
files[copyName] = files[name];
saveToStorage();
setActive(copyName);
}
function deleteFile(){
if(!active) return alert('No file selected');
if(!confirm(`Delete ${active}?`)) return;
delete files[active];
saveToStorage();
active = null;
localStorage.removeItem('java_learner_active');
activeFileEl.innerText = '—';
editor.setValue('// Create a new file to start coding');
renderFiles();
}
function saveFile(){
if(!active) return alert('No file selected');
files[active] = editor.getValue();
saveToStorage();
flashMessage('Saved ✔');
}
function downloadFile(){
if(!active) return alert('No file selected');
const blob = new Blob([editor.getValue()], {type:'text/plain'});
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = active;
a.click();
URL.revokeObjectURL(a.href);
}
// Import from disk
document.getElementById('importBtn').addEventListener('click', ()=>document.getElementById('fileInput').click());
document.getElementById('fileInput').addEventListener('change', (e)=>{
const f = e.target.files[0];
if(!f) return;
const reader = new FileReader();
reader.onload = ()=> {
let name = f.name;
if(!name.endsWith('.java')) name = name + '.java';
files[name] = reader.result;
saveToStorage();
setActive(name);
};
reader.readAsText(f);
e.target.value = '';
});
// Search
document.getElementById('searchFile').addEventListener('input', (e)=>renderFiles(e.target.value));
// Toggle sidebar (mobile)
document.getElementById('toggleSidebar').addEventListener('click', ()=>{
const sb = document.getElementById('sidebar');
if(sb.style.display === 'none'){ sb.style.display='flex'; } else { sb.style.display='none'; }
setTimeout(()=>editor.refresh(),200);
});
// Clipboard actions (cut/copy/paste)
document.getElementById('cutBtn').addEventListener('click', ()=>{
const sel = editor.getSelection();
if(!sel) return;
navigator.clipboard.writeText(sel).then(()=> {
editor.replaceSelection('');
});
});
document.getElementById('copyBtn').addEventListener('click', ()=>{
const sel = editor.getSelection();
if(!sel) return;
navigator.clipboard.writeText(sel);
});
document.getElementById('pasteBtn').addEventListener('click', async ()=>{
const txt = await navigator.clipboard.readText();
editor.replaceSelection(txt);
});
// Format (auto indent)
document.getElementById('formatBtn').addEventListener('click', ()=>{
try {
// basic auto-indent by selecting all and auto indenting
const total = {line: editor.lastLine()+1};
editor.execCommand('selectAll');
if(editor.execCommand('indentAuto')) {
// indentAuto available
} else {
// fallback: indentMore a few times to normalize
for(let i=0;i<3;i++) editor.execCommand('indentMore');
}
editor.execCommand('singleSelection');
flashMessage('Formatted');
} catch(e){
flashMessage('Format not available');
}
});
// Run code (send to FastAPI)
async function runCode(){
if(!active) return alert('No file selected');
saveFile();
consoleEl.innerText = '⏳ Running...';
try {
const resp = await fetch('/run-java', {
method:'POST',
headers:{'Content-Type':'application/json'},
body: JSON.stringify({ code: editor.getValue(), filename: active })
});
const data = await resp.json();
if(data.output) consoleEl.innerText = data.output;
else if(data.error) consoleEl.innerText = 'Error:\n' + data.error;
else consoleEl.innerText = JSON.stringify(data, null, 2);
} catch(err){
consoleEl.innerText = 'Network error: ' + err.message;
}
}
// Hook buttons
document.getElementById('newBtn').addEventListener('click', newFile);
document.getElementById('saveBtn').addEventListener('click', saveFile);
document.getElementById('downloadBtn').addEventListener('click', downloadFile);
document.getElementById('runBtn').addEventListener('click', runCode);
document.getElementById('deleteBtn').addEventListener('click', deleteFile);
// Shortcut: Ctrl+S save, Ctrl+Enter run
window.addEventListener('keydown', function(e){
if((e.ctrlKey || e.metaKey) && e.key.toLowerCase()==='s'){ e.preventDefault(); saveFile(); }
if((e.ctrlKey || e.metaKey) && e.key==='Enter'){ e.preventDefault(); runCode(); }
});
// Visual flash message
function flashMessage(msg){
const el = document.createElement('div');
el.innerText = msg;
el.style.position='fixed';
el.style.right='18px';
el.style.bottom='18px';
el.style.background='linear-gradient(90deg, rgba(108,140,255,0.14), rgba(139,229,208,0.04))';
el.style.border='1px solid rgba(255,255,255,0.04)';
el.style.padding='10px 14px';
el.style.borderRadius='10px';
el.style.color='#eaf6ff';
el.style.boxShadow='0 8px 26px rgba(0,0,0,0.5)';
document.body.appendChild(el);
setTimeout(()=> el.style.opacity='0', 1800);
setTimeout(()=> el.remove(), 2400);
}
// Initialize app state
if(Object.keys(files).length === 0) {
// create default starter file
files['Main.java'] = editor.getValue();
saveToStorage();
}
if(!active) {
setActive(Object.keys(files)[0]);
} else {
// ensure editor shows active file
if(files[active]) editor.setValue(files[active]); else setActive(Object.keys(files)[0]);
}
renderFiles();
// ensure refresh after everything loaded
setTimeout(()=>editor.refresh(),250);
</script>
</body>
</html>