Skip to content

Commit

Permalink
12.2. playKey method
Browse files Browse the repository at this point in the history
  • Loading branch information
ApayRus committed Jun 27, 2022
1 parent 355cd8e commit 51b3c51
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 14 deletions.
5 changes: 5 additions & 0 deletions components/Key.js
Expand Up @@ -42,6 +42,8 @@ const Key = {
keyContent: Object,
activeKey: Object,
setActiveKey: Function,
// add:
playKey: Function,
toggleShiftKey: Function,
shiftKey: Boolean
},
Expand All @@ -68,6 +70,9 @@ const Key = {
methods: {
keyClick(keyContent) {
this.setActiveKey(keyContent)
// add:
this.playKey(keyContent)

if (keyContent.code.includes('Shift')) {
this.toggleShiftKey()
}
Expand Down
22 changes: 8 additions & 14 deletions components/Keyboard.js
Expand Up @@ -30,6 +30,7 @@ const Keyboard = {
:keyContent="keyContent"
:activeKey="activeKey"
:setActiveKey="setActiveKey"
:playKey="playKey"
:toggleShiftKey="toggleShiftKey"
:shiftKey="shiftKey"
/>
Expand Down Expand Up @@ -60,16 +61,11 @@ const Keyboard = {
window.addEventListener('keydown', event => {
event.preventDefault()
const { code, shiftKey } = event
/* replace :

const keyContent = this.keyboardData[this.currentLang]
.flat()
.find(elem => elem.code === code)
with : */
const keyContent = this.getKeyContent(this.currentLang, code)

this.setActiveKey(keyContent)
this.playKey(keyContent)
})

window.addEventListener('keydown', event => {
Expand All @@ -95,18 +91,20 @@ const Keyboard = {
getKeyContent(lang, code) {
return this.keyboardData[lang].flat().find(elem => elem.code === code)
},
/* add: */
setActiveKey(keyContent) {
this.activeKey = keyContent
clearTimeout(this.timeout)
this.timeout = setTimeout(() => (this.activeKey = { code: '' }), 1000)
},
playKey(keyContent) {
const { code } = keyContent
const { shiftKey, currentLang } = this

// we created a new function
// because we call all this code twice in this method
const playKeyAudio = (lang, code, shiftKey) => {
const keyContent = this.getKeyContent(lang, code)
const fileName = getAudioFileName(keyContent, shiftKey)
const audio = new Audio(`../keyboardData/${lang}/${fileName}.mp3`)
return audio.play() // promise, we can catch error if file doesn't exist
return audio.play()
}

playKeyAudio(currentLang, code, shiftKey).catch(() => {
Expand All @@ -115,10 +113,6 @@ const Keyboard = {
playKeyAudio('en', code, shiftKey)
}
})

this.activeKey = keyContent
clearTimeout(this.timeout)
this.timeout = setTimeout(() => (this.activeKey = { code: '' }), 1000)
},
toggleShiftKey() {
this.shiftKey = !this.shiftKey
Expand Down

0 comments on commit 51b3c51

Please sign in to comment.