refactor: 在旧的PhyExp基础上进行重构,采用了monorepo结构,分为frontend和backend两个子项目

这个提交包含在:
2026-05-23 18:15:31 +08:00
当前提交 41813abe48
共有 87 个文件被更改,包括 13257 次插入 和 0 次删除

查看文件

@ -0,0 +1,472 @@
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { streamChat, extractJsonBlock, safeParseJson, type ChatMessage as ApiChatMessage } from '@/utils/aiClient'
import { renderMarkdownWithLatex } from '@/utils/markdown'
import { useDraggable } from '@/composables/useDraggable'
const props = defineProps<{
isOpen: boolean
courseContent?: string
glossaryContent?: string
floating?: boolean
cellContext?: string
inspectActive?: boolean
onToggleInspect?: () => void
onClearCellContext?: () => void
}>()
const emit = defineEmits(['close'])
type ChatMessage = {
id: number
text: string
sender: 'user' | 'ai'
html?: string
raw?: string
status?: 'streaming' | 'done' | 'error'
}
const messages = ref<ChatMessage[]>([
{ id: 1, text: '你好!我是AI助教,有什么可以帮助你的吗?', sender: 'ai', status: 'done' },
])
const newMessage = ref('')
const sending = ref(false)
const errorText = ref('')
const panelRef = ref<HTMLElement | null>(null)
const isFloatingDisabled = computed(() => !props.floating)
const { style: floatingStyle, onPointerDown } = useDraggable(panelRef, {
initialX: window.innerWidth - 420,
initialY: 60,
boundary: 'window',
handleSelector: '.chat-header',
disabled: isFloatingDisabled,
})
const panelStyle = computed(() => {
if (props.floating) {
return floatingStyle.value
}
return {}
})
const truncateText = (text: string, maxLength: number) => {
if (text.length <= maxLength) return text
return `${text.slice(0, maxLength)}...`
}
const buildContext = () => {
const parts: string[] = []
if (props.courseContent) {
parts.push(`【预习材料】\n${truncateText(props.courseContent, 2000)}`)
}
if (props.glossaryContent) {
parts.push(`【术语表】\n${truncateText(props.glossaryContent, 2000)}`)
}
if (props.cellContext) {
parts.push(`【选中的单元格信息】\n${props.cellContext}`)
}
return parts.join('\n\n')
}
const buildUserContent = (question: string) => {
const context = buildContext()
const instruction = '请用中文、语气严谨但鼓励的方式回答。'
if (context) {
return `${instruction}\n${context}\n\n学生问题:${question}`
}
return `${instruction}\n学生问题:${question}`
}
const buildHistory = (): ApiChatMessage[] => {
return messages.value
.filter((message) => message.status !== 'streaming')
.map((message) => ({
role: (message.sender === 'user' ? 'user' : 'assistant') as ApiChatMessage['role'],
content: message.raw || message.text,
}))
}
const formatQaResponse = (rawText: string) => {
const jsonBlock = extractJsonBlock(rawText)
if (jsonBlock) {
const parsed = safeParseJson<Record<string, any>>(jsonBlock)
if (parsed.value) {
const payload = parsed.value
const sections: string[] = []
if (payload.core_concept) {
sections.push(`**核心概念**:${payload.core_concept}`)
}
if (payload.direct_answer) {
sections.push(`**直接回答**:${payload.direct_answer}`)
}
if (payload.understanding) {
sections.push(`**理解提示**:${payload.understanding}`)
}
if (payload.deep_dive) {
sections.push(`**深入说明**:${payload.deep_dive}`)
}
if (Array.isArray(payload.practical_tips) && payload.practical_tips.length > 0) {
const tips = payload.practical_tips.map((item: string) => `- ${item}`).join('\n')
sections.push(`**实验提示**\n${tips}`)
}
if (Array.isArray(payload.self_check_questions) && payload.self_check_questions.length > 0) {
const checks = payload.self_check_questions
.map((item: { question?: string; hint?: string }, index: number) => {
const q = item.question || `自检问题 ${index + 1}`
const hint = item.hint ? `(提示:${item.hint})` : ''
return `- ${q}${hint}`
})
.join('\n')
sections.push(`**自检问题**\n${checks}`)
}
const markdown = sections.join('\n\n') || '已收到AI回复,但内容为空。'
return { html: renderMarkdownWithLatex(markdown), text: markdown, raw: rawText }
}
}
return { html: renderMarkdownWithLatex(rawText), text: rawText || 'AI未返回可解析的内容。', raw: rawText }
}
const sendMessage = () => {
const trimmed = newMessage.value.trim()
if (!trimmed || sending.value) return
errorText.value = ''
const history = buildHistory()
messages.value.push({ id: Date.now(), text: trimmed, sender: 'user' })
newMessage.value = ''
sending.value = true
const aiMessage: ChatMessage = {
id: Date.now() + 1,
text: 'AI正在输入...',
sender: 'ai',
status: 'streaming',
}
messages.value.push(aiMessage)
const aiIndex = messages.value.length - 1
const userContent = buildUserContent(trimmed)
const requestMessages: ApiChatMessage[] = [...history, { role: 'user' as const, content: userContent }]
streamChat(
{
teacherType: 'question',
messages: requestMessages,
stream: true,
},
(_token, fullText) => {
const target = messages.value[aiIndex]
if (target) {
target.text = fullText
}
},
)
.then((fullText) => {
const target = messages.value[aiIndex]
if (!target) return
const formatted = formatQaResponse(fullText)
target.text = formatted.text
target.html = formatted.html
target.raw = formatted.raw
target.status = 'done'
})
.catch((error) => {
const target = messages.value[aiIndex]
if (target) {
target.text = 'AI请求失败,请稍后重试。'
target.status = 'error'
}
errorText.value = error instanceof Error ? error.message : 'AI请求失败'
})
.finally(() => {
sending.value = false
})
}
watch(() => props.isOpen, (newVal) => {
if (newVal) {}
})
</script>
<template>
<div
v-show="!floating || isOpen"
ref="panelRef"
class="chat-sidebar"
:class="{ open: isOpen, floating: floating }"
:style="panelStyle"
@pointerdown="onPointerDown"
>
<div class="chat-header">
<h3>AI 助教</h3>
<div class="chat-header-actions">
<button
v-if="onToggleInspect"
class="inspect-btn"
:class="{ active: inspectActive }"
@pointerdown.stop
@click="onToggleInspect()"
:title="inspectActive ? '退出单元格选择' : '选择实验表格单元格'"
>
{{ inspectActive ? '退出选择' : '🔍 单元格' }}
</button>
<button class="close-btn" @pointerdown.stop @click="$emit('close')">&times;</button>
</div>
</div>
<div v-if="cellContext" class="cell-context-bar">
<div class="cell-context-header">
<span class="cell-context-label">已选中单元格:</span>
<button
v-if="onClearCellContext"
class="context-clear-btn"
@click="onClearCellContext()"
>
&times;
</button>
</div>
<pre class="cell-context-text">{{ cellContext }}</pre>
</div>
<div class="chat-messages">
<div v-if="errorText" class="chat-error">{{ errorText }}</div>
<div v-if="inspectActive" class="inspect-hint">
🔍 点击实验表格中的任意单元格将其信息添加到AI上下文
</div>
<div
v-for="message in messages"
:key="message.id"
class="message"
:class="[message.sender]"
>
<div
v-if="message.sender === 'ai' && message.html && message.status === 'done'"
v-html="message.html"
></div>
<div v-else>{{ message.text }}</div>
</div>
</div>
<div class="chat-input">
<input
v-model="newMessage"
@keyup.enter="sendMessage"
placeholder="输入你的问题..."
:disabled="sending"
/>
<button @click="sendMessage" :disabled="sending">发送</button>
</div>
</div>
</template>
<style scoped>
.chat-sidebar {
position: fixed;
right: -400px;
top: 0;
width: 380px;
height: 100%;
background-color: white;
box-shadow: -5px 0 15px rgba(0, 0, 0, 0.1);
transition: right 0.4s ease-in-out;
display: flex;
flex-direction: column;
z-index: 1001;
}
.chat-sidebar.open {
right: 0;
}
.chat-sidebar.floating {
right: auto;
top: auto;
height: 520px;
border-radius: 12px;
overflow: hidden;
transition: none;
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.2);
}
.chat-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.8rem 1.2rem;
background-color: #007bff;
color: white;
}
.chat-header h3 {
margin: 0;
font-size: 1.1rem;
}
.chat-header-actions {
display: flex;
align-items: center;
gap: 6px;
}
.chat-sidebar.floating .chat-header {
cursor: grab;
user-select: none;
}
.chat-sidebar.floating .chat-header:active {
cursor: grabbing;
}
.inspect-btn {
background: rgba(255,255,255,0.25);
border: 1px solid rgba(255,255,255,0.5);
color: white;
padding: 3px 10px;
border-radius: 14px;
cursor: pointer;
font-size: 0.8rem;
font-weight: 600;
white-space: nowrap;
transition: background 0.2s;
}
.inspect-btn:hover {
background: rgba(255,255,255,0.4);
}
.inspect-btn.active {
background: rgba(255,255,255,0.5);
border-color: white;
}
.close-btn {
background: none;
border: none;
color: white;
font-size: 1.6rem;
cursor: pointer;
padding: 0;
line-height: 1;
}
.cell-context-bar {
background: #e8f5e9;
border-bottom: 1px solid #c8e6c9;
padding: 0.5rem 0.8rem;
max-height: 140px;
overflow-y: auto;
}
.cell-context-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 4px;
}
.cell-context-label {
font-size: 0.75rem;
font-weight: 600;
color: #2e7d32;
}
.context-clear-btn {
background: none;
border: none;
color: #888;
font-size: 1.2rem;
cursor: pointer;
padding: 0 4px;
line-height: 1;
}
.context-clear-btn:hover {
color: #333;
}
.cell-context-text {
margin: 0;
font-size: 0.75rem;
color: #333;
white-space: pre-wrap;
font-family: monospace;
}
.inspect-hint {
background: #e3f2fd;
color: #1565c0;
padding: 0.5rem 0.8rem;
border-radius: 8px;
font-size: 0.8rem;
text-align: center;
}
.chat-messages {
flex-grow: 1;
padding: 1rem;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 0.8rem;
}
.chat-error {
background-color: #fff1f0;
color: #c71d1d;
border: 1px solid #ffd5d5;
padding: 0.6rem 0.8rem;
border-radius: 8px;
font-size: 0.9rem;
}
.message {
padding: 0.8rem 1rem;
border-radius: 10px;
max-width: 85%;
word-wrap: break-word;
}
.message.ai {
background-color: #f1f1f1;
align-self: flex-start;
}
.message.user {
background-color: #dcf8c6;
align-self: flex-end;
}
.chat-input {
display: flex;
padding: 1rem;
border-top: 1px solid #eee;
}
.chat-input input {
flex-grow: 1;
border: 1px solid #ddd;
border-radius: 20px;
padding: 0.8rem 1rem;
margin-right: 0.5rem;
}
.chat-input button {
background-color: #007bff;
color: white;
border: none;
border-radius: 20px;
padding: 0.8rem 1.2rem;
cursor: pointer;
font-weight: 600;
}
.chat-input button:hover {
background-color: #0056b3;
}
</style>

查看文件

@ -0,0 +1,457 @@
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useDraggable } from '@/composables/useDraggable'
import { aiLogs, clearAiLogs, getBaseUrl, setBaseUrl, type AiLogEntry } from '@/utils/aiClient'
const isVisible = ref(false)
const panelRef = ref<HTMLElement | null>(null)
const debugEnabled = ref(false)
const { style: panelStyle, onPointerDown } = useDraggable(panelRef, {
initialX: 100,
initialY: 100,
boundary: 'window',
handleSelector: '.debug-header',
})
type DebugExperience = {
id: string
title: string
author: string
image: string
}
const experiences = ref<DebugExperience[]>([])
const skipStageCheck = ref(false)
const aiProviderUrl = ref(getBaseUrl() || '')
const aiLogExpanded = ref<number | null>(null)
watch(skipStageCheck, (val) => {
;(window as any).__DEBUG_SKIP_STAGE__ = val
})
const saveAiProvider = () => {
const trimmed = aiProviderUrl.value.trim()
setBaseUrl(trimmed || null)
}
const loadExperiences = async () => {
try {
const response = await fetch('/src/assets/experiences.json')
if (!response.ok) return
const data = await response.json()
if (data?.experiences) {
experiences.value = Object.values(data.experiences) as DebugExperience[]
}
} catch {
try {
const response = await fetch('/assets/experiences.json')
if (!response.ok) return
const data = await response.json()
if (data?.experiences) {
experiences.value = Object.values(data.experiences) as DebugExperience[]
}
} catch {
experiences.value = []
}
}
}
const togglePanel = () => {
if (!isVisible.value) {
loadExperiences()
aiProviderUrl.value = getBaseUrl() || ''
}
isVisible.value = !isVisible.value
}
const toggleLogExpand = (id: number) => {
aiLogExpanded.value = aiLogExpanded.value === id ? null : id
}
const formatLogPreview = (entry: AiLogEntry): string => {
if (entry.type === 'error') return entry.error || 'Unknown error'
if (entry.type === 'request') return (entry.payload || '').slice(0, 100)
return (entry.body || '').slice(0, 100)
}
const formatTime = (ts: number): string => {
const d = new Date(ts)
return `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`
}
onMounted(() => {
debugEnabled.value = localStorage.getItem('DEBUG') === 'true'
skipStageCheck.value = !!(window as any).__DEBUG_SKIP_STAGE__
if (debugEnabled.value) {
loadExperiences()
}
})
const navToExperience = (id: string) => {
window.location.hash = `#/exp?expid=${encodeURIComponent(id)}`
}
</script>
<template>
<div v-if="debugEnabled">
<button
v-if="!isVisible"
class="debug-trigger"
@click="togglePanel"
>
🔧 调试
</button>
<div
ref="panelRef"
v-show="isVisible"
class="debug-panel"
:style="panelStyle"
@pointerdown="onPointerDown"
>
<div class="debug-header">
<span>调试面板</span>
<button class="debug-close" @click="isVisible = false">&times;</button>
</div>
<div class="debug-body">
<div class="debug-section">
<h4>实验导航</h4>
<label class="debug-checkbox">
<input type="checkbox" v-model="skipStageCheck" />
跳过阶段限制(无视 skipable)
</label>
<div v-if="experiences.length === 0" class="debug-empty">暂无实验项目</div>
<div
v-for="exp in experiences"
:key="exp.id"
class="debug-item"
@click="navToExperience(exp.id)"
>
<div class="debug-item-title">{{ exp.title }}</div>
<div class="debug-item-id">{{ exp.id }}</div>
</div>
</div>
<div class="debug-section">
<h4>AI 设置</h4>
<div class="debug-field">
<label>Provider URL</label>
<div class="debug-input-row">
<input
v-model="aiProviderUrl"
placeholder="例如 http://localhost:8000"
class="debug-input"
/>
<button class="debug-btn debug-btn-sm" @click="saveAiProvider">保存</button>
</div>
</div>
<div class="debug-ai-logs">
<div class="debug-logs-header">
<span>AI 请求/响应日志({{ aiLogs.length }})</span>
<button v-if="aiLogs.length" class="debug-btn debug-btn-sm" @click="clearAiLogs">清空</button>
</div>
<div v-if="aiLogs.length === 0" class="debug-empty">暂无日志</div>
<div
v-for="entry in aiLogs"
:key="entry.id"
class="debug-log-entry"
:class="entry.type"
>
<div class="debug-log-summary" @click="toggleLogExpand(entry.id)">
<span class="debug-log-badge">{{ entry.type === 'error' ? '❌' : entry.type === 'request' ? '📤' : '📥' }}</span>
<span class="debug-log-type">{{ entry.teacherType }}</span>
<span class="debug-log-time">{{ formatTime(entry.timestamp) }}</span>
<span class="debug-log-preview">{{ formatLogPreview(entry) }}</span>
</div>
<div v-if="aiLogExpanded === entry.id" class="debug-log-detail">
<div class="debug-log-meta">端点: {{ entry.endpoint }}</div>
<div v-if="entry.status" class="debug-log-meta">状态: {{ entry.status }}</div>
<pre class="debug-log-body">{{ entry.payload || entry.body || entry.error }}</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.debug-trigger {
position: fixed;
left: 1rem;
bottom: 1rem;
z-index: 9999;
background: #6c757d;
color: white;
border: none;
border-radius: 50px;
padding: 0.6rem 1.2rem;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
transition: all 0.2s ease;
}
.debug-trigger:hover {
background: #5a6268;
transform: scale(1.05);
}
.debug-panel {
position: fixed;
width: 380px;
max-height: 550px;
background: white;
border-radius: 12px;
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.2);
z-index: 10000;
display: flex;
flex-direction: column;
overflow: hidden;
}
.debug-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.75rem 1rem;
background: #343a40;
color: white;
font-weight: 600;
cursor: grab;
user-select: none;
flex-shrink: 0;
}
.debug-header:active {
cursor: grabbing;
}
.debug-close {
background: none;
border: none;
color: white;
font-size: 1.5rem;
cursor: pointer;
padding: 0;
line-height: 1;
}
.debug-body {
padding: 0.75rem 1rem;
overflow-y: auto;
flex: 1;
}
.debug-section {
margin-bottom: 1rem;
}
.debug-section h4 {
margin: 0 0 0.5rem 0;
font-size: 0.9rem;
color: #333;
font-weight: 700;
border-bottom: 1px solid #eee;
padding-bottom: 0.3rem;
}
.debug-checkbox {
display: flex;
align-items: center;
gap: 0.4rem;
font-size: 0.85rem;
color: #555;
margin-bottom: 0.5rem;
cursor: pointer;
}
.debug-checkbox input {
margin: 0;
}
.debug-empty {
color: #999;
font-size: 0.85rem;
padding: 0.5rem 0;
}
.debug-item {
padding: 0.6rem 0.75rem;
border: 1px solid #e9ecef;
border-radius: 8px;
margin-bottom: 0.4rem;
cursor: pointer;
transition: all 0.15s ease;
}
.debug-item:hover {
background: #f8f9fa;
border-color: #007bff;
}
.debug-item-title {
font-weight: 600;
font-size: 0.9rem;
color: #333;
}
.debug-item-id {
font-size: 0.75rem;
color: #888;
margin-top: 0.15rem;
}
.debug-field {
margin-bottom: 0.6rem;
}
.debug-field label {
display: block;
font-size: 0.8rem;
color: #666;
margin-bottom: 0.25rem;
font-weight: 600;
}
.debug-input-row {
display: flex;
gap: 0.4rem;
}
.debug-input {
flex: 1;
padding: 0.35rem 0.5rem;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 0.85rem;
outline: none;
}
.debug-input:focus {
border-color: #007bff;
}
.debug-btn {
background: #007bff;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
font-weight: 600;
transition: background 0.15s ease;
}
.debug-btn:hover {
background: #0056b3;
}
.debug-btn-sm {
padding: 0.35rem 0.6rem;
font-size: 0.8rem;
}
.debug-ai-logs {
margin-top: 0.75rem;
}
.debug-logs-header {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.8rem;
color: #666;
font-weight: 600;
margin-bottom: 0.4rem;
}
.debug-log-entry {
border: 1px solid #eee;
border-radius: 6px;
margin-bottom: 0.3rem;
overflow: hidden;
font-size: 0.78rem;
}
.debug-log-entry.request {
border-left: 3px solid #007bff;
}
.debug-log-entry.response {
border-left: 3px solid #28a745;
}
.debug-log-entry.error {
border-left: 3px solid #dc3545;
}
.debug-log-summary {
display: flex;
align-items: center;
gap: 0.4rem;
padding: 0.35rem 0.5rem;
cursor: pointer;
background: #fafafa;
}
.debug-log-summary:hover {
background: #f0f0f0;
}
.debug-log-badge {
font-size: 0.75rem;
flex-shrink: 0;
}
.debug-log-type {
font-weight: 600;
color: #333;
flex-shrink: 0;
}
.debug-log-time {
color: #999;
font-size: 0.7rem;
flex-shrink: 0;
}
.debug-log-preview {
color: #888;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
}
.debug-log-detail {
padding: 0.4rem 0.5rem;
background: #f8f9fa;
border-top: 1px solid #eee;
}
.debug-log-meta {
font-size: 0.75rem;
color: #666;
margin-bottom: 0.2rem;
}
.debug-log-body {
margin: 0;
font-size: 0.75rem;
white-space: pre-wrap;
word-break: break-all;
max-height: 160px;
overflow-y: auto;
background: #fff;
border: 1px solid #eee;
border-radius: 4px;
padding: 0.4rem;
color: #333;
}
</style>

查看文件

@ -0,0 +1,441 @@
<script lang="ts">
import { defineComponent, type PropType } from 'vue'
import { type QuestionType } from '@/types/question'
type answerStatus = 'right' | 'wrong' | 'part' | 'blank' | 'waiting'
export default defineComponent({
props: {
question: {
type: Object as PropType<QuestionType>,
required: true,
},
doAnswer: {
type: Function as any,
required: false,
},
},
data() {
return {
choice: '', // 单选
choices: [] as number[], // 多选
answers: [] as string[], // 填空
answer: '', // 简答
enabled: true, // 是否可编辑
corret: null as boolean | null, // 正确
optionStatus: [] as Array<'correct' | 'wrong' | ''>, // 每个选项的状态
fillStatuses: [] as Array<boolean>, // 每个填空的状态
essayStatus: { isCorrect: null as boolean | null, correctAnswer: '' }, // 简答题状态
}
},
methods: {
calc(): [number, answerStatus] {
this.enabled = false
let score = 0
let fullScore = 0
let status: answerStatus = 'wrong'
switch (this.question.type) {
case '单选题': {
fullScore = 10
const correctAnswer = this.question.answer
const userChoice = this.choice
const isCorrect = userChoice !== '' && Number(userChoice) === correctAnswer
score = isCorrect ? fullScore : 0
this.corret = isCorrect
status = isCorrect ? 'right' : 'wrong'
// 设置每个选项的样式标记
const choicesLen = this.question.choices.length
const statuses = new Array(choicesLen).fill('') as Array<'correct' | 'wrong' | ''>
// 正确选项永远标绿
statuses[correctAnswer] = 'correct'
// 如果用户选错,把用户选的选项标红
if (!isCorrect && userChoice !== '') {
statuses[Number(userChoice)] = 'wrong'
}
this.optionStatus = statuses
break
}
case '多选题': {
fullScore = 12
const correctAnswers: number[] = this.question.answer
const userChoices: number[] = this.choices
const correctSet = new Set(correctAnswers)
const userSet = new Set(userChoices)
let hasWrong = false
for (const choice of userChoices) {
if (!correctSet.has(choice)) {
hasWrong = true
break
}
}
if (hasWrong) {
// 多选(选择了错误选项)得0分
score = 0
this.corret = false
status = 'wrong'
} else {
// 只有正确选项(可能少选)
const unitScore = fullScore / correctAnswers.length
let correctSelectedCount = 0
for (const ans of correctAnswers) {
if (userSet.has(ans)) correctSelectedCount++
}
score = correctSelectedCount * unitScore
score = Math.round(score * 100) / 100
this.corret = score === fullScore
status = this.corret ? 'right' : score == 0 ? 'wrong' : 'part'
}
// 设置每个选项的样式标记(正确选项标绿,错误选项标红)
const totalOptions = this.question.choices.length
const statuses = new Array(totalOptions).fill('') as Array<'correct' | 'wrong' | ''>
for (let i = 0; i < totalOptions; i++) {
if (correctSet.has(i)) {
statuses[i] = 'correct' // 正确答案永远标绿
} else if (userSet.has(i) && !correctSet.has(i)) {
statuses[i] = 'wrong' // 用户错误选择的选项标红
}
}
this.optionStatus = statuses
break
}
case '填空题': {
const standardAnswer = this.question.answer
const userAnswer = this.answers
let fullScore = standardAnswer.length * 5
for (const i in standardAnswer) {
let right = standardAnswer[i]?.trim() == userAnswer[i]?.trim()
this.fillStatuses[i] = right
score += right ? 5 : 0
}
status = fullScore == score ? 'right' : score == 0 ? 'wrong' : 'part'
break
}
case '简答题': {
const hasAnswer = this.answer.trim().length > 0
this.essayStatus = {
isCorrect: hasAnswer ? null : false,
correctAnswer: '',
}
status = hasAnswer ? 'waiting' : 'blank'
break
}
}
return [score, status]
},
getAnswer() {
switch (this.question.type) {
case '单选题':
return this.choice
case '多选题':
return this.choices
case '填空题':
return this.answers
case '简答题':
return this.answer
default:
return null
}
},
},
})
</script>
<template>
<div class="QuestionArea" @focusin="doAnswer">
<!-- 题目头部:包含题型标签 + 题目文本 -->
<div class="question-header">
<span class="question-type-tag">{{ question.type }}</span>
<span
class="question-text"
:class="{
'text-green-600': corret === true,
'text-red-600': corret === false
}"
>
{{ question.question }}
</span>
</div>
<!-- 单选题 -->
<div class="options-group" v-if="question.type === '单选题'">
<div
class="option-item"
v-for="(c, i) in question.choices"
:key="i"
>
<label class="option-label">
<input
type="radio"
v-model="choice"
:value="i"
:disabled="!enabled"
class="option-radio"
/>
<span
class="option-content"
:class="{
'correct-option': optionStatus[i] === 'correct',
'wrong-option': optionStatus[i] === 'wrong',
}"
>
{{ c }}
</span>
</label>
</div>
</div>
<!-- 多选题 -->
<div class="options-group" v-if="question.type === '多选题'">
<div
class="option-item"
v-for="(c, i) in question.choices"
:key="i"
>
<label class="option-label">
<input
type="checkbox"
v-model="choices"
:value="i"
:disabled="!enabled"
class="option-checkbox"
/>
<span
class="option-content"
:class="{
'correct-option': optionStatus[i] === 'correct',
'wrong-option': optionStatus[i] === 'wrong',
}"
>
{{ c }}
</span>
</label>
</div>
</div>
<!-- 填空题 -->
<div class="fill-group" v-if="question.type === '填空题'">
<div class="fill-item" v-for="(c, i) in question.answer" :key="i">
<span class="fill-label">({{ i + 1 }})</span>
<input
type="text"
v-model="answers[i]"
:disabled="!enabled"
class="fill-input"
:class="{
'correct-input': fillStatuses[i] == true,
'wrong-input': fillStatuses[i] == false,
}"
/>
<!-- 错误时显示正确答案(绿色) -->
<span v-if="fillStatuses[i] == false" class="correct-hint">
(正确答案:{{ question.answer[i] }})
</span>
</div>
</div>
<!-- 简答题 -->
<div class="essay-group" v-if="question.type === '简答题'">
<textarea
v-model="answer"
:disabled="!enabled"
class="essay-textarea"
:class="{
'correct-input': essayStatus.isCorrect === true,
'wrong-input': essayStatus.isCorrect === false && !enabled,
}"
placeholder="请输入你的答案..."
></textarea>
<!-- 错误时显示正确答案(绿色) -->
<div
v-if="essayStatus.isCorrect === false && !enabled && essayStatus.correctAnswer"
class="correct-hint essay-hint"
>
参考答案:{{ essayStatus.correctAnswer }}
</div>
</div>
</div>
</template>
<style scoped>
/* 基础容器样式 */
.QuestionArea {
border: 1px solid #e5e7eb;
border-radius: 12px;
padding: 24px;
margin-bottom: 20px;
background-color: #ffffff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
transition: all 0.3s ease;
}
.QuestionArea:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
transform: translateY(-2px);
}
/* 题目头部样式 */
.question-header {
display: flex;
align-items: flex-start;
margin-bottom: 20px;
gap: 12px;
}
.question-type-tag {
background-color: #007bff;
color: white;
padding: 4px 10px;
border-radius: 15px;
font-size: 0.8rem;
font-weight: bold;
flex-shrink: 0;
}
.question-text {
font-size: 1.1rem;
line-height: 1.6;
color: #333;
}
.text-green-600 {
color: #16a34a;
}
.text-red-600 {
color: #dc2626;
}
/* 选项组通用样式 */
.options-group {
display: flex;
flex-direction: column;
gap: 12px;
}
.option-item {
display: block;
}
.option-label {
display: flex;
align-items: center;
padding: 14px;
border: 1px solid #e0e0e0;
border-radius: 8px;
cursor: pointer;
transition: all 0.2s ease;
}
.option-label:hover {
background-color: #f8f9fa;
border-color: #007bff;
}
.option-radio,
.option-checkbox {
margin-right: 12px;
width: 18px;
height: 18px;
}
.option-content {
font-size: 1rem;
color: #555;
}
/* 答案状态样式 */
.correct-option {
color: #28a745;
font-weight: bold;
}
.wrong-option {
color: #dc3545;
text-decoration: line-through;
}
.option-label:has(.correct-option) {
background-color: #e9f7ef;
border-color: #28a745;
}
.option-label:has(.wrong-option) {
background-color: #fbe9e7;
border-color: #dc3545;
}
/* 填空题样式 */
.fill-group {
display: flex;
flex-direction: column;
gap: 15px;
}
.fill-item {
display: flex;
align-items: center;
gap: 10px;
}
.fill-label {
font-weight: bold;
}
.fill-input {
padding: 10px;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 1rem;
flex-grow: 1;
}
.correct-input {
border-color: #28a745;
background-color: #e9f7ef;
}
.wrong-input {
border-color: #dc3545;
background-color: #fbe9e7;
}
.correct-hint {
color: #28a745;
font-size: 0.9rem;
}
/* 简答题样式 */
.essay-group {
display: flex;
flex-direction: column;
gap: 10px;
}
.essay-textarea {
padding: 12px;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 1rem;
min-height: 120px;
resize: vertical;
}
.essay-hint {
background-color: #e9f7ef;
padding: 10px;
border-radius: 6px;
}
/* 禁用状态样式 */
input:disabled,
textarea:disabled {
cursor: not-allowed;
opacity: 0.9;
}
</style>

查看文件

@ -0,0 +1,301 @@
<script setup lang="ts">
import { computed, watch, provide } from 'vue'
import type { ExperimentGridConfig, GridInputCell } from '@/types/experiment'
import ExperimentGrid from './ExperimentGrid.vue'
import { useExperimentStore } from '@/stores/experiment'
import { useStudentStore } from '@/stores/student'
import { storeToRefs } from 'pinia'
import { chatOnce, extractJsonBlock, safeParseJson } from '@/utils/aiClient'
import { AIEvalContextKey, type ConfigSummary, type AIEvalFocus, type AIEvalResult } from '@/utils/aiEvalContext'
const props = defineProps<{
config: ExperimentGridConfig
validationUrl?: string
cellInspectMode?: boolean
}>()
const emit = defineEmits<{
'field-update': [fieldId: string, value: any]
'field-validate': [fieldId: string]
'all-validated': []
'cell-inspect': [info: { sheetTitle?: string; cellType: string; label: string; value: any; unit?: string; validation?: any }]
}>()
const experimentStore = useExperimentStore()
const studentStore = useStudentStore()
const { StudentInfo } = storeToRefs(studentStore)
experimentStore.setConfig(props.config, props.validationUrl)
const fieldData = computed(() => experimentStore.data)
const areaResults = computed(() => experimentStore.areaResults)
const allFieldsValidated = computed(() => experimentStore.allFieldsValidated)
const dataVersion = computed(() => experimentStore.dataVersion)
const configSummary = computed<ConfigSummary>(() => {
const fields: ConfigSummary['fields'] = []
const areas: ConfigSummary['areas'] = []
props.config.sheets.forEach((sheet) => {
sheet.cells.forEach((row) => {
row.forEach((cell) => {
if (!cell) return
if (cell.type === 'input') {
const inp = cell as GridInputCell
fields.push({
id: inp.fieldId,
label: inp.fieldId,
unit: inp.unit,
validation: inp.validation,
})
}
if (cell.type === 'computed') {
areas.push({
id: cell.areaId,
label: cell.areaId,
expression: cell.expression,
variables: cell.variables,
format: cell.format,
})
}
})
})
})
return {
title: props.config.title,
description: props.config.description,
fields,
areas,
}
})
const evalCache = new Map<string, { version: number; result: AIEvalResult }>()
const formatDataEvalResponse = (rawText: string): AIEvalResult => {
const jsonBlock = extractJsonBlock(rawText)
if (jsonBlock) {
const parsed = safeParseJson<Record<string, any>>(jsonBlock)
if (parsed.value) {
const payload = parsed.value
const sections: string[] = []
if (payload.grade && payload.grade_description) {
sections.push(`**评级**:${payload.grade}(${payload.grade_description})`)
}
if (payload.metrics?.relative_error_percent !== undefined) {
sections.push(`**相对误差**:${payload.metrics.relative_error_percent}%`)
}
if (payload.metrics?.data_quality_assessment) {
sections.push(`**数据质量**:${payload.metrics.data_quality_assessment}`)
}
if (payload.teacher_comments) {
sections.push(`**点评**:${payload.teacher_comments}`)
}
if (Array.isArray(payload.improvement_suggestions) && payload.improvement_suggestions.length > 0) {
const suggestions = payload.improvement_suggestions
.map((item: any) => `- ${item.issue || ''}:${item.suggestion || ''}`)
.join('\n')
sections.push(`**改进建议**\n${suggestions}`)
}
return { rawText, displayText: sections.join('\n\n') || rawText, parsed: payload }
}
}
return { rawText, displayText: rawText || 'AI未返回可解析的评价结果。', parsed: null }
}
const requestEvaluation = async (focus: AIEvalFocus): Promise<AIEvalResult> => {
const cacheKey = `${focus.type}:${focus.id}`
const cached = evalCache.get(cacheKey)
if (cached && cached.version === dataVersion.value) {
return cached.result
}
const payload = {
student_id: String(StudentInfo.value?.SID ?? ''),
student_name: String(StudentInfo.value?.Name ?? ''),
focus_field: focus,
field_values: fieldData.value,
area_results: areaResults.value,
config_summary: configSummary.value,
}
const userContent = [
'请用中文、语气严谨但鼓励的方式评价以下实验数据。',
'请输出符合JSON Schema的结果,避免额外文本。',
'',
JSON.stringify(payload, null, 2),
].join('\n')
const rawText = await chatOnce({
teacherType: 'data_eval',
messages: [{ role: 'user', content: userContent }],
stream: false,
})
const result = formatDataEvalResponse(rawText)
evalCache.set(cacheKey, { version: dataVersion.value, result })
return result
}
provide(AIEvalContextKey, {
configSummary,
fieldData,
areaResults,
dataVersion,
studentInfo: StudentInfo,
requestEvaluation,
})
const handleFieldUpdate = (fieldId: string, value: any) => {
experimentStore.setFieldValue(fieldId, value)
emit('field-update', fieldId, value)
}
const handleFieldValidate = async (fieldId: string) => {
await experimentStore.validateField(fieldId)
emit('field-validate', fieldId)
if (experimentStore.allFieldsValidated) {
emit('all-validated')
}
}
watch(allFieldsValidated, (newValue) => {
if (newValue) {
emit('all-validated')
}
})
</script>
<template>
<div class="experiment-form">
<div class="form-header">
<h2 class="form-title">{{ config.title }}</h2>
<p v-if="config.description" class="form-description">{{ config.description }}</p>
</div>
<div class="form-sheets">
<ExperimentGrid
v-for="sheet in config.sheets"
:key="sheet.id"
:sheet="sheet"
:field-data="fieldData"
:area-results="areaResults"
:on-field-update="handleFieldUpdate"
:on-field-validate="handleFieldValidate"
:cell-inspect-mode="cellInspectMode"
:on-cell-inspect="(info: any) => emit('cell-inspect', info)"
/>
</div>
<div class="form-status">
<div class="status-indicator" :class="{ 'all-valid': allFieldsValidated }">
<span class="status-icon">
<svg v-if="allFieldsValidated" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M20 6L9 17L4 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<svg v-else width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="currentColor" stroke-width="2"/>
<path d="M12 6V12L16 14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</span>
{{ allFieldsValidated ? '所有字段已验证' : '请完成所有字段验证' }}
</div>
<div class="progress">
<div class="progress-bar">
<div
class="progress-fill"
:style="{ width: `${experimentStore.allInputCount > 0 ? (experimentStore.validatedCount / experimentStore.allInputCount) * 100 : 0}%` }"
></div>
</div>
<span class="progress-text">
{{ experimentStore.validatedCount }} / {{ experimentStore.allInputCount }} 字段
</span>
</div>
</div>
</div>
</template>
<style scoped>
.experiment-form {
width: 100%;
}
.form-header {
margin-bottom: 2rem;
text-align: center;
padding-bottom: 1.25rem;
border-bottom: 2px solid #333;
}
.form-title {
font-size: 1.5rem;
font-weight: 700;
color: #1a1a1a;
margin-bottom: 0.4rem;
letter-spacing: 0.02em;
}
.form-description {
font-size: 0.95rem;
color: #666;
}
.form-sheets {
display: flex;
flex-direction: column;
gap: 2rem;
}
.form-status {
margin-top: 2rem;
padding: 0.75rem 1rem;
border-top: 1px solid #dee2e6;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.9rem;
}
.status-indicator {
font-weight: 600;
display: flex;
align-items: center;
gap: 0.4rem;
color: #555;
}
.status-indicator.all-valid {
color: #28a745;
}
.progress {
display: flex;
align-items: center;
gap: 0.6rem;
width: 220px;
}
.progress-bar {
height: 6px;
background: #e9ecef;
border-radius: 3px;
overflow: hidden;
flex-grow: 1;
}
.progress-fill {
height: 100%;
background: #333;
border-radius: 3px;
transition: width 0.5s ease;
}
.progress-text {
font-size: 0.8rem;
color: #888;
white-space: nowrap;
}
</style>

查看文件

@ -0,0 +1,198 @@
<script setup lang="ts">
import { computed, inject } from 'vue'
import type { GridSheet, GridCell, GridInputCell } from '@/types/experiment'
import ExperimentGridCell from './ExperimentGridCell.vue'
import { AIEvalContextKey } from '@/utils/aiEvalContext'
const props = defineProps<{
sheet: GridSheet
fieldData: Record<string, { value: any; validated: boolean; validationResult?: { accept: boolean; message: string } }>
areaResults: Record<string, { value: any; formatted: string; error?: string }>
onFieldUpdate: (fieldId: string, value: any) => void
onFieldValidate: (fieldId: string) => void
cellInspectMode?: boolean
onCellInspect?: (info: { sheetTitle?: string; cellType: string; label: string; value: any; unit?: string; validation?: any }) => void
}>()
const aiContext = inject(AIEvalContextKey, null)
const effectiveRows = computed(() => {
const rows = props.sheet.cells
return { rows }
})
function getCellValue(cell: GridCell) {
if (!cell) return null
if (cell.type === 'input') {
return props.fieldData[cell.fieldId]?.value ?? null
}
return null
}
function getCellValidated(cell: GridCell) {
if (!cell || cell.type !== 'input') return false
return props.fieldData[cell.fieldId]?.validated ?? false
}
function getCellValidationResult(cell: GridCell) {
if (!cell || cell.type !== 'input') return undefined
return props.fieldData[cell.fieldId]?.validationResult
}
function getCellAreaResult(cell: GridCell) {
if (!cell || cell.type !== 'computed') return undefined
return props.areaResults[cell.areaId]
}
function onCellInput(fieldId: string, value: any) {
props.onFieldUpdate(fieldId, value)
}
function onCellBlur(fieldId: string) {
props.onFieldValidate(fieldId)
}
function handleCellInspect(cell: GridCell) {
if (!props.onCellInspect || !cell) return
let label = ''
let value: any = undefined
let unit: string | undefined
let validation: any = undefined
let cellType = cell.type
if (cell.type === 'input') {
const inp = cell as GridInputCell
label = inp.fieldId
value = props.fieldData[inp.fieldId]?.value
unit = inp.unit
validation = inp.validation
} else if (cell.type === 'computed') {
label = cell.areaId
value = props.areaResults[cell.areaId]?.formatted
} else if (cell.type === 'label') {
label = cell.content
}
props.onCellInspect({
sheetTitle: props.sheet.title,
cellType,
label,
value,
unit,
validation,
})
}
const isFirstRowHeader = computed(() => {
return props.sheet.columnHeaders && props.sheet.columnHeaders.length > 0
})
</script>
<template>
<div class="grid-sheet">
<div v-if="sheet.title" class="sheet-title" v-html="sheet.title" />
<div class="grid-wrapper">
<table class="grid-table">
<thead v-if="isFirstRowHeader">
<tr>
<th class="grid-row-header-th"></th>
<th
v-for="(header, hi) in sheet.columnHeaders"
:key="hi"
class="grid-header-cell"
>
<span v-html="header" />
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in effectiveRows.rows" :key="ri" class="grid-row">
<td
v-for="(cell, ci) in row"
:key="ci"
class="grid-cell-wrapper"
:class="{
'cell-colspan': (cell?.colSpan ?? 1) > 1,
}"
:colspan="cell?.colSpan ?? 1"
:rowspan="cell?.rowSpan ?? 1"
>
<ExperimentGridCell
v-if="cell"
:cell="cell"
:value="getCellValue(cell)"
:validated="getCellValidated(cell)"
:validation-result="getCellValidationResult(cell)"
:area-result="getCellAreaResult(cell)"
:inspect-mode="cellInspectMode"
@input="(val: any) => onCellInput((cell as GridInputCell).fieldId, val)"
@blur="() => onCellBlur((cell as GridInputCell).fieldId)"
@inspect="handleCellInspect(cell)"
/>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<style scoped>
.grid-sheet {
margin-bottom: 2rem;
}
.sheet-title {
font-size: 1.1rem;
font-weight: 700;
color: #1a1a1a;
margin-bottom: 0.5rem;
padding-left: 2px;
}
.grid-wrapper {
overflow-x: auto;
}
.grid-table {
width: 100%;
border-collapse: collapse;
border: 2px solid #333;
table-layout: auto;
}
.grid-row-header-th {
width: 1%;
white-space: nowrap;
background: #eef1f5;
border: 1px solid #d0d4da;
padding: 6px 8px;
min-width: 50px;
}
.grid-header-cell {
background: #eef1f5;
border: 1px solid #d0d4da;
padding: 4px 6px;
font-weight: 700;
font-size: 0.8rem;
text-align: center;
color: #333;
white-space: nowrap;
}
.grid-row {
border: none;
}
.grid-cell-wrapper {
border: 1px solid #d0d4da;
padding: 0;
vertical-align: middle;
}
.grid-cell-wrapper:first-child {
min-width: 70px;
}
</style>

查看文件

@ -0,0 +1,336 @@
<script setup lang="ts">
import { ref, computed, watch, inject, onBeforeUnmount } from 'vue'
import type { GridCell, GridInputCell, GridComputedCell, GridLabelCell } from '@/types/experiment'
import { renderTextWithLatex } from '@/utils/latex'
import { renderMarkdownWithLatex } from '@/utils/markdown'
import { AIEvalContextKey } from '@/utils/aiEvalContext'
const props = defineProps<{
cell: GridCell
value?: any
validated?: boolean
validationResult?: { accept: boolean; message: string }
areaResult?: { value: any; formatted: string; error?: string }
inspectMode?: boolean
}>()
const emit = defineEmits<{
input: [value: any]
blur: []
inspect: []
}>()
const isInput = computed(() => props.cell?.type === 'input')
const isComputed = computed(() => props.cell?.type === 'computed')
const isLabel = computed(() => props.cell?.type === 'label')
const inputCell = computed(() => (isInput.value ? (props.cell as GridInputCell) : null))
const computedCell = computed(() => (isComputed.value ? (props.cell as GridComputedCell) : null))
const labelCell = computed(() => (isLabel.value ? (props.cell as GridLabelCell) : null))
const internalValue = ref(props.value ?? '')
const isFocused = ref(false)
const isHovering = ref(false)
const aiContext = inject(AIEvalContextKey, null)
const tooltipVisible = ref(false)
const tooltipLoading = ref(false)
const tooltipHtml = ref('')
const tooltipError = ref('')
let hoverTimer: number | null = null
const hasValue = computed(() => {
return props.value !== null && props.value !== undefined && props.value !== ''
})
watch(() => props.value, (newVal) => {
internalValue.value = newVal ?? ''
})
const bgColor = computed(() => {
if (isLabel.value) return 'transparent'
if (!isInput.value) return 'transparent'
if (isFocused.value) return '#e8f0fe'
if (props.validated && props.validationResult?.accept) {
return '#d4edda'
}
if (props.validated && props.validationResult && !props.validationResult.accept) {
return '#f8d7da'
}
if (props.value !== null && props.value !== undefined && props.value !== '') {
return '#fff3cd'
}
return '#ffffff'
})
const labelBgColor = computed(() => {
if (!isLabel.value) return 'transparent'
if (labelCell.value?.style === 'header') return '#eef1f5'
return '#f8f9fa'
})
const labelHtml = computed(() => {
if (!isLabel.value || !labelCell.value) return ''
return renderTextWithLatex(labelCell.value.content)
})
const unitHtml = computed(() => {
if (!isInput.value || !inputCell.value?.unit) return ''
return renderTextWithLatex(inputCell.value.unit)
})
const hasError = computed(() => {
if (isComputed.value && props.areaResult?.error) return true
return false
})
function handleInput(event: Event) {
const target = event.target as HTMLInputElement
const val = target.value
internalValue.value = val
emit('input', val)
}
function handleBlur() {
isFocused.value = false
if (isInput.value) {
emit('blur')
}
}
function handleFocus() {
isFocused.value = true
tooltipVisible.value = false
clearHoverTimer()
}
function clearHoverTimer() {
if (hoverTimer !== null) {
window.clearTimeout(hoverTimer)
hoverTimer = null
}
}
function handleMouseEnter() {
isHovering.value = true
if (props.inspectMode) return
if (!aiContext || !hasValue.value || isFocused.value) return
clearHoverTimer()
hoverTimer = window.setTimeout(async () => {
if (!hasValue.value || isFocused.value) return
tooltipVisible.value = true
tooltipError.value = ''
tooltipHtml.value = ''
tooltipLoading.value = true
try {
const focusInfo = {
type: isInput.value ? 'field' as const : 'area' as const,
id: isInput.value ? (inputCell.value?.fieldId ?? '') : (computedCell.value?.areaId ?? ''),
label: isInput.value ? (inputCell.value?.fieldId ?? '') : (computedCell.value?.areaId ?? ''),
value: props.value ?? props.areaResult?.value,
unit: inputCell.value?.unit,
formatted: props.areaResult?.formatted,
}
const result = await aiContext.requestEvaluation(focusInfo)
tooltipHtml.value = renderMarkdownWithLatex(result.displayText)
} catch (error) {
tooltipError.value = error instanceof Error ? error.message : 'AI评价失败'
tooltipHtml.value = renderMarkdownWithLatex('AI评价失败,请稍后再试。')
} finally {
tooltipLoading.value = false
}
}, 600)
}
function handleMouseLeave() {
isHovering.value = false
clearHoverTimer()
tooltipVisible.value = false
}
function handleClick() {
if (props.inspectMode) {
emit('inspect')
}
}
onBeforeUnmount(() => {
clearHoverTimer()
})
</script>
<template>
<div
class="grid-cell"
:class="{
'cell-label': isLabel,
'cell-input': isInput,
'cell-computed': isComputed,
'cell-focused': isFocused,
'cell-inspect-mode': inspectMode,
'cell-inspect-hover': inspectMode && isHovering,
}"
:style="{
backgroundColor: isLabel ? labelBgColor : isInput ? bgColor : isComputed ? (areaResult?.error ? '#f8d7da' : '#f0fff4') : 'transparent',
}"
@mouseenter="handleMouseEnter"
@mouseleave="handleMouseLeave"
@click="handleClick"
>
<template v-if="isLabel">
<span class="label-text" v-html="labelHtml" />
</template>
<template v-else-if="isInput">
<input
class="cell-input-field"
:value="internalValue"
:placeholder="inputCell?.placeholder || ''"
@input="handleInput"
@blur="handleBlur"
@focus="handleFocus"
/>
<span v-if="unitHtml" class="cell-unit" v-html="unitHtml" />
</template>
<template v-else-if="isComputed">
<span v-if="areaResult?.error" class="computed-error">错误</span>
<span v-else-if="areaResult?.value != null" class="computed-value">
{{ areaResult?.formatted }}
</span>
<span v-else class="computed-pending">--</span>
</template>
<div
v-if="tooltipVisible && !isFocused"
class="ai-tooltip"
@mouseenter="clearHoverTimer"
@mouseleave="handleMouseLeave"
>
<div v-if="tooltipLoading" class="ai-tooltip-loading">AI正在评价...</div>
<div v-else-if="tooltipError" class="ai-tooltip-error">{{ tooltipError }}</div>
<div v-else v-html="tooltipHtml"></div>
</div>
</div>
</template>
<style scoped>
.grid-cell {
display: flex;
align-items: center;
justify-content: center;
min-height: 32px;
padding: 3px 6px;
gap: 3px;
font-size: 0.85rem;
transition: background-color 0.2s ease;
position: relative;
}
.cell-label {
justify-content: flex-start;
font-weight: 600;
color: #1a1a1a;
white-space: nowrap;
padding: 3px 10px;
}
.cell-input {
gap: 3px;
}
.cell-computed {
font-family: monospace;
font-weight: 600;
}
.cell-focused {
outline: 2px solid #4a90d9;
outline-offset: -1px;
}
.cell-inspect-mode {
cursor: pointer;
}
.cell-inspect-hover {
outline: 2px dashed #007bff;
outline-offset: -1px;
}
.label-text {
display: inline-block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.cell-input-field {
border: none;
outline: none;
width: 100%;
font-size: 0.85rem;
font-family: inherit;
background: transparent;
text-align: center;
min-width: 0;
}
.cell-input-field::placeholder {
color: #bbb;
font-size: 0.75rem;
}
.cell-unit {
font-size: 0.75rem;
color: #666;
white-space: nowrap;
flex-shrink: 0;
}
.computed-value {
color: #155724;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.computed-error {
color: #dc3545;
}
.computed-pending {
color: #aaa;
}
.ai-tooltip {
position: absolute;
right: 0;
top: calc(100% + 4px);
width: min(320px, 85vw);
background: #ffffff;
border: 1px solid #d9d9d9;
border-radius: 8px;
padding: 0.7rem 0.85rem;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
z-index: 20;
font-size: 0.82rem;
line-height: 1.5;
pointer-events: auto;
}
.ai-tooltip-loading {
color: #555;
}
.ai-tooltip-error {
color: #c71d1d;
font-weight: 600;
}
</style>

查看文件

@ -0,0 +1,118 @@
<script setup lang="ts">
import type { GridSheet, ExperimentData, AreaCalculationResult, GridCell, GridInputCell, GridComputedCell } from '@/types/experiment'
import { renderTextWithLatex } from '@/utils/latex'
const props = defineProps<{
sheet: GridSheet
fieldData: ExperimentData
areaResults: Record<string, AreaCalculationResult>
}>()
function formatValue(value: unknown): string {
if (value === null || value === undefined) return ''
if (typeof value === 'number') return Number.isFinite(value) ? String(value) : ''
return String(value)
}
function resolveFieldValue(cell: GridCell): string {
if (!cell || cell.type !== 'input') return ''
const inp = cell as GridInputCell
return formatValue(props.fieldData[inp.fieldId]?.value)
}
function resolveAreaValue(cell: GridCell): string {
if (!cell || cell.type !== 'computed') return ''
const comp = cell as GridComputedCell
const formatted = props.areaResults[comp.areaId]?.formatted
if (!formatted || formatted === '等待计算...' || formatted === '等待输入...') return ''
return formatted
}
function renderLabel(content: string): string {
return renderTextWithLatex(content)
}
</script>
<template>
<div class="print-container">
<table class="print-table">
<thead v-if="sheet.columnHeaders && sheet.columnHeaders.length > 0">
<tr>
<th class="print-header-cell">项目</th>
<th
v-for="(header, hi) in sheet.columnHeaders"
:key="hi"
class="print-header-cell"
>
<span v-html="renderLabel(header)" />
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in sheet.cells" :key="ri" class="print-row">
<td
v-for="(cell, ci) in row"
:key="ci"
class="print-cell"
:class="{
'print-cell-label': cell?.type === 'label',
'print-cell-input': cell?.type === 'input',
'print-cell-computed': cell?.type === 'computed',
}"
:colspan="cell?.colSpan ?? 1"
>
<template v-if="cell?.type === 'label'">
<span v-html="renderLabel(cell.content)" />
</template>
<template v-else-if="cell?.type === 'input'">
{{ resolveFieldValue(cell) }}
</template>
<template v-else-if="cell?.type === 'computed'">
{{ resolveAreaValue(cell) }}
</template>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped>
.print-container {
width: 100%;
}
.print-table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
}
.print-table th,
.print-table td {
border: 1px solid #d5d5d5;
padding: 5px 6px;
vertical-align: middle;
word-break: break-word;
}
.print-table th {
background: #f2f4f7;
font-weight: 600;
text-align: center;
}
.print-header-cell {
text-align: center;
}
.print-cell {
text-align: center;
}
.print-cell-label {
text-align: left;
font-weight: 600;
background: #f8f9fb;
}
</style>