refactor: rewrite session store using pinia and fix start button

This commit is contained in:
wancat committed 2024-06-27 11:23:21 +08:00
1 parent 78b9529699
commit 7cdc542c19
13 files changed
+171 -192

No files matched your search

+5 -4
View File
@@ -1,13 +1,14 @@
<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useToast } from 'vue-toastification'
import { createSession } from '../../store/session'
import useSession from '../../store/session'
import { surveyUrl } from '../../config'
const router = useRouter()
const sessionStore = useSession()
const reset = async () => {
console.log('resetting...')
await createSession()
await sessionStore.createSession()
}
const continuePlay = async () => {
try {
@@ -29,7 +30,7 @@ const continuePlay = async () => {
:icon="['fas', 'file-invoice']"
class="text-text-primary px-1"
/>
<p class="text-text-primary inline ml-1 hidden md:flex">問卷</p>
<p class="text-text-primary inline ml-1 md:flex">問卷</p>
</a>
</button>
<button disabled id="solution" class="bg-bg-disabled rounded-lg p-2">
@@ -37,7 +38,7 @@ const continuePlay = async () => {
:icon="['far', 'circle-question']"
class="text-text-disabled px-1"
/>
<p class="text-text-disabled inline ml-1 hidden md:flex">解答</p>
<p class="text-text-disabled inline ml-1 md:flex">解答</p>
</button>
<button id="reset" class="bg-bg-secondary rounded-lg p-2" @click="reset">
<font-awesome-icon
+2 -1
View File
@@ -1,8 +1,9 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import sessionStore from '../../store/session'
import useSession from '../../store/session'
import MarkdownText from '../MarkdownText.vue'
const sessionStore = useSession()
const current = ref(-1)
watch(
() => sessionStore.session.hints,
+2 -1
View File
@@ -1,9 +1,10 @@
<script setup lang="ts">
import { computed } from 'vue'
import MarkdownText from '../MarkdownText.vue'
import sessionStore from '../../store/session'
import useSession from '../../store/session'
import { Task } from '../../types'
const sessionStore = useSession()
const tasks = computed(() => {
return sessionStore.session.tasks.map((task: Task) => {
const prefix = task.completed ? '✓' : '➤'
+12 -26
View File
@@ -1,8 +1,7 @@
<script setup lang="ts">
import { useToast } from 'vue-toastification'
import { ref } from 'vue'
import { getActiveSession, setQuest, createSession } from '../../store/session'
import { LoadQuestError, LoadSessionError } from '../../utils/errors'
import { onMounted, ref } from 'vue'
import useSession from '../../store/session'
const props = defineProps({
questId: {
@@ -12,34 +11,21 @@ const props = defineProps({
})
const toast = useToast()
const showCover = ref(false)
const showCover = ref(true)
const sessionStore = useSession()
function init(questId: string) {
if (!questId) throw new Error('No quest ID provided')
try {
getActiveSession(props.questId)
} catch (err: any) {
if (err instanceof LoadQuestError) {
toast.error(`無法讀取關卡: ${err.questId},請確認網頁連結。`)
return
}
if (err instanceof LoadSessionError) {
toast.error(`無法建立工作階段: ${err.questId},請重新登入再試一次。`)
return
}
console.error(err)
toast.warning('Failed to connect previous session. Creating a new one...')
showCover.value = true
onMounted(async () => {
sessionStore.setQuest(props.questId)
if (await sessionStore.getActiveSession()) {
showCover.value = false
}
}
init(props.questId)
setQuest(props.questId)
sessionStore.setup()
})
const startSession = async () => {
showCover.value = false
try {
createSession()
await sessionStore.createSession()
showCover.value = false
} catch (err: any) {
console.error(err)
toast.error(err.message)
+3 -1
View File
@@ -1,6 +1,8 @@
<script setup lang="ts">
import FileNode from '../FileNode.vue'
import sessionStore from '../../store/session'
import useSession from '../../store/session'
const sessionStore = useSession()
</script>
<template>
@@ -4,10 +4,11 @@ import { useRouter } from 'vue-router'
import { useToast } from 'vue-toastification'
import { logout } from '../../utils/auth'
import { bugReportUrl, surveyUrl } from '../../config'
import { reset } from '../../store/session'
import useSession from '../../store/session'
import useUserProfile from '../../store/userProfile'
const store = useUserProfile()
const userStore = useUserProfile()
const sessionStore = useSession()
const router = useRouter()
const toast = useToast()
@@ -15,8 +16,8 @@ const toast = useToast()
const handleLogout = async () => {
try {
await logout()
store.resetUserProfile()
reset()
userStore.resetUserProfile()
sessionStore.reset()
router.push({ name: 'login' })
} catch (err) {
toast.error('登出失敗')
@@ -26,7 +27,7 @@ const handleLogout = async () => {
onMounted(async () => {
try {
await store.loadUserProfile()
await userStore.loadUserProfile()
} catch (err) {
toast.error('無法讀取使用者資料')
console.error(err)
@@ -57,7 +58,7 @@ onMounted(async () => {
class="text-text inline-block whitespace-nowrap px-1.5"
style="font-size: 2vh"
>
{{ store.username }}
{{ userStore.username }}
</p>
<a
title="Survey"
+86 -125
View File
@@ -1,31 +1,13 @@
import { reactive } from 'vue'
import { useToast } from 'vue-toastification'
import { defineStore } from 'pinia'
import { FileGraph, FileObject } from '@linux-odyssey/file-graph'
import { IQuest } from '@linux-odyssey/models'
import api from '../utils/api'
import { createSession, getQuest, getSessions } from '../utils/api'
import Socket from '../utils/socket'
import SocketTerminal from '../utils/terminal'
import { LoadQuestError, LoadSessionError } from '../utils/errors'
import { Session, StageResponse } from '../types'
const toast = useToast()
function newSession() {
const graph = new FileGraph({
path: '/',
type: 'folder',
discovered: false,
})
return {
_id: '',
status: 'inactive',
graph,
pwd: '',
hints: [],
tasks: [],
responses: [],
}
}
const socket = new Socket()
const term = new SocketTerminal(40, 80)
interface Store {
session: Session
@@ -33,97 +15,93 @@ interface Store {
quest: IQuest | null
}
const store = reactive<Store>({
session: newSession(),
questId: '',
quest: null,
const useSession = defineStore('session', {
state: (): Store => ({
session: {
_id: '',
status: 'inactive',
graph: new FileGraph({
path: '/',
type: 'folder',
discovered: false,
}),
pwd: '',
hints: [],
tasks: [],
responses: [],
},
questId: '',
quest: null,
}),
actions: {
async setQuest(questId: string) {
this.quest = await getQuest(questId)
this.questId = questId
},
async setSession(session: Session) {
this.session = session
this.session.graph = new FileGraph(session.graph)
term.reset()
await socket.connect(session)
term.focus()
},
async createSession() {
const session = await createSession(this.questId)
this.setSession(session)
},
async getActiveSession() {
const sessions = await getSessions({
questId: this.questId,
limit: 1,
order: 'desc',
status: 'active',
})
if (sessions.length > 0) {
this.setSession(sessions[0])
return true
}
return false
},
updateGraph(event: { discover?: FileObject[]; pwd?: string }) {
if (event.discover) {
this.session.graph.discover(event.discover)
}
if (event.pwd) {
this.session.pwd = event.pwd
}
},
newResponse(response: StageResponse) {
this.session.responses.push(response.responses)
this.session.hints.push(response.hints)
this.session.tasks = response.tasks
this.session.status = response.status
},
reset() {
socket.reset()
term.reset()
this.$reset()
},
setup() {
socket.on('terminal', (data: string) => {
term.write(data)
})
term.onData((data: string) => {
socket.emit('terminal', data)
})
socket.on('graph', (event: { discover: FileObject[]; pwd: string }) => {
this.updateGraph(event)
})
socket.on('response', (response: StageResponse) => {
this.newResponse(response)
})
},
},
})
const socket = new Socket()
const term = new SocketTerminal(40, 80)
export function setQuest(questId: string) {
return api.get(`/quests/${questId}`).then((res) => {
store.questId = res.data._id
store.quest = res.data
})
}
async function setSession(session: Session) {
try {
console.log('Setting session...', session)
store.session = session
store.session.graph = new FileGraph(session.graph)
term.reset()
await socket.connect(session)
term.focus()
} catch (err: any) {
console.error(err)
if (err instanceof Error) {
toast.error(err.message)
} else {
toast.error('Failed to connect to the session. Please try again later.')
}
throw err
}
}
export async function createSession() {
try {
console.log('Creating a new session...')
const res = await api.post('/sessions', { questId: store.questId })
const { data } = res
await setSession(data)
socket.emit('terminal', 'echo start')
} catch (err) {
console.error(err)
toast.error('Failed to create a new session. Please try again later.')
}
}
export async function getActiveSession(questId: string) {
try {
// const res = await api.post('/sessions/active', { questId })
const res = await api.get(`/sessions/${questId}`, {
params: { status: 'active' },
})
await setSession(res.data)
} catch (err) {
console.error(err)
throw new LoadSessionError('Failed to load session', questId)
// toast.warning('Failed to connect previous session. Creating a new one...')
// await createSession()
}
}
function updateGraph(event: { discover: FileObject[]; pwd: string }) {
if (event.discover) {
store.session.graph.discover(event.discover)
}
if (event.pwd) {
store.session.pwd = event.pwd
}
}
function newResponse(response: StageResponse) {
console.log('newResponse', response, 'session', store.session)
store.session.responses.push(response.responses)
store.session.hints.push(response.hints)
store.session.tasks = response.tasks
store.session.status = response.status
}
export function useTerminal() {
return term
}
export function reset() {
socket.reset()
term.reset()
store.session = newSession()
store.quest = null
}
// export async function init(questId: string) {
// if (!questId) throw new Error('No quest ID provided')
// reset()
@@ -141,21 +119,4 @@ export function reset() {
// }
// }
function setup() {
socket.on('terminal', (data: string) => {
term.write(data)
})
term.onData((data: string) => {
socket.emit('terminal', data)
})
socket.on('graph', (event: { discover: FileObject[]; pwd: string }) => {
updateGraph(event)
})
socket.on('response', (response: StageResponse) => {
newResponse(response)
})
}
setup()
export default store
export default useSession
+20
View File
@@ -1,4 +1,7 @@
import axios from 'axios'
import { IQuest } from '@linux-odyssey/models'
import { GetSessionsRequest } from '@linux-odyssey/constants'
import { Session } from '../types'
import { UserProfile } from '../store/userProfile'
const api = axios.create({
@@ -14,3 +17,20 @@ export async function getUserProfile(): Promise<UserProfile> {
const res = await api.get<UserProfile>('/users/me')
return res.data
}
export async function getQuest(id: string): Promise<IQuest> {
const res = await api.get<IQuest>(`/quests/${id}`)
return res.data
}
export async function createSession(questId: string): Promise<Session> {
const res = await api.post<Session>('/sessions', { questId })
return res.data
}
export async function getSessions(
request: GetSessionsRequest
): Promise<Session[]> {
const res = await api.get<Session[]>('/sessions', { params: request })
return res.data
}
+3 -25
View File
@@ -2,7 +2,7 @@
import { computed } from 'vue'
// import { onMounted } from 'vue'
// import { useToast } from 'vue-toastification'
import sessionStore from '../store/session'
import useSession from '../store/session'
// import { init } from '../store/session'
import HeaderPart from '../components/header/HeaderPart.vue'
import GameHeaderComponents from '../components/header/GameHeaderComponents.vue'
@@ -13,19 +13,14 @@ import TerminalPart from '../components/game/TerminalPart.vue'
import VisualizationPart from '../components/game/VisualizationPart.vue'
import ControlPalette from '../components/game/ControlPalette.vue'
import CompleteModal from '../components/game/CompleteModal.vue'
// import { LoadQuestError, LoadSessionError } from '../utils/errors'
import StartButton from '../components/game/StartButton.vue'
const sessionStore = useSession()
const completed = computed(() => {
return sessionStore.session.status === 'finished'
})
// const props = defineProps({
// questId: {
// type: String,
// required: true,
// },
// })
defineProps({
questId: {
type: String,
@@ -33,23 +28,6 @@ defineProps({
},
})
// const toast = useToast()
// onMounted(async () => {
// try {
// await init(props.questId)
// } catch (err: any) {
// if (err instanceof LoadQuestError) {
// toast.error(`無法讀取關卡: ${err.questId},請確認網頁連結。`)
// return
// }
// if (err instanceof LoadSessionError) {
// toast.error(`無法建立工作階段: ${err.questId},請重新登入再試一次。`)
// return
// }
// console.error(err)
// toast.error(err.message)
// }
// })
</script>
<template>