2014-01-03 13:32:13 -05:00
|
|
|
module.exports = class DialogueAnimator
|
|
|
|
jqueryElement: null
|
|
|
|
childrenToAdd: null
|
|
|
|
charsToAdd: null
|
|
|
|
childAnimator: null
|
2014-06-30 22:16:26 -04:00
|
|
|
|
2014-01-03 13:32:13 -05:00
|
|
|
constructor: (html, @jqueryElement) ->
|
|
|
|
d = $('<div></div>').html(html)
|
|
|
|
@childrenToAdd = _.map(d[0].childNodes, (e) -> return e)
|
2014-08-26 14:29:16 -04:00
|
|
|
@t0 = new Date()
|
|
|
|
@charsAdded = 0
|
2014-11-08 14:35:25 -05:00
|
|
|
@charsPerSecond = 25
|
2014-06-30 22:16:26 -04:00
|
|
|
|
2014-01-03 13:32:13 -05:00
|
|
|
tick: ->
|
|
|
|
if not @charsToAdd and not @childAnimator
|
|
|
|
@addNextElement()
|
2014-06-30 22:16:26 -04:00
|
|
|
|
2014-01-03 13:32:13 -05:00
|
|
|
if @charsToAdd
|
|
|
|
@addSingleChar()
|
|
|
|
return
|
2014-06-30 22:16:26 -04:00
|
|
|
|
2014-01-03 13:32:13 -05:00
|
|
|
if @childAnimator
|
|
|
|
@childAnimator.tick()
|
|
|
|
if @childAnimator.done()
|
|
|
|
@childAnimator = null
|
2014-06-30 22:16:26 -04:00
|
|
|
|
2014-01-03 13:32:13 -05:00
|
|
|
addNextElement: ->
|
|
|
|
return unless @childrenToAdd.length
|
|
|
|
nextElem = @childrenToAdd[0]
|
|
|
|
@childrenToAdd = @childrenToAdd[1..]
|
|
|
|
if nextElem.nodeName is '#text'
|
2014-08-26 14:29:16 -04:00
|
|
|
@charsToAdd = nextElem.nodeValue
|
2014-01-03 13:32:13 -05:00
|
|
|
else
|
|
|
|
value = nextElem.innerHTML
|
|
|
|
newElem = $(nextElem).html('')
|
|
|
|
@jqueryElement.append(newElem)
|
|
|
|
if value
|
2014-08-26 14:29:16 -04:00
|
|
|
@charsAdded += @childAnimator.getCharsAdded() if @childAnimator
|
2014-01-03 13:32:13 -05:00
|
|
|
@childAnimator = new DialogueAnimator(value, newElem)
|
2014-06-30 22:16:26 -04:00
|
|
|
|
2014-01-03 13:32:13 -05:00
|
|
|
addSingleChar: ->
|
2014-08-26 14:29:16 -04:00
|
|
|
elapsed = (new Date()) - @t0
|
|
|
|
nAdded = @getCharsAdded()
|
|
|
|
nToHaveBeenAdded = Math.round @charsPerSecond * elapsed / 1000
|
|
|
|
nToAdd = Math.min nToHaveBeenAdded - nAdded, @charsToAdd.length
|
|
|
|
@jqueryElement.html(@jqueryElement.html() + @charsToAdd.slice(0, nToAdd))
|
|
|
|
@charsToAdd = @charsToAdd.slice(nToAdd)
|
2014-01-03 13:32:13 -05:00
|
|
|
if @charsToAdd.length is 0
|
|
|
|
@charsToAdd = null
|
2014-08-26 14:29:16 -04:00
|
|
|
@charsAdded += nToAdd
|
|
|
|
|
|
|
|
getCharsAdded: ->
|
|
|
|
@charsAdded + (@childAnimator?.charsAdded ? 0)
|
2014-06-30 22:16:26 -04:00
|
|
|
|
2014-01-03 13:32:13 -05:00
|
|
|
done: ->
|
|
|
|
return false if @childrenToAdd.length > 0
|
|
|
|
return false if @charsToAdd
|
|
|
|
return false if @childAnimator
|
|
|
|
return true
|