重构自学模块

This commit is contained in:
2025-06-15 14:40:47 +08:00
parent 70dd3540c9
commit 73b86c644a
36 changed files with 1118 additions and 848 deletions

2
.env
View File

@@ -1,4 +1,4 @@
VITE_MAXKB_URL=https://maxkb.xuyue.cc/api/application/embed?protocol=https&host=maxkb.xuyue.cc&token=1b7cd529423b3f36 VITE_MAXKB_URL=https://maxkb.xuyue.cc/api/application/embed?protocol=https&host=maxkb.xuyue.cc&token=1b7cd529423b3f36
VITE_OJ_URL=https://ojtest.xuyue.cc VITE_OJ_URL=http://localhost:8000
VITE_CODE_URL=https://code.xuyue.cc VITE_CODE_URL=https://code.xuyue.cc
VITE_JUDGE0_URL=https://judge0api.xuyue.cc VITE_JUDGE0_URL=https://judge0api.xuyue.cc

1384
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -22,6 +22,7 @@
"copy-text-to-clipboard": "^3.2.0", "copy-text-to-clipboard": "^3.2.0",
"date-fns": "^4.1.0", "date-fns": "^4.1.0",
"highlight.js": "^11.11.1", "highlight.js": "^11.11.1",
"md-editor-v3": "^5.7.0",
"naive-ui": "^2.41.1", "naive-ui": "^2.41.1",
"normalize.css": "^8.0.1", "normalize.css": "^8.0.1",
"pinia": "^3.0.3", "pinia": "^3.0.3",
@@ -32,7 +33,6 @@
}, },
"devDependencies": { "devDependencies": {
"@iconify/vue": "^5.0.0", "@iconify/vue": "^5.0.0",
"@shikijs/markdown-it": "^3.6.0",
"@types/canvas-confetti": "^1.9.0", "@types/canvas-confetti": "^1.9.0",
"@types/node": "^24.0.1", "@types/node": "^24.0.1",
"@vitejs/plugin-vue": "^5.2.4", "@vitejs/plugin-vue": "^5.2.4",
@@ -41,7 +41,6 @@
"typescript": "^5.8.3", "typescript": "^5.8.3",
"unplugin-auto-import": "^19.3.0", "unplugin-auto-import": "^19.3.0",
"unplugin-vue-components": "^28.7.0", "unplugin-vue-components": "^28.7.0",
"unplugin-vue-markdown": "^28.3.1",
"vite": "^6.3.5", "vite": "^6.3.5",
"vue-tsc": "^2.2.10" "vue-tsc": "^2.2.10"
} }

View File

@@ -8,6 +8,7 @@ import {
Contest, Contest,
Server, Server,
TestcaseUploadedReturns, TestcaseUploadedReturns,
Tutorial,
User, User,
WebsiteConfig, WebsiteConfig,
} from "~/utils/types" } from "~/utils/types"
@@ -222,3 +223,31 @@ export function getCommentList(offset = 0, limit = 10, problem: string) {
export function deleteComment(id: number) { export function deleteComment(id: number) {
return http.delete("admin/comment", { params: { id } }) return http.delete("admin/comment", { params: { id } })
} }
export async function getTutorialList() {
const res = await http.get("admin/tutorial")
return res.data
}
export async function getTutorial(id: number) {
const res = await http.get("admin/tutorial", { params: { id } })
return res.data
}
export async function createTutorial(data: Partial<Tutorial>) {
const res = await http.post("admin/tutorial", data)
return res.data
}
export async function updateTutorial(data: Partial<Tutorial>) {
const res = await http.put("admin/tutorial", data)
return res.data
}
export function deleteTutorial(id: number) {
return http.delete("admin/tutorial", { params: { id } })
}
export function setTutorialVisibility(id: number, is_public: boolean) {
return http.put("admin/tutorial/visibility", { id, is_public })
}

View File

@@ -0,0 +1,43 @@
<script lang="ts" setup>
import { deleteTutorial } from "~/admin/api"
interface Props {
tutorialID: number
}
const props = defineProps<Props>()
const emit = defineEmits(["deleted"])
const router = useRouter()
const message = useMessage()
function goEdit() {
router.push({
name: "admin tutorial edit",
params: { tutorialID: props.tutorialID },
})
}
async function handleDelete() {
try {
await deleteTutorial(props.tutorialID)
message.success("删除成功")
emit("deleted")
} catch (err: any) {
message.error(err.data)
}
}
</script>
<template>
<n-flex>
<n-button size="small" type="success" secondary @click="goEdit">
编辑
</n-button>
<n-popconfirm @positive-click="handleDelete">
<template #trigger>
<n-button size="small" type="error" secondary>删除</n-button>
</template>
确定删除这个教程吗
</n-popconfirm>
</n-flex>
</template>
<style scoped></style>

View File

@@ -0,0 +1,125 @@
<script lang="ts" setup>
import CodeEditor from "~/shared/components/CodeEditor.vue"
import MarkdownEditor from "~/shared/components/MarkdownEditor.vue"
import { Tutorial } from "~/utils/types"
import { createTutorial, getTutorial, updateTutorial } from "../api"
interface Props {
tutorialID?: string
}
const route = useRoute()
const router = useRouter()
const message = useMessage()
const props = defineProps<Props>()
const tutorial = reactive<Tutorial>({
id: 0,
title: "",
content: "",
code: "",
is_public: false,
order: 0,
type: "python", // 默认选择 Python
})
const typeOptions = [
{ label: "Python", value: "python" },
{ label: "C 语言", value: "c" },
]
async function init() {
if (!props.tutorialID) {
return
}
const id = parseInt(route.params.tutorialID as string)
const data = await getTutorial(id)
tutorial.id = data.id
tutorial.title = data.title
tutorial.content = data.content
tutorial.code = data.code || ""
tutorial.is_public = data.is_public
tutorial.order = data.order
tutorial.type = data.type || "python"
}
async function submit() {
if (!tutorial.title || !tutorial.content) {
message.error("标题和正文必填")
return
}
try {
if (route.name === "admin tutorial create") {
await createTutorial({
title: tutorial.title,
content: tutorial.content,
code: tutorial.code,
is_public: tutorial.is_public,
order: tutorial.order,
type: tutorial.type,
})
message.success("成功新建教程 💐")
} else {
await updateTutorial(tutorial)
message.success("修改已保存")
}
router.push({ name: "admin tutorial list" })
} catch (err: any) {
message.error(err.data)
}
}
onMounted(init)
</script>
<template>
<h2 class="title">
{{ route.name === "admin tutorial create" ? "新建教程" : "编辑教程" }}
</h2>
<n-form inline>
<n-form-item label="标题">
<n-input class="contestTitle" v-model:value="tutorial.title" />
</n-form-item>
<n-form-item label="语言">
<n-select
v-model:value="tutorial.type"
:options="typeOptions"
class="select"
/>
</n-form-item>
<n-form-item label="顺序">
<n-input-number style="width: 100px" v-model:value="tutorial.order" :min="0" />
</n-form-item>
<n-form-item label="可见">
<n-switch v-model:value="tutorial.is_public" />
</n-form-item>
<n-form-item>
<n-button type="primary" @click="submit">保存</n-button>
</n-form-item>
</n-form>
<n-tabs type="line" animated>
<n-tab-pane name="content" tab="教程内容">
<MarkdownEditor v-model:value="tutorial.content" />
</n-tab-pane>
<n-tab-pane name="code" tab="示例代码">
<CodeEditor
v-model:value="tutorial.code"
:language="tutorial.type === 'python' ? 'Python3' : 'C'"
height="400px"
/>
</n-tab-pane>
</n-tabs>
</template>
<style scoped>
.title {
margin-top: 0;
}
.select {
width: 100px;
}
.contestTitle {
width: 400px;
}
</style>

100
src/admin/tutorial/list.vue Normal file
View File

@@ -0,0 +1,100 @@
<script setup lang="ts">
import { NSwitch } from "naive-ui"
import { parseTime } from "~/utils/functions"
import { Tutorial } from "~/utils/types"
import { getTutorialList, setTutorialVisibility } from "../api"
import Actions from "./components/Actions.vue"
const tutorials = ref<{ [key: string]: Tutorial[] }>({
python: [],
c: []
})
const message = useMessage()
const activeTab = ref('python')
const columns: DataTableColumn<Tutorial>[] = [
{ title: "ID", key: "id", width: 60 },
{ title: "标题", key: "title", minWidth: 300 },
{
title: "创建时间",
key: "created_at",
width: 180,
render: (row) => parseTime(row.created_at!, "YYYY-MM-DD HH:mm:ss"),
},
{
title: "顺序",
key: "order",
},
{
title: "作者",
key: "created_by",
render: (row) => row.created_by?.username,
width: 80,
},
{
title: "可见",
key: "is_public",
render: (row) =>
h(NSwitch, {
value: row.is_public,
size: "small",
rubberBand: false,
onUpdateValue: () => toggleVisible(row),
}),
},
{
title: "操作",
key: "actions",
width: 140,
render: (row) =>
h(Actions, { tutorialID: row.id, onDeleted: listTutorials }),
},
]
async function toggleVisible(tutorial: Tutorial) {
tutorial.is_public = !tutorial.is_public
try {
await setTutorialVisibility(tutorial.id, tutorial.is_public)
message.success("更新成功")
} catch (err: any) {
message.error(err.data)
tutorial.is_public = !tutorial.is_public
}
}
async function listTutorials() {
tutorials.value = await getTutorialList()
}
onMounted(listTutorials)
</script>
<template>
<n-flex align="center" class="titleWrapper">
<h2 class="title">教程列表</h2>
<n-button
type="primary"
@click="$router.push({ name: 'admin tutorial create' })"
>
新建
</n-button>
</n-flex>
<n-tabs v-model:value="activeTab" type="line" animated>
<n-tab-pane name="python" tab="Python">
<n-data-table striped :columns="columns" :data="tutorials.python" />
</n-tab-pane>
<n-tab-pane name="c" tab="C 语言">
<n-data-table striped :columns="columns" :data="tutorials.c" />
</n-tab-pane>
</n-tabs>
</template>
<style scoped>
.titleWrapper {
margin-bottom: 16px;
}
.title {
margin: 0;
}
</style>

View File

Before

Width:  |  Height:  |  Size: 165 KiB

After

Width:  |  Height:  |  Size: 165 KiB

View File

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 35 KiB

View File

Before

Width:  |  Height:  |  Size: 1.5 MiB

After

Width:  |  Height:  |  Size: 1.5 MiB

View File

Before

Width:  |  Height:  |  Size: 1.4 MiB

After

Width:  |  Height:  |  Size: 1.4 MiB

View File

Before

Width:  |  Height:  |  Size: 118 KiB

After

Width:  |  Height:  |  Size: 118 KiB

12
src/learn_old/api.ts Normal file
View File

@@ -0,0 +1,12 @@
import http from "utils/http"
export async function list() {
const res = await http.get("tutorials")
return res.data
}
export async function get(id: string) {
const res = await http.get(`tutorial/${id}`)
return res.data
}

View File

@@ -2,6 +2,6 @@
会赢的! 会赢的!
不是,你怎么说话带空格啊? 不是,你怎么说话带空格啊?
你这身高绝对没有1米76 你这身高绝对没有1米76
优美的Python语言之f\*\*k-string 优美的Python语言之f**k-string
全都怪我,不该沉默时沉默 全都怪我,不该沉默时沉默
可以看到的循环 可以看到的循环

View File

@@ -6,13 +6,13 @@ import { STORAGE_KEY } from "utils/constants"
import storage from "utils/storage" import storage from "utils/storage"
import App from "./App.vue" import App from "./App.vue"
import { admins, learns, ojs } from "./routes" import { admins, ojs } from "./routes"
import { toggleLogin } from "./shared/composables/modal" import { toggleLogin } from "./shared/composables/modal"
const router = createRouter({ const router = createRouter({
history: createWebHistory(), history: createWebHistory(),
routes: [ojs, admins, learns], routes: [ojs, admins],
}) })
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {

View File

@@ -232,3 +232,11 @@ export function refreshUserProblemDisplayIds() {
export function getMetrics(userid: number) { export function getMetrics(userid: number) {
return http.get("metrics", { params: { userid } }) return http.get("metrics", { params: { userid } })
} }
export function getTutorial(id: number) {
return http.get("tutorial", { params: { id } })
}
export function getTutorials() {
return http.get("tutorials")
}

144
src/oj/learn/index.vue Normal file
View File

@@ -0,0 +1,144 @@
<template>
<n-grid :cols="2" :x-gap="24" v-if="!!tutorial.id">
<n-gi :span="1">
<n-flex vertical>
<n-flex align="center">
<n-button text :disabled="step == 1" @click="prev">
<Icon :width="30" icon="pepicons-pencil:arrow-left"></Icon>
</n-button>
<n-dropdown size="large" :options="menu" trigger="click">
<n-button tertiary style="flex: 1" size="large">
<n-flex align="center">
<span style="font-weight: bold">
{{ title }}
</span>
<Icon :width="24" icon="proicons:chevron-down"></Icon>
</n-flex>
</n-button>
</n-dropdown>
<n-button text :disabled="step == titles.length" @click="next">
<Icon :width="30" icon="pepicons-pencil:arrow-right"></Icon>
</n-button>
</n-flex>
<n-flex vertical size="large">
<MdPreview
:theme="isDark ? 'dark' : 'light'"
:model-value="tutorial.content"
/>
<n-flex justify="space-between">
<div style="flex: 1">
<n-button
block
style="height: 60px"
v-if="step !== 1"
@click="prev"
>
上一课时
</n-button>
</div>
<div style="flex: 1">
<n-button
block
style="height: 60px"
v-if="step !== titles.length"
@click="next"
>
下一课时
</n-button>
</div>
</n-flex>
</n-flex>
</n-flex>
</n-gi>
<n-gi :span="1">
<n-flex vertical>
<CodeEditor
v-show="!!tutorial.code"
language="Python3"
v-model="tutorial.code"
/>
</n-flex>
</n-gi>
</n-grid>
</template>
<script setup lang="ts">
import { Icon } from "@iconify/vue"
import { MdPreview } from "md-editor-v3"
import "md-editor-v3/lib/preview.css"
import { Tutorial } from "~/utils/types"
import { getTutorial, getTutorials } from "../api"
const CodeEditor = defineAsyncComponent(
() => import("~/shared/components/CodeEditor.vue"),
)
const isDark = useDark()
const route = useRoute()
const router = useRouter()
const step = computed(() => {
if (!route.params.step || !route.params.step.length) return 1
else {
return parseInt(route.params.step[0])
}
})
const tutorial = ref<Partial<Tutorial>>({
id: 0,
title: "",
content: "",
code: "",
})
const titles = ref<{ id: number; title: string }[]>([])
const title = computed(
() => `${step.value} 课:${titles.value[step.value - 1].title}`,
)
const menu = computed<DropdownOption[]>(() => {
return titles.value.map((item, index) => {
const id = (index + 1).toString().padStart(2, "0")
const prefix = `${index + 1} 课:`
return {
key: id,
label: prefix + item.title,
props: {
onClick: () => router.push(`/learn/${id}`),
},
}
})
})
async function init() {
const res1 = await getTutorials()
titles.value = res1.data
const id = titles.value[step.value - 1].id
const res2 = await getTutorial(id)
tutorial.value = res2.data
}
function next() {
if (step.value === titles.value.length) return
const dest = (step.value + 1).toString().padStart(2, "0")
router.push("/learn/" + dest)
}
function prev() {
if (step.value === 1) return
const dest = (step.value - 1).toString().padStart(2, "0")
router.push("/learn/" + dest)
}
watch(
() => route.params.step,
async () => {
if (route.name !== "learn") return
init()
},
{ immediate: true },
)
</script>
<style></style>

View File

@@ -89,17 +89,11 @@ export const ojs: RouteRecordRaw = {
component: () => import("oj/user/message.vue"), component: () => import("oj/user/message.vue"),
meta: { requiresAuth: true }, meta: { requiresAuth: true },
}, },
],
}
export const learns: RouteRecordRaw = {
path: "/learn/:step+",
component: () => import("~/shared/layout/default.vue"),
children: [
{ {
path: "", path: "learn/:step+",
component: () => import("learn/index.vue"),
name: "learn", name: "learn",
component: () => import("oj/learn/index.vue"),
props: true,
}, },
], ],
} }
@@ -204,5 +198,21 @@ export const admins: RouteRecordRaw = {
name: "admin message list", name: "admin message list",
component: () => import("admin/communication/messages.vue"), component: () => import("admin/communication/messages.vue"),
}, },
{
path: "tutorial/list",
name: "admin tutorial list",
component: () => import("admin/tutorial/list.vue"),
},
{
path: "tutorial/create",
name: "admin tutorial create",
component: () => import("admin/tutorial/detail.vue"),
},
{
path: "tutorial/edit/:tutorialID",
name: "admin tutorial edit",
component: () => import("admin/tutorial/detail.vue"),
props: true,
},
], ],
} }

View File

@@ -0,0 +1,41 @@
<template>
<MdEditor
:theme="isDark ? 'dark' : 'light'"
v-model="modelValue"
@onUploadImg="onUploadImg"
/>
</template>
<script setup lang="ts">
import { MdEditor } from "md-editor-v3"
import "md-editor-v3/lib/style.css"
import { uploadImage } from "../../admin/api"
const isDark = useDark()
const modelValue = defineModel<string>("value")
const message = useMessage()
const onUploadImg = async (
files: File[],
callback: (urls: string[]) => void,
) => {
try {
const res = await Promise.all(
files.map(async (file) => {
const path = await uploadImage(file)
if (!path) {
message.error("图片上传失败")
return ""
}
return path
}),
)
callback(res.filter((url) => url !== ""))
} catch (err) {
message.error("图片上传失败")
callback([])
}
}
</script>

View File

@@ -50,6 +50,11 @@ const options: MenuOption[] = [
), ),
key: "admin announcement list", key: "admin announcement list",
}, },
{
label: () =>
h(RouterLink, { to: "/admin/tutorial/list" }, { default: () => "教程" }),
key: "admin tutorial list",
},
] ]
const active = computed(() => (route.name as string) || "home") const active = computed(() => (route.name as string) || "home")

View File

@@ -374,3 +374,16 @@ export interface Comment {
create_time: Date create_time: Date
user: SampleUser user: SampleUser
} }
export interface Tutorial {
id: number
title: string
content: string
code: string
is_public: boolean
order: number
type: "python" | "c"
created_by?: User
updated_at?: Date
created_at?: Date
}

View File

@@ -17,7 +17,6 @@
"utils/*": ["./src/utils/*"], "utils/*": ["./src/utils/*"],
"oj/*": ["./src/oj/*"], "oj/*": ["./src/oj/*"],
"admin/*": ["./src/admin/*"], "admin/*": ["./src/admin/*"],
"learn/*": ["./src/learn/*"]
}, },
"types": ["naive-ui/volar"] "types": ["naive-ui/volar"]
}, },

View File

@@ -1,10 +1,8 @@
import Shiki from "@shikijs/markdown-it"
import Vue from "@vitejs/plugin-vue" import Vue from "@vitejs/plugin-vue"
import path from "path" import path from "path"
import AutoImport from "unplugin-auto-import/vite" import AutoImport from "unplugin-auto-import/vite"
import { NaiveUiResolver } from "unplugin-vue-components/resolvers" import { NaiveUiResolver } from "unplugin-vue-components/resolvers"
import Components from "unplugin-vue-components/vite" import Components from "unplugin-vue-components/vite"
import Markdown from "unplugin-vue-markdown/vite"
import { defineConfig, loadEnv } from "vite" import { defineConfig, loadEnv } from "vite"
export default defineConfig(({ mode }) => { export default defineConfig(({ mode }) => {
@@ -32,6 +30,11 @@ export default defineConfig(({ mode }) => {
"@codemirror/lang-cpp", "@codemirror/lang-cpp",
"@codemirror/lang-python", "@codemirror/lang-python",
], ],
md: [
"md-editor-v3",
"md-editor-v3/lib/style.css",
"md-editor-v3/lib/preview.css",
],
}, },
}, },
}, },
@@ -42,11 +45,10 @@ export default defineConfig(({ mode }) => {
utils: path.resolve(__dirname, "./src/utils"), utils: path.resolve(__dirname, "./src/utils"),
oj: path.resolve(__dirname, "./src/oj"), oj: path.resolve(__dirname, "./src/oj"),
admin: path.resolve(__dirname, "./src/admin"), admin: path.resolve(__dirname, "./src/admin"),
learn: path.resolve(__dirname, "./src/learn"),
}, },
}, },
plugins: [ plugins: [
Vue({ include: [/\.vue$/, /\.md$/] }), Vue(),
AutoImport({ AutoImport({
imports: [ imports: [
"vue", "vue",
@@ -83,18 +85,6 @@ export default defineConfig(({ mode }) => {
resolvers: [NaiveUiResolver()], resolvers: [NaiveUiResolver()],
dts: "./src/components.d.ts", dts: "./src/components.d.ts",
}), }),
Markdown({
async markdownItSetup(md) {
md.use(
await Shiki({
themes: {
light: "vitesse-light",
dark: "vitesse-dark",
},
}),
)
},
}),
], ],
server: { server: {
proxy: { proxy: {