协同编辑代码
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
import { PROBLEM_PERMISSION, USER_TYPE } from "~/utils/constants"
|
||||
import { getUserRole } from "~/utils/functions"
|
||||
import { User } from "~/utils/types"
|
||||
import TextCopy from "~/shared/components/TextCopy.vue"
|
||||
|
||||
interface Props {
|
||||
user: User
|
||||
@@ -30,6 +31,6 @@ const isNotRegularUser = computed(
|
||||
: "仅自己"
|
||||
}}
|
||||
</n-tag>
|
||||
{{ props.user.username }}
|
||||
<TextCopy>{{ props.user.username }}</TextCopy>
|
||||
</n-flex>
|
||||
</template>
|
||||
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
import Actions from "./components/Actions.vue"
|
||||
import Name from "./components/Name.vue"
|
||||
import { PROBLEM_PERMISSION, USER_TYPE } from "~/utils/constants"
|
||||
import { useRouteQuery } from "@vueuse/router"
|
||||
import TextCopy from "~/shared/components/TextCopy.vue"
|
||||
|
||||
const message = useMessage()
|
||||
|
||||
@@ -23,9 +25,9 @@ interface UserQuery {
|
||||
}
|
||||
|
||||
// 使用分页 composable
|
||||
const { query, clearQuery } = usePagination<UserQuery>({
|
||||
keyword: "",
|
||||
type: "",
|
||||
const { query } = usePagination<UserQuery>({
|
||||
keyword: useRouteQuery("keyword", "").value,
|
||||
type: useRouteQuery("type", "").value,
|
||||
})
|
||||
|
||||
const total = ref(0)
|
||||
@@ -56,6 +58,7 @@ const columns: DataTableColumn<User>[] = [
|
||||
title: "密码",
|
||||
key: "raw_password",
|
||||
width: 100,
|
||||
render: (row) => h(TextCopy, () => row.raw_password),
|
||||
},
|
||||
{
|
||||
title: "创建时间",
|
||||
@@ -72,7 +75,7 @@ const columns: DataTableColumn<User>[] = [
|
||||
? parseTime(row.last_login, "YYYY-MM-DD HH:mm:ss")
|
||||
: "从未登录",
|
||||
},
|
||||
{ title: "真名", key: "real_name", width: 100 },
|
||||
{ title: "真名", key: "real_name", width: 100, render: (row) => h(TextCopy, () => row.real_name) },
|
||||
{ title: "邮箱", key: "email", width: 200 },
|
||||
{
|
||||
key: "actions",
|
||||
|
||||
1
src/env.d.ts
vendored
1
src/env.d.ts
vendored
@@ -7,6 +7,7 @@ interface ImportMetaEnv {
|
||||
readonly PUBLIC_CODE_URL: string
|
||||
readonly PUBLIC_JUDGE0_URL: string
|
||||
readonly PUBLIC_ICONIFY_URL: string
|
||||
readonly PUBLIC_SIGNALING_URL: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
|
||||
@@ -5,56 +5,90 @@ import { SOURCES } from "utils/constants"
|
||||
import CodeEditor from "~/shared/components/CodeEditor.vue"
|
||||
import { isDesktop } from "~/shared/composables/breakpoints"
|
||||
import storage from "~/utils/storage"
|
||||
import { LANGUAGE } from "~/utils/types"
|
||||
import Form from "./Form.vue"
|
||||
|
||||
const route = useRoute()
|
||||
const contestID = !!route.params.contestID ? route.params.contestID : null
|
||||
const formRef = useTemplateRef<InstanceType<typeof Form>>("formRef")
|
||||
|
||||
const sync = ref(false)
|
||||
const otherUserInfo = ref<{ name: string; isSuperAdmin: boolean }>()
|
||||
const hadConnection = ref(false)
|
||||
|
||||
const contestID = route.params.contestID || null
|
||||
const storageKey = computed(
|
||||
() =>
|
||||
`problem_${problem.value!._id}_contest_${contestID}_lang_${code.language}`,
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
if (storage.get(storageKey.value)) {
|
||||
code.value = storage.get(storageKey.value)
|
||||
} else {
|
||||
code.value =
|
||||
problem.value!.template[code.language] || SOURCES[code.language]
|
||||
}
|
||||
})
|
||||
|
||||
const editorHeight = computed(() =>
|
||||
isDesktop.value ? "calc(100vh - 133px)" : "calc(100vh - 172px)",
|
||||
)
|
||||
|
||||
function changeCode(v: string) {
|
||||
onMounted(() => {
|
||||
const savedCode = storage.get(storageKey.value)
|
||||
code.value =
|
||||
savedCode ||
|
||||
problem.value!.template[code.language] ||
|
||||
SOURCES[code.language]
|
||||
})
|
||||
|
||||
const changeCode = (v: string) => {
|
||||
storage.set(storageKey.value, v)
|
||||
}
|
||||
|
||||
function changeLanguage(v: string) {
|
||||
if (
|
||||
storage.get(storageKey.value) &&
|
||||
storageKey.value.split("_").pop() === v
|
||||
) {
|
||||
code.value = storage.get(storageKey.value)
|
||||
} else {
|
||||
code.value =
|
||||
problem.value!.template[code.language] || SOURCES[code.language]
|
||||
const changeLanguage = (v: LANGUAGE) => {
|
||||
const savedCode = storage.get(storageKey.value)
|
||||
code.value =
|
||||
savedCode && storageKey.value.split("_").pop() === v
|
||||
? savedCode
|
||||
: problem.value!.template[code.language] || SOURCES[code.language]
|
||||
}
|
||||
|
||||
const toggleSync = (value: boolean) => {
|
||||
sync.value = value
|
||||
if (!value) {
|
||||
hadConnection.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleSyncClosed = () => {
|
||||
sync.value = false
|
||||
otherUserInfo.value = undefined
|
||||
hadConnection.value = false
|
||||
formRef.value?.resetSyncStatus()
|
||||
}
|
||||
|
||||
const handleSyncStatusChange = (status: {
|
||||
otherUser?: { name: string; isSuperAdmin: boolean }
|
||||
}) => {
|
||||
otherUserInfo.value = status.otherUser
|
||||
if (status.otherUser) {
|
||||
hadConnection.value = true
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<n-flex vertical>
|
||||
<Form :storage-key="storageKey" @change-language="changeLanguage" />
|
||||
<Form
|
||||
ref="formRef"
|
||||
:storage-key="storageKey"
|
||||
:other-user-info="otherUserInfo"
|
||||
:is-synced="sync"
|
||||
:had-connection="hadConnection"
|
||||
@change-language="changeLanguage"
|
||||
@toggle-sync="toggleSync"
|
||||
/>
|
||||
<CodeEditor
|
||||
v-model:value="code.value"
|
||||
@update:model-value="changeCode"
|
||||
:sync="sync"
|
||||
:problem="problem!._id"
|
||||
:language="code.language"
|
||||
:height="editorHeight"
|
||||
@update:model-value="changeCode"
|
||||
@sync-closed="handleSyncClosed"
|
||||
@sync-status-change="handleSyncStatusChange"
|
||||
/>
|
||||
</n-flex>
|
||||
</template>
|
||||
|
||||
<style scoped></style>
|
||||
|
||||
@@ -15,151 +15,187 @@ import IconButton from "~/shared/components/IconButton.vue"
|
||||
interface Props {
|
||||
storageKey: string
|
||||
withTest?: boolean
|
||||
otherUserInfo?: { name: string; isSuperAdmin: boolean }
|
||||
isSynced?: boolean
|
||||
hadConnection?: boolean
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
withTest: false,
|
||||
isSynced: false,
|
||||
hadConnection: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
changeLanguage: [v: LANGUAGE]
|
||||
toggleSync: [v: boolean]
|
||||
}>()
|
||||
|
||||
const message = useMessage()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const userStore = useUserStore()
|
||||
|
||||
const emit = defineEmits(["changeLanguage"])
|
||||
|
||||
const isSynced = ref(false)
|
||||
const statisticPanel = ref(false)
|
||||
|
||||
function copy() {
|
||||
copyText(code.value)
|
||||
message.success("代码复制成功")
|
||||
}
|
||||
|
||||
function reset() {
|
||||
code.value = problem.value!.template[code.language] || SOURCES[code.language]
|
||||
storage.remove(props.storageKey)
|
||||
message.success("代码重置成功")
|
||||
}
|
||||
|
||||
function goSubmissions() {
|
||||
const name = !!route.params.contestID ? "contest submissions" : "submissions"
|
||||
router.push({ name, query: { problem: problem.value!._id } })
|
||||
}
|
||||
|
||||
function goEdit() {
|
||||
let data = router.resolve("/admin/problem/edit/" + problem.value!.id)
|
||||
if (problem.value!.contest) {
|
||||
data = router.resolve(
|
||||
`/admin/contest/${problem.value!.contest}/problem/edit/${problem.value!.id}`,
|
||||
)
|
||||
}
|
||||
window.open(data.href, "_blank")
|
||||
}
|
||||
|
||||
async function test() {
|
||||
const res = await createTestSubmission(code, input.value)
|
||||
output.value = res.output
|
||||
}
|
||||
|
||||
const menu = computed<DropdownOption[]>(() => [
|
||||
{ label: "去自测猫", key: "test", show: isMobile.value },
|
||||
{ label: "复制代码", key: "copy" },
|
||||
{ label: "重置代码", key: "reset" },
|
||||
])
|
||||
|
||||
const options: DropdownOption[] = problem.value!.languages.map((it) => ({
|
||||
label: () => [
|
||||
h("img", {
|
||||
src: `/${it}.svg`,
|
||||
style: {
|
||||
width: "16px",
|
||||
height: "16px",
|
||||
marginRight: "8px",
|
||||
transform: "translateY(3px)",
|
||||
},
|
||||
}),
|
||||
LANGUAGE_SHOW_VALUE[it],
|
||||
],
|
||||
const languageOptions: DropdownOption[] = problem.value!.languages.map((it) => ({
|
||||
label: () =>
|
||||
h("div", { style: "display: flex; align-items: center;" }, [
|
||||
h("img", {
|
||||
src: `/${it}.svg`,
|
||||
style: { width: "16px", height: "16px", marginRight: "8px" },
|
||||
}),
|
||||
LANGUAGE_SHOW_VALUE[it],
|
||||
]),
|
||||
value: it,
|
||||
}))
|
||||
|
||||
async function select(key: string) {
|
||||
switch (key) {
|
||||
case "reset":
|
||||
reset()
|
||||
break
|
||||
case "copy":
|
||||
copy()
|
||||
break
|
||||
case "test":
|
||||
window.open(import.meta.env.PUBLIC_CODE_URL, "_blank")
|
||||
break
|
||||
}
|
||||
const copy = () => {
|
||||
copyText(code.value)
|
||||
message.success("代码复制成功")
|
||||
}
|
||||
|
||||
function changeLanguage(v: LANGUAGE) {
|
||||
const reset = () => {
|
||||
code.value = problem.value!.template[code.language] || SOURCES[code.language]
|
||||
storage.remove(props.storageKey)
|
||||
message.success("代码重置成功")
|
||||
}
|
||||
|
||||
const goSubmissions = () => {
|
||||
const name = route.params.contestID ? "contest submissions" : "submissions"
|
||||
router.push({ name, query: { problem: problem.value!._id } })
|
||||
}
|
||||
|
||||
const goEdit = () => {
|
||||
const baseUrl = "/admin/problem/edit/" + problem.value!.id
|
||||
const url = problem.value!.contest
|
||||
? `/admin/contest/${problem.value!.contest}/problem/edit/${problem.value!.id}`
|
||||
: baseUrl
|
||||
window.open(router.resolve(url).href, "_blank")
|
||||
}
|
||||
|
||||
const test = async () => {
|
||||
const res = await createTestSubmission(code, input.value)
|
||||
output.value = res.output
|
||||
}
|
||||
|
||||
const handleMenuSelect = (key: string) => {
|
||||
const actions: Record<string, () => void> = {
|
||||
reset,
|
||||
copy,
|
||||
test: () => window.open(import.meta.env.PUBLIC_CODE_URL, "_blank"),
|
||||
}
|
||||
actions[key]?.()
|
||||
}
|
||||
|
||||
const changeLanguage = (v: LANGUAGE) => {
|
||||
storage.set(STORAGE_KEY.LANGUAGE, v)
|
||||
emit("changeLanguage", v)
|
||||
}
|
||||
|
||||
function gotoTestCat() {
|
||||
const url = import.meta.env.PUBLIC_CODE_URL
|
||||
window.open(url, "_blank")
|
||||
const toggleSync = () => {
|
||||
isSynced.value = !isSynced.value
|
||||
emit("toggleSync", isSynced.value)
|
||||
}
|
||||
|
||||
function showStatisticsPanel() {
|
||||
statisticPanel.value = true
|
||||
const gotoTestCat = () => {
|
||||
window.open(import.meta.env.PUBLIC_CODE_URL, "_blank")
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
resetSyncStatus: () => {
|
||||
isSynced.value = false
|
||||
},
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<n-flex align="center">
|
||||
<n-select
|
||||
class="language"
|
||||
v-model:value="code.language"
|
||||
@update:value="changeLanguage"
|
||||
class="language"
|
||||
:size="isDesktop ? 'medium' : 'small'"
|
||||
:options="options"
|
||||
:options="languageOptions"
|
||||
@update:value="changeLanguage"
|
||||
/>
|
||||
<n-button v-if="withTest" @click="reset">重置代码</n-button>
|
||||
<n-button v-if="withTest" type="primary" secondary @click="test">
|
||||
运行代码
|
||||
</n-button>
|
||||
<n-flex align="center" v-if="!withTest">
|
||||
|
||||
<template v-if="withTest">
|
||||
<n-button @click="reset">重置代码</n-button>
|
||||
<n-button type="primary" secondary @click="test">运行代码</n-button>
|
||||
</template>
|
||||
|
||||
<n-flex v-else align="center">
|
||||
<Submit />
|
||||
<n-button v-if="isDesktop" @click="gotoTestCat">自测猫</n-button>
|
||||
|
||||
<n-button
|
||||
:size="isDesktop ? 'medium' : 'small'"
|
||||
v-if="!userStore.isSuperAdmin && userStore.showSubmissions"
|
||||
:size="isDesktop ? 'medium' : 'small'"
|
||||
@click="goSubmissions"
|
||||
>
|
||||
提交信息
|
||||
</n-button>
|
||||
|
||||
<n-button
|
||||
:size="isDesktop ? 'medium' : 'small'"
|
||||
v-if="userStore.isSuperAdmin"
|
||||
@click="showStatisticsPanel"
|
||||
:size="isDesktop ? 'medium' : 'small'"
|
||||
@click="statisticPanel = true"
|
||||
>
|
||||
{{ isDesktop ? "统计信息" : "统计" }}
|
||||
</n-button>
|
||||
<n-dropdown size="large" :options="menu" @select="select">
|
||||
|
||||
<n-button v-if="isDesktop" @click="gotoTestCat">自测猫</n-button>
|
||||
|
||||
<n-dropdown size="large" :options="menu" @select="handleMenuSelect">
|
||||
<n-button :size="isDesktop ? 'medium' : 'small'">操作</n-button>
|
||||
</n-dropdown>
|
||||
|
||||
<IconButton
|
||||
v-if="isDesktop && userStore.isSuperAdmin"
|
||||
icon="streamline-ultimate-color:file-code-edit"
|
||||
tip="编辑题目"
|
||||
v-if="isDesktop && userStore.isSuperAdmin"
|
||||
@click="goEdit"
|
||||
/>
|
||||
|
||||
<IconButton
|
||||
v-if="isDesktop && userStore.isAuthed"
|
||||
:icon="
|
||||
isSynced
|
||||
? 'streamline-stickies-color:earpod-connected'
|
||||
: 'streamline-stickies-color:earpod-connected-duo'
|
||||
"
|
||||
:tip="isSynced ? '断开同步' : '打开同步'"
|
||||
:type="isSynced ? 'info' : 'default'"
|
||||
@click="toggleSync"
|
||||
/>
|
||||
|
||||
<template v-if="props.isSynced">
|
||||
<n-tag v-if="otherUserInfo" type="info">
|
||||
与 {{ otherUserInfo.name }} 同步中
|
||||
</n-tag>
|
||||
<n-tag
|
||||
v-if="userStore.isSuperAdmin && !otherUserInfo && hadConnection"
|
||||
type="warning"
|
||||
>
|
||||
学生已退出,可以关闭同步
|
||||
</n-tag>
|
||||
</template>
|
||||
</n-flex>
|
||||
</n-flex>
|
||||
|
||||
<n-modal
|
||||
v-if="userStore.isSuperAdmin"
|
||||
v-model:show="statisticPanel"
|
||||
preset="card"
|
||||
title="提交记录的统计"
|
||||
:style="{ maxWidth: isDesktop && '70vw', maxHeight: '80vh' }"
|
||||
:content-style="{ overflow: 'auto' }"
|
||||
title="提交记录的统计"
|
||||
>
|
||||
<StatisticsPanel :problem="problem!._id" username="" />
|
||||
</n-modal>
|
||||
|
||||
@@ -3,14 +3,12 @@ import { NButton } from "naive-ui"
|
||||
import { getSubmissions, getRankOfProblem } from "~/oj/api"
|
||||
import Pagination from "~/shared/components/Pagination.vue"
|
||||
import SubmissionResultTag from "~/shared/components/SubmissionResultTag.vue"
|
||||
import { useConfigStore } from "~/shared/store/config"
|
||||
import { useUserStore } from "~/shared/store/user"
|
||||
import { LANGUAGE_SHOW_VALUE } from "~/utils/constants"
|
||||
import { parseTime } from "~/utils/functions"
|
||||
import { renderTableTitle } from "~/utils/renders"
|
||||
import { Submission } from "~/utils/types"
|
||||
|
||||
const configStore = useConfigStore()
|
||||
const userStore = useUserStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
@@ -117,7 +115,7 @@ watch(query, listSubmissions)
|
||||
<n-alert
|
||||
class="tip"
|
||||
type="error"
|
||||
v-if="!userStore.showSubmissions"
|
||||
v-if="!userStore.showSubmissions || !userStore.isAuthed"
|
||||
:title="errorMsg"
|
||||
/>
|
||||
|
||||
@@ -126,11 +124,12 @@ watch(query, listSubmissions)
|
||||
<n-alert class="tip" type="success" :show-icon="false" v-if="rank !== -1">
|
||||
<template #header>
|
||||
<n-flex align="center">
|
||||
<div>
|
||||
<span>
|
||||
本道题你在班上排名第 <b>{{ rank }}</b
|
||||
>,你们班共有 <b>{{ class_ac_count }}</b> 人答案正确
|
||||
</div>
|
||||
</span>
|
||||
<n-button
|
||||
secondary
|
||||
v-if="userStore.showSubmissions"
|
||||
@click="
|
||||
router.push({
|
||||
@@ -157,12 +156,10 @@ watch(query, listSubmissions)
|
||||
v-if="rank === -1 && class_ac_count > 0"
|
||||
>
|
||||
<template #header>
|
||||
<n-flex>
|
||||
<div>
|
||||
本道题你还没有解决,
|
||||
<div v-if="class_name">你们班</div>
|
||||
共有 <b>{{ class_ac_count }}</b> 人答案正确
|
||||
</div>
|
||||
<n-flex align="center">
|
||||
<span>
|
||||
本道题你还没有解决,你们班共有 <b>{{ class_ac_count }}</b> 人答案正确
|
||||
</span>
|
||||
<n-button
|
||||
v-if="userStore.showSubmissions"
|
||||
secondary
|
||||
@@ -189,11 +186,10 @@ watch(query, listSubmissions)
|
||||
<n-alert class="tip" type="success" :show-icon="false" v-if="rank !== -1">
|
||||
<template #header>
|
||||
<n-flex align="center">
|
||||
<div>
|
||||
<span>
|
||||
本道题你在全服排名第 <b>{{ rank }}</b
|
||||
>,全服共有 <b>{{ all_ac_count }}</b> 人答案正确
|
||||
</div>
|
||||
<div></div>
|
||||
</span>
|
||||
<n-button
|
||||
secondary
|
||||
v-if="userStore.showSubmissions"
|
||||
@@ -222,10 +218,9 @@ watch(query, listSubmissions)
|
||||
>
|
||||
<template #header>
|
||||
<n-flex align="center">
|
||||
<div>
|
||||
本道题你还没有解决,全服共有
|
||||
<b>{{ all_ac_count }}</b> 人答案正确
|
||||
</div>
|
||||
<span>
|
||||
本道题你还没有解决,全服共有 <b>{{ all_ac_count }}</b> 人答案正确
|
||||
</span>
|
||||
<n-button
|
||||
v-if="userStore.showSubmissions"
|
||||
secondary
|
||||
@@ -249,8 +244,8 @@ watch(query, listSubmissions)
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<template v-if="userStore.showSubmissions">
|
||||
<n-data-table striped :columns="columns" :data="submissions" />
|
||||
<template v-if="userStore.showSubmissions && userStore.isAuthed">
|
||||
<n-data-table v-if="submissions.length > 0" striped :columns="columns" :data="submissions" />
|
||||
<Pagination
|
||||
:total="total"
|
||||
v-model:limit="query.limit"
|
||||
|
||||
@@ -3,23 +3,21 @@ import { cpp } from "@codemirror/lang-cpp"
|
||||
import { python } from "@codemirror/lang-python"
|
||||
import { EditorView } from "@codemirror/view"
|
||||
import { Codemirror } from "vue-codemirror"
|
||||
import type { Extension } from "@codemirror/state"
|
||||
import { LANGUAGE } from "~/utils/types"
|
||||
import { oneDark } from "../themes/oneDark"
|
||||
import { smoothy } from "../themes/smoothy"
|
||||
import { useCodeSync } from "../composables/sync"
|
||||
|
||||
const styleTheme = EditorView.baseTheme({
|
||||
"& .cm-scroller": {
|
||||
"font-family": "Monaco",
|
||||
},
|
||||
"&.cm-editor.cm-focused": {
|
||||
outline: "none",
|
||||
},
|
||||
"&.cm-editor .cm-tooltip.cm-tooltip-autocomplete ul": {
|
||||
"font-family": "Monaco",
|
||||
},
|
||||
})
|
||||
interface EditorReadyPayload {
|
||||
view: EditorView
|
||||
state: any
|
||||
container: HTMLElement
|
||||
}
|
||||
|
||||
interface Props {
|
||||
sync?: boolean
|
||||
problem?: string
|
||||
language?: LANGUAGE
|
||||
fontSize?: number
|
||||
height?: string
|
||||
@@ -28,6 +26,8 @@ interface Props {
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
sync: false,
|
||||
problem: "",
|
||||
language: "Python3",
|
||||
fontSize: 20,
|
||||
height: "100%",
|
||||
@@ -35,25 +35,105 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
placeholder: "",
|
||||
})
|
||||
|
||||
const { readonly, placeholder, height, fontSize } = toRefs(props)
|
||||
const code = defineModel<string>("value")
|
||||
|
||||
const emit = defineEmits<{
|
||||
syncClosed: []
|
||||
syncStatusChange: [
|
||||
status: { otherUser?: { name: string; isSuperAdmin: boolean } },
|
||||
]
|
||||
}>()
|
||||
|
||||
const isDark = useDark()
|
||||
|
||||
const lang = computed(() => {
|
||||
if (["Python2", "Python3"].includes(props.language)) {
|
||||
return python()
|
||||
}
|
||||
return cpp()
|
||||
const styleTheme = EditorView.baseTheme({
|
||||
"& .cm-scroller": { "font-family": "Monaco" },
|
||||
"&.cm-editor.cm-focused": { outline: "none" },
|
||||
"&.cm-editor .cm-tooltip.cm-tooltip-autocomplete ul": {
|
||||
"font-family": "Monaco",
|
||||
},
|
||||
})
|
||||
|
||||
const lang = computed((): Extension => {
|
||||
return ["Python2", "Python3"].includes(props.language) ? python() : cpp()
|
||||
})
|
||||
|
||||
const extensions = computed((): Extension[] => [
|
||||
styleTheme,
|
||||
lang.value,
|
||||
isDark.value ? oneDark : smoothy,
|
||||
getInitialExtension(),
|
||||
])
|
||||
|
||||
const { startSync, stopSync, getInitialExtension } = useCodeSync()
|
||||
const editorView = ref<EditorView | null>(null)
|
||||
let cleanupSync: (() => void) | null = null
|
||||
|
||||
const cleanupSyncResources = () => {
|
||||
if (cleanupSync) {
|
||||
cleanupSync()
|
||||
cleanupSync = null
|
||||
}
|
||||
stopSync()
|
||||
}
|
||||
|
||||
const initSync = async () => {
|
||||
if (!editorView.value || !props.problem) return
|
||||
|
||||
cleanupSyncResources()
|
||||
|
||||
cleanupSync = await startSync({
|
||||
problemId: props.problem,
|
||||
editorView: editorView.value as EditorView,
|
||||
onStatusChange: (status) => {
|
||||
if (status.error === "超管已离开" && !status.connected) {
|
||||
emit("syncClosed")
|
||||
}
|
||||
emit("syncStatusChange", { otherUser: status.otherUser })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const handleEditorReady = (payload: EditorReadyPayload) => {
|
||||
editorView.value = payload.view as EditorView
|
||||
if (props.sync && props.problem) {
|
||||
initSync()
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.sync,
|
||||
(shouldSync) => {
|
||||
if (shouldSync && props.problem && editorView.value) {
|
||||
initSync()
|
||||
} else {
|
||||
cleanupSyncResources()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
watch(
|
||||
() => props.problem,
|
||||
(newProblem, oldProblem) => {
|
||||
if (newProblem !== oldProblem && props.sync && editorView.value) {
|
||||
initSync()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
onUnmounted(cleanupSyncResources)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Codemirror
|
||||
v-model="code"
|
||||
indentWithTab
|
||||
:extensions="[styleTheme, lang, isDark ? oneDark : smoothy]"
|
||||
:disabled="props.readonly"
|
||||
:tabSize="4"
|
||||
:placeholder="props.placeholder"
|
||||
:style="{ height: props.height, fontSize: props.fontSize + 'px' }"
|
||||
:extensions="extensions"
|
||||
:disabled="readonly"
|
||||
:tab-size="4"
|
||||
:placeholder="placeholder"
|
||||
:style="{ height, fontSize: `${fontSize}px` }"
|
||||
@ready="handleEditorReady"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button circle @click="$emit('click')">
|
||||
<n-button circle :type="type ?? 'default'" @click="$emit('click')">
|
||||
<template #icon>
|
||||
<Icon :icon="icon" />
|
||||
</template>
|
||||
@@ -16,6 +16,14 @@ import { Icon } from "@iconify/vue"
|
||||
defineProps<{
|
||||
tip: string
|
||||
icon: string
|
||||
type?:
|
||||
| "default"
|
||||
| "tertiary"
|
||||
| "primary"
|
||||
| "info"
|
||||
| "success"
|
||||
| "warning"
|
||||
| "error"
|
||||
}>()
|
||||
defineEmits(["click"])
|
||||
</script>
|
||||
|
||||
29
src/shared/components/TextCopy.vue
Normal file
29
src/shared/components/TextCopy.vue
Normal file
@@ -0,0 +1,29 @@
|
||||
<template>
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-button text @click="handleClick">
|
||||
<slot />
|
||||
</n-button>
|
||||
</template>
|
||||
点击复制
|
||||
</n-tooltip>
|
||||
</template>
|
||||
<script lang="ts" setup>
|
||||
import copyText from "copy-text-to-clipboard"
|
||||
|
||||
const message = useMessage()
|
||||
|
||||
const slots = useSlots()
|
||||
|
||||
function handleClick() {
|
||||
const textToCopy = getTextFromSlot()
|
||||
copyText(textToCopy)
|
||||
message.success("已复制")
|
||||
}
|
||||
|
||||
function getTextFromSlot() {
|
||||
const vnodes = slots.default?.()
|
||||
if (!vnodes) return ""
|
||||
return vnodes.map((vnode) => vnode.children).join("")
|
||||
}
|
||||
</script>
|
||||
397
src/shared/composables/sync.ts
Normal file
397
src/shared/composables/sync.ts
Normal file
@@ -0,0 +1,397 @@
|
||||
import { useUserStore } from "../store/user"
|
||||
import type { EditorView } from "@codemirror/view"
|
||||
import { Compartment } from "@codemirror/state"
|
||||
import type { WebrtcProvider } from "y-webrtc"
|
||||
import type { Doc, Text } from "yjs"
|
||||
|
||||
// 常量定义
|
||||
const SYNC_CONSTANTS = {
|
||||
MAX_ROOM_USERS: 2,
|
||||
AWARENESS_SYNC_DELAY: 500,
|
||||
INIT_SYNC_TIMEOUT: 500,
|
||||
SUPER_ADMIN_COLOR: "#ff6b6b",
|
||||
REGULAR_USER_COLOR: "#4dabf7",
|
||||
} as const
|
||||
|
||||
// 类型定义
|
||||
type SyncState = "waiting" | "active" | "error"
|
||||
|
||||
interface UserInfo {
|
||||
name: string
|
||||
isSuperAdmin: boolean
|
||||
}
|
||||
|
||||
interface PeersEvent {
|
||||
added: string[]
|
||||
removed: string[]
|
||||
webrtcPeers: string[]
|
||||
}
|
||||
|
||||
interface StatusEvent {
|
||||
connected: boolean
|
||||
}
|
||||
|
||||
interface SyncedEvent {
|
||||
synced: boolean
|
||||
}
|
||||
|
||||
interface SyncOptions {
|
||||
problemId: string
|
||||
editorView: EditorView
|
||||
onStatusChange?: (status: SyncStatus) => void
|
||||
}
|
||||
|
||||
export interface SyncStatus {
|
||||
connected: boolean
|
||||
roomUsers: number
|
||||
canSync: boolean
|
||||
message: string
|
||||
error?: string
|
||||
otherUser?: UserInfo
|
||||
}
|
||||
|
||||
export function useCodeSync() {
|
||||
const userStore = useUserStore()
|
||||
const message = useMessage()
|
||||
|
||||
// 状态变量
|
||||
let ydoc: Doc | null = null
|
||||
let provider: WebrtcProvider | null = null
|
||||
let ytext: Text | null = null
|
||||
const collabCompartment = new Compartment()
|
||||
let currentEditorView: EditorView | null = null
|
||||
let lastSyncState: SyncState | null = null
|
||||
let roomUserInfo = new Map<number, UserInfo>()
|
||||
let hasShownSuperAdminLeftMessage = false
|
||||
|
||||
const updateStatus = (
|
||||
status: SyncStatus,
|
||||
onStatusChange?: (status: SyncStatus) => void,
|
||||
) => {
|
||||
onStatusChange?.(status)
|
||||
}
|
||||
|
||||
const normalizeClientId = (clientId: number | string): number => {
|
||||
return typeof clientId === "string" ? parseInt(clientId, 10) : clientId
|
||||
}
|
||||
|
||||
const checkHasSuperAdmin = (awarenessStates: Map<number, any>): boolean => {
|
||||
if (userStore.isSuperAdmin) return true
|
||||
return Array.from(awarenessStates.values()).some(
|
||||
(state) => state.user?.isSuperAdmin,
|
||||
)
|
||||
}
|
||||
|
||||
const getOtherUserInfo = (
|
||||
awarenessStates: Map<number, any>,
|
||||
): UserInfo | undefined => {
|
||||
if (!provider) return undefined
|
||||
|
||||
const localClientId = provider.awareness.clientID
|
||||
for (const [clientId, state] of awarenessStates) {
|
||||
if (clientId !== localClientId && state.user) {
|
||||
return {
|
||||
name: state.user.name,
|
||||
isSuperAdmin: state.user.isSuperAdmin,
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const checkIfSuperAdminLeft = (
|
||||
removedClientIds: number[],
|
||||
onStatusChange?: (status: SyncStatus) => void,
|
||||
) => {
|
||||
if (userStore.isSuperAdmin || hasShownSuperAdminLeftMessage) return
|
||||
|
||||
const superAdminInfo = removedClientIds
|
||||
.map((id) => roomUserInfo.get(id))
|
||||
.find((info) => info?.isSuperAdmin)
|
||||
|
||||
if (superAdminInfo) {
|
||||
hasShownSuperAdminLeftMessage = true
|
||||
updateStatus(
|
||||
{
|
||||
connected: false,
|
||||
roomUsers: 0,
|
||||
canSync: false,
|
||||
message: `超管 ${superAdminInfo.name} 已退出`,
|
||||
error: "超管已离开",
|
||||
},
|
||||
onStatusChange,
|
||||
)
|
||||
message.warning(`超管 ${superAdminInfo.name} 已退出`)
|
||||
stopSync()
|
||||
}
|
||||
}
|
||||
|
||||
const checkRoomPermissions = (
|
||||
roomUsers: number,
|
||||
onStatusChange?: (status: SyncStatus) => void,
|
||||
) => {
|
||||
const awarenessStates = provider?.awareness.getStates()
|
||||
if (!awarenessStates) return
|
||||
|
||||
const hasSuperAdmin = checkHasSuperAdmin(awarenessStates)
|
||||
const canSync = roomUsers === SYNC_CONSTANTS.MAX_ROOM_USERS && hasSuperAdmin
|
||||
const otherUser = getOtherUserInfo(awarenessStates)
|
||||
|
||||
if (roomUsers === SYNC_CONSTANTS.MAX_ROOM_USERS && !hasSuperAdmin) {
|
||||
updateStatus(
|
||||
{
|
||||
connected: true,
|
||||
roomUsers,
|
||||
canSync: false,
|
||||
message: "房间内必须有一个超级管理员",
|
||||
error: "缺少超级管理员",
|
||||
otherUser,
|
||||
},
|
||||
onStatusChange,
|
||||
)
|
||||
if (lastSyncState !== "error") {
|
||||
message.warning("协同编辑需要至少一个超级管理员")
|
||||
lastSyncState = "error"
|
||||
}
|
||||
} else if (canSync) {
|
||||
updateStatus(
|
||||
{
|
||||
connected: true,
|
||||
roomUsers,
|
||||
canSync: true,
|
||||
message: "协同编辑已激活,可以开始协作!",
|
||||
otherUser,
|
||||
},
|
||||
onStatusChange,
|
||||
)
|
||||
if (lastSyncState !== "active") {
|
||||
message.success("协同编辑已激活,可以开始协作!")
|
||||
lastSyncState = "active"
|
||||
}
|
||||
} else {
|
||||
updateStatus(
|
||||
{
|
||||
connected: true,
|
||||
roomUsers,
|
||||
canSync: false,
|
||||
message: roomUsers === 1 ? "正在等待加入" : "等待超级管理员加入...",
|
||||
otherUser,
|
||||
},
|
||||
onStatusChange,
|
||||
)
|
||||
lastSyncState = "waiting"
|
||||
}
|
||||
}
|
||||
|
||||
const setupContentSync = (
|
||||
editorView: EditorView,
|
||||
ytext: Text,
|
||||
provider: WebrtcProvider,
|
||||
savedContent: string,
|
||||
) => {
|
||||
let hasInitialized = false
|
||||
|
||||
const initTimeout = setTimeout(() => {
|
||||
if (!hasInitialized && ytext.length === 0 && savedContent) {
|
||||
ytext.insert(0, savedContent)
|
||||
}
|
||||
hasInitialized = true
|
||||
}, SYNC_CONSTANTS.INIT_SYNC_TIMEOUT)
|
||||
|
||||
provider.on("synced", (event: SyncedEvent) => {
|
||||
if (!event.synced || hasInitialized) return
|
||||
|
||||
clearTimeout(initTimeout)
|
||||
if (ytext.length === 0 && savedContent) {
|
||||
ytext.insert(0, savedContent)
|
||||
}
|
||||
hasInitialized = true
|
||||
})
|
||||
}
|
||||
|
||||
async function startSync(options: SyncOptions): Promise<() => void> {
|
||||
const { problemId, editorView, onStatusChange } = options
|
||||
|
||||
if (!userStore.isAuthed) {
|
||||
updateStatus(
|
||||
{
|
||||
connected: false,
|
||||
roomUsers: 0,
|
||||
canSync: false,
|
||||
message: "请先登录后再使用同步功能",
|
||||
error: "用户未登录",
|
||||
},
|
||||
onStatusChange,
|
||||
)
|
||||
message.error("请先登录后再使用同步功能")
|
||||
return () => {}
|
||||
}
|
||||
|
||||
// 动态导入 yjs 相关模块
|
||||
const [Y, { WebrtcProvider }, { yCollab }] = await Promise.all([
|
||||
import("yjs"),
|
||||
import("y-webrtc"),
|
||||
import("y-codemirror.next"),
|
||||
])
|
||||
|
||||
// 初始化文档和提供者
|
||||
ydoc = new Y.Doc()
|
||||
ytext = ydoc.getText("codemirror")
|
||||
const roomName = `problem-${problemId}`
|
||||
|
||||
provider = new WebrtcProvider(roomName, ydoc, {
|
||||
signaling: [import.meta.env.PUBLIC_SIGNALING_URL],
|
||||
maxConns: 1,
|
||||
filterBcConns: true,
|
||||
})
|
||||
|
||||
// 监听连接状态
|
||||
provider.on("status", (event: StatusEvent) => {
|
||||
if (!event.connected) {
|
||||
updateStatus(
|
||||
{
|
||||
connected: false,
|
||||
roomUsers: 0,
|
||||
canSync: false,
|
||||
message: "连接已断开",
|
||||
error: "WebRTC 连接断开",
|
||||
},
|
||||
onStatusChange,
|
||||
)
|
||||
message.warning("协同编辑连接已断开")
|
||||
}
|
||||
})
|
||||
|
||||
// 监听用户加入/离开
|
||||
provider.on("peers", (event: PeersEvent) => {
|
||||
const roomUsers = event.webrtcPeers.length + 1
|
||||
|
||||
if (roomUsers > SYNC_CONSTANTS.MAX_ROOM_USERS) {
|
||||
updateStatus(
|
||||
{
|
||||
connected: false,
|
||||
roomUsers,
|
||||
canSync: false,
|
||||
message: "房间人数已满,已自动断开连接",
|
||||
error: `房间最多只能有${SYNC_CONSTANTS.MAX_ROOM_USERS}个人`,
|
||||
},
|
||||
onStatusChange,
|
||||
)
|
||||
message.warning(
|
||||
`房间人数已满(最多${SYNC_CONSTANTS.MAX_ROOM_USERS}人),已自动断开连接`,
|
||||
)
|
||||
stopSync()
|
||||
return
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
checkRoomPermissions(roomUsers, onStatusChange)
|
||||
}, SYNC_CONSTANTS.AWARENESS_SYNC_DELAY)
|
||||
})
|
||||
|
||||
// 监听 awareness 变化
|
||||
provider.awareness.on("change", (changes: any) => {
|
||||
if (!provider) return
|
||||
|
||||
const awarenessStates = provider.awareness.getStates()
|
||||
|
||||
if (changes.removed?.length > 0) {
|
||||
checkIfSuperAdminLeft(changes.removed, onStatusChange)
|
||||
}
|
||||
|
||||
awarenessStates.forEach((state, clientId) => {
|
||||
if (state.user) {
|
||||
const normalizedId = normalizeClientId(clientId)
|
||||
roomUserInfo.set(normalizedId, {
|
||||
name: state.user.name,
|
||||
isSuperAdmin: state.user.isSuperAdmin,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
checkRoomPermissions(awarenessStates.size, onStatusChange)
|
||||
})
|
||||
|
||||
// 配置编辑器扩展
|
||||
if (editorView && ytext) {
|
||||
currentEditorView = editorView
|
||||
const userColor = userStore.isSuperAdmin
|
||||
? SYNC_CONSTANTS.SUPER_ADMIN_COLOR
|
||||
: SYNC_CONSTANTS.REGULAR_USER_COLOR
|
||||
const userName = userStore.user?.username || "匿名用户"
|
||||
const savedContent = editorView.state.doc.toString()
|
||||
|
||||
// 设置用户信息
|
||||
provider.awareness.setLocalStateField("user", {
|
||||
name: userName,
|
||||
color: userColor,
|
||||
isSuperAdmin: userStore.isSuperAdmin,
|
||||
})
|
||||
|
||||
// 清空编辑器并应用协同扩展
|
||||
editorView.dispatch({
|
||||
changes: { from: 0, to: editorView.state.doc.length, insert: "" },
|
||||
})
|
||||
|
||||
const collabExt = yCollab(ytext, provider.awareness)
|
||||
editorView.dispatch({
|
||||
effects: collabCompartment.reconfigure(collabExt),
|
||||
})
|
||||
|
||||
// 设置内容同步
|
||||
setupContentSync(editorView, ytext, provider, savedContent)
|
||||
|
||||
// 设置初始状态
|
||||
updateStatus(
|
||||
{
|
||||
connected: true,
|
||||
roomUsers: 1,
|
||||
canSync: false,
|
||||
message: "正在等待加入",
|
||||
},
|
||||
onStatusChange,
|
||||
)
|
||||
|
||||
message.info(
|
||||
userStore.isSuperAdmin ? "正在等待学生加入..." : "正在等待超管加入...",
|
||||
)
|
||||
lastSyncState = "waiting"
|
||||
}
|
||||
|
||||
return () => stopSync()
|
||||
}
|
||||
|
||||
function stopSync() {
|
||||
if (currentEditorView) {
|
||||
try {
|
||||
currentEditorView.dispatch({
|
||||
effects: collabCompartment.reconfigure([]),
|
||||
})
|
||||
} catch (error) {
|
||||
console.warn("移除协同编辑扩展失败:", error)
|
||||
}
|
||||
currentEditorView = null
|
||||
}
|
||||
|
||||
provider?.disconnect()
|
||||
provider?.destroy()
|
||||
ydoc?.destroy()
|
||||
|
||||
provider = null
|
||||
ydoc = null
|
||||
ytext = null
|
||||
lastSyncState = null
|
||||
roomUserInfo.clear()
|
||||
hasShownSuperAdminLeftMessage = false
|
||||
}
|
||||
|
||||
function getInitialExtension() {
|
||||
return collabCompartment.of([])
|
||||
}
|
||||
|
||||
return {
|
||||
startSync,
|
||||
stopSync,
|
||||
getInitialExtension,
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,8 @@ export type LANGUAGE =
|
||||
| "JavaScript"
|
||||
| "Golang"
|
||||
|
||||
export type LANGUAGE_SHOW_LABEL = typeof LANGUAGE_SHOW_VALUE[keyof typeof LANGUAGE_SHOW_VALUE]
|
||||
export type LANGUAGE_SHOW_LABEL =
|
||||
(typeof LANGUAGE_SHOW_VALUE)[keyof typeof LANGUAGE_SHOW_VALUE]
|
||||
|
||||
export type SUBMISSION_RESULT = -2 | -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
|
||||
|
||||
|
||||
Reference in New Issue
Block a user