code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }
Based on JSON2 (http://www.JSON.org/js.html).
quote
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value instanceof Date) { value = date(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } }
Based on JSON2 (http://www.JSON.org/js.html).
str
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); }
Based on JSON2 (http://www.JSON.org/js.html).
walk
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function Transport (socket, sessid) { this.socket = socket; this.sessid = sessid; }
This is the transport template for all supported transport methods. @constructor @api public
Transport
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function Socket (options) { this.options = { port: 80 , secure: false , document: 'document' in global ? document : false , resource: 'socket.io' , transports: io.transports , 'connect timeout': 10000 , 'try multiple transports': true , 'reconnect': true , 'reconnection delay': 500 , 'reconnection limit': Infinity , 'reopen delay': 3000 , 'max reconnection attempts': 10 , 'sync disconnect on unload': true , 'auto connect': true , 'flash policy port': 10843 }; io.util.merge(this.options, options); this.connected = false; this.open = false; this.connecting = false; this.reconnecting = false; this.namespaces = {}; this.buffer = []; this.doBuffer = false; if (this.options['sync disconnect on unload'] && (!this.isXDomain() || io.util.ua.hasCORS)) { var self = this; io.util.on(global, 'beforeunload', function () { self.disconnectSync(); }, false); } if (this.options['auto connect']) { this.connect(); } }
Create a new `Socket.IO client` which can establish a persistent connection with a Socket.IO enabled server. @api public
Socket
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function connect (transports){ if (self.transport) self.transport.clearTimeouts(); self.transport = self.getTransport(transports); if (!self.transport) return self.publish('connect_failed'); // once the transport is ready self.transport.ready(self, function () { self.connecting = true; self.publish('connecting', self.transport.name); self.transport.open(); if (self.options['connect timeout']) { self.connectTimeoutTimer = setTimeout(function () { if (!self.connected) { self.connecting = false; if (self.options['try multiple transports']) { if (!self.remainingTransports) { self.remainingTransports = self.transports.slice(0); } var remaining = self.remainingTransports; while (remaining.length > 0 && remaining.splice(0,1)[0] != self.transport.name) {} if (remaining.length){ connect(remaining); } else { self.publish('connect_failed'); } } } }, self.options['connect timeout']); } }); }
Connects to the server. @param {Function} [fn] Callback. @returns {io.Socket} @api public
connect
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function SocketNamespace (socket, name) { this.socket = socket; this.name = name || ''; this.flags = {}; this.json = new Flag(this, 'json'); this.ackPackets = 0; this.acks = {}; }
Socket namespace constructor. @constructor @api public
SocketNamespace
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function WS (socket) { io.Transport.apply(this, arguments); }
The WebSocket transport uses the HTML5 WebSocket API to establish an persistent connection with the Socket.IO server. This transport will also be inherited by the FlashSocket fallback as it provides a API compatible polyfill for the WebSockets. @constructor @extends {io.Transport} @api public
WS
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function stateChange () { if (this.readyState == 4) { this.onreadystatechange = empty; self.posting = false; if (this.status == 200){ self.socket.setBuffer(false); } else { self.onClose(); } } }
Posts a encoded message to the Socket.IO server. @param {String} data A encoded message. @api private
stateChange
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function onload () { this.onload = empty; self.socket.setBuffer(false); }
Posts a encoded message to the Socket.IO server. @param {String} data A encoded message. @api private
onload
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function HTMLFile (socket) { io.Transport.XHR.apply(this, arguments); }
The HTMLFile transport creates a `forever iframe` based transport for Internet Explorer. Regular forever iframe implementations will continuously trigger the browsers buzy indicators. If the forever iframe is created inside a `htmlfile` these indicators will not be trigged. @constructor @extends {io.Transport.XHR} @api public
HTMLFile
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function XHRPolling () { io.Transport.XHR.apply(this, arguments); }
The XHR-polling transport uses long polling XHR requests to create a "persistent" connection with the server. @constructor @api public
XHRPolling
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function stateChange () { if (this.readyState == 4) { this.onreadystatechange = empty; if (this.status == 200) { self.onData(this.responseText); self.get(); } else { self.onClose(); } } }
Starts a XHR request to wait for incoming messages. @api private
stateChange
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function onload () { this.onload = empty; self.onData(this.responseText); self.get(); }
Starts a XHR request to wait for incoming messages. @api private
onload
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function JSONPPolling (socket) { io.Transport['xhr-polling'].apply(this, arguments); this.index = io.j.length; var self = this; io.j.push(function (msg) { self._(msg); }); }
The JSONP transport creates an persistent connection by dynamically inserting a script tag in the page. This script tag will receive the information of the Socket.IO server. When new information is received it creates a new script tag for the new data stream. @constructor @extends {io.Transport.xhr-polling} @api public
JSONPPolling
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function complete () { initIframe(); self.socket.setBuffer(false); }
Posts a encoded message to the Socket.IO server using an iframe. The iframe is used because script tags can create POST based requests. The iframe is positioned outside of the view so the user does not notice it's existence. @param {String} data A encoded message. @api private
complete
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function initIframe () { if (self.iframe) { self.form.removeChild(self.iframe); } try { // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) iframe = document.createElement('<iframe name="'+ self.iframeId +'">'); } catch (e) { iframe = document.createElement('iframe'); iframe.name = self.iframeId; } iframe.id = self.iframeId; self.form.appendChild(iframe); self.iframe = iframe; }
Posts a encoded message to the Socket.IO server using an iframe. The iframe is used because script tags can create POST based requests. The iframe is positioned outside of the view so the user does not notice it's existence. @param {String} data A encoded message. @api private
initIframe
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
Juggernaut = function(options){ this.options = options || {}; this.options.host = this.options.host || window.location.hostname; this.options.port = this.options.port || 8080; this.handlers = {}; this.meta = this.options.meta; this.io = io.connect(this.options.host, this.options); this.io.on("connect", this.proxy(this.onconnect)); this.io.on("message", this.proxy(this.onmessage)); this.io.on("disconnect", this.proxy(this.ondisconnect)); this.on("connect", this.proxy(this.writeMeta)); }
Add the transport to your public io.transports array. @api private
Juggernaut
javascript
maccman/juggernaut
client.js
https://github.com/maccman/juggernaut/blob/master/client.js
MIT
function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; }
Based on JSON2 (http://www.JSON.org/js.html).
f
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function date(d, key) { return isFinite(d.valueOf()) ? d.getUTCFullYear() + '-' + f(d.getUTCMonth() + 1) + '-' + f(d.getUTCDate()) + 'T' + f(d.getUTCHours()) + ':' + f(d.getUTCMinutes()) + ':' + f(d.getUTCSeconds()) + 'Z' : null; }
Based on JSON2 (http://www.JSON.org/js.html).
date
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }
Based on JSON2 (http://www.JSON.org/js.html).
quote
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value instanceof Date) { value = date(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } }
Based on JSON2 (http://www.JSON.org/js.html).
str
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); }
Based on JSON2 (http://www.JSON.org/js.html).
walk
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function Transport (socket, sessid) { this.socket = socket; this.sessid = sessid; }
This is the transport template for all supported transport methods. @constructor @api public
Transport
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function Socket (options) { this.options = { port: 80 , secure: false , document: 'document' in global ? document : false , resource: 'socket.io' , transports: io.transports , 'connect timeout': 10000 , 'try multiple transports': true , 'reconnect': true , 'reconnection delay': 500 , 'reconnection limit': Infinity , 'reopen delay': 3000 , 'max reconnection attempts': 10 , 'sync disconnect on unload': true , 'auto connect': true , 'flash policy port': 10843 }; io.util.merge(this.options, options); this.connected = false; this.open = false; this.connecting = false; this.reconnecting = false; this.namespaces = {}; this.buffer = []; this.doBuffer = false; if (this.options['sync disconnect on unload'] && (!this.isXDomain() || io.util.ua.hasCORS)) { var self = this; io.util.on(global, 'beforeunload', function () { self.disconnectSync(); }, false); } if (this.options['auto connect']) { this.connect(); } }
Create a new `Socket.IO client` which can establish a persistent connection with a Socket.IO enabled server. @api public
Socket
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function connect (transports){ if (self.transport) self.transport.clearTimeouts(); self.transport = self.getTransport(transports); if (!self.transport) return self.publish('connect_failed'); // once the transport is ready self.transport.ready(self, function () { self.connecting = true; self.publish('connecting', self.transport.name); self.transport.open(); if (self.options['connect timeout']) { self.connectTimeoutTimer = setTimeout(function () { if (!self.connected) { self.connecting = false; if (self.options['try multiple transports']) { if (!self.remainingTransports) { self.remainingTransports = self.transports.slice(0); } var remaining = self.remainingTransports; while (remaining.length > 0 && remaining.splice(0,1)[0] != self.transport.name) {} if (remaining.length){ connect(remaining); } else { self.publish('connect_failed'); } } } }, self.options['connect timeout']); } }); }
Connects to the server. @param {Function} [fn] Callback. @returns {io.Socket} @api public
connect
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function SocketNamespace (socket, name) { this.socket = socket; this.name = name || ''; this.flags = {}; this.json = new Flag(this, 'json'); this.ackPackets = 0; this.acks = {}; }
Socket namespace constructor. @constructor @api public
SocketNamespace
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function WS (socket) { io.Transport.apply(this, arguments); }
The WebSocket transport uses the HTML5 WebSocket API to establish an persistent connection with the Socket.IO server. This transport will also be inherited by the FlashSocket fallback as it provides a API compatible polyfill for the WebSockets. @constructor @extends {io.Transport} @api public
WS
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function stateChange () { if (this.readyState == 4) { this.onreadystatechange = empty; self.posting = false; if (this.status == 200){ self.socket.setBuffer(false); } else { self.onClose(); } } }
Posts a encoded message to the Socket.IO server. @param {String} data A encoded message. @api private
stateChange
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function onload () { this.onload = empty; self.socket.setBuffer(false); }
Posts a encoded message to the Socket.IO server. @param {String} data A encoded message. @api private
onload
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function HTMLFile (socket) { io.Transport.XHR.apply(this, arguments); }
The HTMLFile transport creates a `forever iframe` based transport for Internet Explorer. Regular forever iframe implementations will continuously trigger the browsers buzy indicators. If the forever iframe is created inside a `htmlfile` these indicators will not be trigged. @constructor @extends {io.Transport.XHR} @api public
HTMLFile
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function XHRPolling () { io.Transport.XHR.apply(this, arguments); }
The XHR-polling transport uses long polling XHR requests to create a "persistent" connection with the server. @constructor @api public
XHRPolling
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function stateChange () { if (this.readyState == 4) { this.onreadystatechange = empty; if (this.status == 200) { self.onData(this.responseText); self.get(); } else { self.onClose(); } } }
Starts a XHR request to wait for incoming messages. @api private
stateChange
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function onload () { this.onload = empty; self.onData(this.responseText); self.get(); }
Starts a XHR request to wait for incoming messages. @api private
onload
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function JSONPPolling (socket) { io.Transport['xhr-polling'].apply(this, arguments); this.index = io.j.length; var self = this; io.j.push(function (msg) { self._(msg); }); }
The JSONP transport creates an persistent connection by dynamically inserting a script tag in the page. This script tag will receive the information of the Socket.IO server. When new information is received it creates a new script tag for the new data stream. @constructor @extends {io.Transport.xhr-polling} @api public
JSONPPolling
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function complete () { initIframe(); self.socket.setBuffer(false); }
Posts a encoded message to the Socket.IO server using an iframe. The iframe is used because script tags can create POST based requests. The iframe is positioned outside of the view so the user does not notice it's existence. @param {String} data A encoded message. @api private
complete
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function initIframe () { if (self.iframe) { self.form.removeChild(self.iframe); } try { // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) iframe = document.createElement('<iframe name="'+ self.iframeId +'">'); } catch (e) { iframe = document.createElement('iframe'); iframe.name = self.iframeId; } iframe.id = self.iframeId; self.form.appendChild(iframe); self.iframe = iframe; }
Posts a encoded message to the Socket.IO server using an iframe. The iframe is used because script tags can create POST based requests. The iframe is positioned outside of the view so the user does not notice it's existence. @param {String} data A encoded message. @api private
initIframe
javascript
maccman/juggernaut
client/vendor/assets/javascripts/socket_io.js
https://github.com/maccman/juggernaut/blob/master/client/vendor/assets/javascripts/socket_io.js
MIT
function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; }
Based on JSON2 (http://www.JSON.org/js.html).
f
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function date(d, key) { return isFinite(d.valueOf()) ? d.getUTCFullYear() + '-' + f(d.getUTCMonth() + 1) + '-' + f(d.getUTCDate()) + 'T' + f(d.getUTCHours()) + ':' + f(d.getUTCMinutes()) + ':' + f(d.getUTCSeconds()) + 'Z' : null; }
Based on JSON2 (http://www.JSON.org/js.html).
date
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }
Based on JSON2 (http://www.JSON.org/js.html).
quote
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value instanceof Date) { value = date(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } }
Based on JSON2 (http://www.JSON.org/js.html).
str
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); }
Based on JSON2 (http://www.JSON.org/js.html).
walk
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function Transport (socket, sessid) { this.socket = socket; this.sessid = sessid; }
This is the transport template for all supported transport methods. @constructor @api public
Transport
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function Socket (options) { this.options = { port: 80 , secure: false , document: 'document' in global ? document : false , resource: 'socket.io' , transports: io.transports , 'connect timeout': 10000 , 'try multiple transports': true , 'reconnect': true , 'reconnection delay': 500 , 'reconnection limit': Infinity , 'reopen delay': 3000 , 'max reconnection attempts': 10 , 'sync disconnect on unload': true , 'auto connect': true , 'flash policy port': 10843 }; io.util.merge(this.options, options); this.connected = false; this.open = false; this.connecting = false; this.reconnecting = false; this.namespaces = {}; this.buffer = []; this.doBuffer = false; if (this.options['sync disconnect on unload'] && (!this.isXDomain() || io.util.ua.hasCORS)) { var self = this; io.util.on(global, 'beforeunload', function () { self.disconnectSync(); }, false); } if (this.options['auto connect']) { this.connect(); } }
Create a new `Socket.IO client` which can establish a persistent connection with a Socket.IO enabled server. @api public
Socket
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function connect (transports){ if (self.transport) self.transport.clearTimeouts(); self.transport = self.getTransport(transports); if (!self.transport) return self.publish('connect_failed'); // once the transport is ready self.transport.ready(self, function () { self.connecting = true; self.publish('connecting', self.transport.name); self.transport.open(); if (self.options['connect timeout']) { self.connectTimeoutTimer = setTimeout(function () { if (!self.connected) { self.connecting = false; if (self.options['try multiple transports']) { if (!self.remainingTransports) { self.remainingTransports = self.transports.slice(0); } var remaining = self.remainingTransports; while (remaining.length > 0 && remaining.splice(0,1)[0] != self.transport.name) {} if (remaining.length){ connect(remaining); } else { self.publish('connect_failed'); } } } }, self.options['connect timeout']); } }); }
Connects to the server. @param {Function} [fn] Callback. @returns {io.Socket} @api public
connect
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function SocketNamespace (socket, name) { this.socket = socket; this.name = name || ''; this.flags = {}; this.json = new Flag(this, 'json'); this.ackPackets = 0; this.acks = {}; }
Socket namespace constructor. @constructor @api public
SocketNamespace
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function WS (socket) { io.Transport.apply(this, arguments); }
The WebSocket transport uses the HTML5 WebSocket API to establish an persistent connection with the Socket.IO server. This transport will also be inherited by the FlashSocket fallback as it provides a API compatible polyfill for the WebSockets. @constructor @extends {io.Transport} @api public
WS
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function stateChange () { if (this.readyState == 4) { this.onreadystatechange = empty; self.posting = false; if (this.status == 200){ self.socket.setBuffer(false); } else { self.onClose(); } } }
Posts a encoded message to the Socket.IO server. @param {String} data A encoded message. @api private
stateChange
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function onload () { this.onload = empty; self.socket.setBuffer(false); }
Posts a encoded message to the Socket.IO server. @param {String} data A encoded message. @api private
onload
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function HTMLFile (socket) { io.Transport.XHR.apply(this, arguments); }
The HTMLFile transport creates a `forever iframe` based transport for Internet Explorer. Regular forever iframe implementations will continuously trigger the browsers buzy indicators. If the forever iframe is created inside a `htmlfile` these indicators will not be trigged. @constructor @extends {io.Transport.XHR} @api public
HTMLFile
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function XHRPolling () { io.Transport.XHR.apply(this, arguments); }
The XHR-polling transport uses long polling XHR requests to create a "persistent" connection with the server. @constructor @api public
XHRPolling
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function stateChange () { if (this.readyState == 4) { this.onreadystatechange = empty; if (this.status == 200) { self.onData(this.responseText); self.get(); } else { self.onClose(); } } }
Starts a XHR request to wait for incoming messages. @api private
stateChange
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function onload () { this.onload = empty; self.onData(this.responseText); self.get(); }
Starts a XHR request to wait for incoming messages. @api private
onload
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function JSONPPolling (socket) { io.Transport['xhr-polling'].apply(this, arguments); this.index = io.j.length; var self = this; io.j.push(function (msg) { self._(msg); }); }
The JSONP transport creates an persistent connection by dynamically inserting a script tag in the page. This script tag will receive the information of the Socket.IO server. When new information is received it creates a new script tag for the new data stream. @constructor @extends {io.Transport.xhr-polling} @api public
JSONPPolling
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function complete () { initIframe(); self.socket.setBuffer(false); }
Posts a encoded message to the Socket.IO server using an iframe. The iframe is used because script tags can create POST based requests. The iframe is positioned outside of the view so the user does not notice it's existence. @param {String} data A encoded message. @api private
complete
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
function initIframe () { if (self.iframe) { self.form.removeChild(self.iframe); } try { // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) iframe = document.createElement('<iframe name="'+ self.iframeId +'">'); } catch (e) { iframe = document.createElement('iframe'); iframe.name = self.iframeId; } iframe.id = self.iframeId; self.form.appendChild(iframe); self.iframe = iframe; }
Posts a encoded message to the Socket.IO server using an iframe. The iframe is used because script tags can create POST based requests. The iframe is positioned outside of the view so the user does not notice it's existence. @param {String} data A encoded message. @api private
initIframe
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
Juggernaut = function(options){ this.options = options || {}; this.options.host = this.options.host || window.location.hostname; this.options.port = this.options.port || 8080; this.handlers = {}; this.meta = this.options.meta; this.io = io.connect(this.options.host, this.options); this.io.on("connect", this.proxy(this.onconnect)); this.io.on("message", this.proxy(this.onmessage)); this.io.on("disconnect", this.proxy(this.ondisconnect)); this.on("connect", this.proxy(this.writeMeta)); }
Add the transport to your public io.transports array. @api private
Juggernaut
javascript
maccman/juggernaut
public/application.js
https://github.com/maccman/juggernaut/blob/master/public/application.js
MIT
banner = (format, addTypes) => { const date = new Date(); return `/** * anime.js - ${ format } * @version v${ pkg.version } * @author Julian Garnier * @license MIT * @copyright (c) ${ date.getFullYear() } Julian Garnier * @see https://animejs.com */${addTypes ? jsDocTypes : ''} ` }
@param {String} format @param {Boolean} [addTypes] @return {String}
banner
javascript
juliangarnier/anime
rollup.config.js
https://github.com/juliangarnier/anime/blob/master/rollup.config.js
MIT
banner = (format, addTypes) => { const date = new Date(); return `/** * anime.js - ${ format } * @version v${ pkg.version } * @author Julian Garnier * @license MIT * @copyright (c) ${ date.getFullYear() } Julian Garnier * @see https://animejs.com */${addTypes ? jsDocTypes : ''} ` }
@param {String} format @param {Boolean} [addTypes] @return {String}
banner
javascript
juliangarnier/anime
rollup.config.js
https://github.com/juliangarnier/anime/blob/master/rollup.config.js
MIT
GUIBanner = (format, addTypes) => { const date = new Date(); return `/** * anime.js GUI - ${ format } * @version v${ pkg.version } * @author Julian Garnier * @license MIT * @copyright (c) ${ date.getFullYear() } Julian Garnier * @see https://animejs.com */${addTypes ? jsDocTypes : ''} ` }
@param {String} format @param {Boolean} [addTypes] @return {String}
GUIBanner
javascript
juliangarnier/anime
rollup.config.js
https://github.com/juliangarnier/anime/blob/master/rollup.config.js
MIT
GUIBanner = (format, addTypes) => { const date = new Date(); return `/** * anime.js GUI - ${ format } * @version v${ pkg.version } * @author Julian Garnier * @license MIT * @copyright (c) ${ date.getFullYear() } Julian Garnier * @see https://animejs.com */${addTypes ? jsDocTypes : ''} ` }
@param {String} format @param {Boolean} [addTypes] @return {String}
GUIBanner
javascript
juliangarnier/anime
rollup.config.js
https://github.com/juliangarnier/anime/blob/master/rollup.config.js
MIT
getTotalWidth = (total, $el) => { const style= getComputedStyle($el); const marginsWidth = parseInt(style.marginLeft) + parseInt(style.marginRight); return total + $el.offsetWidth + marginsWidth; }
@param {Number} total @param {HTMLElement} $el @return {Number}
getTotalWidth
javascript
juliangarnier/anime
examples/draggable-infinite-auto-carousel/index.js
https://github.com/juliangarnier/anime/blob/master/examples/draggable-infinite-auto-carousel/index.js
MIT
getTotalWidth = (total, $el) => { const style= getComputedStyle($el); const marginsWidth = parseInt(style.marginLeft) + parseInt(style.marginRight); return total + $el.offsetWidth + marginsWidth; }
@param {Number} total @param {HTMLElement} $el @return {Number}
getTotalWidth
javascript
juliangarnier/anime
examples/draggable-infinite-auto-carousel/index.js
https://github.com/juliangarnier/anime/blob/master/examples/draggable-infinite-auto-carousel/index.js
MIT
parseNumber = str => isStr(str) ? parseFloat(/** @type {String} */(str)) : /** @type {Number} */(str)
@param {Number|String} str @return {Number}
parseNumber
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
parseNumber = str => isStr(str) ? parseFloat(/** @type {String} */(str)) : /** @type {Number} */(str)
@param {Number|String} str @return {Number}
parseNumber
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
round = (v, decimalLength) => { if (decimalLength < 0) return v; if (!decimalLength) return _round(v); let p = powCache[decimalLength]; if (!p) p = powCache[decimalLength] = 10 ** decimalLength; return _round(v * p) / p; }
@param {Number} v @param {Number} decimalLength @return {Number}
round
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
round = (v, decimalLength) => { if (decimalLength < 0) return v; if (!decimalLength) return _round(v); let p = powCache[decimalLength]; if (!p) p = powCache[decimalLength] = 10 ** decimalLength; return _round(v * p) / p; }
@param {Number} v @param {Number} decimalLength @return {Number}
round
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => { let next = parent._head; let adjustedNextProp = nextProp; if (reverse) { next = parent._tail; adjustedNextProp = prevProp; } while (next) { const currentNext = next[adjustedNextProp]; callback(next); next = currentNext; } }
@param {Object} parent @param {Function} callback @param {Boolean} [reverse] @param {String} [prevProp] @param {String} [nextProp] @return {void}
forEachChildren
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
forEachChildren = (parent, callback, reverse, prevProp = '_prev', nextProp = '_next') => { let next = parent._head; let adjustedNextProp = nextProp; if (reverse) { next = parent._tail; adjustedNextProp = prevProp; } while (next) { const currentNext = next[adjustedNextProp]; callback(next); next = currentNext; } }
@param {Object} parent @param {Function} callback @param {Boolean} [reverse] @param {String} [prevProp] @param {String} [nextProp] @return {void}
forEachChildren
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => { const prev = child[prevProp]; const next = child[nextProp]; prev ? prev[nextProp] = next : parent._head = next; next ? next[prevProp] = prev : parent._tail = prev; child[prevProp] = null; child[nextProp] = null; }
@param {Object} parent @param {Object} child @param {String} [prevProp] @param {String} [nextProp] @return {void}
removeChild
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
removeChild = (parent, child, prevProp = '_prev', nextProp = '_next') => { const prev = child[prevProp]; const next = child[nextProp]; prev ? prev[nextProp] = next : parent._head = next; next ? next[prevProp] = prev : parent._tail = prev; child[prevProp] = null; child[nextProp] = null; }
@param {Object} parent @param {Object} child @param {String} [prevProp] @param {String} [nextProp] @return {void}
removeChild
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => { let prev = parent._tail; while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp]; const next = prev ? prev[nextProp] : parent._head; prev ? prev[nextProp] = child : parent._head = child; next ? next[prevProp] = child : parent._tail = child; child[prevProp] = prev; child[nextProp] = next; }
@param {Object} parent @param {Object} child @param {Function} [sortMethod] @param {String} prevProp @param {String} nextProp @return {void}
addChild
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
addChild = (parent, child, sortMethod, prevProp = '_prev', nextProp = '_next') => { let prev = parent._tail; while (prev && sortMethod && sortMethod(prev, child)) prev = prev[prevProp]; const next = prev ? prev[nextProp] : parent._head; prev ? prev[nextProp] = child : parent._head = child; next ? next[prevProp] = child : parent._tail = child; child[prevProp] = prev; child[nextProp] = next; }
@param {Object} parent @param {Object} child @param {Function} [sortMethod] @param {String} prevProp @param {String} nextProp @return {void}
addChild
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
render = (tickable, time, muteCallbacks, internalRender, tickMode) => { const parent = tickable.parent; const duration = tickable.duration; const completed = tickable.completed; const iterationDuration = tickable.iterationDuration; const iterationCount = tickable.iterationCount; const _currentIteration = tickable._currentIteration; const _loopDelay = tickable._loopDelay; const _reversed = tickable._reversed; const _alternate = tickable._alternate; const _hasChildren = tickable._hasChildren; const tickableDelay = tickable._delay; const tickablePrevAbsoluteTime = tickable._currentTime; // TODO: rename ._currentTime to ._absoluteCurrentTime const tickableEndTime = tickableDelay + iterationDuration; const tickableAbsoluteTime = time - tickableDelay; const tickablePrevTime = clamp(tickablePrevAbsoluteTime, -tickableDelay, duration); const tickableCurrentTime = clamp(tickableAbsoluteTime, -tickableDelay, duration); const deltaTime = tickableAbsoluteTime - tickablePrevAbsoluteTime; const isCurrentTimeAboveZero = tickableCurrentTime > 0; const isCurrentTimeEqualOrAboveDuration = tickableCurrentTime >= duration; const isSetter = duration <= minValue; const forcedTick = tickMode === tickModes.FORCE; let isOdd = 0; let iterationElapsedTime = tickableAbsoluteTime; // Render checks // Used to also check if the children have rendered in order to trigger the onRender callback on the parent timer let hasRendered = 0; // Execute the "expensive" iterations calculations only when necessary if (iterationCount > 1) { // bitwise NOT operator seems to be generally faster than Math.floor() across browsers const currentIteration = ~~(tickableCurrentTime / (iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay))); tickable._currentIteration = clamp(currentIteration, 0, iterationCount); // Prevent the iteration count to go above the max iterations when reaching the end of the animation if (isCurrentTimeEqualOrAboveDuration) tickable._currentIteration--; isOdd = tickable._currentIteration % 2; iterationElapsedTime = tickableCurrentTime % (iterationDuration + _loopDelay) || 0; } // Checks if exactly one of _reversed and (_alternate && isOdd) is true const isReversed = _reversed ^ (_alternate && isOdd); const _ease = /** @type {Renderable} */(tickable)._ease; let iterationTime = isCurrentTimeEqualOrAboveDuration ? isReversed ? 0 : duration : isReversed ? iterationDuration - iterationElapsedTime : iterationElapsedTime; if (_ease) iterationTime = iterationDuration * _ease(iterationTime / iterationDuration) || 0; const isRunningBackwards = (parent ? parent.backwards : tickableAbsoluteTime < tickablePrevAbsoluteTime) ? !isReversed : !!isReversed; tickable._currentTime = tickableAbsoluteTime; tickable._iterationTime = iterationTime; tickable.backwards = isRunningBackwards; if (isCurrentTimeAboveZero && !tickable.began) { tickable.began = true; if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) { tickable.onBegin(/** @type {CallbackArgument} */(tickable)); } } else if (tickableAbsoluteTime <= 0) { tickable.began = false; } // Only triggers onLoop for tickable without children, otherwise call the the onLoop callback in the tick function // Make sure to trigger the onLoop before rendering to allow .refresh() to pickup the current values if (!muteCallbacks && !_hasChildren && isCurrentTimeAboveZero && tickable._currentIteration !== _currentIteration) { tickable.onLoop(/** @type {CallbackArgument} */(tickable)); } if ( forcedTick || tickMode === tickModes.AUTO && ( time >= tickableDelay && time <= tickableEndTime || // Normal render time <= tickableDelay && tickablePrevTime > tickableDelay || // Playhead is before the animation start time so make sure the animation is at its initial state time >= tickableEndTime && tickablePrevTime !== duration // Playhead is after the animation end time so make sure the animation is at its end state ) || iterationTime >= tickableEndTime && tickablePrevTime !== duration || iterationTime <= tickableDelay && tickablePrevTime > 0 || time <= tickablePrevTime && tickablePrevTime === duration && completed || // Force a render if a seek occurs on an completed animation isCurrentTimeEqualOrAboveDuration && !completed && isSetter // This prevents 0 duration tickables to be skipped ) { if (isCurrentTimeAboveZero) { // Trigger onUpdate callback before rendering tickable.computeDeltaTime(tickablePrevTime); if (!muteCallbacks) tickable.onBeforeUpdate(/** @type {CallbackArgument} */(tickable)); } // Start tweens rendering if (!_hasChildren) { // Time has jumped more than globals.tickThreshold so consider this tick manual const forcedRender = forcedTick || (isRunningBackwards ? deltaTime * -1 : deltaTime) >= globals.tickThreshold; const absoluteTime = tickable._offset + (parent ? parent._offset : 0) + tickableDelay + iterationTime; // Only Animation can have tweens, Timer returns undefined let tween = /** @type {Tween} */(/** @type {JSAnimation} */(tickable)._head); let tweenTarget; let tweenStyle; let tweenTargetTransforms; let tweenTargetTransformsProperties; let tweenTransformsNeedUpdate = 0; while (tween) { const tweenComposition = tween._composition; const tweenCurrentTime = tween._currentTime; const tweenChangeDuration = tween._changeDuration; const tweenAbsEndTime = tween._absoluteStartTime + tween._changeDuration; const tweenNextRep = tween._nextRep; const tweenPrevRep = tween._prevRep; const tweenHasComposition = tweenComposition !== compositionTypes.none; if ((forcedRender || ( (tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenAbsEndTime + (tweenNextRep ? tweenNextRep._delay : 0)) && (tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime) )) && (!tweenHasComposition || ( !tween._isOverridden && (!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) && (!tweenNextRep || (tweenNextRep._isOverridden || absoluteTime <= tweenNextRep._absoluteStartTime)) && (!tweenPrevRep || (tweenPrevRep._isOverridden || (absoluteTime >= (tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration) + tween._delay))) )) ) { const tweenNewTime = tween._currentTime = clamp(iterationTime - tween._startTime, 0, tweenChangeDuration); const tweenProgress = tween._ease(tweenNewTime / tween._updateDuration); const tweenModifier = tween._modifier; const tweenValueType = tween._valueType; const tweenType = tween._tweenType; const tweenIsObject = tweenType === tweenTypes.OBJECT; const tweenIsNumber = tweenValueType === valueTypes.NUMBER; // Only round the in-between frames values if the final value is a string const tweenPrecision = (tweenIsNumber && tweenIsObject) || tweenProgress === 0 || tweenProgress === 1 ? -1 : globals.precision; // Recompose tween value /** @type {String|Number} */ let value; /** @type {Number} */ let number; if (tweenIsNumber) { value = number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision ))); } else if (tweenValueType === valueTypes.UNIT) { // Rounding the values speed up string composition number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision))); value = `${number}${tween._unit}`; } else if (tweenValueType === valueTypes.COLOR) { const fn = tween._fromNumbers; const tn = tween._toNumbers; const r = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[0], tn[0], tweenProgress))), 0, 255), 0); const g = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[1], tn[1], tweenProgress))), 0, 255), 0); const b = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[2], tn[2], tweenProgress))), 0, 255), 0); const a = clamp(/** @type {Number} */(tweenModifier(round(interpolate(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1); value = `rgba(${r},${g},${b},${a})`; if (tweenHasComposition) { const ns = tween._numbers; ns[0] = r; ns[1] = g; ns[2] = b; ns[3] = a; } } else if (tweenValueType === valueTypes.COMPLEX) { value = tween._strings[0]; for (let j = 0, l = tween._toNumbers.length; j < l; j++) { const n = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision))); const s = tween._strings[j + 1]; value += `${s ? n + s : n}`; if (tweenHasComposition) { tween._numbers[j] = n; } } } // For additive tweens and Animatables if (tweenHasComposition) { tween._number = number; } if (!internalRender && tweenComposition !== compositionTypes.blend) { const tweenProperty = tween.property; tweenTarget = tween.target; if (tweenIsObject) { tweenTarget[tweenProperty] = value; } else if (tweenType === tweenTypes.ATTRIBUTE) { /** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(value)); } else { tweenStyle = /** @type {DOMTarget} */(tweenTarget).style; if (tweenType === tweenTypes.TRANSFORM) { if (tweenTarget !== tweenTargetTransforms) { tweenTargetTransforms = tweenTarget; // NOTE: Referencing the cachedTransforms in the tween property directly can be a little bit faster but appears to increase memory usage. tweenTargetTransformsProperties = tweenTarget[transformsSymbol]; } tweenTargetTransformsProperties[tweenProperty] = value; tweenTransformsNeedUpdate = 1; } else if (tweenType === tweenTypes.CSS) { tweenStyle[tweenProperty] = value; } else if (tweenType === tweenTypes.CSS_VAR) { tweenStyle.setProperty(tweenProperty,/** @type {String} */(value)); } } if (isCurrentTimeAboveZero) hasRendered = 1; } else { // Used for composing timeline tweens without having to do a real render tween._value = value; } } // NOTE: Possible improvement: Use translate(x,y) / translate3d(x,y,z) syntax // to reduce memory usage on string composition if (tweenTransformsNeedUpdate && tween._renderTransforms) { let str = emptyString; for (let key in tweenTargetTransformsProperties) { str += `${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `; } tweenStyle.transform = str; tweenTransformsNeedUpdate = 0; } tween = tween._next; } if (!muteCallbacks && hasRendered) { /** @type {JSAnimation} */(tickable).onRender(/** @type {JSAnimation} */(tickable)); } } if (!muteCallbacks && isCurrentTimeAboveZero) { tickable.onUpdate(/** @type {CallbackArgument} */(tickable)); } } // End tweens rendering // Handle setters on timeline differently and allow re-trigering the onComplete callback when seeking backwards if (parent && isSetter) { if (!muteCallbacks && ( (parent.began && !isRunningBackwards && tickableAbsoluteTime >= duration && !completed) || (isRunningBackwards && tickableAbsoluteTime <= minValue && completed) )) { tickable.onComplete(/** @type {CallbackArgument} */(tickable)); tickable.completed = !isRunningBackwards; } // If currentTime is both above 0 and at least equals to duration, handles normal onComplete or infinite loops } else if (isCurrentTimeAboveZero && isCurrentTimeEqualOrAboveDuration) { if (iterationCount === Infinity) { // Offset the tickable _startTime with its duration to reset _currentTime to 0 and continue the infinite timer tickable._startTime += tickable.duration; } else if (tickable._currentIteration >= iterationCount - 1) { // By setting paused to true, we tell the engine loop to not render this tickable and removes it from the list on the next tick tickable.paused = true; if (!completed && !_hasChildren) { // If the tickable has children, triggers onComplete() only when all children have completed in the tick function tickable.completed = true; if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) { tickable.onComplete(/** @type {CallbackArgument} */(tickable)); tickable._resolve(/** @type {CallbackArgument} */(tickable)); } } } // Otherwise set the completed flag to false } else { tickable.completed = false; } // NOTE: hasRendered * direction (negative for backwards) this way we can remove the tickable.backwards property completly ? return hasRendered; }
@param {Tickable} tickable @param {Number} time @param {Number} muteCallbacks @param {Number} internalRender @param {tickModes} tickMode @return {Number}
render
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
render = (tickable, time, muteCallbacks, internalRender, tickMode) => { const parent = tickable.parent; const duration = tickable.duration; const completed = tickable.completed; const iterationDuration = tickable.iterationDuration; const iterationCount = tickable.iterationCount; const _currentIteration = tickable._currentIteration; const _loopDelay = tickable._loopDelay; const _reversed = tickable._reversed; const _alternate = tickable._alternate; const _hasChildren = tickable._hasChildren; const tickableDelay = tickable._delay; const tickablePrevAbsoluteTime = tickable._currentTime; // TODO: rename ._currentTime to ._absoluteCurrentTime const tickableEndTime = tickableDelay + iterationDuration; const tickableAbsoluteTime = time - tickableDelay; const tickablePrevTime = clamp(tickablePrevAbsoluteTime, -tickableDelay, duration); const tickableCurrentTime = clamp(tickableAbsoluteTime, -tickableDelay, duration); const deltaTime = tickableAbsoluteTime - tickablePrevAbsoluteTime; const isCurrentTimeAboveZero = tickableCurrentTime > 0; const isCurrentTimeEqualOrAboveDuration = tickableCurrentTime >= duration; const isSetter = duration <= minValue; const forcedTick = tickMode === tickModes.FORCE; let isOdd = 0; let iterationElapsedTime = tickableAbsoluteTime; // Render checks // Used to also check if the children have rendered in order to trigger the onRender callback on the parent timer let hasRendered = 0; // Execute the "expensive" iterations calculations only when necessary if (iterationCount > 1) { // bitwise NOT operator seems to be generally faster than Math.floor() across browsers const currentIteration = ~~(tickableCurrentTime / (iterationDuration + (isCurrentTimeEqualOrAboveDuration ? 0 : _loopDelay))); tickable._currentIteration = clamp(currentIteration, 0, iterationCount); // Prevent the iteration count to go above the max iterations when reaching the end of the animation if (isCurrentTimeEqualOrAboveDuration) tickable._currentIteration--; isOdd = tickable._currentIteration % 2; iterationElapsedTime = tickableCurrentTime % (iterationDuration + _loopDelay) || 0; } // Checks if exactly one of _reversed and (_alternate && isOdd) is true const isReversed = _reversed ^ (_alternate && isOdd); const _ease = /** @type {Renderable} */(tickable)._ease; let iterationTime = isCurrentTimeEqualOrAboveDuration ? isReversed ? 0 : duration : isReversed ? iterationDuration - iterationElapsedTime : iterationElapsedTime; if (_ease) iterationTime = iterationDuration * _ease(iterationTime / iterationDuration) || 0; const isRunningBackwards = (parent ? parent.backwards : tickableAbsoluteTime < tickablePrevAbsoluteTime) ? !isReversed : !!isReversed; tickable._currentTime = tickableAbsoluteTime; tickable._iterationTime = iterationTime; tickable.backwards = isRunningBackwards; if (isCurrentTimeAboveZero && !tickable.began) { tickable.began = true; if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) { tickable.onBegin(/** @type {CallbackArgument} */(tickable)); } } else if (tickableAbsoluteTime <= 0) { tickable.began = false; } // Only triggers onLoop for tickable without children, otherwise call the the onLoop callback in the tick function // Make sure to trigger the onLoop before rendering to allow .refresh() to pickup the current values if (!muteCallbacks && !_hasChildren && isCurrentTimeAboveZero && tickable._currentIteration !== _currentIteration) { tickable.onLoop(/** @type {CallbackArgument} */(tickable)); } if ( forcedTick || tickMode === tickModes.AUTO && ( time >= tickableDelay && time <= tickableEndTime || // Normal render time <= tickableDelay && tickablePrevTime > tickableDelay || // Playhead is before the animation start time so make sure the animation is at its initial state time >= tickableEndTime && tickablePrevTime !== duration // Playhead is after the animation end time so make sure the animation is at its end state ) || iterationTime >= tickableEndTime && tickablePrevTime !== duration || iterationTime <= tickableDelay && tickablePrevTime > 0 || time <= tickablePrevTime && tickablePrevTime === duration && completed || // Force a render if a seek occurs on an completed animation isCurrentTimeEqualOrAboveDuration && !completed && isSetter // This prevents 0 duration tickables to be skipped ) { if (isCurrentTimeAboveZero) { // Trigger onUpdate callback before rendering tickable.computeDeltaTime(tickablePrevTime); if (!muteCallbacks) tickable.onBeforeUpdate(/** @type {CallbackArgument} */(tickable)); } // Start tweens rendering if (!_hasChildren) { // Time has jumped more than globals.tickThreshold so consider this tick manual const forcedRender = forcedTick || (isRunningBackwards ? deltaTime * -1 : deltaTime) >= globals.tickThreshold; const absoluteTime = tickable._offset + (parent ? parent._offset : 0) + tickableDelay + iterationTime; // Only Animation can have tweens, Timer returns undefined let tween = /** @type {Tween} */(/** @type {JSAnimation} */(tickable)._head); let tweenTarget; let tweenStyle; let tweenTargetTransforms; let tweenTargetTransformsProperties; let tweenTransformsNeedUpdate = 0; while (tween) { const tweenComposition = tween._composition; const tweenCurrentTime = tween._currentTime; const tweenChangeDuration = tween._changeDuration; const tweenAbsEndTime = tween._absoluteStartTime + tween._changeDuration; const tweenNextRep = tween._nextRep; const tweenPrevRep = tween._prevRep; const tweenHasComposition = tweenComposition !== compositionTypes.none; if ((forcedRender || ( (tweenCurrentTime !== tweenChangeDuration || absoluteTime <= tweenAbsEndTime + (tweenNextRep ? tweenNextRep._delay : 0)) && (tweenCurrentTime !== 0 || absoluteTime >= tween._absoluteStartTime) )) && (!tweenHasComposition || ( !tween._isOverridden && (!tween._isOverlapped || absoluteTime <= tweenAbsEndTime) && (!tweenNextRep || (tweenNextRep._isOverridden || absoluteTime <= tweenNextRep._absoluteStartTime)) && (!tweenPrevRep || (tweenPrevRep._isOverridden || (absoluteTime >= (tweenPrevRep._absoluteStartTime + tweenPrevRep._changeDuration) + tween._delay))) )) ) { const tweenNewTime = tween._currentTime = clamp(iterationTime - tween._startTime, 0, tweenChangeDuration); const tweenProgress = tween._ease(tweenNewTime / tween._updateDuration); const tweenModifier = tween._modifier; const tweenValueType = tween._valueType; const tweenType = tween._tweenType; const tweenIsObject = tweenType === tweenTypes.OBJECT; const tweenIsNumber = tweenValueType === valueTypes.NUMBER; // Only round the in-between frames values if the final value is a string const tweenPrecision = (tweenIsNumber && tweenIsObject) || tweenProgress === 0 || tweenProgress === 1 ? -1 : globals.precision; // Recompose tween value /** @type {String|Number} */ let value; /** @type {Number} */ let number; if (tweenIsNumber) { value = number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision ))); } else if (tweenValueType === valueTypes.UNIT) { // Rounding the values speed up string composition number = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumber, tween._toNumber, tweenProgress), tweenPrecision))); value = `${number}${tween._unit}`; } else if (tweenValueType === valueTypes.COLOR) { const fn = tween._fromNumbers; const tn = tween._toNumbers; const r = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[0], tn[0], tweenProgress))), 0, 255), 0); const g = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[1], tn[1], tweenProgress))), 0, 255), 0); const b = round(clamp(/** @type {Number} */(tweenModifier(interpolate(fn[2], tn[2], tweenProgress))), 0, 255), 0); const a = clamp(/** @type {Number} */(tweenModifier(round(interpolate(fn[3], tn[3], tweenProgress), tweenPrecision))), 0, 1); value = `rgba(${r},${g},${b},${a})`; if (tweenHasComposition) { const ns = tween._numbers; ns[0] = r; ns[1] = g; ns[2] = b; ns[3] = a; } } else if (tweenValueType === valueTypes.COMPLEX) { value = tween._strings[0]; for (let j = 0, l = tween._toNumbers.length; j < l; j++) { const n = /** @type {Number} */(tweenModifier(round(interpolate(tween._fromNumbers[j], tween._toNumbers[j], tweenProgress), tweenPrecision))); const s = tween._strings[j + 1]; value += `${s ? n + s : n}`; if (tweenHasComposition) { tween._numbers[j] = n; } } } // For additive tweens and Animatables if (tweenHasComposition) { tween._number = number; } if (!internalRender && tweenComposition !== compositionTypes.blend) { const tweenProperty = tween.property; tweenTarget = tween.target; if (tweenIsObject) { tweenTarget[tweenProperty] = value; } else if (tweenType === tweenTypes.ATTRIBUTE) { /** @type {DOMTarget} */(tweenTarget).setAttribute(tweenProperty, /** @type {String} */(value)); } else { tweenStyle = /** @type {DOMTarget} */(tweenTarget).style; if (tweenType === tweenTypes.TRANSFORM) { if (tweenTarget !== tweenTargetTransforms) { tweenTargetTransforms = tweenTarget; // NOTE: Referencing the cachedTransforms in the tween property directly can be a little bit faster but appears to increase memory usage. tweenTargetTransformsProperties = tweenTarget[transformsSymbol]; } tweenTargetTransformsProperties[tweenProperty] = value; tweenTransformsNeedUpdate = 1; } else if (tweenType === tweenTypes.CSS) { tweenStyle[tweenProperty] = value; } else if (tweenType === tweenTypes.CSS_VAR) { tweenStyle.setProperty(tweenProperty,/** @type {String} */(value)); } } if (isCurrentTimeAboveZero) hasRendered = 1; } else { // Used for composing timeline tweens without having to do a real render tween._value = value; } } // NOTE: Possible improvement: Use translate(x,y) / translate3d(x,y,z) syntax // to reduce memory usage on string composition if (tweenTransformsNeedUpdate && tween._renderTransforms) { let str = emptyString; for (let key in tweenTargetTransformsProperties) { str += `${transformsFragmentStrings[key]}${tweenTargetTransformsProperties[key]}) `; } tweenStyle.transform = str; tweenTransformsNeedUpdate = 0; } tween = tween._next; } if (!muteCallbacks && hasRendered) { /** @type {JSAnimation} */(tickable).onRender(/** @type {JSAnimation} */(tickable)); } } if (!muteCallbacks && isCurrentTimeAboveZero) { tickable.onUpdate(/** @type {CallbackArgument} */(tickable)); } } // End tweens rendering // Handle setters on timeline differently and allow re-trigering the onComplete callback when seeking backwards if (parent && isSetter) { if (!muteCallbacks && ( (parent.began && !isRunningBackwards && tickableAbsoluteTime >= duration && !completed) || (isRunningBackwards && tickableAbsoluteTime <= minValue && completed) )) { tickable.onComplete(/** @type {CallbackArgument} */(tickable)); tickable.completed = !isRunningBackwards; } // If currentTime is both above 0 and at least equals to duration, handles normal onComplete or infinite loops } else if (isCurrentTimeAboveZero && isCurrentTimeEqualOrAboveDuration) { if (iterationCount === Infinity) { // Offset the tickable _startTime with its duration to reset _currentTime to 0 and continue the infinite timer tickable._startTime += tickable.duration; } else if (tickable._currentIteration >= iterationCount - 1) { // By setting paused to true, we tell the engine loop to not render this tickable and removes it from the list on the next tick tickable.paused = true; if (!completed && !_hasChildren) { // If the tickable has children, triggers onComplete() only when all children have completed in the tick function tickable.completed = true; if (!muteCallbacks && !(parent && (isRunningBackwards || !parent.began))) { tickable.onComplete(/** @type {CallbackArgument} */(tickable)); tickable._resolve(/** @type {CallbackArgument} */(tickable)); } } } // Otherwise set the completed flag to false } else { tickable.completed = false; } // NOTE: hasRendered * direction (negative for backwards) this way we can remove the tickable.backwards property completly ? return hasRendered; }
@param {Tickable} tickable @param {Number} time @param {Number} muteCallbacks @param {Number} internalRender @param {tickModes} tickMode @return {Number}
render
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
tick = (tickable, time, muteCallbacks, internalRender, tickMode) => { const _currentIteration = tickable._currentIteration; render(tickable, time, muteCallbacks, internalRender, tickMode); if (tickable._hasChildren) { const tl = /** @type {Timeline} */(tickable); const tlIsRunningBackwards = tl.backwards; const tlChildrenTime = internalRender ? time : tl._iterationTime; const tlCildrenTickTime = now(); let tlChildrenHasRendered = 0; let tlChildrenHaveCompleted = true; // If the timeline has looped forward, we need to manually triggers children skipped callbacks if (!internalRender && tl._currentIteration !== _currentIteration) { const tlIterationDuration = tl.iterationDuration; forEachChildren(tl, (/** @type {JSAnimation} */child) => { if (!tlIsRunningBackwards) { // Force an internal render to trigger the callbacks if the child has not completed on loop if (!child.completed && !child.backwards && child._currentTime < child.iterationDuration) { render(child, tlIterationDuration, muteCallbacks, 1, tickModes.FORCE); } // Reset their began and completed flags to allow retrigering callbacks on the next iteration child.began = false; child.completed = false; } else { const childDuration = child.duration; const childStartTime = child._offset + child._delay; const childEndTime = childStartTime + childDuration; // Triggers the onComplete callback on reverse for children on the edges of the timeline if (!muteCallbacks && childDuration <= minValue && (!childStartTime || childEndTime === tlIterationDuration)) { child.onComplete(child); } } }); if (!muteCallbacks) tl.onLoop(/** @type {CallbackArgument} */(tl)); } forEachChildren(tl, (/** @type {JSAnimation} */child) => { const childTime = round((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds const childTickMode = child._fps < tl._fps ? child.requestTick(tlCildrenTickTime) : tickMode; tlChildrenHasRendered += render(child, childTime, muteCallbacks, internalRender, childTickMode); if (!child.completed && tlChildrenHaveCompleted) tlChildrenHaveCompleted = false; }, tlIsRunningBackwards); // Renders on timeline are triggered by its children so it needs to be set after rendering the children if (!muteCallbacks && tlChildrenHasRendered) tl.onRender(/** @type {CallbackArgument} */(tl)); // Triggers the timeline onComplete() once all chindren all completed and the current time has reached the end if (tlChildrenHaveCompleted && tl._currentTime >= tl.duration) { // Make sure the paused flag is false in case it has been skipped in the render function tl.paused = true; if (!tl.completed) { tl.completed = true; if (!muteCallbacks) { tl.onComplete(/** @type {CallbackArgument} */(tl)); tl._resolve(/** @type {CallbackArgument} */(tl)); } } } } }
@param {Tickable} tickable @param {Number} time @param {Number} muteCallbacks @param {Number} internalRender @param {Number} tickMode @return {void}
tick
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
tick = (tickable, time, muteCallbacks, internalRender, tickMode) => { const _currentIteration = tickable._currentIteration; render(tickable, time, muteCallbacks, internalRender, tickMode); if (tickable._hasChildren) { const tl = /** @type {Timeline} */(tickable); const tlIsRunningBackwards = tl.backwards; const tlChildrenTime = internalRender ? time : tl._iterationTime; const tlCildrenTickTime = now(); let tlChildrenHasRendered = 0; let tlChildrenHaveCompleted = true; // If the timeline has looped forward, we need to manually triggers children skipped callbacks if (!internalRender && tl._currentIteration !== _currentIteration) { const tlIterationDuration = tl.iterationDuration; forEachChildren(tl, (/** @type {JSAnimation} */child) => { if (!tlIsRunningBackwards) { // Force an internal render to trigger the callbacks if the child has not completed on loop if (!child.completed && !child.backwards && child._currentTime < child.iterationDuration) { render(child, tlIterationDuration, muteCallbacks, 1, tickModes.FORCE); } // Reset their began and completed flags to allow retrigering callbacks on the next iteration child.began = false; child.completed = false; } else { const childDuration = child.duration; const childStartTime = child._offset + child._delay; const childEndTime = childStartTime + childDuration; // Triggers the onComplete callback on reverse for children on the edges of the timeline if (!muteCallbacks && childDuration <= minValue && (!childStartTime || childEndTime === tlIterationDuration)) { child.onComplete(child); } } }); if (!muteCallbacks) tl.onLoop(/** @type {CallbackArgument} */(tl)); } forEachChildren(tl, (/** @type {JSAnimation} */child) => { const childTime = round((tlChildrenTime - child._offset) * child._speed, 12); // Rounding is needed when using seconds const childTickMode = child._fps < tl._fps ? child.requestTick(tlCildrenTickTime) : tickMode; tlChildrenHasRendered += render(child, childTime, muteCallbacks, internalRender, childTickMode); if (!child.completed && tlChildrenHaveCompleted) tlChildrenHaveCompleted = false; }, tlIsRunningBackwards); // Renders on timeline are triggered by its children so it needs to be set after rendering the children if (!muteCallbacks && tlChildrenHasRendered) tl.onRender(/** @type {CallbackArgument} */(tl)); // Triggers the timeline onComplete() once all chindren all completed and the current time has reached the end if (tlChildrenHaveCompleted && tl._currentTime >= tl.duration) { // Make sure the paused flag is false in case it has been skipped in the render function tl.paused = true; if (!tl.completed) { tl.completed = true; if (!muteCallbacks) { tl.onComplete(/** @type {CallbackArgument} */(tl)); tl._resolve(/** @type {CallbackArgument} */(tl)); } } } } }
@param {Tickable} tickable @param {Number} time @param {Number} muteCallbacks @param {Number} internalRender @param {Number} tickMode @return {void}
tick
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
parseInlineTransforms = (target, propName, animationInlineStyles) => { const inlineTransforms = target.style.transform; let inlinedStylesPropertyValue; if (inlineTransforms) { const cachedTransforms = target[transformsSymbol]; let t; while (t = transformsExecRgx.exec(inlineTransforms)) { const inlinePropertyName = t[1]; // const inlinePropertyValue = t[2]; const inlinePropertyValue = t[2].slice(1, -1); cachedTransforms[inlinePropertyName] = inlinePropertyValue; if (inlinePropertyName === propName) { inlinedStylesPropertyValue = inlinePropertyValue; // Store the new parsed inline styles if animationInlineStyles is provided if (animationInlineStyles) { animationInlineStyles[propName] = inlinePropertyValue; } } } } return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue : stringStartsWith(propName, 'scale') ? '1' : stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px'; }
@param {DOMTarget} target @param {String} propName @param {Object} animationInlineStyles @return {String}
parseInlineTransforms
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
parseInlineTransforms = (target, propName, animationInlineStyles) => { const inlineTransforms = target.style.transform; let inlinedStylesPropertyValue; if (inlineTransforms) { const cachedTransforms = target[transformsSymbol]; let t; while (t = transformsExecRgx.exec(inlineTransforms)) { const inlinePropertyName = t[1]; // const inlinePropertyValue = t[2]; const inlinePropertyValue = t[2].slice(1, -1); cachedTransforms[inlinePropertyName] = inlinePropertyValue; if (inlinePropertyName === propName) { inlinedStylesPropertyValue = inlinePropertyValue; // Store the new parsed inline styles if animationInlineStyles is provided if (animationInlineStyles) { animationInlineStyles[propName] = inlinePropertyValue; } } } } return inlineTransforms && !isUnd(inlinedStylesPropertyValue) ? inlinedStylesPropertyValue : stringStartsWith(propName, 'scale') ? '1' : stringStartsWith(propName, 'rotate') || stringStartsWith(propName, 'skew') ? '0deg' : '0px'; }
@param {DOMTarget} target @param {String} propName @param {Object} animationInlineStyles @return {String}
parseInlineTransforms
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
function getNodeList(v) { const n = isStr(v) ? globals.root.querySelectorAll(v) : v; if (n instanceof NodeList || n instanceof HTMLCollection) return n; }
@param {DOMTargetsParam|TargetsParam} v @return {NodeList|HTMLCollection}
getNodeList
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
function parseTargets(targets) { if (isNil(targets)) return /** @type {TargetsArray} */([]); if (isArr(targets)) { const flattened = targets.flat(Infinity); /** @type {TargetsArray} */ const parsed = []; for (let i = 0, l = flattened.length; i < l; i++) { const item = flattened[i]; if (!isNil(item)) { const nodeList = getNodeList(item); if (nodeList) { for (let j = 0, jl = nodeList.length; j < jl; j++) { const subItem = nodeList[j]; if (!isNil(subItem)) { let isDuplicate = false; for (let k = 0, kl = parsed.length; k < kl; k++) { if (parsed[k] === subItem) { isDuplicate = true; break; } } if (!isDuplicate) { parsed.push(subItem); } } } } else { let isDuplicate = false; for (let j = 0, jl = parsed.length; j < jl; j++) { if (parsed[j] === item) { isDuplicate = true; break; } } if (!isDuplicate) { parsed.push(item); } } } } return parsed; } if (!isBrowser) return /** @type {JSTargetsArray} */([targets]); const nodeList = getNodeList(targets); if (nodeList) return /** @type {DOMTargetsArray} */(Array.from(nodeList)); return /** @type {TargetsArray} */([targets]); }
@overload @param {DOMTargetsParam} targets @return {DOMTargetsArray} @overload @param {JSTargetsParam} targets @return {JSTargetsArray} @overload @param {TargetsParam} targets @return {TargetsArray} @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
parseTargets
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
function registerTargets(targets) { const parsedTargetsArray = parseTargets(targets); const parsedTargetsLength = parsedTargetsArray.length; if (parsedTargetsLength) { for (let i = 0; i < parsedTargetsLength; i++) { const target = parsedTargetsArray[i]; if (!target[isRegisteredTargetSymbol]) { target[isRegisteredTargetSymbol] = true; const isSvgType = isSvg(target); const isDom = /** @type {DOMTarget} */(target).nodeType || isSvgType; if (isDom) { target[isDomSymbol] = true; target[isSvgSymbol] = isSvgType; target[transformsSymbol] = {}; } } } } return parsedTargetsArray; }
@overload @param {DOMTargetsParam} targets @return {DOMTargetsArray} @overload @param {JSTargetsParam} targets @return {JSTargetsArray} @overload @param {TargetsParam} targets @return {TargetsArray} @param {DOMTargetsParam|JSTargetsParam|TargetsParam} targets
registerTargets
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
getPath = path => { const parsedTargets = parseTargets(path); const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]); if (!$parsedSvg || !isSvg($parsedSvg)) return; return $parsedSvg; }
@param {TargetsParam} path @return {SVGGeometryElement|undefined}
getPath
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
getPath = path => { const parsedTargets = parseTargets(path); const $parsedSvg = /** @type {SVGGeometryElement} */(parsedTargets[0]); if (!$parsedSvg || !isSvg($parsedSvg)) return; return $parsedSvg; }
@param {TargetsParam} path @return {SVGGeometryElement|undefined}
getPath
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
morphTo = (path2, precision = .33) => ($path1) => { const $path2 = /** @type {SVGGeometryElement} */(getPath(path2)); if (!$path2) return; const isPath = $path1.tagName === 'path'; const separator = isPath ? ' ' : ','; const previousPoints = $path1[morphPointsSymbol]; if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints); let v1 = '', v2 = ''; if (!precision) { v1 = $path1.getAttribute(isPath ? 'd' : 'points'); v2 = $path2.getAttribute(isPath ? 'd' : 'points'); } else { const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength(); const length2 = $path2.getTotalLength(); const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision)); for (let i = 0; i < maxPoints; i++) { const t = i / (maxPoints - 1); const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t); const pointOnPath2 = $path2.getPointAtLength(length2 * t); const prefix = isPath ? (i === 0 ? 'M' : 'L') : ''; v1 += prefix + round(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' '; v2 += prefix + round(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' '; } } $path1[morphPointsSymbol] = v2; return [v1, v2]; }
@param {TargetsParam} path2 @param {Number} [precision] @return {FunctionValue}
morphTo
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
morphTo = (path2, precision = .33) => ($path1) => { const $path2 = /** @type {SVGGeometryElement} */(getPath(path2)); if (!$path2) return; const isPath = $path1.tagName === 'path'; const separator = isPath ? ' ' : ','; const previousPoints = $path1[morphPointsSymbol]; if (previousPoints) $path1.setAttribute(isPath ? 'd' : 'points', previousPoints); let v1 = '', v2 = ''; if (!precision) { v1 = $path1.getAttribute(isPath ? 'd' : 'points'); v2 = $path2.getAttribute(isPath ? 'd' : 'points'); } else { const length1 = /** @type {SVGGeometryElement} */($path1).getTotalLength(); const length2 = $path2.getTotalLength(); const maxPoints = Math.max(Math.ceil(length1 * precision), Math.ceil(length2 * precision)); for (let i = 0; i < maxPoints; i++) { const t = i / (maxPoints - 1); const pointOnPath1 = /** @type {SVGGeometryElement} */($path1).getPointAtLength(length1 * t); const pointOnPath2 = $path2.getPointAtLength(length2 * t); const prefix = isPath ? (i === 0 ? 'M' : 'L') : ''; v1 += prefix + round(pointOnPath1.x, 3) + separator + pointOnPath1.y + ' '; v2 += prefix + round(pointOnPath2.x, 3) + separator + pointOnPath2.y + ' '; } } $path1[morphPointsSymbol] = v2; return [v1, v2]; }
@param {TargetsParam} path2 @param {Number} [precision] @return {FunctionValue}
morphTo
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
createDrawableProxy = ($el, start, end) => { const pathLength = K; const computedStyles = getComputedStyle($el); const strokeLineCap = computedStyles.strokeLinecap; // @ts-ignore const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null; let currentCap = strokeLineCap; const proxy = new Proxy($el, { get(target, property) { const value = target[property]; if (property === proxyTargetSymbol) return target; if (property === 'setAttribute') { return (...args) => { if (args[0] === 'draw') { const value = args[1]; const values = value.split(' '); const v1 = +values[0]; const v2 = +values[1]; // TOTO: Benchmark if performing two slices is more performant than one split // const spaceIndex = value.indexOf(' '); // const v1 = round(+value.slice(0, spaceIndex), precision); // const v2 = round(+value.slice(spaceIndex + 1), precision); const scaleFactor = getScaleFactor($scalled); const os = v1 * -1e3 * scaleFactor; const d1 = (v2 * pathLength * scaleFactor) + os; const d2 = (pathLength * scaleFactor + ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1); if (strokeLineCap !== 'butt') { const newCap = v1 === v2 ? 'butt' : strokeLineCap; if (currentCap !== newCap) { target.style.strokeLinecap = `${newCap}`; currentCap = newCap; } } target.setAttribute('stroke-dashoffset', `${os}`); target.setAttribute('stroke-dasharray', `${d1} ${d2}`); } return Reflect.apply(value, target, args); }; } if (isFnc(value)) { return (...args) => Reflect.apply(value, target, args); } else { return value; } } }); if ($el.getAttribute('pathLength') !== `${pathLength}`) { $el.setAttribute('pathLength', `${pathLength}`); proxy.setAttribute('draw', `${start} ${end}`); } return /** @type {DrawableSVGGeometry} */(proxy); }
Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality. @param {SVGGeometryElement} $el - The SVG element to transform into a drawable @param {number} start - Starting position (0-1) @param {number} end - Ending position (0-1) @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
createDrawableProxy
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
createDrawableProxy = ($el, start, end) => { const pathLength = K; const computedStyles = getComputedStyle($el); const strokeLineCap = computedStyles.strokeLinecap; // @ts-ignore const $scalled = computedStyles.vectorEffect === 'non-scaling-stroke' ? $el : null; let currentCap = strokeLineCap; const proxy = new Proxy($el, { get(target, property) { const value = target[property]; if (property === proxyTargetSymbol) return target; if (property === 'setAttribute') { return (...args) => { if (args[0] === 'draw') { const value = args[1]; const values = value.split(' '); const v1 = +values[0]; const v2 = +values[1]; // TOTO: Benchmark if performing two slices is more performant than one split // const spaceIndex = value.indexOf(' '); // const v1 = round(+value.slice(0, spaceIndex), precision); // const v2 = round(+value.slice(spaceIndex + 1), precision); const scaleFactor = getScaleFactor($scalled); const os = v1 * -1e3 * scaleFactor; const d1 = (v2 * pathLength * scaleFactor) + os; const d2 = (pathLength * scaleFactor + ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1); if (strokeLineCap !== 'butt') { const newCap = v1 === v2 ? 'butt' : strokeLineCap; if (currentCap !== newCap) { target.style.strokeLinecap = `${newCap}`; currentCap = newCap; } } target.setAttribute('stroke-dashoffset', `${os}`); target.setAttribute('stroke-dasharray', `${d1} ${d2}`); } return Reflect.apply(value, target, args); }; } if (isFnc(value)) { return (...args) => Reflect.apply(value, target, args); } else { return value; } } }); if ($el.getAttribute('pathLength') !== `${pathLength}`) { $el.setAttribute('pathLength', `${pathLength}`); proxy.setAttribute('draw', `${start} ${end}`); } return /** @type {DrawableSVGGeometry} */(proxy); }
Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality. @param {SVGGeometryElement} $el - The SVG element to transform into a drawable @param {number} start - Starting position (0-1) @param {number} end - Ending position (0-1) @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
createDrawableProxy
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
get(target, property) { const value = target[property]; if (property === proxyTargetSymbol) return target; if (property === 'setAttribute') { return (...args) => { if (args[0] === 'draw') { const value = args[1]; const values = value.split(' '); const v1 = +values[0]; const v2 = +values[1]; // TOTO: Benchmark if performing two slices is more performant than one split // const spaceIndex = value.indexOf(' '); // const v1 = round(+value.slice(0, spaceIndex), precision); // const v2 = round(+value.slice(spaceIndex + 1), precision); const scaleFactor = getScaleFactor($scalled); const os = v1 * -1e3 * scaleFactor; const d1 = (v2 * pathLength * scaleFactor) + os; const d2 = (pathLength * scaleFactor + ((v1 === 0 && v2 === 1) || (v1 === 1 && v2 === 0) ? 0 : 10 * scaleFactor) - d1); if (strokeLineCap !== 'butt') { const newCap = v1 === v2 ? 'butt' : strokeLineCap; if (currentCap !== newCap) { target.style.strokeLinecap = `${newCap}`; currentCap = newCap; } } target.setAttribute('stroke-dashoffset', `${os}`); target.setAttribute('stroke-dasharray', `${d1} ${d2}`); } return Reflect.apply(value, target, args); }; } if (isFnc(value)) { return (...args) => Reflect.apply(value, target, args); } else { return value; } }
Creates a proxy that wraps an SVGGeometryElement and adds drawing functionality. @param {SVGGeometryElement} $el - The SVG element to transform into a drawable @param {number} start - Starting position (0-1) @param {number} end - Ending position (0-1) @return {DrawableSVGGeometry} - Returns a proxy that preserves the original element's type with additional 'draw' attribute functionality
get
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
createDrawable = (selector, start = 0, end = 0) => { const els = parseTargets(selector); return els.map($el => createDrawableProxy( /** @type {SVGGeometryElement} */($el), start, end )); }
Creates drawable proxies for multiple SVG elements. @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors @param {number} [start=0] - Starting position (0-1) @param {number} [end=0] - Ending position (0-1) @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
createDrawable
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
createDrawable = (selector, start = 0, end = 0) => { const els = parseTargets(selector); return els.map($el => createDrawableProxy( /** @type {SVGGeometryElement} */($el), start, end )); }
Creates drawable proxies for multiple SVG elements. @param {TargetsParam} selector - CSS selector, SVG element, or array of elements and selectors @param {number} [start=0] - Starting position (0-1) @param {number} [end=0] - Ending position (0-1) @return {Array<DrawableSVGGeometry>} - Array of proxied elements with drawing functionality
createDrawable
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
getPathPoint = ($path, progress, lookup = 0) => { return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0); }
@param {SVGGeometryElement} $path @param {Number} progress @param {Number}lookup @return {DOMPoint}
getPathPoint
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
getPathPoint = ($path, progress, lookup = 0) => { return $path.getPointAtLength(progress + lookup >= 1 ? progress + lookup : 0); }
@param {SVGGeometryElement} $path @param {Number} progress @param {Number}lookup @return {DOMPoint}
getPathPoint
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
getPathProgess = ($path, pathProperty) => { return $el => { const totalLength = +($path.getTotalLength()); const inSvg = $el[isSvgSymbol]; const ctm = $path.getCTM(); /** @type {TweenObjectValue} */ return { from: 0, to: totalLength, /** @type {TweenModifier} */ modifier: progress => { if (pathProperty === 'a') { const p0 = getPathPoint($path, progress, -1); const p1 = getPathPoint($path, progress, 1); return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI; } else { const p = getPathPoint($path, progress, 0); return pathProperty === 'x' ? inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e : inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f } } } } }
@param {SVGGeometryElement} $path @param {String} pathProperty @return {FunctionValue}
getPathProgess
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
getPathProgess = ($path, pathProperty) => { return $el => { const totalLength = +($path.getTotalLength()); const inSvg = $el[isSvgSymbol]; const ctm = $path.getCTM(); /** @type {TweenObjectValue} */ return { from: 0, to: totalLength, /** @type {TweenModifier} */ modifier: progress => { if (pathProperty === 'a') { const p0 = getPathPoint($path, progress, -1); const p1 = getPathPoint($path, progress, 1); return atan2(p1.y - p0.y, p1.x - p0.x) * 180 / PI; } else { const p = getPathPoint($path, progress, 0); return pathProperty === 'x' ? inSvg || !ctm ? p.x : p.x * ctm.a + p.y * ctm.c + ctm.e : inSvg || !ctm ? p.y : p.x * ctm.b + p.y * ctm.d + ctm.f } } } } }
@param {SVGGeometryElement} $path @param {String} pathProperty @return {FunctionValue}
getPathProgess
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
isValidSVGAttribute = (el, propertyName) => { // Return early and use CSS opacity animation instead (already better default values (opacity: 1 instead of 0)) and rotate should be considered a transform if (cssReservedProperties.includes(propertyName)) return false; if (el.getAttribute(propertyName) || propertyName in el) { if (propertyName === 'scale') { // Scale const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode); // Only consider scale as a valid SVG attribute on filter element return elParentNode && elParentNode.tagName === 'filter'; } return true; } }
@param {Target} el @param {String} propertyName @return {Boolean}
isValidSVGAttribute
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
isValidSVGAttribute = (el, propertyName) => { // Return early and use CSS opacity animation instead (already better default values (opacity: 1 instead of 0)) and rotate should be considered a transform if (cssReservedProperties.includes(propertyName)) return false; if (el.getAttribute(propertyName) || propertyName in el) { if (propertyName === 'scale') { // Scale const elParentNode = /** @type {SVGGeometryElement} */(/** @type {DOMTarget} */(el).parentNode); // Only consider scale as a valid SVG attribute on filter element return elParentNode && elParentNode.tagName === 'filter'; } return true; } }
@param {Target} el @param {String} propertyName @return {Boolean}
isValidSVGAttribute
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
rgbToRgba = rgbValue => { const rgba = rgbExecRgx.exec(rgbValue) || rgbaExecRgx.exec(rgbValue); const a = !isUnd(rgba[4]) ? +rgba[4] : 1; return [ +rgba[1], +rgba[2], +rgba[3], a ] }
RGB / RGBA Color value string -> RGBA values array @param {String} rgbValue @return {ColorArray}
rgbToRgba
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
rgbToRgba = rgbValue => { const rgba = rgbExecRgx.exec(rgbValue) || rgbaExecRgx.exec(rgbValue); const a = !isUnd(rgba[4]) ? +rgba[4] : 1; return [ +rgba[1], +rgba[2], +rgba[3], a ] }
RGB / RGBA Color value string -> RGBA values array @param {String} rgbValue @return {ColorArray}
rgbToRgba
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT
hexToRgba = hexValue => { const hexLength = hexValue.length; const isShort = hexLength === 4 || hexLength === 5; return [ +('0x' + hexValue[1] + hexValue[isShort ? 1 : 2]), +('0x' + hexValue[isShort ? 2 : 3] + hexValue[isShort ? 2 : 4]), +('0x' + hexValue[isShort ? 3 : 5] + hexValue[isShort ? 3 : 6]), ((hexLength === 5 || hexLength === 9) ? +(+('0x' + hexValue[isShort ? 4 : 7] + hexValue[isShort ? 4 : 8]) / 255).toFixed(3) : 1) ] }
HEX3 / HEX3A / HEX6 / HEX6A Color value string -> RGBA values array @param {String} hexValue @return {ColorArray}
hexToRgba
javascript
juliangarnier/anime
lib/anime.esm.js
https://github.com/juliangarnier/anime/blob/master/lib/anime.esm.js
MIT