| 1 |
export default class StockpackTimer { |
| 2 |
/** |
| 3 |
* @param {Object} $element |
| 4 |
*/ |
| 5 |
constructor( $element ) { |
| 6 |
this.$ = {}; |
| 7 |
this.$.element = $element; |
| 8 |
this.timerTimeout = null; |
| 9 |
this.seconds = 0; |
| 10 |
this.timer(); |
| 11 |
} |
| 12 |
|
| 13 |
timer() { |
| 14 |
if ( ! this.$.element.length ) { |
| 15 |
return false; |
| 16 |
} |
| 17 |
if ( ! this.$.element.hasClass( 'parsed' ) ) { |
| 18 |
this.seconds = 0; |
| 19 |
const time = this.$.element.text().split( ':' ); |
| 20 |
let increment = 1; |
| 21 |
time.reverse().forEach( ( element ) => { |
| 22 |
this.seconds += increment * element; |
| 23 |
increment = increment * 60; |
| 24 |
} ); |
| 25 |
this.$.element.addClass( 'parsed' ); |
| 26 |
} |
| 27 |
|
| 28 |
const days = Math.floor( this.seconds / 24 / 60 / 60 ); |
| 29 |
const hoursLeft = Math.floor( ( this.seconds ) - ( days * 86400 ) ); |
| 30 |
const hours = Math.floor( hoursLeft / 3600 ); |
| 31 |
const minutesLeft = Math.floor( ( hoursLeft ) - ( hours * 3600 ) ); |
| 32 |
const minutes = Math.floor( minutesLeft / 60 ); |
| 33 |
const remainingSeconds = this.seconds % 60; |
| 34 |
|
| 35 |
function pad( n ) { |
| 36 |
return ( n < 10 ? '0' + n : n ); |
| 37 |
} |
| 38 |
|
| 39 |
let text = pad( hours ) + ':' + pad( minutes ) + ':' + pad( remainingSeconds ); |
| 40 |
if ( days ) { |
| 41 |
text = pad( days ) + ':' + text; |
| 42 |
} |
| 43 |
this.$.element.text( text ); |
| 44 |
if ( this.seconds === 0 ) { |
| 45 |
clearTimeout( this.timerTimeout ); |
| 46 |
this.$.element.text( wp.media.view.l10n.stockpack.limit.reset ); |
| 47 |
} else { |
| 48 |
this.seconds--; |
| 49 |
} |
| 50 |
clearTimeout( this.timerTimeout ); |
| 51 |
this.timerTimeout = setTimeout( |
| 52 |
() => { |
| 53 |
this.timer(); |
| 54 |
}, 1000, this, |
| 55 |
); |
| 56 |
} |
| 57 |
|
| 58 |
destroy() { |
| 59 |
if ( this.$.el ) { |
| 60 |
this.$.el.remove(); |
| 61 |
} |
| 62 |
clearTimeout( this.timerTimeout ); |
| 63 |
} |
| 64 |
} |
| 65 |
|