Add optional chapter field to open-ended questions

This commit is contained in:
2022-11-11 20:08:45 +01:00
parent a269902743
commit c04810ffa6
3 changed files with 184 additions and 88 deletions

View File

@@ -3,7 +3,7 @@
<ValidationObserver ref="observer" v-slot="{ invalid }"> <ValidationObserver ref="observer" v-slot="{ invalid }">
<form @submit.prevent="submit"> <form @submit.prevent="submit">
<v-card-title style="cursor: pointer;" @click="showBody = !showBody"> <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> <span class="flex-grow-1 flex-shrink-0 text-subtitle-1 font-weight-medium">Eigene Frage einsenden</span>
<v-btn icon @click.stop="showBody = !showBody"> <v-btn icon @click.stop="showBody = !showBody">
<v-icon>{{ showBody ? 'mdi-chevron-up' : 'mdi-chevron-down' }}</v-icon> <v-icon>{{ showBody ? 'mdi-chevron-up' : 'mdi-chevron-down' }}</v-icon>
</v-btn> </v-btn>
@@ -13,26 +13,41 @@
<v-card-text> <v-card-text>
<v-row> <v-row>
<v-col cols="12"> <v-col cols="12">
<ValidationProvider v-slot="{ errors }" name="Frage/Aufgabenstellung" rules="required|min:20"> <ValidationProvider v-slot="{ errors }" name="Kapitelnummer" :rules="{ regex: /^[1-9]+$/ }">
<v-text-field
v-model="chapter"
filled
hint="Freilassen, wenn deine Frage das Wissen aus mehreren Kapiteln vereint."
persistent-hint
maxlength="1"
label="Kapitelnummer"
:error-messages="errors"
></v-text-field>
</ValidationProvider>
</v-col>
<v-col cols="12">
<ValidationProvider v-slot="{ errors }" name="Frage/Aufgabenstellung" :rules="{ required: true, min: 20, max: questionMaxLength }">
<v-textarea <v-textarea
v-model="question" v-model="question"
required required
auto-grow auto-grow
filled filled
counter counter
:maxlength="questionMaxLength"
label="Frage/Aufgabenstellung" label="Frage/Aufgabenstellung"
:error-messages="errors" :error-messages="errors"
></v-textarea> ></v-textarea>
</ValidationProvider> </ValidationProvider>
</v-col> </v-col>
<v-col cols="12"> <v-col cols="12">
<ValidationProvider v-slot="{ errors }" name="Musterlösung" rules="required|min:50"> <ValidationProvider v-slot="{ errors }" name="Musterlösung" :rules="{ required: true, min: 50, max: solutionMaxLength }">
<v-textarea <v-textarea
v-model="solution" v-model="solution"
required required
auto-grow auto-grow
filled filled
counter counter
:maxlength="solutionMaxLength"
label="Musterlösung" label="Musterlösung"
:error-messages="errors" :error-messages="errors"
></v-textarea> ></v-textarea>
@@ -58,7 +73,7 @@ import { collection, doc, addDoc, writeBatch } from 'firebase/firestore'
// We use vee-validate@3 for form validation. // We use vee-validate@3 for form validation.
// https://vee-validate.logaretm.com/v3/guide/basics.html // https://vee-validate.logaretm.com/v3/guide/basics.html
import { ValidationProvider, ValidationObserver, extend } from 'vee-validate' import { ValidationProvider, ValidationObserver, extend } from 'vee-validate'
import { required, min } from 'vee-validate/dist/rules' import { required, min, max, regex } from 'vee-validate/dist/rules'
import dedent from 'dedent' import dedent from 'dedent'
import { OpenEndedQuestion, OpenEndedQuestionConverter } from '~/plugins/open-ended-question' import { OpenEndedQuestion, OpenEndedQuestionConverter } from '~/plugins/open-ended-question'
@@ -72,6 +87,16 @@ extend('min', {
message: '{_field_} muss mindestens {length} Zeichen lang sein.' message: '{_field_} muss mindestens {length} Zeichen lang sein.'
}) })
extend('max', {
...max,
message: '{_field_} darf maximal {length} Zeichen lang sein.'
})
extend('regex', {
...regex,
message: '{_field_} muss eine Zahl von 1-9 sein.'
})
export default { export default {
components: { components: {
ValidationProvider, ValidationProvider,
@@ -79,43 +104,60 @@ export default {
}, },
data () { data () {
return { return {
showBody: false, questionMaxLength: 250,
loading: false, solutionMaxLength: 1000,
chapter: null,
question: '', question: '',
solution: '' solution: '',
showBody: false,
loading: false
} }
}, },
methods: { methods: {
submit () { submit () {
this.loading = true // Remove extra spaces at the start and end of the string (trim),
// then remove extra spaces between words (1st replace),
// then remove extra line breaks so that there's max 1 empty line between paragraphs (2nd replace).
this.question = this.question.trim().replace(/ +/g, ' ').replace(/[\r\n]{3,}/g, '\n\n')
this.solution = this.solution.trim().replace(/ +/g, ' ').replace(/[\r\n]{3,}/g, '\n\n')
const q = new OpenEndedQuestion( // Wait until the models are updated in the UI
null, this.$nextTick(() => {
this.question, this.$refs.observer.validate().then((success) => {
this.solution, if (!success) return
this.$auth.currentUser.uid, // Ref: https://firebase.google.com/docs/reference/js/v8/firebase.User
Date.now() / 1000, // Current UNIX timestamp in seconds
[],
{}
)
// Add a new document with a generated id. this.loading = true
addDoc(collection(this.$db, `kurse/${this.$store.state.selectedCourse}/fragenOffen`).withConverter(OpenEndedQuestionConverter), q) const q = new OpenEndedQuestion(
.then((docRef) => { null,
// Successfully added new question to database this.chapter,
q.id = docRef.id this.question,
this.$emit('added', q) this.solution,
this.$toast({ content: 'Deine Frage wurde hinzugefügt!', color: 'success' }) this.$auth.currentUser.uid, // Ref: https://firebase.google.com/docs/reference/js/v8/firebase.User
}) Date.now() / 1000, // Current UNIX timestamp in seconds
.catch((error) => { [],
// Failed to add question to database; display error message {}
this.$toast({content: error, color: 'error'}) )
})
.then(() => { // Add a new document with a generated id.
this.loading = false addDoc(collection(this.$db, `kurse/${this.$store.state.selectedCourse}/fragenOffen`).withConverter(OpenEndedQuestionConverter), q)
.then((docRef) => {
// Successfully added new question to database
q.id = docRef.id
this.$emit('added', q)
this.$toast({ content: 'Deine Frage wurde hinzugefügt!', color: 'success' })
})
.catch((error) => {
// Failed to add question to database; display error message
this.$toast({content: error, color: 'error'})
})
.then(() => {
this.loading = false
})
})
}) })
}, },
clear () { clear () {
this.chapter = ''
this.question = '' this.question = ''
this.solution = '' this.solution = ''
this.$refs.observer.reset() this.$refs.observer.reset()
@@ -145,11 +187,14 @@ export default {
const batch = writeBatch(this.$db) const batch = writeBatch(this.$db)
for (let i = 1; i <= 10; i++) { for (let i = 1; i <= 10; i++) {
// Generate random integer between 1 (inlcusive) and 1000 (inclusive) // Generate random integer between 1 (inclusive) and 1000 (inclusive)
const randomNumber = Math.floor(Math.random() * (1000 - 1 + 1) + 1) const randomNumber = Math.floor(Math.random() * (1000 - 1 + 1) + 1)
// Generate random integer between 1 (inclusive) and 9 (inclusive)
const chapter = Math.floor(Math.random() * (9 - 1 + 1) + 1)
const q = new OpenEndedQuestion( const q = new OpenEndedQuestion(
null, null,
chapter,
`Frage ${randomNumber}: Erläutere den Sinn des Lebens.`, `Frage ${randomNumber}: Erläutere den Sinn des Lebens.`,
solution, solution,
this.$auth.currentUser.uid, // Ref: https://firebase.google.com/docs/reference/js/v8/firebase.User this.$auth.currentUser.uid, // Ref: https://firebase.google.com/docs/reference/js/v8/firebase.User

View File

@@ -1,21 +1,18 @@
<template> <template>
<v-data-iterator <v-data-iterator
:items="questions" :items="items"
:items-per-page.sync="itemsPerPage" :items-per-page.sync="itemsPerPage"
:page.sync="page" :page.sync="page"
:search="search" :search="search"
:sort-by="sortBy" disable-sort
:sort-desc="sortDesc"
no-data-text="Keine Daten vorhanden" no-data-text="Keine Daten vorhanden"
no-results-text="Keine passenden Ergebnisse gefunden" no-results-text="Keine passenden Ergebnisse gefunden"
locale="de-DE" locale="de-DE"
class="text-center" class="text-center"
:footer-props="{ itemsPerPageOptions: itemsPerPageArray, itemsPerPageText: 'Fragen pro Seite'}"
> >
<template #header> <template #header>
<v-toolbar <v-toolbar flat class="mb-1">
flat
class="mb-1"
>
<v-text-field <v-text-field
v-model="search" v-model="search"
clearable clearable
@@ -43,19 +40,11 @@
v-model="sortDesc" v-model="sortDesc"
mandatory mandatory
> >
<v-btn <v-btn large depressed :value="false">
large <v-icon>mdi-sort-ascending</v-icon>
depressed
:value="false"
>
<v-icon>mdi-arrow-up</v-icon>
</v-btn> </v-btn>
<v-btn <v-btn large depressed :value="true">
large <v-icon>mdi-sort-descending</v-icon>
depressed
:value="true"
>
<v-icon>mdi-arrow-down</v-icon>
</v-btn> </v-btn>
</v-btn-toggle> </v-btn-toggle>
</template> </template>
@@ -73,6 +62,9 @@
> >
<v-expansion-panel-header v-slot="{ open }"> <v-expansion-panel-header v-slot="{ open }">
<v-row dense> <v-row dense>
<v-col cols="12" class="text-overline text--secondary">
<strong>Kapitel {{ item.chapter || '-' }}</strong>
</v-col>
<v-col cols="12" class="text-pre-wrap"> <v-col cols="12" class="text-pre-wrap">
<strong>{{ item.question }}</strong> <strong>{{ item.question }}</strong>
</v-col> </v-col>
@@ -95,29 +87,16 @@
<v-col cols="12" class="mb-4"> <v-col cols="12" class="mb-4">
<div class="text-left text-pre-wrap">{{ item.solution }}</div> <div class="text-left text-pre-wrap">{{ item.solution }}</div>
</v-col> </v-col>
<v-col cols="auto" class="mr-4"> <v-col v-for="(btn, btni) in actionButtons" :key="btni" cols="auto" :class="btn.class">
<v-btn icon :color="helpful ? 'primary' : ''" @click="toggleHelpful"> <v-tooltip bottom>
<v-icon>{{ helpful ? 'mdi-thumb-up' : 'mdi-thumb-up-outline' }}</v-icon> <template #activator="{ on, attrs }">
</v-btn> <v-btn icon :color="btn.active ? btn.iconColor : ''" v-bind="attrs" v-on="on" @click="btn.onClick">
<div class="text-caption text--secondary">{{ item.helpful.length }}</div> <v-icon>{{ btn.active ? btn.iconActive : btn.iconInactive }}</v-icon>
</v-col> </v-btn>
<v-col cols="auto"> </template>
<v-btn icon :color="difficulty === 'easy' ? 'amber' : ''" @click="toggleDifficulty('easy')"> <span>{{ btn.tooltip }}</span>
<v-icon>{{ difficulty === 'easy' ? 'mdi-emoticon' : 'mdi-emoticon-outline' }}</v-icon> </v-tooltip>
</v-btn> <div class="text-caption text--secondary">{{ btn.caption }}</div>
<div class="text-caption text--secondary">{{ item.difficulty.easy.length }}</div>
</v-col>
<v-col cols="auto">
<v-btn icon :color="difficulty === 'medium' ? 'amber' : ''" @click="toggleDifficulty('medium')">
<v-icon>{{ difficulty === 'medium' ? 'mdi-emoticon-happy' : 'mdi-emoticon-happy-outline' }}</v-icon>
</v-btn>
<div class="text-caption text--secondary">{{ item.difficulty.medium.length }}</div>
</v-col>
<v-col cols="auto">
<v-btn icon :color="difficulty === 'hard' ? 'amber' : ''" @click="toggleDifficulty('hard')">
<v-icon>{{ difficulty === 'hard' ? 'mdi-emoticon-confused' : 'mdi-emoticon-confused-outline' }}</v-icon>
</v-btn>
<div class="text-caption text--secondary">{{ item.difficulty.hard.length }}</div>
</v-col> </v-col>
</v-row> </v-row>
</v-expansion-panel-content> </v-expansion-panel-content>
@@ -126,6 +105,11 @@
</v-card> </v-card>
</v-container> </v-container>
</template> </template>
<!-- eslint-disable-next-line -->
<template #footer.page-text="{ pageStart, pageStop, itemsLength }">
<span>{{ pageStart }} - {{ pageStop }} von {{ itemsLength }}</span>
</template>
</v-data-iterator> </v-data-iterator>
</template> </template>
@@ -142,15 +126,16 @@ export default {
}, },
data () { data () {
return { return {
itemsPerPageArray: [10, 20, 30], items: [],
itemsPerPageArray: [10, 25, 50],
search: '', search: '',
filter: {},
sortDesc: true, sortDesc: true,
page: 1, page: 1,
itemsPerPage: 10, itemsPerPage: 10,
sortBy: 'created', sortBy: 'created',
keys: [ keys: [
{ key: 'Neueste', value: 'created' }, { key: 'Neueste', value: 'created' },
{ key: 'Kapitel', value: 'chapter' },
{ key: 'Hilfreich', value: 'helpful' }, { key: 'Hilfreich', value: 'helpful' },
{ key: 'Schwierigkeit', value: 'difficultyLevel' } { key: 'Schwierigkeit', value: 'difficultyLevel' }
], ],
@@ -165,8 +150,51 @@ export default {
numberOfPages () { numberOfPages () {
return Math.ceil(this.questions.length / this.itemsPerPage) return Math.ceil(this.questions.length / this.itemsPerPage)
}, },
filteredKeys () { actionButtons () {
return this.keys.filter(key => key !== 'Name') const self = this
return [
// Button "Helpful"
{
active: this.helpful,
iconActive: 'mdi-thumb-up',
iconInactive: 'mdi-thumb-up-outline',
iconColor: 'primary',
caption: this.selectedQuestion && this.selectedQuestion.helpful.length,
tooltip: 'Hilfreich',
class: 'mr-4',
onClick() { self.toggleHelpful() }
},
// Button "Easy Question"
{
active: this.difficulty === 'easy',
iconActive: 'mdi-emoticon',
iconInactive: 'mdi-emoticon-outline',
iconColor: 'amber',
caption: this.selectedQuestion && this.selectedQuestion.difficulty.easy.length,
tooltip: 'Leichte Frage',
onClick() { self.toggleDifficulty('easy') }
},
// Button "Moderate Question"
{
active: this.difficulty === 'medium',
iconActive: 'mdi-emoticon-happy',
iconInactive: 'mdi-emoticon-happy-outline',
iconColor: 'amber',
caption: this.selectedQuestion && this.selectedQuestion.difficulty.medium.length,
tooltip: 'Mittelschwere Frage',
onClick() { self.toggleDifficulty('medium') }
},
// Button "Hard Question"
{
active: this.difficulty === 'hard',
iconActive: 'mdi-emoticon-confused',
iconInactive: 'mdi-emoticon-confused-outline',
iconColor: 'amber',
caption: this.selectedQuestion && this.selectedQuestion.difficulty.hard.length,
tooltip: 'Schwere Frage',
onClick() { self.toggleDifficulty('hard') }
}
]
}, },
helpful () { helpful () {
return this.selectedQuestion && this.selectedQuestion.helpful.includes(this.$auth.currentUser.uid) return this.selectedQuestion && this.selectedQuestion.helpful.includes(this.$auth.currentUser.uid)
@@ -178,15 +206,33 @@ export default {
else return null else return null
} }
}, },
watch: {
questions () {
this.items = [...this.questions]
this.sort()
},
sortBy () {
this.sort()
},
sortDesc () {
this.sort()
}
},
methods: { methods: {
nextPage () { sort () {
if (this.page + 1 <= this.numberOfPages) this.page += 1 if (this.items && this.items.length > 0) {
}, this.items.sort((a, b) => {
formerPage () { if (this.sortBy === 'helpful') {
if (this.page - 1 >= 1) this.page -= 1 return this.sortDesc
}, ? b[this.sortBy].length - a[this.sortBy].length
updateItemsPerPage (number) { : a[this.sortBy].length - b[this.sortBy].length
this.itemsPerPage = number } else {
return this.sortDesc
? b[this.sortBy] - a[this.sortBy]
: a[this.sortBy] - b[this.sortBy]
}
})
}
}, },
setSelectedQuestion(q) { setSelectedQuestion(q) {
this.selectedQuestion = q this.selectedQuestion = q
@@ -238,6 +284,7 @@ export default {
if (indexHard !== -1) this.selectedQuestion.difficulty.hard.splice(indexHard, 1) if (indexHard !== -1) this.selectedQuestion.difficulty.hard.splice(indexHard, 1)
this.selectedQuestion.difficulty[type].push(this.$auth.currentUser.uid) this.selectedQuestion.difficulty[type].push(this.$auth.currentUser.uid)
} }
this.selectedQuestion.updateDifficultyLevel()
}).catch((error) => { }).catch((error) => {
// Failed to update the question; display error message // Failed to update the question; display error message
this.$toast({ content: error, color: 'error' }) this.$toast({ content: error, color: 'error' })

View File

@@ -1,6 +1,7 @@
export class OpenEndedQuestion { export class OpenEndedQuestion {
constructor (id, question, solution, creator, created, helpful, difficulty) { constructor (id, chapter, question, solution, creator, created, helpful, difficulty) {
this.id = id this.id = id
this.chapter = chapter
this.question = question this.question = question
this.solution = solution this.solution = solution
this.creator = creator this.creator = creator
@@ -40,6 +41,7 @@ export const OpenEndedQuestionConverter = {
toFirestore: (openEndedQuestion) => { toFirestore: (openEndedQuestion) => {
return { return {
frage: openEndedQuestion.question, frage: openEndedQuestion.question,
kapitel: openEndedQuestion.chapter,
musterloesung: openEndedQuestion.solution, musterloesung: openEndedQuestion.solution,
ersteller: openEndedQuestion.creator, ersteller: openEndedQuestion.creator,
erstellt: openEndedQuestion.created, erstellt: openEndedQuestion.created,
@@ -53,6 +55,8 @@ export const OpenEndedQuestionConverter = {
}, },
fromFirestore: (snapshot, options) => { fromFirestore: (snapshot, options) => {
const data = snapshot.data(options) const data = snapshot.data(options)
return new OpenEndedQuestion(snapshot.id, data.frage, data.musterloesung, data.ersteller, data.erstellt, data.hilfreich, data.schwierigkeit) return new OpenEndedQuestion(snapshot.id,
data.kapitel, data.frage, data.musterloesung, data.ersteller, data.erstellt, data.hilfreich, data.schwierigkeit
)
} }
} }