-
Notifications
You must be signed in to change notification settings - Fork 0
/
ascii-animation.html
582 lines (563 loc) · 20.6 KB
/
ascii-animation.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="ascii-animation-keyframe.html">
<!--
An element to provide a way to animate ascii text. Animation is keyframe based.
A sequence of keyframes are used with a selector property indicating the frame should display when the duration is that % out of 100.
Example:
<ascii-animation duration="1" autoplay>
<ascii-animation-keyframe name="smiley" selector="0">:)</ascii-animation-keyframe>
<ascii-animation-keyframe name="meh" selector="50">:|</ascii-animation-keyframe>
<ascii-animation-keyframe name="frownie" selector="100">:(</ascii-animation-keyframe>
</ascii-animation>
@demo demo/index.html
@hero hero.svg
-->
<dom-module id="ascii-animation">
<template>
<style>
:host {
display: block;
box-sizing: border-box;
}
#ascii-view {
font-family: monospace;
margin: 0;
padding: 0;
white-space: pre;
overflow: hidden;
position: relative;
}
#ascii-content {
width: 0ch;
position: relative;
}
</style>
<div id="ascii-view">
<div id="ascii-content">[[_renderedText]]</div>
</div>
<div id="keyframe-content" hidden>
<content></content>
</div>
</template>
<script>
/* @typedef {Object} Keyframe
* @property {number} selector - 0 to 100 percentage of animation where keyframe is shown.
* @property {string} name - name of frame for organizational reasons
* @property {string} display - ascii text to be displayed in frame.
*/
Polymer({
is: 'ascii-animation',
properties: {
/**
* `autoplay` indicates that the element should begin animating immediately
* when attached.
*/
autoplay: Boolean,
/**
* `loop` indicates that playback should restart when it reaches the end.
*/
loop: Boolean,
/**
* `reverse` indicates that playback should be backwards.
*/
reverse: {
type: Boolean,
notify: true,
observer: '_directionChanged'
},
/**
* `bounce` indicates playback should alternate between forwards and reverse.
* can be used a long with loop.
*/
bounce: Boolean,
/**
* `running` is true when the animation is currently playing.
*/
running: {
type: Boolean,
notify: true,
value: false
},
/**
* array of keyframes either from `<ascii-animation-keyframe>` elements in the content
* or can be set programmatically.
* @type Array.{Keyframe}
*/
keyframes: {
type: Array,
notify: true,
value: function () {
// this needs to get the keyframes from the content.
return [];
}
},
/**
* 0-100 starting point of animation, default is 0
*/
inPoint: {
type: Number,
value: 0
},
/**
* 0-100 ending point of animation
*/
outPoint: {
type: Number,
value: 100
},
/**
* duration of animation in seconds
*/
duration: {
type: Number,
value: 1
},
// private
/**
* `_renderedText` contains all the frames rendered into one string with proper padding for rows and cols.
*/
_renderedText: {
type: String,
notify: true
},
/**
* `_charCols` stores the number of columns in the longest line of any keyframe.
* all lines in all frames will be padded to this value when generating _renderedText
*/
_charCols: {
type: Number,
notify: true,
value: 0
},
/**
* `_charRows` stores the highest number of rows in any keyframe.
* all frames are then padded to this value when generating _renderedText
*/
_charRows: {
type: Number,
notify: true,
value: 0
},
/**
* `_keyFramePositions` is a simplified array of all the selectors in the provided keyframes
* example: if there are keyframes for 0, 33, 66, and 100, the array will be
* [0,33,66,100]
*/
_keyFramePositions: {
type: Array
},
/**
* `_handle` is the current async handle so pause and stop can cancel it.
*/
_handle: {
type: Object
},
/**
* `_ready` set after ready event fires
*/
_ready: Boolean,
/**
* `_attached` set after attached event fires
*/
_attached: Boolean,
/**
* `_percent` is the current position of the play head from 0 - 100
*/
_percent: {
type: Number,
notify: true,
value: 0,
observer: '_percentChanged'
},
/**
* used during the loop to store the value
*/
_newPercent: {
type: Number,
value: 0
}
},
observers: ['_keyFramesChanged(keyframes.*)'],
// Element Lifecycle
ready: function () {
// `ready` is called after all elements have been configured, but
// propagates bottom-up. This element's children are ready, but parents
// are not.
//
// This is the point where you should make modifications to the DOM (when
// necessary), or kick off any processes the element wants to perform.
this._ready = true;
},
attached: function () {
// `attached` fires once the element and its parents have been inserted
// into a document. This is where keyframes are populated from the element's content
// if they are already defined the ones in content will be pushed to the end of the array.
// get keyframes from content
var keyFrames = this.querySelectorAll('ascii-animation-keyframe');
//var keyFrames = Polymer.dom(this).getEffectiveChildren(); ?
// vars for manual notification
var startIndex = keyFrames.length != undefined ? keyFrames.length + 1 : 0;
var addedCount = 0;
for (var k = 0; k < keyFrames.length; k++) {
var kf = {
"name": keyFrames[k].name,
"selector": keyFrames[k].selector,
"display": keyFrames[k].display
};
// deliberately avoiding `this.push()` so we don't update the text render until all frames are added.
this.keyframes.push(kf);
}
// setting this after the keyframe add loop so any attempts to render from the for loop won't fire since it checks the `_attached`s property.
this._attached = true;
// this should cause the the _keyFramesChanged observer to fire properly.
this.notifySplices('keyframes', [{
"index": startIndex,
"removed": [],
"addedCount": addedCount,
"object": this.keyframes,
"type": 'splice'
}]);
if (this.autoplay) {
this.play();
}
},
detached: function () {
// The analog to `attached`, `detached` fires when the element has been
// removed from a document.
//
// Use this to clean up anything you did in `attached`.
this._attached = false;
},
// Element Behavior
/**
* Runs the animation from the current `_percent` position.
*/
play: function () {
console.log('play');
this.running = true;
if (!this.bounce && this._percent == this.outPoint) {
// start from beginning
this._runLoop(this.inPoint);
} else {
// resume
this._runLoop(this._percent);
}
},
/**
* Sets the running state to false but keeps position at least to last keyframe.
*/
pause: function () {
this.cancelAsync(this._handle);
this.running = false;
},
/**
* Pauses and then sets the animation back to beginning (`inPoint`)
*/
stop: function () {
console.log('stop');
this.pause();
this._percent = this.inPoint;
},
/**
* Sets animation `_percent` back to beginning (`inPoint`), does not affect `running` state
*/
first: function () {
this._percent = this.inPoint;
},
/**
* Sets the animation `_percent` to the end (`outPoint`), does not affect `running` state
*/
last: function () {
this._percent = this.outPoint;
},
/**
* Moves `_percent` position to the next keyframe
*/
skipForward: function () {},
/**
* Moves `_percent` position to the previous keyframe
*/
skipBack: function () {
},
/**
* Moves to a `_percent` position by keyframe name
* @return {Boolean} true if frame found, false if not.
*/
skipTo: function(keyFrameName) {
var newPos = this._getKeyFrameSelectorFromName(keyFrameName);
if (newPos != undefined) {
this._percent = newPos;
return true;
}
return false;
},
/**
* Sets an in or out point to the name of a keyframe
* @param {string} trimType - either 'in' or 'out'
* @param {string} keyFrameName - name of a keyframe.
* @return {Boolean} true if successful
*/
setTrim: function (trimType, keyFrameName) {
if (trimType != 'in' && trimType != 'out') {
if (console.error) {
console.error('Error: ascii-animation.setTrim() trimType \'' + trimType + '\' must be either \'in\' or \'out\'');
}
return false;
}
// todo: use _getKeyFrameSelectorFromName()
for (var k = 0; k < this.keyframes; k++) {
if (this.keyframes[k].name == keyFrameName) {
switch (trimType) {
case 'in':
this.inPoint = this.keyframes[k].selector;
break;
case 'out':
this.outPoint = this.keyframes[k].selector;
break;
}
return true;
}
}
return false;
},
_getKeyFrameSelectorFromName: function(keyFrameName) {
for (var k = 0; k < this.keyframes; k++) {
if (this.keyframes[k].name == keyFrameName) {
return this.keyframes[k].selector;
}
}
return undefined;
},
/**
* `_percent` observer, meaning the position in the animation changed so we need
* to update the frame (maybe)
*/
_percentChanged: function (newVal, oldVal) {
if (this._keyFramePositions != undefined && this._attached && newVal != undefined) {
var frameIndex = this._keyFramePositions.indexOf(newVal);
console.log("index of val " + this._keyFramePositions.indexOf(newVal));
if (frameIndex > -1) {
console.log('showing frame ' + frameIndex);
this._showFrame(frameIndex);
}
} else {
console.log(this._keyFramePositions);
}
},
/**
* Main loop that triggers the _percent value to move and then sets the next async call
* @return {boolean} true if running
*/
_runLoop: function () {
var newPercent = this._newPercent;
console.log('_runLoop at ' + newPercent + '%');
// don't run this code if element state is not running
if (!this.running) {
return false;
}
// make sure _percentChange observer runs to update the frame.
console.log('setting percent to ' + newPercent);
this.set('_percent', newPercent);
// after the frame update figure out the next frame and set the loop.
// first, we try the easy way, ++ or -- the keyframe position index
var currentIndex = this._keyFramePositions.indexOf(newPercent);
var endOfAnimation = false;
// we will change these values later on, just need something defined and not 0.
var nextPercent = -1;
var nextIndex = -1;
if (currentIndex >= 0) {
nextIndex = this.reverse ? currentIndex - 1 : currentIndex + 1;
// validate our assumption - we could be at the start or end of the array.
if (nextIndex >= 0 && nextIndex < this._keyFramePositions.length) {
// everything went as well as could be expected
nextPercent = this._keyFramePositions[nextIndex];
} else {
// next index will be out of bounds of the _keyFramePositions array so we must be done
endOfAnimation = true;
}
} else {
// this is where we hit some complexity to find the closest next index
// and also show the frame before so fine the last index but set the time differently
var lowestOffset = null;
var kfpLength = this._keyFramePositions.length; // just grab this once.
for (var k; k < kfpLength; k++) {
if (
((!this.reverse && this._keyFramePositions[k] > newPercent) ||
(this.reverse && this._keyFramePositions[k] < newPercent))
) {
var absOffset = Math.abs(newPercent - this._keyFramePositions[k]);
if (lowestOffset == null || absOffset < lowestOffset) {
lowestOffset = absOffset;
nextPercent = this._keyFramePositions[k];
nextIndex = k;
}
}
}
}
var scale = 100 // todo: use scale multiplier if we are going to allow more than 100 frames.
// this is the percent to multiply the total delay to arrive at the next frame on time.
// setting this now because we may override it if the animation loops
var delayPercent = Math.abs(nextPercent - newPercent);
// validate that the next percent is within our in and out points. We should have some sort of proposed value by now.
if (!(nextPercent >= this.inPoint && nextPercent <= this.outPoint)) {
endOfAnimation = true;
}
// handle end of animation
if (endOfAnimation) {
// so we can check for a flip on a bounce.
var newInpoint = this.inPoint;
var currentOutpoint = this.outPoint;
if (this.bounce) {
// if we are in bounce mode we'll flip the direction
// can't promise the change handler will do this yet so let's set the right inpoint.
newInpoint = this.outPoint;
this.set('reverse', !this.reverse);
}
// if we are not looping then we have to stop.
if (!this.loop) {
this.running = false;
} else {
// set up the next percent based on the loop.
nextPercent = newInpoint;
if (newPercent == currentOutpoint) {
// we are at the end and we need to loop right away
delayPercent = 0;
} else {
// we may be at 80%, out is at 100% and we're going to loop to 0. So we still need to wait.
delayPercent = Math.abs(currentOutpoint - newPercent);
}
}
}
this._newPercent = nextPercent;
// only if running still do we set up the next async call.
if (this.running) {
var delay = (this.duration * 1000) * (delayPercent / scale);
console.log('next step is ' + nextPercent + ' in ' + delay + 'ms');
this.set('_handle', this.async(this._runLoop, delay));
}
return this.running;
},
/**
* swaps `inPoint` and `outPoint` when the value of reverse is set.
* sanity checks direction in case it gets called at a weird time, like from
* undefined to true.
*/
_directionChanged: function (newVal, oldVal) {
if (newVal == undefined) { return; }
var oldIn = this.inPoint;
var oldOut = this.outPoint;
// sanity check before swapping
// if reversed then inpoint > outpoint or not reversed and inpoint < outpoint
if ((newVal && oldOut > oldIn) || (!newVal && oldOut < oldIn)) {
this.set('inPoint', oldOut);
this.set('outPoint', oldIn);
}
},
/**
* Updates `_renderedText` when keyframe array changes.
* Populates `_keyFramePositons`
* Then sets `_charCols` and `_charRows` and then ascii-view dimensions
*/
_keyFramesChanged: function (changeRecord) {
// abort for 0 keyframes.
if (this.keyframes == null || this.keyframes.length < 1 || !this._attached) {
return;
}
// for each keyframe:
var maxWidth = 0;
var maxLines = 0;
var keyFrames = this.keyframes;
this._keyFramePositions = [];
this._lastFramePercent = 0;
var frames = keyFrames.length;
// first loop gets dimensions of everything.
for (var k = 0; k < keyFrames.length; k++) {
// split each frame content into lines
if (keyFrames == undefined || keyFrames[k].selector == undefined || keyFrames[k].display == undefined) {
if (console.error) {
console.error('Error: render aborted due to invalid keyframe ' + k + ' ' + JSON.stringify(keyFrames[k]));
}
this._renderedText = '';
return;
}
var lines = keyFrames[k].display.split(/\n/);
// we populate `_keyFramePositions` from this loop.
this.push('_keyFramePositions', keyFrames[k].selector);
// grab the number of lines in the longest element.
if (maxLines < lines.length) {
maxLines = lines.length;
}
// grab the number of chars in the longest line.
for (var l = 0; l < lines.length; l++) {
// find maximum width
if (maxWidth < lines[l].length) {
maxWidth = lines[l].length;
}
}
}
// sort keyframe positions by number
this._keyFramePositions.sort(function(a, b) {
return a - b;
});
var frames = [];
// now that we have the max values we can loop again to set padding.
for (var k = 0; k < keyFrames.length; k++) {
var frame = [];
var lines = keyFrames[k].display.split(/\n/);
for (var l = 0; l < lines.length; l++) {
// add each line with padding to frame.
frame.push(this._rightPad(lines[l], ' ', maxWidth));
}
// pad with blank lines
var blankLinesNeeded = maxLines - frame.length;
for (var b = 0; b < blankLinesNeeded; b++) {
frame.push(this._rightPad('', ' ', maxWidth));
}
frames.push(frame);
}
var renderBuffer = '';
// now render the text into one continuous block by line with a fixed width.
for (var l = 0; l < lines.length; l++) {
for (var f = 0; f < frames.length; f++) {
renderBuffer += frames[f][l];
}
renderBuffer += "\n";
}
// update the element property only once with the complete render from the buffer.
this.set('_renderedText', renderBuffer);
this._charCols = maxWidth;
this._charRows = maxLines;
this.$['ascii-view'].style.width = this._charCols + 'ch';
this.$['ascii-view'].style.height;
this._charRows + 'ch';
},
_showFrame: function (frameIndex) {
console.log(this.$['ascii-content'].style.left);
this.$$('#ascii-content').style.left = "-" + this._charCols * frameIndex + "ch";
},
/**
* Utility function used for text rendering. Not a node package.
* shoutout to: https://eureka.ykyuen.info/2011/08/23/javascript-leftright-pad-a-string/
*/
_rightPad: function (s, c, n) {
if (!s || !c || s.length >= n) {
return s;
}
var max = (n - s.length) / c.length;
for (var i = 0; i < max; i++) {
s += c;
}
return s;
}
});
</script>
</dom-module>