feat(阶段1): 搬入 ojnext 为 apps/web,未改业务代码

This commit is contained in:
2026-08-06 21:18:16 -06:00
parent 3c975e85ee
commit ae1fb329b5
258 changed files with 40490 additions and 91 deletions
@@ -0,0 +1,121 @@
<script setup lang="ts">
import type { Exercise, ExerciseDebugData } from "utils/types"
import { highlightLines } from "../composables/useCodeHighlight"
import "./exercise-highlight.css"
const props = defineProps<{ exercise: Exercise; lang?: string }>()
const data = computed(() => props.exercise.data as ExerciseDebugData)
const lineHtml = computed(() => highlightLines(data.value.lines, props.lang))
const selected = ref<Set<number>>(new Set())
const submitted = ref(false)
watch(() => props.exercise.id, reset, { immediate: true })
const allCorrect = computed(() => {
const ans = new Set(data.value.answer)
if (selected.value.size !== ans.size) return false
for (const i of selected.value) if (!ans.has(i)) return false
return true
})
const locked = computed(() => submitted.value && allCorrect.value)
function toggle(i: number) {
if (locked.value) return
submitted.value = false
const s = new Set(selected.value)
if (s.has(i)) s.delete(i)
else s.add(i)
selected.value = s
}
function lineStatus(i: number): "correct" | "wrong" | "selected" | "default" {
if (!submitted.value) return selected.value.has(i) ? "selected" : "default"
const isAns = data.value.answer.includes(i)
const isSel = selected.value.has(i)
if (isAns) return isSel ? "correct" : "wrong" // 漏选也标红
if (isSel) return "wrong"
return "default"
}
function lineStyle(i: number): Record<string, string> {
const status = lineStatus(i)
const color =
status === "correct"
? "#18a058"
: status === "wrong"
? "#d03050"
: status === "selected"
? "#2080f0"
: "var(--n-border-color)"
const plain = color === "var(--n-border-color)"
return {
display: "flex",
alignItems: "center",
gap: "10px",
padding: "6px 12px",
borderRadius: "6px",
border: `1.5px solid ${color}`,
background: plain ? "transparent" : color + "14",
cursor: locked.value ? "default" : "pointer",
fontFamily: "Monaco",
userSelect: "none",
}
}
function submit() {
submitted.value = true
}
function reset() {
selected.value = new Set()
submitted.value = false
}
</script>
<template>
<n-card style="margin: 16px 0; border: 1.5px solid var(--n-border-color)">
<template #header>
<n-tag type="info" :bordered="false">练一练 · 代码找错</n-tag>
</template>
<p style="font-weight: 500; font-size: 16px; margin-bottom: 8px">
{{ data.question }}
</p>
<p style="color: var(--n-text-color-3); font-size: 13px; margin: 0 0 12px">
点击你认为有错误的代码行可多选
</p>
<n-space vertical :size="6">
<div
v-for="(line, idx) in data.lines"
:key="idx"
:style="lineStyle(idx)"
@click="toggle(idx)"
>
<span
style="color: #bbb; width: 22px; text-align: right; flex-shrink: 0"
>
{{ idx + 1 }}
</span>
<span v-html="lineHtml[idx]" style="white-space: pre" />
</div>
</n-space>
<n-alert
v-if="submitted"
:type="allCorrect ? 'success' : 'error'"
:title="allCorrect ? '找对了!' : '还没找全,红色行是错误所在'"
style="margin-top: 12px"
>
<template v-if="submitted && data.explanation" #default>
{{ data.explanation }}
</template>
</n-alert>
<n-space style="margin-top: 12px" :size="8">
<n-button type="info" :disabled="locked" @click="submit">提交</n-button>
<n-button @click="reset">重置</n-button>
</n-space>
</n-card>
</template>
@@ -0,0 +1,135 @@
<script setup lang="ts">
import type { Exercise, ExerciseFillData } from "utils/types"
import { highlight } from "../composables/useCodeHighlight"
import "./exercise-highlight.css"
const props = defineProps<{ exercise: Exercise; lang?: string }>()
const data = computed(() => props.exercise.data as ExerciseFillData)
type CodeSeg = { type: "code"; html: string }
type BlankSeg = { type: "blank"; answers: string[]; index: number }
type Segment = CodeSeg | BlankSeg
const segments = computed<Segment[]>(() => {
const blanks: string[][] = []
const markedCode = data.value.code.replace(/\{\{([^}]+)\}\}/g, (_, inner) => {
blanks.push(inner.split("|"))
return `____${blanks.length - 1}____`
})
const highlighted = highlight(markedCode, props.lang)
const parts = highlighted.split(/____(\d+)____/)
const result: Segment[] = []
for (let i = 0; i < parts.length; i++) {
if (i % 2 === 0) {
if (parts[i]) result.push({ type: "code", html: parts[i] })
} else {
const idx = parseInt(parts[i])
result.push({ type: "blank", answers: blanks[idx], index: idx })
}
}
return result
})
const blankCount = computed(
() => segments.value.filter((s) => s.type === "blank").length,
)
const userInputs = ref<string[]>([])
const wrongBlanks = ref<Set<number>>(new Set())
const allCorrect = ref(false)
watch(() => props.exercise.id, reset, { immediate: true })
function reset() {
userInputs.value = Array(blankCount.value).fill("")
wrongBlanks.value = new Set()
allCorrect.value = false
}
function submit() {
if (allCorrect.value) return
const wrong = new Set<number>()
for (const seg of segments.value) {
if (seg.type !== "blank") continue
if (!seg.answers.includes(userInputs.value[seg.index]?.trim() ?? "")) {
wrong.add(seg.index)
}
}
wrongBlanks.value = wrong
allCorrect.value = wrong.size === 0
}
function inputWidth(idx: number): string {
return Math.max(4, (userInputs.value[idx]?.length ?? 0) + 2) + "ch"
}
</script>
<template>
<n-card style="margin: 16px 0; border: 1.5px solid var(--n-border-color)">
<template #header>
<n-tag type="warning" :bordered="false">练一练 · 代码填空</n-tag>
</template>
<p style="font-weight: 500; font-size: 16px; margin-bottom: 12px">
{{ data.question }}
</p>
<pre
:style="{
fontFamily: 'Monaco',
fontSize: '16px',
lineHeight: '1.6',
background: 'var(--n-color)',
border: '1px solid var(--n-border-color)',
borderRadius: '6px',
padding: '12px',
overflowX: 'auto',
whiteSpace: 'pre-wrap',
margin: 0,
}"
><template v-for="(seg, i) in segments" :key="i"
><span v-if="seg.type === 'code'" v-html="seg.html" /><input
v-else
:value="userInputs[seg.index]"
:disabled="allCorrect"
:style="{
width: inputWidth(seg.index),
fontFamily: 'Monaco',
fontSize: '16px',
padding: '2px 6px',
borderRadius: '3px',
border: `1.5px solid ${
allCorrect
? '#18a058'
: wrongBlanks.has(seg.index)
? '#d03050'
: 'var(--n-border-color)'
}`,
background: allCorrect
? 'rgba(24,160,88,0.08)'
: wrongBlanks.has(seg.index)
? 'rgba(208,48,80,0.07)'
: 'transparent',
outline: 'none',
color: 'inherit',
minWidth: '4ch',
}"
@input="userInputs[seg.index] = ($event.target as HTMLInputElement).value"
/></template></pre>
<n-alert
v-if="wrongBlanks.size > 0 || allCorrect"
:type="allCorrect ? 'success' : 'error'"
:title="allCorrect ? '全部正确!' : '有填写错误,请检查红色标注的空位'"
style="margin-top: 12px"
/>
<n-space style="margin-top: 12px" :size="8">
<n-button type="warning" :disabled="allCorrect" @click="submit">
提交
</n-button>
<n-button @click="reset">重置</n-button>
</n-space>
</n-card>
</template>
@@ -0,0 +1,183 @@
<script setup lang="ts">
import type { Exercise, ExerciseGroupData } from "utils/types"
import { shuffle } from "../composables/useShuffle"
const props = defineProps<{ exercise: Exercise; lang?: string }>()
const data = computed(() => props.exercise.data as ExerciseGroupData)
const order = ref<number[]>([]) // item 的稳定展示顺序(初始乱序)
const placement = ref<number[]>([]) // placement[itemIdx] = 桶下标,-1 表示在池中
const dragIdx = ref<number | null>(null)
const submitted = ref(false)
function init() {
order.value = shuffle(data.value.items.map((_, i) => i))
placement.value = Array(data.value.items.length).fill(-1)
dragIdx.value = null
submitted.value = false
}
onMounted(init)
watch(() => props.exercise.id, init)
const allPlaced = computed(() => placement.value.every((p) => p !== -1))
const allCorrect = computed(() =>
placement.value.every((p, i) => p === data.value.answer[i]),
)
const locked = computed(() => submitted.value && allCorrect.value)
function onDragStart(i: number) {
if (locked.value) return
dragIdx.value = i
}
function dropTo(bucket: number) {
if (locked.value || dragIdx.value === null) return
placement.value[dragIdx.value] = bucket
dragIdx.value = null
submitted.value = false
}
const poolItems = computed(() =>
order.value.filter((i) => placement.value[i] === -1),
)
function itemsIn(bucket: number): number[] {
return order.value.filter((i) => placement.value[i] === bucket)
}
function itemStatus(i: number): "correct" | "wrong" | "default" {
if (!submitted.value || placement.value[i] === -1) return "default"
return placement.value[i] === data.value.answer[i] ? "correct" : "wrong"
}
function chipStyle(i: number): Record<string, string> {
const status = itemStatus(i)
const color =
status === "correct"
? "#18a058"
: status === "wrong"
? "#d03050"
: "var(--n-border-color)"
const plain = color === "var(--n-border-color)"
return {
padding: "6px 12px",
borderRadius: "6px",
border: `1.5px solid ${color}`,
background: plain ? "var(--n-color)" : color + "14",
cursor: locked.value ? "default" : "grab",
userSelect: "none",
fontSize: "15px",
}
}
function submit() {
submitted.value = true
}
function reset() {
init()
}
</script>
<template>
<n-card style="margin: 16px 0; border: 1.5px solid var(--n-border-color)">
<template #header>
<n-tag type="warning" :bordered="false">练一练 · 归类分组</n-tag>
</template>
<p style="font-weight: 500; font-size: 16px; margin-bottom: 8px">
{{ data.question }}
</p>
<p style="color: var(--n-text-color-3); font-size: 13px; margin: 0 0 12px">
把下面的项目拖到对应的分组里可在分组间拖动调整
</p>
<div
:style="{
display: 'flex',
flexWrap: 'wrap',
gap: '8px',
minHeight: '48px',
padding: '10px',
border: '1.5px dashed var(--n-border-color)',
borderRadius: '8px',
marginBottom: '14px',
}"
@dragover.prevent
@drop="dropTo(-1)"
>
<span
v-if="poolItems.length === 0"
style="color: var(--n-text-color-3); font-size: 13px"
>
已全部归类
</span>
<div
v-for="i in poolItems"
:key="i"
draggable="true"
:style="chipStyle(i)"
@dragstart="onDragStart(i)"
>
{{ data.items[i] }}
</div>
</div>
<div
:style="{
display: 'grid',
gridTemplateColumns: `repeat(${data.buckets.length}, 1fr)`,
gap: '12px',
}"
>
<div
v-for="(bucket, b) in data.buckets"
:key="b"
:style="{
minHeight: '88px',
padding: '10px',
border: '1.5px solid var(--n-border-color)',
borderRadius: '8px',
}"
@dragover.prevent
@drop="dropTo(b)"
>
<p
style="
font-weight: 600;
margin: 0 0 8px;
text-align: center;
font-size: 14px;
"
>
{{ bucket }}
</p>
<n-space :size="8">
<div
v-for="i in itemsIn(b)"
:key="i"
draggable="true"
:style="chipStyle(i)"
@dragstart="onDragStart(i)"
>
{{ data.items[i] }}
</div>
</n-space>
</div>
</div>
<n-alert
v-if="submitted"
:type="allCorrect ? 'success' : 'error'"
:title="allCorrect ? '归类全部正确!' : '有归类错误,红色项需要调整'"
style="margin-top: 12px"
/>
<n-space style="margin-top: 12px" :size="8">
<n-button type="warning" :disabled="!allPlaced || locked" @click="submit">
提交
</n-button>
<n-button @click="reset">重置</n-button>
</n-space>
</n-card>
</template>
@@ -0,0 +1,184 @@
<script setup lang="ts">
import type { Exercise, ExerciseMatchData } from "utils/types"
import { shuffle } from "../composables/useShuffle"
const props = defineProps<{ exercise: Exercise; lang?: string }>()
const data = computed(() => props.exercise.data as ExerciseMatchData)
const PALETTE = [
"#2080f0",
"#18a058",
"#f0a020",
"#d03050",
"#8a2be2",
"#0891b2",
"#db2777",
"#65a30d",
]
const rightOrder = ref<number[]>([]) // 显示顺序里的 right 原始下标
const pairs = ref<(number | null)[]>([]) // pairs[leftIdx] = 配对的 right 原始下标
const selectedLeft = ref<number | null>(null)
const submitted = ref(false)
function init() {
const n = data.value.right.length
rightOrder.value = shuffle(Array.from({ length: n }, (_, i) => i))
pairs.value = Array(data.value.left.length).fill(null)
selectedLeft.value = null
submitted.value = false
}
onMounted(init)
watch(() => props.exercise.id, init)
const allPaired = computed(() => pairs.value.every((p) => p !== null))
const allCorrect = computed(() =>
pairs.value.every((p, i) => p === data.value.answer[i]),
)
const locked = computed(() => submitted.value && allCorrect.value)
function leftOf(rightIdx: number): number {
return pairs.value.findIndex((p) => p === rightIdx)
}
function onLeftClick(i: number) {
if (locked.value) return
submitted.value = false
if (pairs.value[i] !== null) {
pairs.value[i] = null
selectedLeft.value = i
return
}
selectedLeft.value = selectedLeft.value === i ? null : i
}
function onRightClick(rightIdx: number) {
if (locked.value) return
submitted.value = false
if (selectedLeft.value === null) {
const l = leftOf(rightIdx)
if (l !== -1) pairs.value[l] = null
return
}
const prev = leftOf(rightIdx)
if (prev !== -1) pairs.value[prev] = null
pairs.value[selectedLeft.value] = rightIdx
selectedLeft.value = null
}
function submit() {
submitted.value = true
}
function reset() {
init()
}
function leftColor(i: number): string {
if (submitted.value) {
if (pairs.value[i] === null) return "#d03050"
return pairs.value[i] === data.value.answer[i] ? "#18a058" : "#d03050"
}
if (selectedLeft.value === i) return "#2080f0"
if (pairs.value[i] !== null) return PALETTE[i % PALETTE.length]
return "var(--n-border-color)"
}
function rightColor(rightIdx: number): string {
const l = leftOf(rightIdx)
if (submitted.value) {
if (l === -1) return "var(--n-border-color)"
return pairs.value[l] === data.value.answer[l] ? "#18a058" : "#d03050"
}
if (l === -1) return "var(--n-border-color)"
return PALETTE[l % PALETTE.length]
}
function itemStyle(color: string, selected: boolean): Record<string, string> {
const plain = color === "var(--n-border-color)"
return {
display: "flex",
alignItems: "center",
gap: "8px",
padding: "10px 12px",
borderRadius: "6px",
border: `${selected ? "2px" : "1.5px"} solid ${color}`,
background: plain ? "transparent" : color + "14",
cursor: locked.value ? "default" : "pointer",
userSelect: "none",
fontSize: "15px",
}
}
function dotStyle(color: string): Record<string, string> {
return {
width: "10px",
height: "10px",
borderRadius: "50%",
background: color,
flexShrink: "0",
}
}
</script>
<template>
<n-card style="margin: 16px 0; border: 1.5px solid var(--n-border-color)">
<template #header>
<n-tag type="primary" :bordered="false">练一练 · 连线匹配</n-tag>
</template>
<p style="font-weight: 500; font-size: 16px; margin-bottom: 8px">
{{ data.question }}
</p>
<p style="color: var(--n-text-color-3); font-size: 13px; margin: 0 0 12px">
先点左边一项再点右边一项即可连线点击已连线的项可取消
</p>
<div style="display: flex; gap: 24px; align-items: flex-start">
<n-space vertical :size="8" style="flex: 1">
<div
v-for="(item, i) in data.left"
:key="'l' + i"
:style="itemStyle(leftColor(i), selectedLeft === i)"
@click="onLeftClick(i)"
>
<span
v-if="pairs[i] !== null && !submitted"
:style="dotStyle(PALETTE[i % PALETTE.length])"
/>
<span>{{ item }}</span>
</div>
</n-space>
<n-space vertical :size="8" style="flex: 1">
<div
v-for="rightIdx in rightOrder"
:key="'r' + rightIdx"
:style="itemStyle(rightColor(rightIdx), false)"
@click="onRightClick(rightIdx)"
>
<span
v-if="leftOf(rightIdx) !== -1 && !submitted"
:style="dotStyle(PALETTE[leftOf(rightIdx) % PALETTE.length])"
/>
<span>{{ data.right[rightIdx] }}</span>
</div>
</n-space>
</div>
<n-alert
v-if="submitted"
:type="allCorrect ? 'success' : 'error'"
:title="allCorrect ? '全部匹配正确!' : '有匹配错误,红色项需要重新连线'"
style="margin-top: 12px"
/>
<n-space style="margin-top: 12px" :size="8">
<n-button type="primary" :disabled="!allPaired || locked" @click="submit">
提交
</n-button>
<n-button @click="reset">重置</n-button>
</n-space>
</n-card>
</template>
@@ -0,0 +1,123 @@
<script setup lang="ts">
import type { Exercise, ExerciseMcqData } from "utils/types"
const props = defineProps<{ exercise: Exercise }>()
const data = computed(() => props.exercise.data as ExerciseMcqData)
const isSingle = computed(() => data.value.answer.length === 1)
const selected = ref<Set<number>>(new Set())
const correct = ref(false)
const wrong = ref(false)
const partial = ref(false)
function select(idx: number) {
if (correct.value) return
const s = new Set(selected.value)
if (isSingle.value) {
s.clear()
if (!selected.value.has(idx)) s.add(idx)
} else {
if (s.has(idx)) s.delete(idx)
else s.add(idx)
}
selected.value = s
wrong.value = false
partial.value = false
}
function submit() {
if (selected.value.size === 0 || correct.value) return
const answer = new Set(data.value.answer)
const sel = selected.value
const isEqual =
sel.size === answer.size && [...sel].every((v) => answer.has(v))
if (isEqual) {
correct.value = true
wrong.value = false
partial.value = false
} else {
selected.value = new Set()
const hasIntersection = [...sel].some((v) => answer.has(v))
if (hasIntersection) {
partial.value = true
wrong.value = false
} else {
wrong.value = true
partial.value = false
}
}
}
function reset() {
selected.value = new Set()
correct.value = false
wrong.value = false
partial.value = false
}
function optionType(idx: number): "default" | "primary" | "success" {
if (correct.value && data.value.answer.includes(idx)) return "success"
if (selected.value.has(idx)) return "primary"
return "default"
}
</script>
<template>
<n-card style="margin: 16px 0; border: 1.5px solid var(--n-border-color)">
<template #header>
<n-space align="center" :size="8">
<n-tag type="success" :bordered="false">
练一练 · {{ isSingle ? "单选题" : "多选题" }}
</n-tag>
</n-space>
</template>
<p style="font-weight: 500; font-size: 16px; margin-bottom: 12px">
{{ data.question }}
</p>
<n-space vertical :size="8">
<n-button
v-for="(opt, idx) in data.options"
:key="idx"
:type="optionType(idx)"
:secondary="optionType(idx) !== 'default'"
:tertiary="optionType(idx) === 'default'"
:strong="selected.has(idx)"
:style="{
justifyContent: 'flex-start',
width: '100%',
textAlign: 'left',
}"
@click="select(idx)"
>
<template #icon>
<span style="font-weight: 700">{{
String.fromCharCode(65 + idx)
}}</span>
</template>
{{ opt }}
</n-button>
</n-space>
<n-alert
v-if="correct || wrong || partial"
:type="correct ? 'success' : partial ? 'warning' : 'error'"
:title="
correct ? '正确!' : partial ? '部分正确,请重试' : '选择有误,请重试'
"
style="margin-top: 12px"
/>
<n-space style="margin-top: 12px" :size="8">
<n-button
type="primary"
:disabled="selected.size === 0 || correct"
@click="submit"
>
提交
</n-button>
<n-button @click="reset">重置</n-button>
</n-space>
</n-card>
</template>
@@ -0,0 +1,92 @@
<script setup lang="ts">
import type { Exercise, ExercisePredictData } from "utils/types"
import { highlight } from "../composables/useCodeHighlight"
import "./exercise-highlight.css"
const props = defineProps<{ exercise: Exercise; lang?: string }>()
const data = computed(() => props.exercise.data as ExercisePredictData)
const codeHtml = computed(() => highlight(data.value.code, props.lang))
const userInput = ref("")
const submitted = ref(false)
watch(() => props.exercise.id, reset, { immediate: true })
function normalize(s: string): string {
return s
.replace(/\r\n/g, "\n")
.split("\n")
.map((l) => l.replace(/\s+$/, ""))
.join("\n")
.replace(/^\n+/, "")
.replace(/\n+$/, "")
}
const allCorrect = computed(() =>
data.value.answer.some((a) => normalize(a) === normalize(userInput.value)),
)
function submit() {
submitted.value = true
}
function reset() {
userInput.value = ""
submitted.value = false
}
</script>
<template>
<n-card style="margin: 16px 0; border: 1.5px solid var(--n-border-color)">
<template #header>
<n-tag type="error" :bordered="false">练一练 · 输出预测</n-tag>
</template>
<p style="font-weight: 500; font-size: 16px; margin-bottom: 12px">
{{ data.question }}
</p>
<pre
:style="{
fontFamily: 'Monaco',
fontSize: '16px',
lineHeight: '1.6',
background: 'var(--n-color)',
border: '1px solid var(--n-border-color)',
borderRadius: '6px',
padding: '12px',
overflowX: 'auto',
margin: 0,
}"
><code v-html="codeHtml" /></pre>
<p style="font-weight: 500; margin: 14px 0 8px">这段代码会输出什么</p>
<n-input
v-model:value="userInput"
type="textarea"
:rows="3"
:disabled="submitted && allCorrect"
placeholder="在这里输入程序会打印的内容"
style="font-family: Monaco"
/>
<n-alert
v-if="submitted"
:type="allCorrect ? 'success' : 'error'"
:title="allCorrect ? '输出正确!' : '输出不正确,再读读代码看看'"
style="margin-top: 12px"
/>
<n-space style="margin-top: 12px" :size="8">
<n-button
type="error"
:disabled="submitted && allCorrect"
@click="submit"
>
提交
</n-button>
<n-button @click="reset">重置</n-button>
</n-space>
</n-card>
</template>
@@ -0,0 +1,130 @@
<script setup lang="ts">
import type { Exercise, ExerciseSortData } from "utils/types"
import { shuffle } from "../composables/useShuffle"
import { highlightLines } from "../composables/useCodeHighlight"
import "./exercise-highlight.css"
const props = defineProps<{ exercise: Exercise; lang?: string }>()
const data = computed(() => props.exercise.data as ExerciseSortData)
type LineItem = { originalIdx: number; text: string }
const lines = ref<LineItem[]>([])
const submitted = ref(false)
function init() {
const shuffled = shuffle(
data.value.lines.map((text, idx) => ({ originalIdx: idx, text })),
)
// 打乱后若恰好与原顺序一致,交换前两项,避免一进入就是已解出状态
const isCorrect = shuffled.every((item, i) => item.originalIdx === i)
if (isCorrect && shuffled.length > 1) {
;[shuffled[0], shuffled[1]] = [shuffled[1], shuffled[0]]
}
lines.value = shuffled
submitted.value = false
}
onMounted(init)
watch(() => props.exercise.id, init)
const dragIdx = ref<number | null>(null)
function onDragStart(idx: number) {
dragIdx.value = idx
}
function onDrop(targetIdx: number) {
if (dragIdx.value === null || dragIdx.value === targetIdx) return
const newLines = [...lines.value]
const [moved] = newLines.splice(dragIdx.value, 1)
newLines.splice(targetIdx, 0, moved)
lines.value = newLines
dragIdx.value = null
submitted.value = false
}
function lineStatus(idx: number): "correct" | "wrong" | "default" {
if (!submitted.value) return "default"
return lines.value[idx].originalIdx === idx ? "correct" : "wrong"
}
const allCorrect = computed(() =>
lines.value.every((item, i) => item.originalIdx === i),
)
function submit() {
submitted.value = true
}
function reset() {
init()
}
const lineHtml = computed<string[]>(() =>
highlightLines(data.value.lines, props.lang),
)
</script>
<template>
<n-card style="margin: 16px 0; border: 1.5px solid var(--n-border-color)">
<template #header>
<n-tag type="info" :bordered="false">练一练 · 代码排序</n-tag>
</template>
<p style="font-weight: 500; font-size: 16px; margin-bottom: 12px">
{{ data.question }}
</p>
<n-space vertical :size="6">
<div
v-for="(line, idx) in lines"
:key="line.originalIdx"
draggable="true"
:style="{
display: 'flex',
alignItems: 'center',
gap: '10px',
padding: '8px 12px',
borderRadius: '6px',
border: `1.5px ${submitted ? 'solid' : 'dashed'} ${
lineStatus(idx) === 'correct'
? '#18a058'
: lineStatus(idx) === 'wrong'
? '#d03050'
: 'var(--n-border-color)'
}`,
background:
lineStatus(idx) === 'correct'
? 'rgba(24,160,88,0.08)'
: lineStatus(idx) === 'wrong'
? 'rgba(208,48,80,0.07)'
: 'transparent',
cursor: 'grab',
fontFamily: 'Monaco',
userSelect: 'none',
}"
@dragstart="onDragStart(idx)"
@dragover.prevent
@drop="onDrop(idx)"
>
<span style="color: #bbb; cursor: grab"></span>
<span v-html="lineHtml[line.originalIdx]" style="white-space: pre" />
</div>
</n-space>
<n-alert
v-if="submitted"
:type="allCorrect ? 'success' : 'error'"
:title="allCorrect ? '顺序正确!' : '顺序有误,红色行需要调整'"
style="margin-top: 12px"
/>
<n-space style="margin-top: 12px" :size="8">
<n-button type="info" :disabled="submitted && allCorrect" @click="submit">
提交
</n-button>
<n-button @click="reset">重置</n-button>
</n-space>
</n-card>
</template>
@@ -0,0 +1,41 @@
<script setup lang="ts">
import type { Exercise } from "utils/types"
const ExerciseMcq = defineAsyncComponent(() => import("./ExerciseMcq.vue"))
const ExerciseSort = defineAsyncComponent(() => import("./ExerciseSort.vue"))
const ExerciseFill = defineAsyncComponent(() => import("./ExerciseFill.vue"))
const ExerciseMatch = defineAsyncComponent(() => import("./ExerciseMatch.vue"))
const ExercisePredict = defineAsyncComponent(
() => import("./ExercisePredict.vue"),
)
const ExerciseDebug = defineAsyncComponent(() => import("./ExerciseDebug.vue"))
const ExerciseGroup = defineAsyncComponent(() => import("./ExerciseGroup.vue"))
defineProps<{ exercise: Exercise; lang?: string }>()
</script>
<template>
<ExerciseMcq v-if="exercise.type === 'mcq'" :exercise="exercise" />
<ExerciseSort
v-else-if="exercise.type === 'sort'"
:exercise="exercise"
:lang="lang"
/>
<ExerciseFill
v-else-if="exercise.type === 'fill'"
:exercise="exercise"
:lang="lang"
/>
<ExerciseMatch v-else-if="exercise.type === 'match'" :exercise="exercise" />
<ExercisePredict
v-else-if="exercise.type === 'predict'"
:exercise="exercise"
:lang="lang"
/>
<ExerciseDebug
v-else-if="exercise.type === 'debug'"
:exercise="exercise"
:lang="lang"
/>
<ExerciseGroup v-else-if="exercise.type === 'group'" :exercise="exercise" />
</template>
@@ -0,0 +1,50 @@
/* 练一练代码高亮配色(明 / 暗),由涉及代码高亮的题型组件统一引入 */
.hljs-keyword,
.hljs-operator,
.hljs-selector-tag {
color: #d73a49;
}
.hljs-string,
.hljs-regexp,
.hljs-template-literal {
color: #032f62;
}
.hljs-comment,
.hljs-quote {
color: #6a737d;
font-style: italic;
}
.hljs-number,
.hljs-literal {
color: #005cc5;
}
.hljs-built_in,
.hljs-title.function_,
.hljs-class .hljs-title {
color: #6f42c1;
}
.dark .hljs-keyword,
.dark .hljs-operator,
.dark .hljs-selector-tag {
color: #c678dd;
}
.dark .hljs-string,
.dark .hljs-regexp,
.dark .hljs-template-literal {
color: #98c379;
}
.dark .hljs-comment,
.dark .hljs-quote {
color: #7f848e;
font-style: italic;
}
.dark .hljs-number,
.dark .hljs-literal {
color: #e5c07b;
}
.dark .hljs-built_in,
.dark .hljs-title.function_,
.dark .hljs-class .hljs-title {
color: #61afef;
}
@@ -0,0 +1,41 @@
import hljs from "highlight.js/lib/core"
import python from "highlight.js/lib/languages/python"
import c from "highlight.js/lib/languages/c"
hljs.registerLanguage("python", python)
hljs.registerLanguage("c", c)
export function escapeHtml(text: string): string {
return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
}
function normalizeLang(lang?: string): "python" | "c" | null {
return lang === "python" ? "python" : lang === "c" ? "c" : null
}
// 把整段代码高亮为 HTML;不支持的语言或异常时回退为转义文本
export function highlight(code: string, lang?: string): string {
const language = normalizeLang(lang)
if (language) {
try {
return hljs.highlight(code, { language }).value
} catch {
// fall through
}
}
return escapeHtml(code)
}
// 按行高亮:整体高亮后再按行切分,保证跨行 token 着色正确,返回逐行 HTML 数组
export function highlightLines(lines: string[], lang?: string): string[] {
const language = normalizeLang(lang)
if (language) {
try {
const html = hljs.highlight(lines.join("\n"), { language }).value
return html.split("\n")
} catch {
// fall through
}
}
return lines.map((line) => escapeHtml(line))
}
@@ -0,0 +1,36 @@
import type { Exercise } from "utils/types"
type Segment =
{ type: "md"; content: string } | { type: "exercise"; exercise: Exercise }
export function parseExercises(
content: string,
exercises: Exercise[],
): Segment[] {
const exerciseMap = new Map(exercises.map((e) => [e.id, e]))
const segments: Segment[] = []
const regex = /\[\[exercise:(\d+)\]\]/g
let lastIndex = 0
let match: RegExpExecArray | null
while ((match = regex.exec(content)) !== null) {
if (match.index > lastIndex) {
segments.push({
type: "md",
content: content.slice(lastIndex, match.index),
})
}
const id = parseInt(match[1])
const exercise = exerciseMap.get(id)
if (exercise) {
segments.push({ type: "exercise", exercise })
}
lastIndex = regex.lastIndex
}
if (lastIndex < content.length) {
segments.push({ type: "md", content: content.slice(lastIndex) })
}
return segments
}
@@ -0,0 +1,9 @@
// Fisher–Yates 洗牌,返回新数组,不修改原数组
export function shuffle<T>(arr: T[]): T[] {
const a = [...arr]
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[a[i], a[j]] = [a[j], a[i]]
}
return a
}
+255
View File
@@ -0,0 +1,255 @@
<template>
<div class="learn-container">
<!-- 桌面端布局 -->
<n-grid
:cols="5"
:x-gap="16"
v-if="tutorial.id && isDesktop"
class="learn-grid"
>
<n-gi :span="1" class="learn-col">
<n-card title="教程目录" :bordered="false" size="small">
<n-list hoverable clickable>
<n-list-item
v-for="(item, index) in titles"
:key="item.id"
@click="goToLesson(index + 1)"
>
<n-text
:type="step === index + 1 ? 'primary' : undefined"
:strong="step === index + 1"
>
{{ index + 1 }}. {{ item.title }}
</n-text>
</n-list-item>
</n-list>
</n-card>
</n-gi>
<n-gi :span="tutorial.code ? 2 : 4" class="learn-col">
<n-card
:title="`第 ${step} 课:${titles[step - 1]?.title}`"
:bordered="false"
size="small"
>
<template v-for="(seg, i) in segments" :key="i">
<MdPreview
v-if="seg.type === 'md'"
preview-theme="vuepress"
:theme="isDark ? 'dark' : 'light'"
:model-value="seg.content"
/>
<ExerciseWidget
v-else
:exercise="seg.exercise"
:lang="tutorial.type"
/>
</template>
</n-card>
</n-gi>
<n-gi :span="2" v-if="tutorial.code" class="learn-col learn-col--code">
<n-card
title="示例代码"
:bordered="false"
size="small"
class="code-card"
content-style="height: calc(100% - 44px); padding: 0;"
>
<CodeEditor
:language="editorLanguage"
v-model="tutorial.code"
height="100%"
/>
</n-card>
</n-gi>
</n-grid>
<!-- 手机端布局 -->
<template v-if="tutorial.id && !isDesktop">
<n-tabs type="line" animated v-model:value="activeTab">
<n-tab-pane name="catalog" tab="目录">
<n-list hoverable clickable>
<n-list-item
v-for="(item, index) in titles"
:key="item.id"
@click="goToLesson(index + 1)"
>
<n-text
:type="step === index + 1 ? 'primary' : undefined"
:strong="step === index + 1"
>
{{ index + 1 }}. {{ item.title }}
</n-text>
</n-list-item>
</n-list>
</n-tab-pane>
<n-tab-pane name="content" :tab="`第 ${step} 课`">
<template v-for="(seg, i) in segments" :key="i">
<MdPreview
v-if="seg.type === 'md'"
preview-theme="vuepress"
:theme="isDark ? 'dark' : 'light'"
:model-value="seg.content"
/>
<ExerciseWidget
v-else
:exercise="seg.exercise"
:lang="tutorial.type"
/>
</template>
</n-tab-pane>
<n-tab-pane name="code" tab="示例代码" v-if="tutorial.code">
<CodeEditor :language="editorLanguage" v-model="tutorial.code" />
</n-tab-pane>
</n-tabs>
<n-divider style="margin: 12px 0" />
<n-flex align="center" justify="space-between">
<n-button
secondary
type="primary"
:disabled="isFirstLesson"
@click="goToPrevLesson"
>
上一课
</n-button>
<n-text>{{ step }} / {{ titles.length }}</n-text>
<n-button
secondary
type="primary"
:disabled="isLastLesson"
@click="goToNextLesson"
>
下一课
</n-button>
</n-flex>
</template>
<n-empty
v-if="isEmpty"
description="该教程还没有公开"
style="margin-top: 80px"
/>
</div>
</template>
<script setup lang="ts">
import { MdPreview } from "md-editor-v3"
import "md-editor-v3/lib/preview.css"
import type { Tutorial, Exercise, LANGUAGE } from "utils/types"
import { getTutorial, getTutorials, getExercises } from "../api"
import { parseExercises } from "./composables/useExerciseParse"
import { useBreakpoints } from "shared/composables/breakpoints"
import { useLearnProgress } from "shared/composables/learnProgress"
const ExerciseWidget = defineAsyncComponent(
() => import("./components/ExerciseWidget.vue"),
)
const CodeEditor = defineAsyncComponent(
() => import("shared/components/CodeEditor.vue"),
)
const isDark = useDark()
const route = useRoute()
const router = useRouter()
const { isDesktop } = useBreakpoints()
const { learnStep } = useLearnProgress()
const step = computed(() => {
const value = route.params.step as string | undefined
if (!value) return 1
return parseInt(value)
})
const type = computed<"python" | "c">(() =>
route.params.type === "c" ? "c" : "python",
)
const tutorial = ref<Partial<Tutorial>>({
id: 0,
title: "",
content: "",
code: "",
})
const editorLanguage = computed<LANGUAGE>(() =>
tutorial.value.type === "c" ? "C" : "Python3",
)
const titles = ref<{ id: number; title: string }[]>([])
const exercises = ref<Exercise[]>([])
const activeTab = ref("content")
const isEmpty = ref(false)
const segments = computed(() =>
parseExercises(tutorial.value.content ?? "", exercises.value),
)
const isFirstLesson = computed(() => step.value === 1)
const isLastLesson = computed(() => step.value === titles.value.length)
function goToLesson(lessonNumber: number) {
activeTab.value = "content"
router.push(
`/learn/${type.value}/${lessonNumber.toString().padStart(2, "0")}`,
)
}
function goToPrevLesson() {
if (step.value > 1) goToLesson(step.value - 1)
}
function goToNextLesson() {
if (step.value < titles.value.length) goToLesson(step.value + 1)
}
async function init() {
const res1 = await getTutorials(type.value)
titles.value = res1.data
isEmpty.value = titles.value.length === 0
if (isEmpty.value) return
const id = titles.value[step.value - 1].id
const [res2, exs] = await Promise.allSettled([
getTutorial(id),
getExercises(id),
])
if (res2.status === "fulfilled") tutorial.value = res2.value.data
exercises.value = exs.status === "fulfilled" ? exs.value : []
learnStep.value[type.value] = step.value
}
watch(
() => [route.params.type, route.params.step],
async () => {
if (route.name === "learn") init()
},
{ immediate: true },
)
</script>
<style scoped>
/* 桌面端固定高度,让目录/内容/代码三栏各自内部滚动;移动端不限高,交给页面整体滚动 */
@media (min-width: 769px) {
.learn-container {
height: calc(100vh - 138px);
}
}
.learn-grid {
height: 100%;
}
.learn-col {
overflow-y: auto;
height: 100%;
}
.learn-col--code {
overflow-y: hidden;
}
.code-card {
height: 100%;
}
</style>