auto
This commit is contained in:
@@ -22,3 +22,8 @@ dist-ssr
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
# C 编译器运行服务 - 编译器二进制文件
|
||||
server/bin/
|
||||
server/*.ps1
|
||||
tmp/
|
||||
|
||||
Generated
+856
File diff suppressed because it is too large
Load Diff
@@ -5,12 +5,16 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"server": "node server/server.cjs",
|
||||
"start": "node server/server.js & vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"cors": "^2.8.6",
|
||||
"express": "^5.2.1",
|
||||
"vue": "^3.5.34",
|
||||
"vue-router": "^4.6.4"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* C 代码编译运行后端服务
|
||||
* 接收 C 代码 → 编译 → 运行 → 返回输出
|
||||
*/
|
||||
const express = require('express')
|
||||
const cors = require('cors')
|
||||
const { execSync } = require('child_process')
|
||||
const path = require('path')
|
||||
const fs = require('fs')
|
||||
|
||||
const app = express()
|
||||
const PORT = 3001
|
||||
|
||||
app.use(cors())
|
||||
app.use(express.json({ limit: '1mb' }))
|
||||
|
||||
// 查找可用的 C 编译器
|
||||
// w64devkit GCC 路径
|
||||
const W64DEVKIT_DIR = path.join(__dirname, 'bin', 'w64devkit', 'w64devkit')
|
||||
const W64DEVKIT_GCC = path.join(W64DEVKIT_DIR, 'bin', 'gcc.exe')
|
||||
const W64DEVKIT_PREFIX = path.join(W64DEVKIT_DIR, 'lib', 'gcc')
|
||||
|
||||
function findCompiler() {
|
||||
const candidates = [
|
||||
// MinGW / MSYS2 (PATH)
|
||||
'gcc.exe',
|
||||
'x86_64-w64-mingw32-gcc.exe',
|
||||
'i686-w64-mingw32-gcc.exe',
|
||||
// TCC (Tiny C Compiler)
|
||||
'tcc.exe',
|
||||
// Clang
|
||||
'clang.exe',
|
||||
// MSVC
|
||||
'cl.exe',
|
||||
// 本项目的便携编译器
|
||||
path.join(__dirname, 'bin', 'tcc.exe'),
|
||||
path.join(__dirname, 'bin', 'gcc.exe'),
|
||||
path.join(__dirname, '..', 'tools', 'tcc', 'tcc.exe'),
|
||||
]
|
||||
|
||||
// 先在 PATH 中查找
|
||||
for (const name of ['gcc.exe', 'tcc.exe', 'clang.exe', 'cl.exe']) {
|
||||
try {
|
||||
execSync(`where ${name}`, { stdio: 'pipe', timeout: 3000 })
|
||||
return { path: name, name }
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// 检查 w64devkit GCC(需设置 GCC_EXEC_PREFIX)
|
||||
if (fs.existsSync(W64DEVKIT_GCC)) {
|
||||
return { path: W64DEVKIT_GCC, name: 'gcc.exe', execPrefix: W64DEVKIT_PREFIX }
|
||||
}
|
||||
|
||||
// 再检查其他具体路径
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const absPath = path.resolve(candidate)
|
||||
if (fs.existsSync(absPath)) {
|
||||
return { path: absPath, name: path.basename(absPath) }
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// 搜索 Visual Studio MSVC 安装目录
|
||||
try {
|
||||
const vsPaths = [
|
||||
'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC',
|
||||
'C:\\Program Files\\Microsoft Visual Studio\\2022\\Professional\\VC\\Tools\\MSVC',
|
||||
'C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC',
|
||||
'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC',
|
||||
'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC',
|
||||
]
|
||||
for (const vsPath of vsPaths) {
|
||||
if (fs.existsSync(vsPath)) {
|
||||
const versions = fs.readdirSync(vsPath).sort().reverse()
|
||||
for (const ver of versions) {
|
||||
const clPath = path.join(vsPath, ver, 'bin', 'Hostx64', 'x64', 'cl.exe')
|
||||
if (fs.existsSync(clPath)) {
|
||||
return { path: clPath, name: 'cl.exe' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
// 编译并运行 C 代码
|
||||
app.post('/api/run-c', (req, res) => {
|
||||
const { code } = req.body
|
||||
if (!code) {
|
||||
return res.status(400).json({ error: '请提供 C 代码' })
|
||||
}
|
||||
|
||||
const compiler = findCompiler()
|
||||
if (!compiler) {
|
||||
return res.status(400).json({
|
||||
error: '未找到 C 编译器',
|
||||
hint: '请安装 MinGW-w64 GCC 编译器',
|
||||
installGuide: [
|
||||
'--- 安装 MinGW-w64 ---',
|
||||
'方法一(推荐):下载 MinGW-w64 GCC',
|
||||
' 1. 访问 https://winlibs.com/ 下载 GCC (MinGW-w64)',
|
||||
' 2. 解压并将 bin/ 目录添加到系统 PATH 环境变量',
|
||||
' 3. 重启终端后即可使用',
|
||||
'',
|
||||
'方法二(轻量):下载 TCC (Tiny C Compiler)',
|
||||
' 将 tcc.exe 放入 server/bin/ 目录',
|
||||
'',
|
||||
'安装后重新启动: npm run server',
|
||||
].join('\n')
|
||||
})
|
||||
}
|
||||
|
||||
const tmpDir = path.join(__dirname, '..', 'tmp')
|
||||
if (!fs.existsSync(tmpDir)) {
|
||||
fs.mkdirSync(tmpDir, { recursive: true })
|
||||
}
|
||||
|
||||
const srcFile = path.join(tmpDir, `code_${Date.now()}.c`)
|
||||
const outFile = path.join(tmpDir, `code_${Date.now()}.exe`)
|
||||
|
||||
try {
|
||||
// 写入源码
|
||||
fs.writeFileSync(srcFile, code, 'utf-8')
|
||||
|
||||
let compileCmd
|
||||
const execOptions = {
|
||||
timeout: 15000,
|
||||
cwd: tmpDir,
|
||||
encoding: 'utf-8',
|
||||
env: { ...process.env }
|
||||
}
|
||||
|
||||
if (compiler.name.includes('tcc')) {
|
||||
// TCC: 编译并运行一步到位(支持 -run)
|
||||
compileCmd = `"${compiler.path}" -run "${srcFile}"`
|
||||
} else if (compiler.execPrefix) {
|
||||
// w64devkit GCC: 需要设置 GCC_EXEC_PREFIX 并加入 PATH
|
||||
const w64binDir = path.dirname(compiler.path)
|
||||
execOptions.env.GCC_EXEC_PREFIX = compiler.execPrefix + path.sep
|
||||
execOptions.env.PATH = w64binDir + path.delimiter + (execOptions.env.PATH || '')
|
||||
compileCmd = `"${compiler.path}" "${srcFile}" -o "${outFile}" -Wall -std=c99`
|
||||
} else {
|
||||
// GCC/Clang: 先编译再运行
|
||||
compileCmd = `"${compiler.path}" "${srcFile}" -o "${outFile}" -Wall -std=c99 2>&1`
|
||||
}
|
||||
|
||||
// 编译
|
||||
const compileOutput = execSync(compileCmd, execOptions)
|
||||
|
||||
let runOutput = compileOutput
|
||||
|
||||
// GCC/Clang: 编译后还需运行 exe
|
||||
if (!compiler.name.includes('tcc') && fs.existsSync(outFile)) {
|
||||
try {
|
||||
runOutput = execSync(`"${outFile}"`, {
|
||||
timeout: 10000,
|
||||
cwd: tmpDir,
|
||||
encoding: 'utf-8',
|
||||
env: execOptions.env
|
||||
})
|
||||
} catch (runErr) {
|
||||
runOutput = runErr.stdout || runErr.message
|
||||
}
|
||||
}
|
||||
|
||||
// 清理临时文件
|
||||
try {
|
||||
if (fs.existsSync(srcFile)) fs.unlinkSync(srcFile)
|
||||
if (fs.existsSync(outFile)) fs.unlinkSync(outFile)
|
||||
} catch {}
|
||||
|
||||
res.json({ output: runOutput })
|
||||
} catch (compileErr) {
|
||||
// 编译错误
|
||||
res.json({
|
||||
output: compileErr.stdout || compileErr.message,
|
||||
isError: true
|
||||
})
|
||||
} finally {
|
||||
// 确保清理
|
||||
try {
|
||||
if (fs.existsSync(srcFile)) fs.unlinkSync(srcFile)
|
||||
if (fs.existsSync(outFile)) fs.unlinkSync(outFile)
|
||||
} catch {}
|
||||
}
|
||||
})
|
||||
|
||||
// 健康检查
|
||||
app.get('/api/status', (req, res) => {
|
||||
const compiler = findCompiler()
|
||||
res.json({
|
||||
status: 'ok',
|
||||
compiler: compiler ? `${compiler.name} (${compiler.path})` : '未安装'
|
||||
})
|
||||
})
|
||||
|
||||
// 下载 TCC 脚本
|
||||
app.get('/api/setup-compiler', (req, res) => {
|
||||
res.json({
|
||||
message: '请手动下载 TCC:',
|
||||
url: 'https://raw.githubusercontent.com/FooBarWidget/tinycc/master/tcc.exe',
|
||||
instructions: `将 tcc.exe 放入 ${path.join(__dirname, 'bin')} 目录`
|
||||
})
|
||||
})
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`✅ C 代码运行服务已启动: http://localhost:${PORT}`)
|
||||
const compiler = findCompiler()
|
||||
if (compiler) {
|
||||
console.log(` 检测到编译器: ${compiler.name}`)
|
||||
} else {
|
||||
console.log(` ⚠️ 未检测到 C 编译器,请安装后使用`)
|
||||
console.log(` 下载 TCC: https://raw.githubusercontent.com/FooBarWidget/tinycc/master/tcc.exe`)
|
||||
console.log(` 放置路径: ${path.join(__dirname, 'bin', 'tcc.exe')}`)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { highlightC } from '../utils/codeUtils.js'
|
||||
|
||||
describe('highlightC', () => {
|
||||
it('should highlight keywords', () => {
|
||||
const result = highlightC('int main()')
|
||||
expect(result).toContain('<span class="hl-keyword">int</span>')
|
||||
expect(result).toContain('<span class="hl-keyword">main</span>')
|
||||
})
|
||||
|
||||
it('should highlight single-line comments', () => {
|
||||
const result = highlightC('// this is a comment')
|
||||
expect(result).toContain('<span class="hl-comment">')
|
||||
expect(result).toContain('// this is a comment')
|
||||
})
|
||||
|
||||
it('should highlight multi-line comments', () => {
|
||||
const result = highlightC('/* multi\nline */')
|
||||
expect(result).toContain('<span class="hl-comment">')
|
||||
expect(result).toContain('/* multi')
|
||||
expect(result).toContain('line */')
|
||||
})
|
||||
|
||||
it('should highlight string literals', () => {
|
||||
const result = highlightC('printf("hello world");')
|
||||
expect(result).toContain('<span class="hl-string">')
|
||||
expect(result).toContain('"hello world"')
|
||||
})
|
||||
|
||||
it('should highlight char literals', () => {
|
||||
const result = highlightC("char c = 'A';")
|
||||
expect(result).toContain("<span class=\"hl-string\">'A'</span>")
|
||||
})
|
||||
|
||||
it('should highlight numbers', () => {
|
||||
const result = highlightC('int x = 42;')
|
||||
expect(result).toContain('<span class="hl-number">42</span>')
|
||||
})
|
||||
|
||||
it('should highlight float numbers', () => {
|
||||
const result = highlightC('float f = 3.14;')
|
||||
expect(result).toContain('<span class="hl-number">3.14</span>')
|
||||
})
|
||||
|
||||
it('should highlight preprocessor directives', () => {
|
||||
const result = highlightC('#include <stdio.h>')
|
||||
expect(result).toContain('<span class="hl-preprocessor">')
|
||||
expect(result).toContain('#include <stdio.h>')
|
||||
})
|
||||
|
||||
it('should NOT produce nested broken HTML tags', () => {
|
||||
const result = highlightC('#include <stdio.h>\nint main() {\n printf("hello");\n}')
|
||||
// Should not contain any raw '<span' as visible text (it should be inside proper tags)
|
||||
expect(result).not.toContain('<span')
|
||||
// Should not contain unescaped "<span" inside text content
|
||||
const stripped = result.replace(/<[^>]+>/g, '')
|
||||
expect(stripped).not.toContain('hl-keyword')
|
||||
expect(stripped).not.toContain('hl-comment')
|
||||
expect(stripped).not.toContain('hl-string')
|
||||
expect(stripped).not.toContain('hl-number')
|
||||
})
|
||||
|
||||
it('should escape HTML in code content', () => {
|
||||
const result = highlightC('int x = a < b && b > c;')
|
||||
expect(result).toContain('<')
|
||||
expect(result).toContain('>')
|
||||
expect(result).not.toContain(' < ')
|
||||
expect(result).not.toContain(' > ')
|
||||
})
|
||||
|
||||
it('should handle empty string', () => {
|
||||
expect(highlightC('')).toBe('')
|
||||
})
|
||||
|
||||
it('should handle code with mixed content', () => {
|
||||
const code = `#include <stdio.h>
|
||||
// main function
|
||||
int main() {
|
||||
printf("Hello, World!\\n");
|
||||
return 0;
|
||||
}`
|
||||
const result = highlightC(code)
|
||||
expect(result).toContain('hl-preprocessor')
|
||||
expect(result).toContain('hl-comment')
|
||||
expect(result).toContain('hl-keyword')
|
||||
expect(result).toContain('hl-string')
|
||||
expect(result).toContain('hl-number')
|
||||
})
|
||||
})
|
||||
+280
-14
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div class="code-viewer">
|
||||
<div class="code-viewer" ref="viewerRef" :class="{ fullscreen: isFullscreen }">
|
||||
<div class="code-toolbar">
|
||||
<div class="file-info">
|
||||
<span class="file-icon">📄</span>
|
||||
@@ -8,13 +8,38 @@
|
||||
</div>
|
||||
<div class="toolbar-actions">
|
||||
<span v-if="description" class="file-desc-tip" :title="description">ℹ️</span>
|
||||
<button class="copy-btn" @click="copyCode" :title="copied ? '已复制!' : '复制代码'">
|
||||
|
||||
<!-- 字号控制 -->
|
||||
<div class="font-size-control">
|
||||
<button class="tool-btn" @click="fontSizeDown" title="缩小字体">A−</button>
|
||||
<span class="font-size-value">{{ fontSize }}px</span>
|
||||
<button class="tool-btn" @click="fontSizeUp" title="放大字体">A+</button>
|
||||
<button class="tool-btn reset-btn" @click="fontSizeReset" title="重置字号">↺</button>
|
||||
</div>
|
||||
|
||||
<!-- 全屏 -->
|
||||
<button class="tool-btn" @click="toggleFullscreen" :title="isFullscreen ? '退出全屏' : '全屏'">
|
||||
{{ isFullscreen ? '⛶' : '⛶' }}
|
||||
</button>
|
||||
|
||||
<!-- 运行 -->
|
||||
<button
|
||||
class="tool-btn run-btn"
|
||||
@click="runCode"
|
||||
:disabled="running"
|
||||
:title="running ? '正在编译运行...' : '编译并运行 C 代码'"
|
||||
>
|
||||
{{ running ? '⏳' : '▶' }} 运行
|
||||
</button>
|
||||
|
||||
<!-- 复制 -->
|
||||
<button class="tool-btn" @click="copyCode" :title="copied ? '已复制!' : '复制代码'">
|
||||
{{ copied ? '✅' : '📋' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="code-content" ref="codeRef">
|
||||
<pre><code v-html="highlightedCode"></code></pre>
|
||||
<div class="code-content" ref="codeRef" @wheel="onWheel">
|
||||
<pre :style="{ fontSize: fontSize + 'px', lineHeight: lineHeight + 'px' }"><code v-html="highlightedCode"></code></pre>
|
||||
<div v-if="loading" class="loading-overlay">
|
||||
<div class="loading-spinner">加载中...</div>
|
||||
</div>
|
||||
@@ -22,6 +47,20 @@
|
||||
<p>⚠️ {{ error }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 运行输出面板 -->
|
||||
<div v-if="runOutput !== null" class="run-output" :class="{ collapsed: outputCollapsed }">
|
||||
<div class="output-header" @click="outputCollapsed = !outputCollapsed">
|
||||
<span class="output-title">
|
||||
{{ runOutput.isError ? '❌' : '✅' }} 运行结果
|
||||
</span>
|
||||
<span class="output-toggle">{{ outputCollapsed ? '展开' : '折叠' }}</span>
|
||||
<button class="tool-btn close-btn" @click.stop="runOutput = null" title="关闭">✕</button>
|
||||
</div>
|
||||
<div class="output-body">
|
||||
<pre :class="{ 'error-text': runOutput.isError }">{{ runOutput.text }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -40,12 +79,22 @@ const codeContent = ref('')
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const copied = ref(false)
|
||||
const fontSize = ref(13)
|
||||
const isFullscreen = ref(false)
|
||||
const viewerRef = ref(null)
|
||||
const codeRef = ref(null)
|
||||
|
||||
const MIN_FONT = 10
|
||||
const MAX_FONT = 36
|
||||
const FONT_STEP = 2
|
||||
|
||||
const highlightedCode = computed(() => {
|
||||
if (!codeContent.value) return ''
|
||||
return highlightC(codeContent.value)
|
||||
})
|
||||
|
||||
const lineHeight = computed(() => Math.max(22, fontSize.value * 1.5))
|
||||
|
||||
async function loadCode() {
|
||||
if (!props.filePath) return
|
||||
loading.value = true
|
||||
@@ -62,13 +111,90 @@ async function loadCode() {
|
||||
|
||||
watch(() => props.filePath, loadCode, { immediate: true })
|
||||
|
||||
// 字号控制
|
||||
function fontSizeUp() {
|
||||
fontSize.value = Math.min(fontSize.value + FONT_STEP, MAX_FONT)
|
||||
}
|
||||
function fontSizeDown() {
|
||||
fontSize.value = Math.max(fontSize.value - FONT_STEP, MIN_FONT)
|
||||
}
|
||||
function fontSizeReset() {
|
||||
fontSize.value = 13
|
||||
}
|
||||
|
||||
// Ctrl+滚轮缩放
|
||||
function onWheel(e) {
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
e.preventDefault()
|
||||
if (e.deltaY < 0) fontSizeUp()
|
||||
else fontSizeDown()
|
||||
}
|
||||
}
|
||||
|
||||
// 全屏
|
||||
async function toggleFullscreen() {
|
||||
if (!viewerRef.value) return
|
||||
if (isFullscreen.value) {
|
||||
try {
|
||||
await document.exitFullscreen()
|
||||
} catch {}
|
||||
isFullscreen.value = false
|
||||
} else {
|
||||
try {
|
||||
await viewerRef.value.requestFullscreen()
|
||||
isFullscreen.value = true
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
function onFullscreenChange() {
|
||||
isFullscreen.value = !!document.fullscreenElement
|
||||
}
|
||||
|
||||
// 监听全屏变化
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('fullscreenchange', onFullscreenChange)
|
||||
}
|
||||
|
||||
const running = ref(false)
|
||||
const runOutput = ref(null) // { text: string, isError: boolean }
|
||||
const outputCollapsed = ref(false)
|
||||
|
||||
async function runCode() {
|
||||
if (!codeContent.value) return
|
||||
running.value = true
|
||||
runOutput.value = null
|
||||
outputCollapsed.value = false
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/run-c', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code: codeContent.value })
|
||||
})
|
||||
const data = await res.json()
|
||||
runOutput.value = {
|
||||
text: data.error || data.hint
|
||||
? `⚠️ ${data.error || '未知错误'}\n${data.hint || ''}\n${data.installGuide || ''}`
|
||||
: data.output,
|
||||
isError: data.isError || !!data.error
|
||||
}
|
||||
} catch (e) {
|
||||
runOutput.value = {
|
||||
text: `❌ 无法连接到运行服务\n请确认后端服务已启动 (npm run server)`,
|
||||
isError: true
|
||||
}
|
||||
} finally {
|
||||
running.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function copyCode() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(codeContent.value)
|
||||
copied.value = true
|
||||
setTimeout(() => { copied.value = false }, 2000)
|
||||
} catch {
|
||||
// fallback
|
||||
const textarea = document.createElement('textarea')
|
||||
textarea.value = codeContent.value
|
||||
document.body.appendChild(textarea)
|
||||
@@ -127,7 +253,7 @@ async function copyCode() {
|
||||
.toolbar-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.file-desc-tip {
|
||||
@@ -135,36 +261,176 @@ async function copyCode() {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.copy-btn {
|
||||
/* 字型控制 */
|
||||
.font-size-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 0 6px;
|
||||
border-right: 1px solid var(--border-color);
|
||||
border-left: 1px solid var(--border-color);
|
||||
margin: 0 4px;
|
||||
}
|
||||
|
||||
.font-size-value {
|
||||
font-size: 11px;
|
||||
font-family: var(--mono);
|
||||
color: var(--text-tertiary);
|
||||
min-width: 28px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* 通用工具栏按钮 */
|
||||
.tool-btn {
|
||||
background: var(--hover-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
padding: 4px 10px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
transition: all 0.2s;
|
||||
font-size: 13px;
|
||||
transition: all 0.15s;
|
||||
line-height: 1;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.copy-btn:hover {
|
||||
.tool-btn:hover {
|
||||
background: var(--active-bg);
|
||||
color: var(--text-primary);
|
||||
border-color: var(--primary-color);
|
||||
}
|
||||
|
||||
.reset-btn {
|
||||
font-size: 14px;
|
||||
padding: 4px 6px;
|
||||
}
|
||||
|
||||
/* 代码内容区域 */
|
||||
.code-content {
|
||||
position: relative;
|
||||
overflow-x: auto;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.code-content pre {
|
||||
padding: 16px;
|
||||
padding: 16px 20px;
|
||||
margin: 0;
|
||||
font-family: 'Fira Code', 'JetBrains Mono', 'Consolas', monospace;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
line-height: 22px;
|
||||
color: var(--code-text);
|
||||
text-align: left;
|
||||
white-space: pre;
|
||||
tab-size: 4;
|
||||
}
|
||||
|
||||
.code-content code {
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
/* 全屏模式 */
|
||||
.code-viewer.fullscreen {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 9999;
|
||||
border-radius: 0;
|
||||
background: var(--code-bg);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.code-viewer.fullscreen .code-content {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.code-viewer.fullscreen .code-content pre {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
/* 运行按钮 */
|
||||
.run-btn {
|
||||
background: #22c55e;
|
||||
color: white;
|
||||
border-color: #22c55e;
|
||||
font-weight: 600;
|
||||
padding: 4px 12px;
|
||||
}
|
||||
|
||||
.run-btn:hover:not(:disabled) {
|
||||
background: #16a34a;
|
||||
border-color: #16a34a;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.run-btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
/* 运行输出面板 */
|
||||
.run-output {
|
||||
border-top: 1px solid var(--border-color);
|
||||
background: #1a1a2e;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.run-output.collapsed .output-body {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.output-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
background: rgba(255,255,255,0.03);
|
||||
}
|
||||
|
||||
.output-title {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: #e2e8f0;
|
||||
}
|
||||
|
||||
.output-toggle {
|
||||
font-size: 11px;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: #94a3b8;
|
||||
padding: 2px 6px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.close-btn:hover {
|
||||
color: #ef4444;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.output-body {
|
||||
max-height: 300px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.output-body pre {
|
||||
margin: 0;
|
||||
padding: 12px 16px;
|
||||
font-family: 'Fira Code', 'Consolas', monospace;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: #e2e8f0;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.output-body pre.error-text {
|
||||
color: #fca5a5;
|
||||
}
|
||||
|
||||
.loading-overlay,
|
||||
|
||||
+134
-25
@@ -16,40 +16,149 @@ export async function loadCodeFile(path) {
|
||||
}
|
||||
|
||||
/**
|
||||
* C语言关键字高亮
|
||||
* C语言关键字高亮(基于 Token 的稳健实现)
|
||||
* 逐字符解析,避免正则误匹配已插入的 HTML 标签
|
||||
*/
|
||||
export function highlightC(code) {
|
||||
const keywords = [
|
||||
const keywords = new Set([
|
||||
'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
|
||||
'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if',
|
||||
'int', 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static',
|
||||
'struct', 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while',
|
||||
'include', 'define', 'ifdef', 'ifndef', 'endif', 'main', 'printf', 'scanf'
|
||||
]
|
||||
])
|
||||
|
||||
// 先转义 HTML
|
||||
let escaped = code
|
||||
let result = ''
|
||||
let i = 0
|
||||
const len = code.length
|
||||
|
||||
while (i < len) {
|
||||
// 预处理指令(行首 #)
|
||||
if (code[i] === '#' && (i === 0 || code[i - 1] === '\n')) {
|
||||
let end = i + 1
|
||||
while (end < len && code[end] !== '\n') end++
|
||||
const line = code.slice(i, end)
|
||||
result += '<span class="hl-preprocessor">' + escapeHtml(line) + '</span>'
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
|
||||
// 单行注释 //
|
||||
if (code[i] === '/' && i + 1 < len && code[i + 1] === '/') {
|
||||
let end = i + 2
|
||||
while (end < len && code[end] !== '\n') end++
|
||||
result += '<span class="hl-comment">' + escapeHtml(code.slice(i, end)) + '</span>'
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
|
||||
// 多行注释 /* */
|
||||
if (code[i] === '/' && i + 1 < len && code[i + 1] === '*') {
|
||||
let end = i + 2
|
||||
while (end + 1 < len && !(code[end] === '*' && code[end + 1] === '/')) end++
|
||||
if (end + 1 < len) end += 2
|
||||
result += '<span class="hl-comment">' + escapeHtml(code.slice(i, end)) + '</span>'
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
|
||||
// 双引号字符串 "..."
|
||||
if (code[i] === '"') {
|
||||
let end = i + 1
|
||||
while (end < len && code[end] !== '"') {
|
||||
if (code[end] === '\\') end++ // 跳过转义字符
|
||||
end++
|
||||
}
|
||||
if (end < len) end++ // 包含结束引号
|
||||
result += '<span class="hl-string">' + escapeHtml(code.slice(i, end)) + '</span>'
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
|
||||
// 单引号字符 '...'
|
||||
if (code[i] === "'") {
|
||||
let end = i + 1
|
||||
while (end < len && code[end] !== "'") {
|
||||
if (code[end] === '\\') end++
|
||||
end++
|
||||
}
|
||||
if (end < len) end++
|
||||
result += '<span class="hl-string">' + escapeHtml(code.slice(i, end)) + '</span>'
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
|
||||
// 数字(整数/浮点数)
|
||||
if (isDigit(code[i]) || (code[i] === '.' && i + 1 < len && isDigit(code[i + 1]))) {
|
||||
let start = i
|
||||
if (code[i] === '0' && i + 1 < len && (code[i + 1] === 'x' || code[i + 1] === 'X')) {
|
||||
// 十六进制
|
||||
i += 2
|
||||
while (i < len && isHexDigit(code[i])) i++
|
||||
} else {
|
||||
while (i < len && isDigit(code[i])) i++
|
||||
if (i < len && code[i] === '.') {
|
||||
i++
|
||||
while (i < len && isDigit(code[i])) i++
|
||||
}
|
||||
if (i < len && (code[i] === 'e' || code[i] === 'E')) {
|
||||
i++
|
||||
if (i < len && (code[i] === '+' || code[i] === '-')) i++
|
||||
while (i < len && isDigit(code[i])) i++
|
||||
}
|
||||
}
|
||||
// 确保不是标识符的一部分
|
||||
if (i < len && isWordChar(code[i])) {
|
||||
// 回退,按普通文本处理
|
||||
i = start
|
||||
result += escapeHtml(code[i])
|
||||
i++
|
||||
} else {
|
||||
result += '<span class="hl-number">' + escapeHtml(code.slice(start, i)) + '</span>'
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 标识符/关键字
|
||||
if (isWordStart(code[i])) {
|
||||
let start = i
|
||||
while (i < len && isWordChar(code[i])) i++
|
||||
const word = code.slice(start, i)
|
||||
if (keywords.has(word)) {
|
||||
result += '<span class="hl-keyword">' + escapeHtml(word) + '</span>'
|
||||
} else {
|
||||
result += escapeHtml(word)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 其他字符
|
||||
result += escapeHtml(code[i])
|
||||
i++
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
function escapeHtml(str) {
|
||||
return str
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
|
||||
// 关键字高亮
|
||||
const keywordPattern = new RegExp(`\\b(${keywords.join('|')})\\b`, 'g')
|
||||
escaped = escaped.replace(keywordPattern, '<span class="hl-keyword">$1</span>')
|
||||
|
||||
// 注释高亮 (// 和 /* */)
|
||||
escaped = escaped.replace(/(\/\/.*)/g, '<span class="hl-comment">$1</span>')
|
||||
escaped = escaped.replace(/(\/\*[\s\S]*?\*\/)/g, '<span class="hl-comment">$1</span>')
|
||||
|
||||
// 字符串高亮
|
||||
escaped = escaped.replace(/"([^"\\]*(\\.[^"\\]*)*)"/g, '<span class="hl-string">"$1"</span>')
|
||||
escaped = escaped.replace(/'([^'\\]*(\\.[^'\\]*)*)'/g, '<span class="hl-string">\'$1\'</span>')
|
||||
|
||||
// 数字高亮
|
||||
escaped = escaped.replace(/\b(\d+\.?\d*)\b/g, '<span class="hl-number">$1</span>')
|
||||
|
||||
// 预处理指令高亮
|
||||
escaped = escaped.replace(/(^#\s*\w+.*)/gm, '<span class="hl-preprocessor">$1</span>')
|
||||
|
||||
return escaped
|
||||
}
|
||||
|
||||
function isDigit(c) {
|
||||
return c >= '0' && c <= '9'
|
||||
}
|
||||
|
||||
function isHexDigit(c) {
|
||||
return isDigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
|
||||
}
|
||||
|
||||
function isWordStart(c) {
|
||||
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c === '_'
|
||||
}
|
||||
|
||||
function isWordChar(c) {
|
||||
return isWordStart(c) || isDigit(c)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,14 @@ import vue from '@vitejs/plugin-vue'
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3001',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
globals: true,
|
||||
|
||||
Reference in New Issue
Block a user