eSentences/public/app.js

96 lines
2.8 KiB
JavaScript
Raw Normal View History

2024-07-15 16:39:31 +03:00
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.classList.add('dark');
}
const app = new Vue({
el: '#app',
data() {
return {
phrase: {ru: 'wait', en: ''},
levels: {easy: {name: 'Easy', from: 4, to: 8},
medium: {name: 'Medium', from: 9, to: 16},
hard: {name: 'Hard', from: 17, to: 26},
expert: {name: 'Expert', from: 27, to: 40}
},
level: 'medium',
userInput: '',
partsMode: false,
parts: [],
userParts: []
}
},
mounted() {
this.newPhrase()
},
computed: {
isValid: function() {
return this.userInput.toLowerCase() === this.phrase.en.toLowerCase()
},
censored: function() {
let input = this.userInput.toLowerCase()
let phrase = this.phrase.en.toLowerCase()
let phraseLength = phrase.length
let min = Math.min(input.length, phraseLength)
if (min == 0) return '*'.repeat(phraseLength)
for (let i = 0; i < min; i++) {
// Valid part of a word
if (input[i] !== phrase[i]) {
return this.phrase.en.substr(0, i) + '*'.repeat(phraseLength - i)
}
}
return this.phrase.en.substr(0, min) + '*'.repeat(phraseLength - min)
}
},
methods: {
newPhrase: function() {
this.userInput = ""
this.userParts = []
this.parts = []
let levelInfo = this.levels[this.level]
let min = levelInfo.from
let max = levelInfo.to
let wordsCount = Math.floor(Math.random() * (max - min) + min)
fetch('/phrase/' + wordsCount)
.then(resp => resp.json())
.then(data => {
this.phrase = data
this.createParts()
})
},
onLevelChange: function() {
this.newPhrase()
},
togglePartsMode: function() {
this.partsMode = !this.partsMode
this.createParts()
},
createParts: function() {
if (!this.partsMode) return
this.parts = this.phrase.en.split(" ")
.map(value => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value)
this.userParts = []
},
insertPart: function(p, id) {
this.parts.splice(id, 1)
this.userParts.push(p)
this.userInput = this.userParts.join(' ')
if (this.parts.length == 0) {
window.nextPhraseButton.focus()
}
},
removePart: function(p, id) {
this.userParts.splice(id, 1)
this.parts.push(p)
this.userInput = this.userParts.join(' ')
},
shutdown: function() {
fetch('/shutdown/')
this.phrase = {id: 0, ru: 'Сервер остановлен', en: 'Server is stopped'}
this.createParts()
}
}
});