// 代码格式化工具的JavaScript逻辑 document.addEventListener('DOMContentLoaded', function() { initCodeFormatter(); }); function initCodeFormatter() { // 获取DOM元素 const languageSelect = document.getElementById('language-select'); const indentSlider = document.getElementById('indent-slider'); const indentValue = document.getElementById('indent-value'); const optIndent = document.getElementById('opt-indent'); const optRemoveComments = document.getElementById('opt-remove-comments'); const optSingleQuotes = document.getElementById('opt-single-quotes'); const codeInput = document.getElementById('code-input'); const codeOutput = document.getElementById('code-output'); const formatBtn = document.getElementById('format-btn'); const copyBtn = document.getElementById('copy-btn'); const clearBtn = document.getElementById('clear-btn'); const downloadBtn = document.getElementById('download-btn'); const themeSelect = document.getElementById('theme-select'); // 初始化highlight.js hljs.highlightAll(); // 更新缩进值显示 indentSlider.addEventListener('input', function() { indentValue.textContent = this.value; }); // 切换代码高亮主题 themeSelect.addEventListener('change', function() { const currentLink = document.querySelector('link[href*="highlight.js"]'); const newHref = `https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/${this.value}.min.css`; currentLink.setAttribute('href', newHref); }); // 清空代码输入 clearBtn.addEventListener('click', function() { codeInput.value = ''; codeInput.focus(); }); // 格式化代码 formatBtn.addEventListener('click', function() { formatCode(); }); // 复制格式化后的代码 copyBtn.addEventListener('click', function() { const formattedCode = codeOutput.textContent; if (formattedCode) { navigator.clipboard.writeText(formattedCode).then(() => { showNotification('代码已复制到剪贴板'); }).catch(err => { console.error('复制失败:', err); }); } }); // 下载格式化后的代码 downloadBtn.addEventListener('click', function() { const formattedCode = codeOutput.textContent; if (!formattedCode) return; const language = languageSelect.value; let extension = getFileExtension(language); const fileName = `formatted-code.${extension}`; const blob = new Blob([formattedCode], {type: 'text/plain'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = fileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }); // 格式化代码的主函数 function formatCode() { const code = codeInput.value.trim(); if (!code) { showNotification('请输入要格式化的代码', 'error'); return; } const language = languageSelect.value; const indentSize = parseInt(indentSlider.value); const useIndent = optIndent.checked; const removeComments = optRemoveComments.checked; const useSingleQuotes = optSingleQuotes.checked; // 格式化选项 const options = { indent_size: indentSize, indent_with_tabs: false, preserve_newlines: true, max_preserve_newlines: 2, space_in_empty_paren: false, jslint_happy: false, space_after_anon_function: false, brace_style: 'collapse', break_chained_methods: false, keep_array_indentation: false, unescape_strings: false, wrap_line_length: 0, end_with_newline: true, comma_first: false, e4x: false, indent_empty_lines: false }; if (!useIndent) { options.indent_size = 0; } if (useSingleQuotes) { options.end_with_newline = true; } let formattedCode = ''; try { // 根据语言选择合适的格式化方法 switch (language) { case 'javascript': formattedCode = js_beautify(code, options); break; case 'html': formattedCode = html_beautify(code, options); break; case 'css': formattedCode = css_beautify(code, options); break; case 'json': // 对于JSON,先尝试解析以验证有效性 try { const jsonObj = JSON.parse(code); formattedCode = JSON.stringify(jsonObj, null, useIndent ? indentSize : 0); } catch (e) { showNotification('无效的JSON格式', 'error'); return; } break; default: // 对于其他语言,我们只能做基本的缩进 formattedCode = code; break; } // 如果需要删除注释 if (removeComments && ['javascript', 'css', 'java', 'csharp', 'cpp', 'php'].includes(language)) { formattedCode = removeCodeComments(formattedCode, language); } // 更新输出区域 codeOutput.textContent = formattedCode; codeOutput.className = `hljs language-${language}`; hljs.highlightElement(codeOutput); // 记录使用历史 addToHistory({ type: 'code-formatter', language: language, timestamp: new Date().toISOString() }); // 增加使用计数 incrementUsageCount(); showNotification('代码格式化成功'); } catch (error) { console.error('格式化错误:', error); showNotification('格式化过程中出现错误', 'error'); } } // 获取语言对应的文件扩展名 function getFileExtension(language) { const extensions = { 'javascript': 'js', 'html': 'html', 'css': 'css', 'json': 'json', 'xml': 'xml', 'sql': 'sql', 'python': 'py', 'java': 'java', 'csharp': 'cs', 'cpp': 'cpp', 'php': 'php' }; return extensions[language] || 'txt'; } // 移除代码中的注释 function removeCodeComments(code, language) { switch (language) { case 'javascript': case 'java': case 'csharp': case 'cpp': // 移除 // 行注释和 /* */ 块注释 return code.replace(/\/\/.*?$/gm, '') .replace(/\/\*[\s\S]*?\*\//g, ''); case 'css': // 移除 /* */ 注释 return code.replace(/\/\*[\s\S]*?\*\//g, ''); case 'php': // 移除 // 行注释, # 行注释和 /* */ 块注释 return code.replace(/\/\/.*?$/gm, '') .replace(/#.*?$/gm, '') .replace(/\/\*[\s\S]*?\*\//g, ''); default: return code; } } // 显示通知 function showNotification(message, type = 'success') { const notification = document.createElement('div'); notification.className = `fixed bottom-4 right-4 px-4 py-2 rounded-md shadow-lg transition-opacity duration-300 ${ type === 'success' ? 'bg-green-500' : 'bg-red-500' } text-white max-w-xs z-50`; notification.textContent = message; document.body.appendChild(notification); setTimeout(() => { notification.style.opacity = '0'; setTimeout(() => { document.body.removeChild(notification); }, 300); }, 3000); } // 添加一些示例代码 codeInput.value = `function example() { const items = [1, 2, 3, 4]; let sum = 0; // 计算总和 for(let i=0;i