Refactor: layout

This commit is contained in:
2022-11-05 18:44:52 +01:00
parent cc20ed870c
commit 1ed0790804
9 changed files with 377 additions and 164 deletions

View File

@@ -10,3 +10,8 @@
border-radius: map.get($rounded, "lg") !important; border-radius: map.get($rounded, "lg") !important;
box-shadow: 0px 0px 0px 0px rgb(0 0 0 / 20%) !important; box-shadow: 0px 0px 0px 0px rgb(0 0 0 / 20%) !important;
} }
.v-expansion-panel::before {
border-radius: map.get($rounded, "lg") !important;
box-shadow: 0px 0px 0px 0px rgb(0 0 0 / 20%) !important;
}

View File

@@ -2,7 +2,14 @@
<v-card> <v-card>
<ValidationObserver ref="observer" v-slot="{ invalid }"> <ValidationObserver ref="observer" v-slot="{ invalid }">
<form @submit.prevent="submit"> <form @submit.prevent="submit">
<v-card-title>Geschlossene Frage einreichen</v-card-title> <v-card-title style="cursor: pointer;" @click="showBody = !showBody">
<span class="flex-grow-1 flex-shrink-0 text-subtitle-1 font-weight-medium">Eigene Quizfrage einreichen</span>
<v-btn icon @click.stop="showBody = !showBody">
<v-icon>{{ showBody ? 'mdi-chevron-up' : 'mdi-chevron-down' }}</v-icon>
</v-btn>
</v-card-title>
<v-expand-transition>
<div v-show="showBody">
<v-card-text> <v-card-text>
<v-row> <v-row>
<v-col cols="12"> <v-col cols="12">
@@ -10,7 +17,7 @@
<v-text-field v-model="question" required label="Frage" :error-messages="errors"></v-text-field> <v-text-field v-model="question" required label="Frage" :error-messages="errors"></v-text-field>
</ValidationProvider> </ValidationProvider>
</v-col> </v-col>
<v-col v-for="(n, index) in 4" :key="index"> <v-col v-for="(n, index) in 4" :key="index" cols="6">
<ValidationProvider v-slot="{ errors }" :name="`antwort${n}`" rules="required"> <ValidationProvider v-slot="{ errors }" :name="`antwort${n}`" rules="required">
<v-text-field v-model="answers[index]" required :label="`Antwort #${n}`" :error-messages="errors"></v-text-field> <v-text-field v-model="answers[index]" required :label="`Antwort #${n}`" :error-messages="errors"></v-text-field>
</ValidationProvider> </ValidationProvider>
@@ -41,6 +48,8 @@
<v-btn text color="primary" @click="clear">Reset</v-btn> <v-btn text color="primary" @click="clear">Reset</v-btn>
<v-btn type="submit" depressed color="primary" :loading="loading" :disabled="invalid">Einreichen</v-btn> <v-btn type="submit" depressed color="primary" :loading="loading" :disabled="invalid">Einreichen</v-btn>
</v-card-actions> </v-card-actions>
</div>
</v-expand-transition>
</form> </form>
</ValidationObserver> </ValidationObserver>
</v-card> </v-card>
@@ -67,6 +76,7 @@ export default {
}, },
data () { data () {
return { return {
showBody: false,
loading: false, loading: false,
question: '', question: '',
answers: [], answers: [],

View File

@@ -2,7 +2,14 @@
<v-card> <v-card>
<ValidationObserver ref="observer" v-slot="{ invalid }"> <ValidationObserver ref="observer" v-slot="{ invalid }">
<form @submit.prevent="submit"> <form @submit.prevent="submit">
<v-card-title>Offene Frage einreichen</v-card-title> <v-card-title style="cursor: pointer;" @click="showBody = !showBody">
<span class="flex-grow-1 flex-shrink-0 text-subtitle-1 font-weight-medium">Eigene Frage einreichen</span>
<v-btn icon @click.stop="showBody = !showBody">
<v-icon>{{ showBody ? 'mdi-chevron-up' : 'mdi-chevron-down' }}</v-icon>
</v-btn>
</v-card-title>
<v-expand-transition>
<div v-show="showBody">
<v-card-text> <v-card-text>
<v-row> <v-row>
<v-col cols="12"> <v-col cols="12">
@@ -39,6 +46,8 @@
<v-btn text color="primary" @click="clear">Reset</v-btn> <v-btn text color="primary" @click="clear">Reset</v-btn>
<v-btn type="submit" depressed color="primary" :loading="loading" :disabled="invalid">Einreichen</v-btn> <v-btn type="submit" depressed color="primary" :loading="loading" :disabled="invalid">Einreichen</v-btn>
</v-card-actions> </v-card-actions>
</div>
</v-expand-transition>
</form> </form>
</ValidationObserver> </ValidationObserver>
</v-card> </v-card>
@@ -70,6 +79,7 @@ export default {
}, },
data () { data () {
return { return {
showBody: false,
loading: false, loading: false,
question: '', question: '',
solution: '' solution: ''

View File

@@ -1,22 +1,10 @@
<template> <template>
<v-container fluid> <v-card>
<v-subheader class="text-h5 text--primary">Offene Fragen</v-subheader> <v-card-title>Community Fragen</v-card-title>
<OpenEndedQuestionsList :questions="questions" />
<v-divider></v-divider> <v-divider></v-divider>
<v-expansion-panels focusable class="my-3">
<v-expansion-panel
v-for="(item, i) in questions"
:key="i"
>
<v-expansion-panel-header>
{{ item.question }}
</v-expansion-panel-header>
<v-expansion-panel-content class="text-pre-wrap">
<div class="text-pre-wrap">{{ item.solution }}</div>
</v-expansion-panel-content>
</v-expansion-panel>
</v-expansion-panels>
<AddOpenEndedQuestion /> <AddOpenEndedQuestion />
</v-container> </v-card>
</template> </template>
<script> <script>

View File

@@ -0,0 +1,126 @@
<template>
<v-data-iterator
:items="questions"
:items-per-page.sync="itemsPerPage"
:page.sync="page"
:search="search"
:sort-by="sortBy.toLowerCase()"
:sort-desc="sortDesc"
>
<template #header>
<v-toolbar
flat
class="mb-1"
>
<v-text-field
v-model="search"
clearable
flat
solo-inverted
hide-details
prepend-inner-icon="mdi-magnify"
label="Search"
></v-text-field>
<template v-if="$vuetify.breakpoint.mdAndUp">
<v-spacer></v-spacer>
<v-select
v-model="sortBy"
flat
solo-inverted
hide-details
:items="keys"
prepend-inner-icon="mdi-magnify"
label="Sort by"
></v-select>
<v-spacer></v-spacer>
<v-btn-toggle
v-model="sortDesc"
mandatory
>
<v-btn
large
depressed
color="blue"
:value="false"
>
<v-icon>mdi-arrow-up</v-icon>
</v-btn>
<v-btn
large
depressed
color="blue"
:value="true"
>
<v-icon>mdi-arrow-down</v-icon>
</v-btn>
</v-btn-toggle>
</template>
</v-toolbar>
</template>
<template #default="props">
<v-container fluid>
<v-card outlined>
<v-expansion-panels hover accordion>
<v-expansion-panel
v-for="(item, i) in props.items"
:key="i"
>
<v-expansion-panel-header>
<strong>{{ item.question }}</strong>
</v-expansion-panel-header>
<v-expansion-panel-content class="text-pre-wrap">
<div class="text-pre-wrap">{{ item.solution }}</div>
</v-expansion-panel-content>
</v-expansion-panel>
</v-expansion-panels>
</v-card>
</v-container>
</template>
</v-data-iterator>
</template>
<script>
export default {
name: 'OpenEndedQuestionsList',
props: {
questions: {
type: Array,
required: true
}
},
data () {
return {
itemsPerPageArray: [10, 20, 30],
search: '',
filter: {},
sortDesc: false,
page: 1,
itemsPerPage: 10,
sortBy: 'created',
keys: [
'Created'
]
}
},
computed: {
numberOfPages () {
return Math.ceil(this.questions.length / this.itemsPerPage)
},
filteredKeys () {
return this.keys.filter(key => key !== 'Name')
},
},
methods: {
nextPage () {
if (this.page + 1 <= this.numberOfPages) this.page += 1
},
formerPage () {
if (this.page - 1 >= 1) this.page -= 1
},
updateItemsPerPage (number) {
this.itemsPerPage = number
},
},
}
</script>

View File

@@ -1,7 +1,6 @@
<template> <template>
<v-container v-if="newQuestions.length > 0" fluid> <v-card v-if="newQuestions.length > 0">
<v-card class="my-3"> <v-card-title>
<v-card-title class="text-h5 text--primary">
<v-badge color="primary" offset-x="-5" offset-y="10" :content="newQuestions.length"> <v-badge color="primary" offset-x="-5" offset-y="10" :content="newQuestions.length">
Neue Fragen Neue Fragen
</v-badge> </v-badge>
@@ -41,7 +40,6 @@
</v-window-item> </v-window-item>
</v-window> </v-window>
</v-card> </v-card>
</v-container>
</template> </template>
<script> <script>

View File

@@ -13,6 +13,9 @@ export default {
}, },
created () { created () {
this.courseID = this.$route.params.course this.courseID = this.$route.params.course
if (!this.$store.state.user.games[this.courseID]) {
this.$store.commit('initCourse', this.courseID)
}
} }
} }
</script> </script>

View File

@@ -1,5 +1,5 @@
<template> <template>
<v-container fluid class="pa-0"> <v-container fluid>
<v-row> <v-row>
<v-col cols="12" sm="6"> <v-col cols="12" sm="6">
<v-card height="100%" class="d-flex align-center pa-2"> <v-card height="100%" class="d-flex align-center pa-2">

View File

@@ -1,9 +1,16 @@
<template> <template>
<v-container v-if="selectedQuestion" fluid class="fill-height"> <v-container v-if="selectedQuestion" fluid class="fill-height">
<GameResultDialog ref="resultDialog" :game="game" :course-id="courseID" />
<v-row dense> <v-row dense>
<v-col cols="12"> <v-col cols="12">
<p class="text-h6 text-center">{{ game.player1name }} vs. {{ game.player2name || '???' }}</p> <p class="text-h6 text-center">{{ game.player1name }} vs. {{ game.player2name || '???' }}</p>
</v-col> </v-col>
<v-col cols="12">
<v-icon
v-for="oneIndex, zeroIndex in game.questionIds.length" :key="zeroIndex"
:color="dotColor(zeroIndex)"
>mdi-circle</v-icon>
</v-col>
<v-col cols="12"> <v-col cols="12">
<v-card class="d-flex align-center" height="250" :disabled="submittedAnswer === null" @click="nextQuestion"> <v-card class="d-flex align-center" height="250" :disabled="submittedAnswer === null" @click="nextQuestion">
<span class="flex-grow-1 text-h5 font-weight-medium text-center">{{ selectedQuestion.question }}</span> <span class="flex-grow-1 text-h5 font-weight-medium text-center">{{ selectedQuestion.question }}</span>
@@ -36,10 +43,11 @@
<script> <script>
import { import {
collection, doc, getDocs, getDoc, addDoc, updateDoc, collection, doc, getDocs, getDoc, addDoc, updateDoc,
query, where, orderBy, limit, arrayUnion, arrayRemove, writeBatch writeBatch, query, where, orderBy, limit, arrayUnion, arrayRemove, increment
} from 'firebase/firestore' } from 'firebase/firestore'
import _sampleSize from 'lodash-es/sampleSize' import _sampleSize from 'lodash-es/sampleSize'
import _shuffle from 'lodash-es/shuffle' import _shuffle from 'lodash-es/shuffle'
import _isEmpty from 'lodash-es/isEmpty'
import { ClosedEndedQuestionConverter, states } from '~/plugins/closed-ended-question' import { ClosedEndedQuestionConverter, states } from '~/plugins/closed-ended-question'
import { Game, GameConverter } from '~/plugins/game' import { Game, GameConverter } from '~/plugins/game'
@@ -50,8 +58,7 @@ export default {
courseID: undefined, courseID: undefined,
game: null, game: null,
questions: [], questions: [],
selectedQuestions: [], selectedQuestion: null,
selectedQuestionID: -1,
submittedAnswer: null, submittedAnswer: null,
timer: null, timer: null,
timePerRound: 20, // in seconds timePerRound: 20, // in seconds
@@ -63,8 +70,12 @@ export default {
playerNumber () { playerNumber () {
return this.game.player1id === this.$auth.currentUser.uid ? 1 : 2 return this.game.player1id === this.$auth.currentUser.uid ? 1 : 2
}, },
selectedQuestion () { unansweredQuestions () {
return this.selectedQuestions[this.selectedQuestionID] || null if (!_isEmpty(this.game)) {
const questionsAnswered = this.game[`player${this.playerNumber}answers`].map(q => q.frage)
return this.game.questions.filter(q => !questionsAnswered.includes(q.id))
}
return []
}, },
answersShuffled () { answersShuffled () {
// Ref: https://lodash.com/docs/#shuffle // Ref: https://lodash.com/docs/#shuffle
@@ -90,6 +101,12 @@ export default {
} }
}) })
}, },
beforeDestroy () {
// Automatically submit a wrong answer when the user leaves without answering the question
if (this.submittedAnswer === null) {
this.submitAnswer(-1)
}
},
methods: { methods: {
getQuestions () { getQuestions () {
// Create a reference to the closed-ended questions collection of the currently selected course // Create a reference to the closed-ended questions collection of the currently selected course
@@ -117,9 +134,7 @@ export default {
if (docSnap.exists()) { if (docSnap.exists()) {
// Convert to Game object // Convert to Game object
this.game = docSnap.data() this.game = docSnap.data()
this.game.questions = this.questions.filter(q => this.game.questionIds.includes(q.id))
const questionsAnswered = this.game[`player${this.playerNumber}answers`].map(q => q.frage)
this.selectedQuestions = this.questions.filter(q => this.game.questions.includes(q.id) && !questionsAnswered.includes(q.id))
// Start the game // Start the game
this.nextQuestion() this.nextQuestion()
@@ -162,10 +177,10 @@ export default {
}, },
joinGame (game) { joinGame (game) {
this.game = game this.game = game
this.game.questions = this.questions.filter(q => game.questionIds.includes(q.id))
this.game.player2id = this.$auth.currentUser.uid this.game.player2id = this.$auth.currentUser.uid
this.game.player2name = this.$store.state.user.displayName this.game.player2name = this.$store.state.user.displayName
this.game.player2answers = [] this.game.player2answers = []
this.selectedQuestions = this.questions.filter(q => game.questions.includes(q.id))
// Get a new write batch // Get a new write batch
const batch = writeBatch(this.$db) const batch = writeBatch(this.$db)
@@ -192,13 +207,12 @@ export default {
}) })
}, },
createGame () { createGame () {
// Randomly pick 10 questions (or less) from the available questions // Randomly pick 5 questions (or less) from the available questions
// Ref: https://lodash.com/docs/#sampleSize // Ref: https://lodash.com/docs/#sampleSize
this.selectedQuestions = _sampleSize(this.questions, 10) const rndQuestions = _sampleSize(this.questions, 5)
const g = new Game( const g = new Game(
null, null,
this.selectedQuestions.map(q => q.id), rndQuestions.map(q => q.id),
Date.now() / 1000, // Current UNIX timestamp in seconds Date.now() / 1000, // Current UNIX timestamp in seconds
this.$auth.currentUser.uid, this.$auth.currentUser.uid,
this.$store.state.user.displayName, this.$store.state.user.displayName,
@@ -207,6 +221,7 @@ export default {
'', '',
[] []
) )
g.questions = rndQuestions
// Add a new document with a generated id // Add a new document with a generated id
addDoc(collection(this.$db, `kurse/${this.courseID}/spiele`).withConverter(GameConverter), g) addDoc(collection(this.$db, `kurse/${this.courseID}/spiele`).withConverter(GameConverter), g)
@@ -231,15 +246,28 @@ export default {
}) })
}, },
updateGame() { updateGame() {
const gameRef = doc(this.$db, `kurse/${this.courseID}/spiele/${this.game.id}`) // Get a new write batch
const batch = writeBatch(this.$db)
// Atomically add a new answer to the "player[ID]answers" array field. // Update the user's given answers for the current game
updateDoc(gameRef, { const gameRef = doc(this.$db, `kurse/${this.courseID}/spiele/${this.game.id}`)
batch.update(gameRef, {
[`spieler${this.playerNumber}antworten`]: arrayUnion({ frage: this.selectedQuestion.id, antwort: this.submittedAnswer }) [`spieler${this.playerNumber}antworten`]: arrayUnion({ frage: this.selectedQuestion.id, antwort: this.submittedAnswer })
}).then((empty) => { })
// Query execution was successful. Nothing else to do here.
// Increment the number of correct/incorrect answers given by the user by 1
const updateField = this.answerCorrect ? 'fragenRichtig' : 'fragenFalsch'
const userRef = doc(this.$db, `benutzer/${this.$auth.currentUser.uid}`)
batch.update(userRef, {
[`spiele.${this.courseID}.${updateField}`]: increment(1)
})
// Commit the batch
batch.commit().then((empty) => {
// Batch execution was successful
this.game[`player${this.playerNumber}answers`].push({ frage: this.selectedQuestion.id, antwort: this.submittedAnswer })
}).catch((error) => { }).catch((error) => {
// Failed to update the game; display error message // Batch execution failed; display error message
this.$toast({content: error, color: 'error'}) this.$toast({content: error, color: 'error'})
}) })
}, },
@@ -249,15 +277,16 @@ export default {
this.updateGame() this.updateGame()
}, },
nextQuestion () { nextQuestion () {
this.submittedAnswer = null if (_isEmpty(this.unansweredQuestions)) {
this.timeLeft = this.timePerRound * 1000 // convert sec to ms this.finishRound()
const interval = 100 // in ms
if (++this.selectedQuestionID >= this.selectedQuestions.length) {
this.finishGame()
return return
} }
this.submittedAnswer = null
this.selectedQuestion = this.unansweredQuestions[0]
this.timeLeft = this.timePerRound * 1000 // convert sec to ms
const interval = 100 // in ms
// Hacky solution to disable v-progress-linear transition when resetting its value // Hacky solution to disable v-progress-linear transition when resetting its value
this.progressBarTransition = 'transition: none;' this.progressBarTransition = 'transition: none;'
setTimeout(() => { setTimeout(() => {
@@ -274,18 +303,62 @@ export default {
} }
}, interval) }, interval)
}, },
finishGame () { finishRound () {
this.$store.commit('removeGameInProgress', this.courseID) const gameComplete = this.game.player2answers.length === this.game.questionIds.length
if (gameComplete) this.completeGame()
this.$store.commit('removeGameInProgress', this.courseID)
const ref = doc(this.$db, `benutzer/${this.$auth.currentUser.uid}`) const ref = doc(this.$db, `benutzer/${this.$auth.currentUser.uid}`)
updateDoc(ref, { updateDoc(ref, {
spieleBegonnen: arrayRemove({ kurs: this.courseID, spiel: this.game.id }) spieleBegonnen: arrayRemove({ kurs: this.courseID, spiel: this.game.id })
}).then((empty) => { }).then((empty) => {
this.$router.push(`/courses/${this.courseID}`) if (!gameComplete) this.$router.push(`/courses/${this.courseID}`)
}).catch((error) => { }).catch((error) => {
this.$toast({content: error, color: 'error'}) this.$toast({content: error, color: 'error'})
}) })
},
completeGame () {
const result = this.game.getResult()
// Figure out which player won and which player lost, or if the game was a tie
let updateFieldPl1 = ''
let updateFieldPl2 = ''
if (result.tie) {
updateFieldPl1 = updateFieldPl2 = 'unentschieden'
} else {
updateFieldPl1 = result.winner === 1 ? 'gewonnen' : 'verloren'
updateFieldPl2 = result.winner === 2 ? 'gewonnen' : 'verloren'
}
// Show the results dialog
this.$refs.resultDialog.show = true
// Get a new write batch
const batch = writeBatch(this.$db)
// Increment the number of games won/lost/tie of player1 by 1
const refPl1 = doc(this.$db, `benutzer/${this.game.player1id}`)
batch.update(refPl1, { [`spiele.${this.courseID}.${updateFieldPl1}`]: increment(1) })
// Increment the number of games won/lost/tie of player2 by 1
const refPl2 = doc(this.$db, `benutzer/${this.game.player2id}`)
batch.update(refPl2, { [`spiele.${this.courseID}.${updateFieldPl2}`]: increment(1) })
// Commit the batch
batch.commit().catch((error) => {
// Batch execution failed; display error message
this.$toast({ content: error, color: 'error' })
})
},
dotColor (index) {
if (!this.game || index + 1 > this.game[`player${this.playerNumber}answers`].length) return ''
else {
const questionId = this.game[`player${this.playerNumber}answers`][index].frage
const answer = this.game[`player${this.playerNumber}answers`][index].antwort
const correct = answer === this.game.questions.find(q => q.id === questionId).correctAnswer
return correct ? 'success' : 'error'
}
} }
} }
} }