| 1 |
import classNames from 'classnames'; |
| 2 |
|
| 3 |
import { Component } from '@wordpress/element'; |
| 4 |
import { withDispatch, withSelect } from '@wordpress/data'; |
| 5 |
import { compose } from '@wordpress/compose'; |
| 6 |
import { __ } from '@wordpress/i18n'; |
| 7 |
|
| 8 |
class ButtonCheck extends Component { |
| 9 |
constructor() { |
| 10 |
super( ...arguments ); |
| 11 |
|
| 12 |
this.state = { |
| 13 |
loading: false, |
| 14 |
}; |
| 15 |
} |
| 16 |
|
| 17 |
checkAnswer = () => { |
| 18 |
const { checkAnswer, question, answered } = this.props; |
| 19 |
|
| 20 |
// Fix temporary for FIB. |
| 21 |
if ( question.type === 'fill_in_blanks' ) { |
| 22 |
const elFIB = document.querySelector( `.question-fill_in_blanks[data-id="${ question.id }"]` ); |
| 23 |
const elInputs = elFIB.querySelectorAll( '.lp-fib-input > input' ); |
| 24 |
elInputs.forEach( ( elInput ) => { |
| 25 |
if ( elInput.value.length > 0 ) { |
| 26 |
this.setState( { |
| 27 |
loading: true, |
| 28 |
} ); |
| 29 |
checkAnswer( question.id ); |
| 30 |
return false; |
| 31 |
} |
| 32 |
} ); |
| 33 |
} |
| 34 |
|
| 35 |
if ( answered ) { |
| 36 |
checkAnswer( question.id ); |
| 37 |
|
| 38 |
this.setState( { |
| 39 |
loading: true, |
| 40 |
} ); |
| 41 |
} |
| 42 |
}; |
| 43 |
|
| 44 |
render() { |
| 45 |
const { answered } = this.props; |
| 46 |
|
| 47 |
return ( |
| 48 |
<> |
| 49 |
<button className={ classNames( 'lp-button', 'instant-check', { |
| 50 |
loading: this.state.loading, |
| 51 |
} ) } onClick={ this.checkAnswer } |
| 52 |
> |
| 53 |
<span className="instant-check__icon" /> |
| 54 |
{ __( 'Check answers', 'learnpress' ) } |
| 55 |
|
| 56 |
{ ! answered && ( |
| 57 |
<div className="instant-check__info" dangerouslySetInnerHTML={ { __html: __( 'You need to answer the question before checking the answer key.', 'learnpress' ) } } /> |
| 58 |
) } |
| 59 |
</button> |
| 60 |
</> |
| 61 |
); |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
export default compose( |
| 66 |
withSelect( ( select, { question: { id } } ) => { |
| 67 |
const { getQuestionAnswered } = select( 'learnpress/quiz' ); |
| 68 |
|
| 69 |
return { |
| 70 |
answered: getQuestionAnswered( id ), |
| 71 |
}; |
| 72 |
} ), |
| 73 |
withDispatch( ( dispatch, { id } ) => { |
| 74 |
const { checkAnswer } = dispatch( 'learnpress/quiz' ); |
| 75 |
|
| 76 |
return { |
| 77 |
checkAnswer( id ) { |
| 78 |
checkAnswer( id ); |
| 79 |
}, |
| 80 |
}; |
| 81 |
} ) |
| 82 |
)( ButtonCheck ); |
| 83 |
|