๐Ÿ’ป Code Formatter
๐Ÿ“ฅ Input Code
Ready
๐Ÿ“ค Formatted Output
Formatted code will appear here...
Waiting for input
', css:'.container{display:flex;flex-direction:column;align-items:center;padding:20px;background:#fff;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,0.1);}.title{font-size:24px;font-weight:bold;color:#333;margin-bottom:16px;}', javascript:'function fetchUser(id){return new Promise((resolve,reject)=>{fetch(`/api/users/${id}`).then(r=>r.json()).then(data=>{if(data.error)reject(data.error);else resolve(data);}).catch(reject);});}', json:'{"name":"CodeCanvas","version":"1.0.0","tools":["json-formatter","hash-generator","color-picker"],"features":{"ai":true,"free":true},"author":{"name":"Developer","email":"dev@codecanvas.top"}}', sql:'SELECT u.id,u.name,u.email,COUNT(o.id) as order_count,SUM(o.total) as total_spent FROM users u LEFT JOIN orders o ON u.id=o.user_id WHERE u.created_at>\'2026-01-01\' AND u.status=\'active\' GROUP BY u.id,u.name,u.email HAVING order_count>0 ORDER BY total_spent DESC LIMIT 50;', kotlin:'data class User(val id:String,val name:String,val email:String,val createdAt:Long=System.currentTimeMillis()){fun isValid()=name.isNotBlank()&&email.contains("@")&&email.contains(".")}\nfun List.filterActive()=filter{it.isValid()}.sortedBy{it.name}', python:'def fetch_users(db,filters=None,limit=100):\n query="SELECT * FROM users"\n params=[]\n if filters:\n conditions=[f"{k}=%s" for k in filters]\n query+=" WHERE "+" AND ".join(conditions)\n params=list(filters.values())\n query+=f" LIMIT {limit}"\n return db.execute(query,params).fetchall()', xml:'John Doejohn@example.comadminJane Smithjane@example.comuser', }; function setLang(lang){ currentLang=lang; document.getElementById('inputLabel').textContent='๐Ÿ“ฅ Input '+lang.toUpperCase(); document.getElementById('outputLabel').textContent='๐Ÿ“ค Formatted '+lang.toUpperCase(); } function getIndent(){ const v=document.getElementById('indentSize').value; return v==='tab'?'\t':' '.repeat(parseInt(v)); } function format(){ const input=document.getElementById('codeInput').value.trim(); if(!input){setStatus('err','Please paste code first!');return;} try{ let formatted=''; const indent=getIndent(); if(currentLang==='json'){ formatted=JSON.stringify(JSON.parse(input),null,indent); } else if(currentLang==='html'){ formatted=formatHTML(input,indent); } else if(currentLang==='css'){ formatted=formatCSS(input,indent); } else if(currentLang==='sql'){ formatted=formatSQL(input); } else if(currentLang==='xml'){ formatted=formatXML(input,indent); } else { formatted=formatGeneric(input,indent); } outputText=formatted; const oc=document.getElementById('outputCode'); oc.className=`language-${currentLang==='kotlin'?'kotlin':currentLang==='dart'?'dart':currentLang}`; oc.textContent=formatted; hljs.highlightElement(oc); setStatus('ok',`โœ“ Formatted ยท ${formatted.split('\n').length} lines`,'output'); updateStats(); }catch(e){ setStatus('err','โœ— '+e.message,'input'); } } function formatHTML(html,indent){ let result='',level=0; const voidTags=new Set(['area','base','br','col','embed','hr','img','input','link','meta','param','source','track','wbr']); html=html.replace(/>\s+<').trim(); const parts=html.split(/(<[^>]+>)/g).filter(Boolean); parts.forEach(part=>{ if(part.match(/^<\/\w/)){level=Math.max(0,level-1);} if(part.trim()){result+=indent.repeat(level)+part.trim()+'\n';} const tagMatch=part.match(/^<(\w+)/); if(tagMatch&&!voidTags.has(tagMatch[1].toLowerCase())&&!part.startsWith(''))level++; }); return result.trim(); } function formatCSS(css,indent){ css=css.replace(/\s+/g,' ').trim(); let result='',level=0; css.split('').forEach((c,i)=>{ if(c==='{'){result+=' {\n'+indent.repeat(++level);} else if(c==='}'){result=result.trimEnd()+'\n'+'}'.repeat(1)+'\n\n';level=Math.max(0,level-1);} else if(c===';'){result+=';\n'+(level>0?indent.repeat(level):'');} else result+=c; }); return result.trim(); } function formatSQL(sql){ const keywords=['SELECT','FROM','WHERE','JOIN','LEFT JOIN','RIGHT JOIN','INNER JOIN','ON','AND','OR','ORDER BY','GROUP BY','HAVING','LIMIT','OFFSET','INSERT INTO','VALUES','UPDATE','SET','DELETE','CREATE TABLE','ALTER TABLE','DROP TABLE','UNION','DISTINCT','AS','IN','NOT IN','IS NULL','IS NOT NULL','BETWEEN','LIKE','COUNT','SUM','AVG','MAX','MIN']; let result=sql.replace(/\s+/g,' ').trim(); keywords.forEach(kw=>{ const regex=new RegExp(`\\b${kw}\\b`,'gi'); result=result.replace(regex,'\n'+kw); }); return result.split('\n').map(l=>l.trim()).filter(Boolean).join('\n'); } function formatXML(xml,indent){ let result='',level=0; xml=xml.replace(/>\s+<').trim(); xml.split(/(<[^>]+>)/).filter(Boolean).forEach(part=>{ if(part.match(/^<\/\w/)){level=Math.max(0,level-1);result+=indent.repeat(level)+part.trim()+'\n';} else if(part.match(/^<\w[^>]*[^\/]>$/)&&!part.match(/^<\?/)){result+=indent.repeat(level)+part.trim()+'\n';level++;} else if(part.trim()){result+=indent.repeat(level)+part.trim()+'\n';} }); return result.trim(); } function formatGeneric(code,indent){ // Simple brace-based formatting for JS/TS/Java/Kotlin/Swift/PHP etc let result='',level=0; const lines=code.replace(/[;{]/g,m=>m===';'?';\n':' {\n').replace(/}/g,'\n}').split('\n'); lines.forEach(line=>{ const t=line.trim(); if(!t)return; if(t==='}')level=Math.max(0,level-1); result+=indent.repeat(level)+t+'\n'; if(t.endsWith('{'))level++; }); return result.trim(); } function minify(){ const input=document.getElementById('codeInput').value.trim(); if(!input)return; let minified=input; if(currentLang==='json'){try{minified=JSON.stringify(JSON.parse(input));}catch(e){}} else{minified=input.replace(/\/\*[\s\S]*?\*\//g,'').replace(/\/\/[^\n]*/g,'').replace(/\n\s*/g,' ').replace(/\s{2,}/g,' ').replace(/;\s*/g,';').replace(/{\s*/g,'{').replace(/}\s*/g,'}').replace(/,\s*/g,',').trim();} outputText=minified; document.getElementById('outputCode').textContent=minified; setStatus('ok',`โœ“ Minified ยท ${minified.length} chars`,'output'); } function swapIO(){ if(!outputText)return; document.getElementById('codeInput').value=outputText; document.getElementById('outputCode').textContent='Formatted code will appear here...'; outputText=''; } function copyOutput(){ if(!outputText){alert('Nothing to copy!');return;} navigator.clipboard.writeText(outputText);showToast('โœ“ Copied!'); } function downloadOutput(){ if(!outputText)return; const ext={html:'html',css:'css',javascript:'js',typescript:'ts',json:'json',sql:'sql',xml:'xml',kotlin:'kt',java:'java',python:'py',php:'php',dart:'dart',go:'go',swift:'swift',yaml:'yaml'}[currentLang]||'txt'; const blob=new Blob([outputText],{type:'text/plain'}); const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=`formatted.${ext}`;a.click(); } async function pasteInput(){try{const t=await navigator.clipboard.readText();document.getElementById('codeInput').value=t;updateStats();}catch(e){}} function clearInput(){document.getElementById('codeInput').value='';outputText='';document.getElementById('outputCode').textContent='Formatted code will appear here...';} function loadSample(){document.getElementById('codeInput').value=SAMPLES[currentLang]||SAMPLES.html;updateStats();} function updateStats(){const v=document.getElementById('codeInput').value;document.getElementById('stats').textContent=`${v.length} chars ยท ${v.split('\n').length} lines`;} function setStatus(type,msg,target='both'){ ['input','output'].forEach(t=>{ if(target==='both'||target===t){ document.getElementById(t+'Dot').className='status-dot '+(type==='ok'?'dot-ok':'dot-err'); document.getElementById(t+'Status').textContent=msg; } }); } function showToast(msg){const t=document.getElementById('toast');t.textContent=msg;t.style.display='block';setTimeout(()=>t.style.display='none',2000);}