code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
function setProperty(el, varName, value) { el.style.setProperty(varName, value); }
# setProperty Apply a CSS var @param {HTMLElement} el @param {string} varName @param {string|number} value
setProperty ( el , varName , value )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function appendChild(el, child) { return el.appendChild(child); }
@param {!HTMLElement} el @param {!HTMLElement} child
appendChild ( el , child )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function createElement(parent, key, text, whitespace) { var el = root.createElement('span'); key && (el.className = key); if (text) { !whitespace && el.setAttribute("data-" + key, text); el.textContent = text; } return (parent && appendChild(parent, el)) || el; }
@param {!HTMLElement} parent @param {string} key @param {string} text @param {boolean} whitespace
createElement ( parent , key , text , whitespace )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function getData(el, key) { return el.getAttribute("data-" + key) }
@param {!HTMLElement} el @param {string} key
getData ( el , key )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function $(e, parent) { return !e || e.length == 0 ? // null or empty string returns empty array [] : e.nodeName ? // a single element is wrapped in an array [e] : // selector and NodeList are converted to Element[] [].slice.call(e[0].nodeName ? e : (parent || root).querySelectorAll(e)); }
@param {import('../types').Target} e @param {!HTMLElement} parent @returns {!Array<!HTMLElement>}
$ ( e , parent )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function Array2D(len) { var a = []; for (; len--; ) { a[len] = []; } return a; }
Creates and fills an array with the value provided @param {number} len @param {() => T} valueProvider @return {T} @template T
Array2D ( len )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function each(items, consumer) { items && items.some(consumer); }
A for loop wrapper used to reduce js minified size. @param {!Array<T>} items @param {function(T):void} consumer @template T
each ( items , consumer )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function selectFrom(obj) { return function (key) { return obj[key]; } }
@param {T} obj @return {function(string):*} @template T
selectFrom ( obj )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function index(element, key, items) { var prefix = '--' + key; var cssVar = prefix + "-index"; each(items, function (items, i) { if (Array.isArray(items)) { each(items, function(item) { setProperty(item, cssVar, i); }); } else { setProperty(items, cssVar, i); } }); setProperty(element, prefix + "-total", items.length); }
# Splitting.index Index split elements and add them to a Splitting instance. @param {HTMLElement} element @param {string} key @param {!Array<!HTMLElement> | !Array<!Array<!HTMLElement>>} items
index ( element , key , items )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function resolvePlugins(by, parent, deps) { // skip if already visited this dependency var index = deps.indexOf(by); if (index == -1) { // if new to dependency array, add to the beginning deps.unshift(by); // recursively call this function for all dependencies var plugin = plugins[by]; if (!plugin) { throw new Error("plugin not loaded: " + by); } each(plugin.depends, function(p) { resolvePlugins(p, by, deps); }); } else { // if this dependency was added already move to the left of // the parent dependency so it gets loaded in order var indexOfParent = deps.indexOf(parent); deps.splice(index, 1); deps.splice(indexOfParent, 0, by); } return deps; }
@param {string} by @param {string} parent @param {!Array<string>} deps @return {!Array<string>}
resolvePlugins ( by , parent , deps )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function createPlugin(by, depends, key, split) { return { by: by, depends: depends, key: key, split: split } }
Internal utility for creating plugins... essentially to reduce the size of the library @param {string} by @param {string} key @param {string[]} depends @param {Function} split @returns {import('./types').ISplittingPlugin}
createPlugin ( by , depends , key , split )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function resolve(by) { return resolvePlugins(by, 0, []).map(selectFrom(plugins)); }
@param {string} by @returns {import('./types').ISplittingPlugin[]}
resolve ( by )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function add(opts) { plugins[opts.by] = opts; }
Adds a new plugin to splitting @param {import('./types').ISplittingPlugin} opts
add ( opts )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function splitText(el, key, splitOn, includePrevious, preserveWhitespace) { // Combine any strange text nodes or empty whitespace. el.normalize(); // Use fragment to prevent unnecessary DOM thrashing. var elements = []; var F = document.createDocumentFragment(); if (includePrevious) { elements.push(el.previousSibling); } var allElements = []; $(el.childNodes).some(function(next) { if (next.tagName && !next.hasChildNodes()) { // keep elements without child nodes (no text and no children) allElements.push(next); return; } // Recursively run through child nodes if (next.childNodes && next.childNodes.length) { allElements.push(next); elements.push.apply(elements, splitText(next, key, splitOn, includePrevious, preserveWhitespace)); return; } // Get the text to split, trimming out the whitespace /** @type {string} */ var wholeText = next.wholeText || ''; var contents = wholeText.trim(); // If there's no text left after trimming whitespace, continue the loop if (contents.length) { // insert leading space if there was one if (wholeText[0] === ' ') { allElements.push(createText(' ')); } // Concatenate the split text children back into the full array var useSegmenter = splitOn === "" && typeof Intl.Segmenter === "function"; each(useSegmenter ? Array.from(new Intl.Segmenter().segment(contents)).map(function(x){return x.segment}) : contents.split(splitOn), function (splitText, i) { if (i && preserveWhitespace) { allElements.push(createElement(F, "whitespace", " ", preserveWhitespace)); } var splitEl = createElement(F, key, splitText); elements.push(splitEl); allElements.push(splitEl); }); // insert trailing space if there was one if (wholeText[wholeText.length - 1] === ' ') { allElements.push(createText(' ')); } } }); each(allElements, function(el) { appendChild(F, el); }); // Clear out the existing element el.innerHTML = ""; appendChild(el, F); return elements; }
# Splitting.split Split an element's textContent into individual elements @param {!HTMLElement} el Element to split @param {string} key @param {string} splitOn @param {boolean} includePrevious @param {boolean} preserveWhitespace @return {!Array<!HTMLElement>}
splitText ( el , key , splitOn , includePrevious , preserveWhitespace )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function html(opts) { opts = opts || {}; var parent = opts.target = createElement(); parent.innerHTML = opts.content; Splitting(opts); return parent.outerHTML }
# Splitting.html @param {import('./types').ISplittingOptions} opts
html ( opts )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function detectGrid(el, options, side) { var items = $(options.matching || el.children, el); var c = {}; each(items, function(w) { var val = Math.round(w[side]); (c[val] || (c[val] = [])).push(w); }); return Object.keys(c).map(Number).sort(byNumber).map(selectFrom(c)); }
Detects the grid by measuring which elements align to a side of it. @param {!HTMLElement} el @param {import('../core/types').ISplittingOptions} options @param {*} side
detectGrid ( el , options , side )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function byNumber(a, b) { return a - b; }
Sorting function for numbers. @param {number} a @param {number} b @return {number}
byNumber ( a , b )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function Splitting (opts) { opts = opts || {}; var key = opts.key; return $(opts.target || '[data-splitting]').map(function(el) { var ctx = el['🍌']; if (!opts.force && ctx) { return ctx; } ctx = el['🍌'] = { el: el }; var by = opts.by || getData(el, 'splitting'); if (!by || by == 'true') { by = CHARS; } var items = resolve(by); var opts2 = copy({}, opts); each(items, function(plugin) { if (plugin.split) { var pluginBy = plugin.by; var key2 = (key ? '-' + key : '') + plugin.key; var results = plugin.split(el, opts2, ctx); key2 && index(el, key2, results); ctx[pluginBy] = results; el.classList.add(pluginBy); } }); el.classList.add('splitting'); return ctx; }) } /** * # Splitting.html * * @param {import('./types').ISplittingOptions} opts */ function html(opts) { opts = opts || {}; var parent = opts.target = createElement(); parent.innerHTML = opts.content; Splitting(opts); return parent.outerHTML } Splitting.html = html; Splitting.add = add; /** * Detects the grid by measuring which elements align to a side of it. * @param {!HTMLElement} el * @param {import('../core/types').ISplittingOptions} options * @param {*} side */ function detectGrid(el, options, side) { var items = $(options.matching || el.children, el); var c = {}; each(items, function(w) { var val = Math.round(w[side]); (c[val] || (c[val] = [])).push(w); }); return Object.keys(c).map(Number).sort(byNumber).map(selectFrom(c)); } /** * Sorting function for numbers. * @param {number} a * @param {number} b * @return {number} */ function byNumber(a, b) { return a - b; } var linePlugin = createPlugin( /* by= */ 'lines', /* depends= */ [WORDS], /* key= */ 'line', /* split= */ function(el, options, ctx) { return detectGrid(el, { matching: ctx[WORDS] }, 'offsetTop') } ); var itemPlugin = createPlugin( /* by= */ 'items', /* depends= */ _, /* key= */ 'item', /* split= */ function(el, options) { return $(options.matching || el.children, el) } ); var rowPlugin = createPlugin( /* by= */ 'rows', /* depends= */ _, /* key= */ 'row', /* split= */ function(el, options) { return detectGrid(el, options, "offsetTop"); } ); var columnPlugin = createPlugin( /* by= */ 'cols', /* depends= */ _, /* key= */ "col", /* split= */ function(el, options) { return detectGrid(el, options, "offsetLeft"); } ); var gridPlugin = createPlugin( /* by= */ 'grid', /* depends= */ ['rows', 'cols'] ); var LAYOUT = "layout"; var layoutPlugin = createPlugin( /* by= */ LAYOUT, /* depends= */ _, /* key= */ _, /* split= */ function(el, opts) { // detect and set options var rows = opts.rows = +(opts.rows || getData(el, 'rows') || 1); var columns = opts.columns = +(opts.columns || getData(el, 'columns') || 1); // Seek out the first <img> if the value is true opts.image = opts.image || getData(el, 'image') || el.currentSrc || el.src; if (opts.image) { var img = $("img", el)[0]; opts.image = img && (img.currentSrc || img.src); } // add optional image to background if (opts.image) { setProperty(el, "background-image", "url(" + opts.image + ")"); } var totalCells = rows * columns; var elements = []; var container = createElement(_, "cell-grid"); while (totalCells--) { // Create a span var cell = createElement(container, "cell"); createElement(cell, "cell-inner"); elements.push(cell); } // Append elements back into the parent appendChild(el, container); return elements; } ); var cellRowPlugin = createPlugin( /* by= */ "cellRows", /* depends= */ [LAYOUT], /* key= */ "row", /* split= */ function(el, opts, ctx) { var rowCount = opts.rows; var result = Array2D(rowCount); each(ctx[LAYOUT], function(cell, i, src) { result[Math.floor(i / (src.length / rowCount))].push(cell); }); return result; } ); var cellColumnPlugin = createPlugin( /* by= */ "cellColumns", /* depends= */ [LAYOUT], /* key= */ "col", /* split= */ function(el, opts, ctx) { var columnCount = opts.columns; var result = Array2D(columnCount); each(ctx[LAYOUT], function(cell, i) { result[i % columnCount].push(cell); }); return result; } ); var cellPlugin = createPlugin( /* by= */ "cells", /* depends= */ ['cellRows', 'cellColumns'], /* key= */ "cell", /* split= */ function(el, opt, ctx) { // re-index the layout as the cells return ctx[LAYOUT]; } ); // install plugins // word/char plugins add(wordPlugin); add(charPlugin); add(linePlugin); // grid plugins add(itemPlugin); add(rowPlugin); add(columnPlugin); add(gridPlugin); // cell-layout plugins add(layoutPlugin); add(cellRowPlugin); add(cellColumnPlugin); add(cellPlugin); return Splitting; })));
# Splitting @param {import('./types').ISplittingOptions} opts @return {!Array<*>}
Splitting ( opts )
javascript
shshaw/Splitting
dist/splitting.js
https://github.com/shshaw/Splitting/blob/master/dist/splitting.js
MIT
function recoverPubKey(curve, e, signature, i) { assert.strictEqual(i & 3, i, 'Recovery param is more than two bits') var n = curve.n var G = curve.G var r = signature.r var s = signature.s assert(r.signum() > 0 && r.compareTo(n) < 0, 'Invalid r value') assert(s.signum() > 0 && s.compareTo(n) < 0, 'Invalid s value') // A set LSB signifies that the y-coordinate is odd var isYOdd = i & 1 // The more significant bit specifies whether we should use the // first or second candidate key. var isSecondKey = i >> 1 // 1.1 Let x = r + jn var x = isSecondKey ? r.add(n) : r var R = curve.pointFromX(isYOdd, x) // 1.4 Check that nR is at infinity var nR = R.multiply(n) assert(curve.isInfinity(nR), 'nR is not a valid curve point') // Compute -e from e var eNeg = e.negate().mod(n) // 1.6.1 Compute Q = r^-1 (sR - eG) // Q = r^-1 (sR + -eG) var rInv = r.modInverse(n) var Q = R.multiplyTwo(s, G, eNeg).multiply(rInv) curve.validate(Q) return Q }
Recover a public key from a signature. See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public Key Recovery Operation". http://www.secg.org/download/aid-780/sec1-v2.pdf
recoverPubKey ( curve , e , signature , i )
javascript
steemit/steem-js
src/auth/ecc/src/ecdsa.js
https://github.com/steemit/steem-js/blob/master/src/auth/ecc/src/ecdsa.js
MIT
function calcPubKeyRecoveryParam(curve, e, signature, Q) { for (var i = 0; i < 4; i++) { var Qprime = recoverPubKey(curve, e, signature, i) // 1.6.2 Verify Q if (Qprime.equals(Q)) { return i } } throw new Error('Unable to find valid recovery factor') }
Calculate pubkey extraction parameter. When extracting a pubkey from a signature, we have to distinguish four different cases. Rather than putting this burden on the verifier, Bitcoin includes a 2-bit value with the signature. This function simply tries all four cases and returns the value that resulted in a successful pubkey recovery.
calcPubKeyRecoveryParam ( curve , e , signature , Q )
javascript
steemit/steem-js
src/auth/ecc/src/ecdsa.js
https://github.com/steemit/steem-js/blob/master/src/auth/ecc/src/ecdsa.js
MIT
function uniqueNonce() { if(unique_nonce_entropy === null) { const b = secureRandom.randomUint8Array(2) unique_nonce_entropy = parseInt(b[0] << 8 | b[1], 10) } let long = Long.fromNumber(Date.now()) const entropy = ++unique_nonce_entropy % 0xFFFF // console.log('uniqueNonce date\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0)) // console.log('uniqueNonce entropy\t', ByteBuffer.allocate(8).writeUint64(Long.fromNumber(entropy)).toHex(0)) long = long.shiftLeft(16).or(Long.fromNumber(entropy)); // console.log('uniqueNonce final\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0)) return long.toString() }
@return {string} unique 64 bit unsigned number string. Being time based, this is careful to never choose the same nonce twice. This value could be recorded in the blockchain for a long time.
uniqueNonce ( )
javascript
steemit/steem-js
src/auth/ecc/src/aes.js
https://github.com/steemit/steem-js/blob/master/src/auth/ecc/src/aes.js
MIT
steemBroadcast.send = function steemBroadcast$send(tx, privKeys, callback) { const resultP = steemBroadcast._prepareTransaction(tx) .then((transaction) => { debug( 'Signing transaction (transaction, transaction.operations)', transaction, transaction.operations ); return Promise.join( transaction, steemAuth.signTransaction(transaction, privKeys) ); }) .spread((transaction, signedTransaction) => { debug( 'Broadcasting transaction (transaction, transaction.operations)', transaction, transaction.operations ); return steemApi.broadcastTransactionSynchronousAsync( signedTransaction ).then((result) => { return Object.assign({}, result, signedTransaction); }); }); resultP.nodeify(callback || noop); };
Sign and broadcast transactions on the steem network
$send ( tx , privKeys , callback )
javascript
steemit/steem-js
src/broadcast/index.js
https://github.com/steemit/steem-js/blob/master/src/broadcast/index.js
MIT
!function(){function c(){return f.Matrix="undefined"!=typeof Float32Array?Float32Array:Array,f.Matrix}function d(a){return[(255&a>>16)/255,(255&a>>8)/255,(255&a)/255]}function d(a){return[(255&a>>16)/255,(255&a>>8)/255,(255&a)/255]}var e=this,f=f||{};f.Point=function(a,b){this.x=a||0,this.y=b||0},f.Point.prototype.clone=function(){return new f.Point(this.x,this.y)},f.Point.prototype.constructor=f.Point,f.Rectangle=function(a,b,c,d){this.x=a||0,this.y=b||0,this.width=c||0,this.height=d||0},f.Rectangle.prototype.clone=function(){return new f.Rectangle(this.x,this.y,this.width,this.height)},f.Rectangle.prototype.contains=function(a,b){if(this.width<=0||this.height<=0)return!1;var c=this.x;if(a>=c&&a<=c+this.width){var d=this.y;if(b>=d&&b<=d+this.height)return!0}return!1},f.Rectangle.prototype.constructor=f.Rectangle,f.Polygon=function(a){if(a instanceof Array||(a=Array.prototype.slice.call(arguments)),"number"==typeof a[0]){for(var b=[],c=0,d=a.length;d>c;c+=2)b.push(new f.Point(a[c],a[c+1]));a=b}this.points=a},f.Polygon.prototype.clone=function(){for(var a=[],b=0;b<this.points.length;b++)a.push(this.points[b].clone());return new f.Polygon(a)},f.Polygon.prototype.contains=function(a,b){for(var c=!1,d=0,e=this.points.length-1;d<this.points.length;e=d++){var f=this.points[d].x,g=this.points[d].y,h=this.points[e].x,i=this.points[e].y,j=g>b!=i>b&&(h-f)*(b-g)/(i-g)+f>a;j&&(c=!c)}return c},f.Polygon.prototype.constructor=f.Polygon,f.Circle=function(a,b,c){this.x=a||0,this.y=b||0,this.radius=c||0},f.Circle.prototype.clone=function(){return new f.Circle(this.x,this.y,this.radius)},f.Circle.prototype.contains=function(a,b){if(this.radius<=0)return!1;var c=this.x-a,d=this.y-b,e=this.radius*this.radius;return c*=c,d*=d,e>=c+d},f.Circle.prototype.constructor=f.Circle,f.Ellipse=function(a,b,c,d){this.x=a||0,this.y=b||0,this.width=c||0,this.height=d||0},f.Ellipse.prototype.clone=function(){return new f.Ellipse(this.x,this.y,this.width,this.height)},f.Ellipse.prototype.contains=function(a,b){if(this.width<=0||this.height<=0)return!1;var c=(a-this.x)/this.width-.5,d=(b-this.y)/this.height-.5;return c*=c,d*=d,.25>c+d},f.Ellipse.getBounds=function(){return new f.Rectangle(this.x,this.y,this.width,this.height)},f.Ellipse.prototype.constructor=f.Ellipse,c(),f.mat3={},f.mat3.create=function(){var a=new f.Matrix(9);return a[0]=1,a[1]=0,a[2]=0,a[3]=0,a[4]=1,a[5]=0,a[6]=0,a[7]=0,a[8]=1,a},f.mat3.identity=function(a){return a[0]=1,a[1]=0,a[2]=0,a[3]=0,a[4]=1,a[5]=0,a[6]=0,a[7]=0,a[8]=1,a},f.mat4={},f.mat4.create=function(){var a=new f.Matrix(16);return a[0]=1,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=1,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=1,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,a},f.mat3.multiply=function(a,b,c){c||(c=a);var d=a[0],e=a[1],f=a[2],g=a[3],h=a[4],i=a[5],j=a[6],k=a[7],l=a[8],m=b[0],n=b[1],o=b[2],p=b[3],q=b[4],r=b[5],s=b[6],t=b[7],u=b[8];return c[0]=m*d+n*g+o*j,c[1]=m*e+n*h+o*k,c[2]=m*f+n*i+o*l,c[3]=p*d+q*g+r*j,c[4]=p*e+q*h+r*k,c[5]=p*f+q*i+r*l,c[6]=s*d+t*g+u*j,c[7]=s*e+t*h+u*k,c[8]=s*f+t*i+u*l,c},f.mat3.clone=function(a){var b=new f.Matrix(9);return b[0]=a[0],b[1]=a[1],b[2]=a[2],b[3]=a[3],b[4]=a[4],b[5]=a[5],b[6]=a[6],b[7]=a[7],b[8]=a[8],b},f.mat3.transpose=function(a,b){if(!b||a===b){var c=a[1],d=a[2],e=a[5];return a[1]=a[3],a[2]=a[6],a[3]=c,a[5]=a[7],a[6]=d,a[7]=e,a}return b[0]=a[0],b[1]=a[3],b[2]=a[6],b[3]=a[1],b[4]=a[4],b[5]=a[7],b[6]=a[2],b[7]=a[5],b[8]=a[8],b},f.mat3.toMat4=function(a,b){return b||(b=f.mat4.create()),b[15]=1,b[14]=0,b[13]=0,b[12]=0,b[11]=0,b[10]=a[8],b[9]=a[7],b[8]=a[6],b[7]=0,b[6]=a[5],b[5]=a[4],b[4]=a[3],b[3]=0,b[2]=a[2],b[1]=a[1],b[0]=a[0],b},f.mat4.create=function(){var a=new f.Matrix(16);return a[0]=1,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=1,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=1,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,a},f.mat4.transpose=function(a,b){if(!b||a===b){var c=a[1],d=a[2],e=a[3],f=a[6],g=a[7],h=a[11];return a[1]=a[4],a[2]=a[8],a[3]=a[12],a[4]=c,a[6]=a[9],a[7]=a[13],a[8]=d,a[9]=f,a[11]=a[14],a[12]=e,a[13]=g,a[14]=h,a}return b[0]=a[0],b[1]=a[4],b[2]=a[8],b[3]=a[12],b[4]=a[1],b[5]=a[5],b[6]=a[9],b[7]=a[13],b[8]=a[2],b[9]=a[6],b[10]=a[10],b[11]=a[14],b[12]=a[3],b[13]=a[7],b[14]=a[11],b[15]=a[15],b},f.mat4.multiply=function(a,b,c){c||(c=a);var d=a[0],e=a[1],f=a[2],g=a[3],h=a[4],i=a[5],j=a[6],k=a[7],l=a[8],m=a[9],n=a[10],o=a[11],p=a[12],q=a[13],r=a[14],s=a[15],t=b[0],u=b[1],v=b[2],w=b[3];return c[0]=t*d+u*h+v*l+w*p,c[1]=t*e+u*i+v*m+w*q,c[2]=t*f+u*j+v*n+w*r,c[3]=t*g+u*k+v*o+w*s,t=b[4],u=b[5],v=b[6],w=b[7],c[4]=t*d+u*h+v*l+w*p,c[5]=t*e+u*i+v*m+w*q,c[6]=t*f+u*j+v*n+w*r,c[7]=t*g+u*k+v*o+w*s,t=b[8],u=b[9],v=b[10],w=b[11],c[8]=t*d+u*h+v*l+w*p,c[9]=t*e+u*i+v*m+w*q,c[10]=t*f+u*j+v*n+w*r,c[11]=t*g+u*k+v*o+w*s,t=b[12],u=b[13],v=b[14],w=b[15],c[12]=t*d+u*h+v*l+w*p,c[13]=t*e+u*i+v*m+w*q,c[14]=t*f+u*j+v*n+w*r,c[15]=t*g+u*k+v*o+w*s,c},f.DisplayObject=function(){this.last=this,this.first=this,this.position=new f.Point,this.scale=new f.Point(1,1),this.pivot=new f.Point(0,0),this.rotation=0,this.alpha=1,this.visible=!0,this.hitArea=null,this.buttonMode=!1,this.renderable=!1,this.parent=null,this.stage=null,this.worldAlpha=1,this._interactive=!1,this.worldTransform=f.mat3.create(),this.localTransform=f.mat3.create(),this.color=[],this.dynamic=!0,this._sr=0,this._cr=1},f.DisplayObject.prototype.constructor=f.DisplayObject,f.DisplayObject.prototype.setInteractive=function(a){this.interactive=a},Object.defineProperty(f.DisplayObject.prototype,"interactive",{get:function(){return this._interactive},set:function(a){this._interactive=a,this.stage&&(this.stage.dirty=!0)}}),Object.defineProperty(f.DisplayObject.prototype,"mask",{get:function(){return this._mask},set:function(a){this._mask=a,a?this.addFilter(a):this.removeFilter()}}),f.DisplayObject.prototype.addFilter=function(a){if(!this.filter){this.filter=!0;var b=new f.FilterBlock,c=new f.FilterBlock;b.mask=a,c.mask=a,b.first=b.last=this,c.first=c.last=this,b.open=!0;var d,e,g=b,h=b;e=this.first._iPrev,e?(d=e._iNext,g._iPrev=e,e._iNext=g):d=this,d&&(d._iPrev=h,h._iNext=d);var g=c,h=c,d=null,e=null;e=this.last,d=e._iNext,d&&(d._iPrev=h,h._iNext=d),g._iPrev=e,e._iNext=g;for(var i=this,j=this.last;i;)i.last==j&&(i.last=c),i=i.parent;this.first=b,this.__renderGroup&&this.__renderGroup.addFilterBlocks(b,c),a.renderable=!1}},f.DisplayObject.prototype.removeFilter=function(){if(this.filter){this.filter=!1;var a=this.first,b=a._iNext,c=a._iPrev;b&&(b._iPrev=c),c&&(c._iNext=b),this.first=a._iNext;var d=this.last,b=d._iNext,c=d._iPrev;b&&(b._iPrev=c),c._iNext=b;for(var e=d._iPrev,f=this;f.last==d&&(f.last=e,f=f.parent););var g=a.mask;g.renderable=!0,this.__renderGroup&&this.__renderGroup.removeFilterBlocks(a,d)}},f.DisplayObject.prototype.updateTransform=function(){this.rotation!==this.rotationCache&&(this.rotationCache=this.rotation,this._sr=Math.sin(this.rotation),this._cr=Math.cos(this.rotation));var a=this.localTransform,b=this.parent.worldTransform,c=this.worldTransform;a[0]=this._cr*this.scale.x,a[1]=-this._sr*this.scale.y,a[3]=this._sr*this.scale.x,a[4]=this._cr*this.scale.y;var d=this.pivot.x,e=this.pivot.y,g=a[0],h=a[1],i=this.position.x-a[0]*d-e*a[1],j=a[3],k=a[4],l=this.position.y-a[4]*e-d*a[3],m=b[0],n=b[1],o=b[2],p=b[3],q=b[4],r=b[5];a[2]=i,a[5]=l,c[0]=m*g+n*j,c[1]=m*h+n*k,c[2]=m*i+n*l+o,c[3]=p*g+q*j,c[4]=p*h+q*k,c[5]=p*i+q*l+r,this.worldAlpha=this.alpha*this.parent.worldAlpha,this.vcount=f.visibleCount},f.visibleCount=0,f.DisplayObjectContainer=function(){f.DisplayObject.call(this),this.children=[]},f.DisplayObjectContainer.prototype=Object.create(f.DisplayObject.prototype),f.DisplayObjectContainer.prototype.constructor=f.DisplayObjectContainer,f.DisplayObjectContainer.prototype.addChild=function(a){if(void 0!=a.parent&&a.parent.removeChild(a),a.parent=this,this.children.push(a),this.stage){var b=a;do b.interactive&&(this.stage.dirty=!0),b.stage=this.stage,b=b._iNext;while(b)}var c,d,e=a.first,f=a.last;d=this.filter?this.last._iPrev:this.last,c=d._iNext;for(var g=this,h=d;g;)g.last==h&&(g.last=a.last),g=g.parent;c&&(c._iPrev=f,f._iNext=c),e._iPrev=d,d._iNext=e,this.__renderGroup&&(a.__renderGroup&&a.__renderGroup.removeDisplayObjectAndChildren(a),this.__renderGroup.addDisplayObjectAndChildren(a))},f.DisplayObjectContainer.prototype.addChildAt=function(a,b){if(!(b>=0&&b<=this.children.length))throw new Error(a+" The index "+b+" supplied is out of bounds "+this.children.length);if(void 0!=a.parent&&a.parent.removeChild(a),a.parent=this,this.stage){var c=a;do c.interactive&&(this.stage.dirty=!0),c.stage=this.stage,c=c._iNext;while(c)}var d,e,f=a.first,g=a.last;if(b==this.children.length){e=this.last;for(var h=this,i=this.last;h;)h.last==i&&(h.last=a.last),h=h.parent}else e=0==b?this:this.children[b-1].last;d=e._iNext,d&&(d._iPrev=g,g._iNext=d),f._iPrev=e,e._iNext=f,this.children.splice(b,0,a),this.__renderGroup&&(a.__renderGroup&&a.__renderGroup.removeDisplayObjectAndChildren(a),this.__renderGroup.addDisplayObjectAndChildren(a))},f.DisplayObjectContainer.prototype.swapChildren=function(){},f.DisplayObjectContainer.prototype.getChildAt=function(a){if(a>=0&&a<this.children.length)return this.children[a];throw new Error(child+" Both the supplied DisplayObjects must be a child of the caller "+this)},f.DisplayObjectContainer.prototype.removeChild=function(a){var b=this.children.indexOf(a);if(-1===b)throw new Error(a+" The supplied DisplayObject must be a child of the caller "+this);var c=a.first,d=a.last,e=d._iNext,f=c._iPrev;if(e&&(e._iPrev=f),f._iNext=e,this.last==d)for(var g=c._iPrev,h=this;h.last==d.last&&(h.last=g,h=h.parent););if(d._iNext=null,c._iPrev=null,this.stage){var i=a;do i.interactive&&(this.stage.dirty=!0),i.stage=null,i=i._iNext;while(i)}a.__renderGroup&&a.__renderGroup.removeDisplayObjectAndChildren(a),a.parent=void 0,this.children.splice(b,1)},f.DisplayObjectContainer.prototype.updateTransform=function(){if(this.visible){f.DisplayObject.prototype.updateTransform.call(this);for(var a=0,b=this.children.length;b>a;a++)this.children[a].updateTransform()}},f.blendModes={},f.blendModes.NORMAL=0,f.blendModes.SCREEN=1,f.Sprite=function(a){f.DisplayObjectContainer.call(this),this.anchor=new f.Point,this.texture=a,this.blendMode=f.blendModes.NORMAL,this._width=0,this._height=0,a.baseTexture.hasLoaded?this.updateFrame=!0:(this.onTextureUpdateBind=this.onTextureUpdate.bind(this),this.texture.addEventListener("update",this.onTextureUpdateBind)),this.renderable=!0},f.Sprite.prototype=Object.create(f.DisplayObjectContainer.prototype),f.Sprite.prototype.constructor=f.Sprite,Object.defineProperty(f.Sprite.prototype,"width",{get:function(){return this.scale.x*this.texture.frame.width},set:function(a){this.scale.x=a/this.texture.frame.width,this._width=a}}),Object.defineProperty(f.Sprite.prototype,"height",{get:function(){return this.scale.y*this.texture.frame.height},set:function(a){this.scale.y=a/this.texture.frame.height,this._height=a}}),f.Sprite.prototype.setTexture=function(a){this.texture.baseTexture!=a.baseTexture?(this.textureChange=!0,this.texture=a,this.__renderGroup&&this.__renderGroup.updateTexture(this)):this.texture=a,this.updateFrame=!0},f.Sprite.prototype.onTextureUpdate=function(){this._width&&(this.scale.x=this._width/this.texture.frame.width),this._height&&(this.scale.y=this._height/this.texture.frame.height),this.updateFrame=!0},f.Sprite.fromFrame=function(a){var b=f.TextureCache[a];if(!b)throw new Error("The frameId '"+a+"' does not exist in the texture cache"+this);return new f.Sprite(b)},f.Sprite.fromImage=function(a){var b=f.Texture.fromImage(a);return new f.Sprite(b)},f.MovieClip=function(a){f.Sprite.call(this,a[0]),this.textures=a,this.animationSpeed=1,this.loop=!0,this.onComplete=null,this.currentFrame=0,this.playing=!1},f.MovieClip.prototype=Object.create(f.Sprite.prototype),f.MovieClip.prototype.constructor=f.MovieClip,f.MovieClip.prototype.stop=function(){this.playing=!1},f.MovieClip.prototype.play=function(){this.playing=!0},f.MovieClip.prototype.gotoAndStop=function(a){this.playing=!1,this.currentFrame=a;var b=0|this.currentFrame+.5;this.setTexture(this.textures[b%this.textures.length])},f.MovieClip.prototype.gotoAndPlay=function(a){this.currentFrame=a,this.playing=!0},f.MovieClip.prototype.updateTransform=function(){if(f.Sprite.prototype.updateTransform.call(this),this.playing){this.currentFrame+=this.animationSpeed;var a=0|this.currentFrame+.5;this.loop||a<this.textures.length?this.setTexture(this.textures[a%this.textures.length]):a>=this.textures.length&&(this.gotoAndStop(this.textures.length-1),this.onComplete&&this.onComplete())}},f.FilterBlock=function(a){this.graphics=a,this.visible=!0,this.renderable=!0},f.Text=function(a,b){this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),f.Sprite.call(this,f.Texture.fromCanvas(this.canvas)),this.setText(a),this.setStyle(b),this.updateText(),this.dirty=!1},f.Text.prototype=Object.create(f.Sprite.prototype),f.Text.prototype.constructor=f.Text,f.Text.prototype.setStyle=function(a){a=a||{},a.font=a.font||"bold 20pt Arial",a.fill=a.fill||"black",a.align=a.align||"left",a.stroke=a.stroke||"black",a.strokeThickness=a.strokeThickness||0,a.wordWrap=a.wordWrap||!1,a.wordWrapWidth=a.wordWrapWidth||100,this.style=a,this.dirty=!0},f.Sprite.prototype.setText=function(a){this.text=a.toString()||" ",this.dirty=!0},f.Text.prototype.updateText=function(){this.context.font=this.style.font;var a=this.text;this.style.wordWrap&&(a=this.wordWrap(this.text));for(var b=a.split(/(?:\r\n|\r|\n)/),c=[],d=0,e=0;e<b.length;e++){var g=this.context.measureText(b[e]).width;c[e]=g,d=Math.max(d,g)}this.canvas.width=d+this.style.strokeThickness;var h=this.determineFontHeight("font: "+this.style.font+";")+this.style.strokeThickness;for(this.canvas.height=h*b.length,this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.lineWidth=this.style.strokeThickness,this.context.textBaseline="top",e=0;e<b.length;e++){var i=new f.Point(this.style.strokeThickness/2,this.style.strokeThickness/2+e*h);"right"==this.style.align?i.x+=d-c[e]:"center"==this.style.align&&(i.x+=(d-c[e])/2),this.style.stroke&&this.style.strokeThickness&&this.context.strokeText(b[e],i.x,i.y),this.style.fill&&this.context.fillText(b[e],i.x,i.y)}this.updateTexture()},f.Text.prototype.updateTexture=function(){this.texture.baseTexture.width=this.canvas.width,this.texture.baseTexture.height=this.canvas.height,this.texture.frame.width=this.canvas.width,this.texture.frame.height=this.canvas.height,this._width=this.canvas.width,this._height=this.canvas.height,f.texturesToUpdate.push(this.texture.baseTexture)},f.Text.prototype.updateTransform=function(){this.dirty&&(this.updateText(),this.dirty=!1),f.Sprite.prototype.updateTransform.call(this)},f.Text.prototype.determineFontHeight=function(a){var b=f.Text.heightCache[a];if(!b){var c=document.getElementsByTagName("body")[0],d=document.createElement("div"),e=document.createTextNode("M");d.appendChild(e),d.setAttribute("style",a+";position:absolute;top:0;left:0"),c.appendChild(d),b=d.offsetHeight,f.Text.heightCache[a]=b,c.removeChild(d)}return b},f.Text.prototype.wordWrap=function(a){for(var b=function(a,b,c,d,e){var f=Math.floor((d-c)/2)+c;return f==c?1:a.measureText(b.substring(0,f)).width<=e?a.measureText(b.substring(0,f+1)).width>e?f:arguments.callee(a,b,f,d,e):arguments.callee(a,b,c,f,e)},c=function(a,c,d){if(a.measureText(c).width<=d||c.length<1)return c;var e=b(a,c,0,c.length,d);return c.substring(0,e)+"\n"+arguments.callee(a,c.substring(e),d)},d="",e=a.split("\n"),f=0;f<e.length;f++)d+=c(this.context,e[f],this.style.wordWrapWidth)+"\n";return d},f.Text.prototype.destroy=function(a){a&&this.texture.destroy()},f.Text.heightCache={},f.BitmapText=function(a,b){f.DisplayObjectContainer.call(this),this.setText(a),this.setStyle(b),this.updateText(),this.dirty=!1},f.BitmapText.prototype=Object.create(f.DisplayObjectContainer.prototype),f.BitmapText.prototype.constructor=f.BitmapText,f.BitmapText.prototype.setText=function(a){this.text=a||" ",this.dirty=!0},f.BitmapText.prototype.setStyle=function(a){a=a||{},a.align=a.align||"left",this.style=a;var b=a.font.split(" ");this.fontName=b[b.length-1],this.fontSize=b.length>=2?parseInt(b[b.length-2],10):f.BitmapText.fonts[this.fontName].size,this.dirty=!0},f.BitmapText.prototype.updateText=function(){for(var a=f.BitmapText.fonts[this.fontName],b=new f.Point,c=null,d=[],e=0,g=[],h=0,i=this.fontSize/a.size,j=0;j<this.text.length;j++){var k=this.text.charCodeAt(j);if(/(?:\r\n|\r|\n)/.test(this.text.charAt(j)))g.push(b.x),e=Math.max(e,b.x),h++,b.x=0,b.y+=a.lineHeight,c=null;else{var l=a.chars[k];l&&(c&&l[c]&&(b.x+=l.kerning[c]),d.push({texture:l.texture,line:h,charCode:k,position:new f.Point(b.x+l.xOffset,b.y+l.yOffset)}),b.x+=l.xAdvance,c=k)}}g.push(b.x),e=Math.max(e,b.x);var m=[];for(j=0;h>=j;j++){var n=0;"right"==this.style.align?n=e-g[j]:"center"==this.style.align&&(n=(e-g[j])/2),m.push(n)}for(j=0;j<d.length;j++){var o=new f.Sprite(d[j].texture);o.position.x=(d[j].position.x+m[d[j].line])*i,o.position.y=d[j].position.y*i,o.scale.x=o.scale.y=i,this.addChild(o)}this.width=b.x*i,this.height=(b.y+a.lineHeight)*i},f.BitmapText.prototype.updateTransform=function(){if(this.dirty){for(;this.children.length>0;)this.removeChild(this.getChildAt(0));this.updateText(),this.dirty=!1}f.DisplayObjectContainer.prototype.updateTransform.call(this)},f.BitmapText.fonts={},f.InteractionManager=function(a){this.stage=a,this.mouse=new f.InteractionData,this.touchs={},this.tempPoint=new f.Point,this.mouseoverEnabled=!0,this.pool=[],this.interactiveItems=[],this.last=0},f.InteractionManager.prototype.constructor=f.InteractionManager,f.InteractionManager.prototype.collectInteractiveSprite=function(a,b){for(var c=a.children,d=c.length,e=d-1;e>=0;e--){var f=c[e];f.interactive?(b.interactiveChildren=!0,this.interactiveItems.push(f),f.children.length>0&&this.collectInteractiveSprite(f,f)):(f.__iParent=null,f.children.length>0&&this.collectInteractiveSprite(f,b))}},f.InteractionManager.prototype.setTarget=function(a){window.navigator.msPointerEnabled&&(a.view.style["-ms-content-zooming"]="none",a.view.style["-ms-touch-action"]="none"),this.target=a,a.view.addEventListener("mousemove",this.onMouseMove.bind(this),!0),a.view.addEventListener("mousedown",this.onMouseDown.bind(this),!0),document.body.addEventListener("mouseup",this.onMouseUp.bind(this),!0),a.view.addEventListener("mouseout",this.onMouseOut.bind(this),!0),a.view.addEventListener("touchstart",this.onTouchStart.bind(this),!0),a.view.addEventListener("touchend",this.onTouchEnd.bind(this),!0),a.view.addEventListener("touchmove",this.onTouchMove.bind(this),!0)},f.InteractionManager.prototype.update=function(){if(this.target){var a=Date.now(),b=a-this.last;if(b=30*b/1e3,!(1>b)){if(this.last=a,this.dirty){this.dirty=!1;for(var c=this.interactiveItems.length,d=0;c>d;d++)this.interactiveItems[d].interactiveChildren=!1;this.interactiveItems=[],this.stage.interactive&&this.interactiveItems.push(this.stage),this.collectInteractiveSprite(this.stage,this.stage)}var e=this.interactiveItems.length;this.target.view.style.cursor="default";for(var d=0;e>d;d++){var f=this.interactiveItems[d];(f.mouseover||f.mouseout||f.buttonMode)&&(f.__hit=this.hitTest(f,this.mouse),this.mouse.target=f,f.__hit?(f.buttonMode&&(this.target.view.style.cursor="pointer"),f.__isOver||(f.mouseover&&f.mouseover(this.mouse),f.__isOver=!0)):f.__isOver&&(f.mouseout&&f.mouseout(this.mouse),f.__isOver=!1))}}}},f.InteractionManager.prototype.onMouseMove=function(a){this.mouse.originalEvent=a||window.event;var b=this.target.view.getBoundingClientRect();this.mouse.global.x=(a.clientX-b.left)*(this.target.width/b.width),this.mouse.global.y=(a.clientY-b.top)*(this.target.height/b.height);var c=this.interactiveItems.length;this.mouse.global;for(var d=0;c>d;d++){var e=this.interactiveItems[d];e.mousemove&&e.mousemove(this.mouse)}},f.InteractionManager.prototype.onMouseDown=function(a){this.mouse.originalEvent=a||window.event;var b=this.interactiveItems.length;this.mouse.global,this.stage;for(var c=0;b>c;c++){var d=this.interactiveItems[c];if((d.mousedown||d.click)&&(d.__mouseIsDown=!0,d.__hit=this.hitTest(d,this.mouse),d.__hit&&(d.mousedown&&d.mousedown(this.mouse),d.__isDown=!0,!d.interactiveChildren)))break}},f.InteractionManager.prototype.onMouseOut=function(){var a=this.interactiveItems.length;this.target.view.style.cursor="default";for(var b=0;a>b;b++){var c=this.interactiveItems[b];c.__isOver&&(this.mouse.target=c,c.mouseout&&c.mouseout(this.mouse),c.__isOver=!1)}},f.InteractionManager.prototype.onMouseUp=function(a){this.mouse.originalEvent=a||window.event,this.mouse.global;for(var b=this.interactiveItems.length,c=!1,d=0;b>d;d++){var e=this.interactiveItems[d];(e.mouseup||e.mouseupoutside||e.click)&&(e.__hit=this.hitTest(e,this.mouse),e.__hit&&!c?(e.mouseup&&e.mouseup(this.mouse),e.__isDown&&e.click&&e.click(this.mouse),e.interactiveChildren||(c=!0)):e.__isDown&&e.mouseupoutside&&e.mouseupoutside(this.mouse),e.__isDown=!1)}},f.InteractionManager.prototype.hitTest=function(a,b){var c=b.global;if(a.vcount!==f.visibleCount)return!1;var d=a instanceof f.Sprite,e=a.worldTransform,g=e[0],h=e[1],i=e[2],j=e[3],k=e[4],l=e[5],m=1/(g*k+h*-j),n=k*m*c.x+-h*m*c.y+(l*h-i*k)*m,o=g*m*c.y+-j*m*c.x+(-l*g+i*j)*m;if(b.target=a,a.hitArea&&a.hitArea.contains)return a.hitArea.contains(n,o)?(b.target=a,!0):!1;if(d){var p,q=a.texture.frame.width,r=a.texture.frame.height,s=-q*a.anchor.x;if(n>s&&s+q>n&&(p=-r*a.anchor.y,o>p&&p+r>o))return b.target=a,!0}for(var t=a.children.length,u=0;t>u;u++){var v=a.children[u],w=this.hitTest(v,b);if(w)return b.target=a,!0}return!1},f.InteractionManager.prototype.onTouchMove=function(a){for(var b=this.target.view.getBoundingClientRect(),c=a.changedTouches,d=0;d<c.length;d++){var e=c[d],f=this.touchs[e.identifier];f.originalEvent=a||window.event,f.global.x=(e.clientX-b.left)*(this.target.width/b.width),f.global.y=(e.clientY-b.top)*(this.target.height/b.height)}for(var g=this.interactiveItems.length,d=0;g>d;d++){var h=this.interactiveItems[d];h.touchmove&&h.touchmove(f)}},f.InteractionManager.prototype.onTouchStart=function(a){for(var b=this.target.view.getBoundingClientRect(),c=a.changedTouches,d=0;d<c.length;d++){var e=c[d],g=this.pool.pop();g||(g=new f.InteractionData),g.originalEvent=a||window.event,this.touchs[e.identifier]=g,g.global.x=(e.clientX-b.left)*(this.target.width/b.width),g.global.y=(e.clientY-b.top)*(this.target.height/b.height);for(var h=this.interactiveItems.length,i=0;h>i;i++){var j=this.interactiveItems[i];if((j.touchstart||j.tap)&&(j.__hit=this.hitTest(j,g),j.__hit&&(j.touchstart&&j.touchstart(g),j.__isDown=!0,j.__touchData=g,!j.interactiveChildren)))break}}},f.InteractionManager.prototype.onTouchEnd=function(a){for(var b=this.target.view.getBoundingClientRect(),c=a.changedTouches,d=0;d<c.length;d++){var e=c[d],f=this.touchs[e.identifier],g=!1;f.global.x=(e.clientX-b.left)*(this.target.width/b.width),f.global.y=(e.clientY-b.top)*(this.target.height/b.height);for(var h=this.interactiveItems.length,i=0;h>i;i++){var j=this.interactiveItems[i],k=j.__touchData;j.__hit=this.hitTest(j,f),k==f&&(f.originalEvent=a||window.event,(j.touchend||j.tap)&&(j.__hit&&!g?(j.touchend&&j.touchend(f),j.__isDown&&j.tap&&j.tap(f),j.interactiveChildren||(g=!0)):j.__isDown&&j.touchendoutside&&j.touchendoutside(f),j.__isDown=!1),j.__touchData=null)}this.pool.push(f),this.touchs[e.identifier]=null}},f.InteractionData=function(){this.global=new f.Point,this.local=new f.Point,this.target,this.originalEvent},f.InteractionData.prototype.getLocalPosition=function(a){var b=a.worldTransform,c=this.global,d=b[0],e=b[1],g=b[2],h=b[3],i=b[4],j=b[5],k=1/(d*i+e*-h);return new f.Point(i*k*c.x+-e*k*c.y+(j*e-g*i)*k,d*k*c.y+-h*k*c.x+(-j*d+g*h)*k)},f.InteractionData.prototype.constructor=f.InteractionData,f.Stage=function(a,b){f.DisplayObjectContainer.call(this),this.worldTransform=f.mat3.create(),this.interactive=b,this.interactionManager=new f.InteractionManager(this),this.dirty=!0,this.__childrenAdded=[],this.__childrenRemoved=[],this.stage=this,this.stage.hitArea=new f.Rectangle(0,0,1e5,1e5),this.setBackgroundColor(a),this.worldVisible=!0},f.Stage.prototype=Object.create(f.DisplayObjectContainer.prototype),f.Stage.prototype.constructor=f.Stage,f.Stage.prototype.updateTransform=function(){this.worldAlpha=1,this.vcount=f.visibleCount;for(var a=0,b=this.children.length;b>a;a++)this.children[a].updateTransform();this.dirty&&(this.dirty=!1,this.interactionManager.dirty=!0),this.interactive&&this.interactionManager.update()},f.Stage.prototype.setBackgroundColor=function(a){this.backgroundColor=a||0,this.backgroundColorSplit=d(this.backgroundColor);var b=this.backgroundColor.toString(16);b="000000".substr(0,6-b.length)+b,this.backgroundColorString="#"+b},f.Stage.prototype.getMousePosition=function(){return this.interactionManager.mouse.global};for(var h=0,i=["ms","moz","webkit","o"],j=0;j<i.length&&!window.requestAnimationFrame;++j)window.requestAnimationFrame=window[i[j]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[i[j]+"CancelAnimationFrame"]||window[i[j]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(a){var b=(new Date).getTime(),c=Math.max(0,16-(b-h)),d=window.setTimeout(function(){a(b+c)},c);return h=b+c,d}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(a){clearTimeout(a)}),window.requestAnimFrame=window.requestAnimationFrame,"function"!=typeof Function.prototype.bind&&(Function.prototype.bind=function(){var a=Array.prototype.slice;return function(b){function c(){var f=e.concat(a.call(arguments));d.apply(this instanceof c?this:b,f)}var d=this,e=a.call(arguments,1);if("function"!=typeof d)throw new TypeError;return c.prototype=function f(a){return a&&(f.prototype=a),this instanceof f?void 0:new f}(d.prototype),c}}());var k=f.AjaxRequest=function(){var a=["Msxml2.XMLHTTP","Microsoft.XMLHTTP"];if(!window.ActiveXObject)return window.XMLHttpRequest?new XMLHttpRequest:!1;for(var b=0;b<a.length;b++)try{return new ActiveXObject(a[b])}catch(c){}};f.runList=function(a){console.log(">>>>>>>>>"),console.log("_");var b=0,c=a.first;for(console.log(c);c._iNext;)if(b++,c=c._iNext,console.log(c),b>100){console.log("BREAK");break}},f.EventTarget=function(){var a={};this.addEventListener=this.on=function(b,c){void 0===a[b]&&(a[b]=[]),-1===a[b].indexOf(c)&&a[b].push(c)},this.dispatchEvent=this.emit=function(b){for(var c in a[b.type])a[b.type][c](b)},this.removeEventListener=this.off=function(b,c){var d=a[b].indexOf(c);-1!==d&&a[b].splice(d,1)}},f.autoDetectRenderer=function(a,b,c,d,e){a||(a=800),b||(b=600);var g=function(){try{return!!window.WebGLRenderingContext&&!!document.createElement("canvas").getContext("experimental-webgl")}catch(a){return!1}}();if(g){var h=-1!=navigator.userAgent.toLowerCase().indexOf("msie");g=!h}return g?new f.WebGLRenderer(a,b,c,d,e):new f.CanvasRenderer(a,b,c,d)},f.PolyK={},f.PolyK.Triangulate=function(a){var b=!0,c=a.length>>1;if(3>c)return[];for(var d=[],e=[],g=0;c>g;g++)e.push(g);for(var g=0,h=c;h>3;){var i=e[(g+0)%h],j=e[(g+1)%h],k=e[(g+2)%h],l=a[2*i],m=a[2*i+1],n=a[2*j],o=a[2*j+1],p=a[2*k],q=a[2*k+1],r=!1;if(f.PolyK._convex(l,m,n,o,p,q,b)){r=!0;for(var s=0;h>s;s++){var t=e[s];if(t!=i&&t!=j&&t!=k&&f.PolyK._PointInTriangle(a[2*t],a[2*t+1],l,m,n,o,p,q)){r=!1;break}}}if(r)d.push(i,j,k),e.splice((g+1)%h,1),h--,g=0;else if(g++>3*h){if(!b)return console.log("PIXI Warning: shape too complex to fill"),[];var d=[];e=[];for(var g=0;c>g;g++)e.push(g);g=0,h=c,b=!1}}return d.push(e[0],e[1],e[2]),d},f.PolyK._PointInTriangle=function(a,b,c,d,e,f,g,h){var i=g-c,j=h-d,k=e-c,l=f-d,m=a-c,n=b-d,o=i*i+j*j,p=i*k+j*l,q=i*m+j*n,r=k*k+l*l,s=k*m+l*n,t=1/(o*r-p*p),u=(r*q-p*s)*t,v=(o*s-p*q)*t;return u>=0&&v>=0&&1>u+v},f.PolyK._convex=function(a,b,c,d,e,f,g){return(b-d)*(e-c)+(c-a)*(f-d)>=0==g},f.shaderFragmentSrc=["precision mediump float;","varying vec2 vTextureCoord;","varying float vColor;","uniform sampler2D uSampler;","void main(void) {","gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y));","gl_FragColor = gl_FragColor * vColor;","}"],f.shaderVertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute float aColor;","uniform vec2 projectionVector;","varying vec2 vTextureCoord;","varying float vColor;","void main(void) {","gl_Position = vec4( aVertexPosition.x / projectionVector.x -1.0, aVertexPosition.y / -projectionVector.y + 1.0 , 0.0, 1.0);","vTextureCoord = aTextureCoord;","vColor = aColor;","}"],f.stripShaderFragmentSrc=["precision mediump float;","varying vec2 vTextureCoord;","varying float vColor;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {","gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y));","gl_FragColor = gl_FragColor * alpha;","}"],f.stripShaderVertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute float aColor;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","varying vec2 vTextureCoord;","varying float vColor;","void main(void) {","vec3 v = translationMatrix * vec3(aVertexPosition, 1.0);","gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);","vTextureCoord = aTextureCoord;","vColor = aColor;","}"],f.primitiveShaderFragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {","gl_FragColor = vColor;","}"],f.primitiveShaderVertexSrc=["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform float alpha;","varying vec4 vColor;","void main(void) {","vec3 v = translationMatrix * vec3(aVertexPosition, 1.0);","gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);","vColor = aColor * alpha;","}"],f.initPrimitiveShader=function(){var a=f.gl,b=f.compileProgram(f.primitiveShaderVertexSrc,f.primitiveShaderFragmentSrc);a.useProgram(b),b.vertexPositionAttribute=a.getAttribLocation(b,"aVertexPosition"),b.colorAttribute=a.getAttribLocation(b,"aColor"),b.projectionVector=a.getUniformLocation(b,"projectionVector"),b.translationMatrix=a.getUniformLocation(b,"translationMatrix"),b.alpha=a.getUniformLocation(b,"alpha"),f.primitiveProgram=b},f.initDefaultShader=function(){var a=this.gl,b=f.compileProgram(f.shaderVertexSrc,f.shaderFragmentSrc);a.useProgram(b),b.vertexPositionAttribute=a.getAttribLocation(b,"aVertexPosition"),b.projectionVector=a.getUniformLocation(b,"projectionVector"),b.textureCoordAttribute=a.getAttribLocation(b,"aTextureCoord"),b.colorAttribute=a.getAttribLocation(b,"aColor"),b.samplerUniform=a.getUniformLocation(b,"uSampler"),f.shaderProgram=b},f.initDefaultStripShader=function(){var a=this.gl,b=f.compileProgram(f.stripShaderVertexSrc,f.stripShaderFragmentSrc);a.useProgram(b),b.vertexPositionAttribute=a.getAttribLocation(b,"aVertexPosition"),b.projectionVector=a.getUniformLocation(b,"projectionVector"),b.textureCoordAttribute=a.getAttribLocation(b,"aTextureCoord"),b.translationMatrix=a.getUniformLocation(b,"translationMatrix"),b.alpha=a.getUniformLocation(b,"alpha"),b.colorAttribute=a.getAttribLocation(b,"aColor"),b.projectionVector=a.getUniformLocation(b,"projectionVector"),b.samplerUniform=a.getUniformLocation(b,"uSampler"),f.stripShaderProgram=b},f.CompileVertexShader=function(a,b){return f._CompileShader(a,b,a.VERTEX_SHADER)},f.CompileFragmentShader=function(a,b){return f._CompileShader(a,b,a.FRAGMENT_SHADER)},f._CompileShader=function(a,b,c){var d=b.join("\n"),e=a.createShader(c);return a.shaderSource(e,d),a.compileShader(e),a.getShaderParameter(e,a.COMPILE_STATUS)?e:(alert(a.getShaderInfoLog(e)),null)},f.compileProgram=function(a,b){var c=f.gl,d=f.CompileFragmentShader(c,b),e=f.CompileVertexShader(c,a),g=c.createProgram();return c.attachShader(g,e),c.attachShader(g,d),c.linkProgram(g),c.getProgramParameter(g,c.LINK_STATUS)||alert("Could not initialise shaders"),g},f.activateDefaultShader=function(){var a=f.gl,b=f.shaderProgram;
@license Pixi.JS - v1.3.0 Copyright (c) 2012, Mat Groves http://goodboydigital.com/ Compiled: 2013-10-17 Pixi.JS is licensed under the MIT License. http://www.opensource.org/licenses/mit-license.php
d ( a )
javascript
prettymuchbryce/easystarjs
demo/static/js/pixi.js
https://github.com/prettymuchbryce/easystarjs/blob/master/demo/static/js/pixi.js
MIT
this.setAcceptableTiles=function(tiles){tiles instanceof Array? // Array acceptableTiles=tiles:!isNaN(parseFloat(tiles))&&isFinite(tiles)&&( // Number acceptableTiles=[tiles])},
Sets the collision grid that EasyStar uses. @param {Array|Number} tiles An array of numbers that represent which tiles in your grid should be considered acceptable, or "walkable". *
this.setAcceptableTiles ( tiles )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.enableSync=function(){syncEnabled=!0},
Enables sync mode for this EasyStar instance.. if you're into that sort of thing. *
this.enableSync ( )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.disableSync=function(){syncEnabled=!1},
Disables sync mode for this EasyStar instance. *
this.disableSync ( )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.setGrid=function(grid){collisionGrid=grid;//Setup cost map for(var y=0;y<collisionGrid.length;y++)for(var x=0;x<collisionGrid[0].length;x++)costMap[collisionGrid[y][x]]||(costMap[collisionGrid[y][x]]=1)},
Sets the collision grid that EasyStar uses. @param {Array} grid The collision grid that this EasyStar instance will read from. This should be a 2D Array of Numbers. *
this.setGrid ( grid )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.setTileCost=function(tileType,cost){costMap[tileType]=cost},
Sets the tile cost for a particular tile type. @param {Number} The tile type to set the cost for. @param {Number} The multiplicative cost associated with the given tile. *
this.setTileCost ( tileType , cost )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.setAdditionalPointCost=function(x,y,cost){void 0===pointsToCost[y]&&(pointsToCost[y]={}),pointsToCost[y][x]=cost},
Sets the an additional cost for a particular point. Overrides the cost from setTileCost. @param {Number} x The x value of the point to cost. @param {Number} y The y value of the point to cost. @param {Number} The multiplicative cost associated with the given point. *
this.setAdditionalPointCost ( x , y , cost )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.removeAdditionalPointCost=function(x,y){void 0!==pointsToCost[y]&&delete pointsToCost[y][x]},
Remove the additional cost for a particular point. @param {Number} x The x value of the point to stop costing. @param {Number} y The y value of the point to stop costing. *
this.removeAdditionalPointCost ( x , y )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.removeAllAdditionalPointCosts=function(){pointsToCost={}},
Remove all additional point costs. *
this.removeAllAdditionalPointCosts ( )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.setDirectionalCondition=function(x,y,allowedDirections){void 0===directionalConditions[y]&&(directionalConditions[y]={}),directionalConditions[y][x]=allowedDirections},
Sets a directional condition on a tile @param {Number} x The x value of the point. @param {Number} y The y value of the point. @param {Array.<String>} allowedDirections A list of all the allowed directions that can access the tile. *
this.setDirectionalCondition ( x , y , allowedDirections )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.setIterationsPerCalculation=function(iterations){iterationsPerCalculation=iterations},
Sets the number of search iterations per calculation. A lower number provides a slower result, but more practical if you have a large tile-map and don't want to block your thread while finding a path. @param {Number} iterations The number of searches to prefrom per calculate() call. *
this.setIterationsPerCalculation ( iterations )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.avoidAdditionalPoint=function(x,y){void 0===pointsToAvoid[y]&&(pointsToAvoid[y]={}),pointsToAvoid[y][x]=1},
Avoid a particular point on the grid, regardless of whether or not it is an acceptable tile. @param {Number} x The x value of the point to avoid. @param {Number} y The y value of the point to avoid. *
this.avoidAdditionalPoint ( x , y )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.stopAvoidingAdditionalPoint=function(x,y){void 0!==pointsToAvoid[y]&&delete pointsToAvoid[y][x]},
Stop avoiding a particular point on the grid. @param {Number} x The x value of the point to stop avoiding. @param {Number} y The y value of the point to stop avoiding. *
this.stopAvoidingAdditionalPoint ( x , y )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.enableCornerCutting=function(){allowCornerCutting=!0},
Enables corner cutting in diagonal movement. *
this.enableCornerCutting ( )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.disableCornerCutting=function(){allowCornerCutting=!1},
Disables corner cutting in diagonal movement. *
this.disableCornerCutting ( )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.stopAvoidingAllAdditionalPoints=function(){pointsToAvoid={}},
Stop avoiding all additional points on the grid. *
this.stopAvoidingAllAdditionalPoints ( )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.findPath=function(startX,startY,endX,endY,callback){ // Wraps the callback for sync vs async logic var callbackWrapper=function(result){syncEnabled?callback(result):setTimeout((function(){callback(result)}))};// No acceptable tiles were set if(void 0===acceptableTiles)throw new Error("You can't set a path without first calling setAcceptableTiles() on EasyStar.");// No grid was set if(void 0===collisionGrid)throw new Error("You can't set a path without first calling setGrid() on EasyStar.");// Start or endpoint outside of scope. if(startX<0||startY<0||endX<0||endY<0||startX>collisionGrid[0].length-1||startY>collisionGrid.length-1||endX>collisionGrid[0].length-1||endY>collisionGrid.length-1)throw new Error("Your start or end point is outside the scope of your grid.");// Start and end are the same tile. if(startX!==endX||startY!==endY){for(// End point is not an acceptable tile. var endTile=collisionGrid[endY][endX],isAcceptable=!1,i=0;i<acceptableTiles.length;i++)if(endTile===acceptableTiles[i]){isAcceptable=!0;break}if(!1!==isAcceptable){// Create the instance var instance=new Instance;instance.openList=new Heap((function(nodeA,nodeB){return nodeA.bestGuessDistance()-nodeB.bestGuessDistance()})),instance.isDoneCalculating=!1,instance.nodeHash={},instance.startX=startX,instance.startY=startY,instance.endX=endX,instance.endY=endY,instance.callback=callbackWrapper,instance.openList.push(coordinateToNode(instance,instance.startX,instance.startY,null,1));var instanceId=nextInstanceId++;return instances[instanceId]=instance,instanceQueue.push(instanceId),instanceId}callbackWrapper(null)}else callbackWrapper([])},
Find a path. @param {Number} startX The X position of the starting point. @param {Number} startY The Y position of the starting point. @param {Number} endX The X position of the ending point. @param {Number} endY The Y position of the ending point. @param {Function} callback A function that is called when your path is found, or no path is found. @return {Number} A numeric, non-zero value which identifies the created instance. This value can be passed to cancelPath to cancel the path calculation. *
this.findPath ( startX , startY , endX , endY , callback )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.cancelPath=function(instanceId){return instanceId in instances&&(delete instances[instanceId],!0)},
Cancel a path calculation. @param {Number} instanceId The instance ID of the path being calculated @return {Boolean} True if an instance was found and cancelled. *
this.cancelPath ( instanceId )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.calculate=function(){if(0!==instanceQueue.length&&void 0!==collisionGrid&&void 0!==acceptableTiles)for(iterationsSoFar=0;iterationsSoFar<iterationsPerCalculation;iterationsSoFar++){if(0===instanceQueue.length)return;syncEnabled&&( // If this is a sync instance, we want to make sure that it calculates synchronously. iterationsSoFar=0);var instanceId=instanceQueue[0],instance=instances[instanceId];if(void 0!==instance)// Couldn't find a path. if(0!==instance.openList.size()){var searchNode=instance.openList.pop();// Handles the case where we have found the destination if(instance.endX!==searchNode.x||instance.endY!==searchNode.y)searchNode.list=0,searchNode.y>0&&checkAdjacentNode(instance,searchNode,0,-1,1*getTileCost(searchNode.x,searchNode.y-1)),searchNode.x<collisionGrid[0].length-1&&checkAdjacentNode(instance,searchNode,1,0,1*getTileCost(searchNode.x+1,searchNode.y)),searchNode.y<collisionGrid.length-1&&checkAdjacentNode(instance,searchNode,0,1,1*getTileCost(searchNode.x,searchNode.y+1)),searchNode.x>0&&checkAdjacentNode(instance,searchNode,-1,0,1*getTileCost(searchNode.x-1,searchNode.y)),diagonalsEnabled&&(searchNode.x>0&&searchNode.y>0&&(allowCornerCutting||isTileWalkable(collisionGrid,acceptableTiles,searchNode.x,searchNode.y-1,searchNode)&&isTileWalkable(collisionGrid,acceptableTiles,searchNode.x-1,searchNode.y,searchNode))&&checkAdjacentNode(instance,searchNode,-1,-1,1.4*getTileCost(searchNode.x-1,searchNode.y-1)),searchNode.x<collisionGrid[0].length-1&&searchNode.y<collisionGrid.length-1&&(allowCornerCutting||isTileWalkable(collisionGrid,acceptableTiles,searchNode.x,searchNode.y+1,searchNode)&&isTileWalkable(collisionGrid,acceptableTiles,searchNode.x+1,searchNode.y,searchNode))&&checkAdjacentNode(instance,searchNode,1,1,1.4*getTileCost(searchNode.x+1,searchNode.y+1)),searchNode.x<collisionGrid[0].length-1&&searchNode.y>0&&(allowCornerCutting||isTileWalkable(collisionGrid,acceptableTiles,searchNode.x,searchNode.y-1,searchNode)&&isTileWalkable(collisionGrid,acceptableTiles,searchNode.x+1,searchNode.y,searchNode))&&checkAdjacentNode(instance,searchNode,1,-1,1.4*getTileCost(searchNode.x+1,searchNode.y-1)),searchNode.x>0&&searchNode.y<collisionGrid.length-1&&(allowCornerCutting||isTileWalkable(collisionGrid,acceptableTiles,searchNode.x,searchNode.y+1,searchNode)&&isTileWalkable(collisionGrid,acceptableTiles,searchNode.x-1,searchNode.y,searchNode))&&checkAdjacentNode(instance,searchNode,-1,1,1.4*getTileCost(searchNode.x-1,searchNode.y+1)));else{var path=[];path.push({x:searchNode.x,y:searchNode.y});for(var parent=searchNode.parent;null!=parent;)path.push({x:parent.x,y:parent.y}),parent=parent.parent;path.reverse();var ip=path;instance.callback(ip),delete instances[instanceId],instanceQueue.shift()}}else instance.callback(null),delete instances[instanceId],instanceQueue.shift();else // This instance was cancelled instanceQueue.shift()}};// Private methods follow
This method steps through the A* Algorithm in an attempt to find your path(s). It will search 4-8 tiles (depending on diagonals) for every calculation. You can change the number of calculations done in a call by using easystar.setIteratonsPerCalculation(). *
this.calculate ( )
javascript
prettymuchbryce/easystarjs
bin/easystar-0.4.4.js
https://github.com/prettymuchbryce/easystarjs/blob/master/bin/easystar-0.4.4.js
MIT
this.bestGuessDistance = function() { return this.costSoFar + this.simpleDistanceToTarget; }
@return {Number} Best guess distance of a cost using this node. *
this.bestGuessDistance ( )
javascript
prettymuchbryce/easystarjs
src/node.js
https://github.com/prettymuchbryce/easystarjs/blob/master/src/node.js
MIT
module.exports = function(parent, x, y, costSoFar, simpleDistanceToTarget) { this.parent = parent; this.x = x; this.y = y; this.costSoFar = costSoFar; this.simpleDistanceToTarget = simpleDistanceToTarget; /** * @return {Number} Best guess distance of a cost using this node. **/ this.bestGuessDistance = function() { return this.costSoFar + this.simpleDistanceToTarget; } };
A simple Node that represents a single tile on the grid. @param {Object} parent The parent node. @param {Number} x The x position on the grid. @param {Number} y The y position on the grid. @param {Number} costSoFar How far this node is in moves*cost from the start. @param {Number} simpleDistanceToTarget Manhatten distance to the end point. *
module.exports ( parent , x , y , costSoFar , simpleDistanceToTarget )
javascript
prettymuchbryce/easystarjs
src/node.js
https://github.com/prettymuchbryce/easystarjs/blob/master/src/node.js
MIT
var calculateDirection = function (diffX, diffY) { if (diffX === 0 && diffY === -1) return EasyStar.TOP else if (diffX === 1 && diffY === -1) return EasyStar.TOP_RIGHT else if (diffX === 1 && diffY === 0) return EasyStar.RIGHT else if (diffX === 1 && diffY === 1) return EasyStar.BOTTOM_RIGHT else if (diffX === 0 && diffY === 1) return EasyStar.BOTTOM else if (diffX === -1 && diffY === 1) return EasyStar.BOTTOM_LEFT else if (diffX === -1 && diffY === 0) return EasyStar.LEFT else if (diffX === -1 && diffY === -1) return EasyStar.TOP_LEFT throw new Error('These differences are not valid: ' + diffX + ', ' + diffY) };
-1, -1 | 0, -1 | 1, -1 -1, 0 | SOURCE | 1, 0 -1, 1 | 0, 1 | 1, 1
calculateDirection ( diffX , diffY )
javascript
prettymuchbryce/easystarjs
src/easystar.js
https://github.com/prettymuchbryce/easystarjs/blob/master/src/easystar.js
MIT
module.exports = function() { this.pointsToAvoid = {}; this.startX; this.callback; this.startY; this.endX; this.endY; this.nodeHash = {}; this.openList; };
Represents a single instance of EasyStar. A path that is in the queue to eventually be found.
module.exports ( )
javascript
prettymuchbryce/easystarjs
src/instance.js
https://github.com/prettymuchbryce/easystarjs/blob/master/src/instance.js
MIT
function hasCompleteOverlap(start1, end1, start2, end2) { // If the starting and end positions are exactly the same // then the first one should stay and this one should be ignored. if (start2 === start1 && end2 === end1) { return false; } return start2 <= start1 && end2 >= end1; }
Determines if two different matches have complete overlap with each other @param {number} start1 start position of existing match @param {number} end1 end position of existing match @param {number} start2 start position of new match @param {number} end2 end position of new match @return {boolean}
hasCompleteOverlap ( start1 , end1 , start2 , end2 )
javascript
ccampbell/rainbow
dist/rainbow.js
https://github.com/ccampbell/rainbow/blob/master/dist/rainbow.js
Apache-2.0
function _generateHandler(element, waitingOn, callback) { return function _handleResponseFromWorker(data) { element.innerHTML = data.result; element.classList.remove('loading'); element.classList.add('rainbow-show'); if (element.parentNode.tagName === 'PRE') { element.parentNode.classList.remove('loading'); element.parentNode.classList.add('rainbow-show'); } // element.addEventListener('animationend', (e) => { // if (e.animationName === 'fade-in') { // setTimeout(() => { // element.classList.remove('decrease-delay'); // }, 1000); // } // }); if (onHighlightCallback) { onHighlightCallback(element, data.lang); } if (--waitingOn.c === 0) { callback(); }
Browser Only - Handles response from web worker, updates DOM with resulting code, and fires callback @param {Element} element @param {object} waitingOn @param {Function} callback @return {void}
_handleResponseFromWorker ( data )
javascript
ccampbell/rainbow
dist/rainbow.js
https://github.com/ccampbell/rainbow/blob/master/dist/rainbow.js
Apache-2.0
function _highlight(node, callback) {
Browser Only - Start highlighting all the code blocks @param {Element} node HTMLElement to search within @param {Function} callback @return {void}
callback ( )
javascript
ccampbell/rainbow
dist/rainbow.js
https://github.com/ccampbell/rainbow/blob/master/dist/rainbow.js
Apache-2.0
function _messageWorker(message, callback) { const worker = _getWorker(); function _listen(e) { if (e.data.id === message.id) { callback(e.data); worker.removeEventListener('message', _listen); // I realized down the road I might look at this and wonder what is going on // so probably it is not a bad idea to leave a comment. // // This is needed because right now the node library for simulating web // workers “web-worker” will keep the worker open and it causes // scripts running from the command line to hang unless the worker is // explicitly closed. // // This means for node we will spawn a new thread for every asynchronous // block we are highlighting, but in the browser we will keep a single // worker open for all requests. if (isNode) { worker.terminate(); } } } worker.addEventListener('message', _listen); worker.postMessage(message); }
Helper for matching up callbacks directly with the post message requests to a web worker. @param {object} message data to send to web worker @param {Function} callback callback function for worker to reply to @return {void}
_messageWorker ( message , callback )
javascript
ccampbell/rainbow
src/rainbow.js
https://github.com/ccampbell/rainbow/blob/master/src/rainbow.js
Apache-2.0
function _highlightCodeBlocks(codeBlocks, callback) { const waitingOn = { c: 0 }; for (const block of codeBlocks) { const language = getLanguageForBlock(block); if (block.classList.contains('rainbow') || !language) { continue; } // This cancels the pending animation to fade the code in on load // since we want to delay doing this until it is actually // highlighted block.classList.add('loading'); block.classList.add('rainbow'); // We need to make sure to also add the loading class to the pre tag // because that is how we will know to show a preloader if (block.parentNode.tagName === 'PRE') { block.parentNode.classList.add('loading'); } const globalClass = block.getAttribute('data-global-class'); const delay = parseInt(block.getAttribute('data-delay'), 10); ++waitingOn.c; _messageWorker(_getWorkerData(block.innerHTML, { language, globalClass, delay }), _generateHandler(block, waitingOn, callback)); } if (waitingOn.c === 0) { callback(); } }
Browser Only - Sends messages to web worker to highlight elements passed in @param {Array} codeBlocks @param {Function} callback @return {void}
_highlightCodeBlocks ( codeBlocks , callback )
javascript
ccampbell/rainbow
src/rainbow.js
https://github.com/ccampbell/rainbow/blob/master/src/rainbow.js
Apache-2.0
function onHighlight(callback) { onHighlightCallback = callback; }
Callback to let you do stuff in your app after a piece of code has been highlighted @param {Function} callback @return {void}
onHighlight ( callback )
javascript
ccampbell/rainbow
src/rainbow.js
https://github.com/ccampbell/rainbow/blob/master/src/rainbow.js
Apache-2.0
function extend(language, languagePatterns, inherits) { // If we extend a language again we shouldn't need to specify the // inheritence for it. For example, if you are adding special highlighting // for a javascript function that is not in the base javascript rules, you // should be able to do // // Rainbow.extend('javascript', [ … ]); // // Without specifying a language it should inherit (generic in this case) if (!inheritenceMap[language]) { inheritenceMap[language] = inherits; } patterns[language] = languagePatterns.concat(patterns[language] || []); }
Extends the language pattern matches @param {string} language name of language @param {object} languagePatterns object of patterns to add on @param {string|undefined} inherits optional language that this language should inherit rules from
extend ( language , languagePatterns , inherits )
javascript
ccampbell/rainbow
src/rainbow.js
https://github.com/ccampbell/rainbow/blob/master/src/rainbow.js
Apache-2.0
function color(...args) { // If you want to straight up highlight a string you can pass the // string of code, the language, and a callback function. // // Example: // // Rainbow.color(code, language, function(highlightedCode, language) { // // this code block is now highlighted // }); if (typeof args[0] === 'string') { const workerData = _getWorkerData(args[0], args[1]); _messageWorker(workerData, (function(cb) { return function(data) { if (cb) { cb(data.result, data.lang); } }; }(args[2]))); return; } // If you pass a callback function then we rerun the color function // on all the code and call the callback function on complete. // // Example: // // Rainbow.color(function() { // console.log('All matching tags on the page are now highlighted'); // }); if (typeof args[0] === 'function') { _highlight(0, args[0]); return; } // Otherwise we use whatever node you passed in with an optional // callback function as the second parameter. // // Example: // // var preElement = document.createElement('pre'); // var codeElement = document.createElement('code'); // codeElement.setAttribute('data-language', 'javascript'); // codeElement.innerHTML = '// Here is some JavaScript'; // preElement.appendChild(codeElement); // Rainbow.color(preElement, function() { // // New element is now highlighted // }); // // If you don't pass an element it will default to `document` _highlight(args[0], args[1]); }
Starts the magic rainbow @return {void}
color ( ... args )
javascript
ccampbell/rainbow
src/rainbow.js
https://github.com/ccampbell/rainbow/blob/master/src/rainbow.js
Apache-2.0
function addAlias(alias, originalLanguage) { aliases[alias] = originalLanguage; }
Method to add an alias for an existing language. For example if you want to have "coffee" map to "coffeescript" @see https://github.com/ccampbell/rainbow/issues/154 @param {string} alias @param {string} originalLanguage @return {void}
addAlias ( alias , originalLanguage )
javascript
ccampbell/rainbow
src/rainbow.js
https://github.com/ccampbell/rainbow/blob/master/src/rainbow.js
Apache-2.0
export function htmlEntities(code) { return code.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&(?![\w\#]+;)/g, '&amp;'); } /** * Finds out the position of group match for a regular expression * * @see http://stackoverflow.com/questions/1985594/how-to-find-index-of-groups-in-match * @param {Object} match * @param {number} groupNumber * @return {number} */ export function indexOfGroup(match, groupNumber) { let index = 0; for (let i = 1; i < groupNumber; ++i) { if (match[i]) { index += match[i].length; } } return index; } /** * Determines if a new match intersects with an existing one * * @param {number} start1 start position of existing match * @param {number} end1 end position of existing match * @param {number} start2 start position of new match * @param {number} end2 end position of new match * @return {boolean} */ export function intersects(start1, end1, start2, end2) { if (start2 >= start1 && start2 < end1) { return true; } return end2 > start1 && end2 < end1; } /** * Sorts an objects keys by index descending * * @param {Object} object * @return {Array} */ export function keys(object) { const locations = []; for (const location in object) { if (object.hasOwnProperty(location)) { locations.push(location); } } // numeric descending return locations.sort((a, b) => b - a); } /** * Substring replace call to replace part of a string at a certain position * * @param {number} position the position where the replacement * should happen * @param {string} replace the text we want to replace * @param {string} replaceWith the text we want to replace it with * @param {string} code the code we are doing the replacing in * @return {string} */ export function replaceAtPosition(position, replace, replaceWith, code) { const subString = code.substr(position); // This is needed to fix an issue where $ signs do not render in the // highlighted code // // @see https://github.com/ccampbell/rainbow/issues/208 replaceWith = replaceWith.replace(/\$/g, '$$$$'); return code.substr(0, position) + subString.replace(replace, replaceWith); } /** * Creates a usable web worker from an anonymous function * * mostly borrowed from https://github.com/zevero/worker-create * * @param {Function} fn * @param {Prism} Prism * @return {Worker} */
Encodes < and > as html entities @param {string} code @return {string}
htmlEntities ( code )
javascript
ccampbell/rainbow
src/util.js
https://github.com/ccampbell/rainbow/blob/master/src/util.js
Apache-2.0
function _matchIsInsideOtherMatch(start, end) { for (let key in replacementPositions) { key = parseInt(key, 10); // If this block completely overlaps with another block // then we should remove the other block and return `false`. if (hasCompleteOverlap(key, replacementPositions[key], start, end)) { delete replacementPositions[key]; delete replacements[key]; } if (intersects(key, replacementPositions[key], start, end)) { return true; } } return false; }
Determines if the match passed in falls inside of an existing match. This prevents a regex pattern from matching inside of another pattern that matches a larger amount of code. For example this prevents a keyword from matching `function` if there is already a match for `function (.*)`. @param {number} start start position of new match @param {number} end end position of new match @return {boolean}
_matchIsInsideOtherMatch ( start , end )
javascript
ccampbell/rainbow
src/prism.js
https://github.com/ccampbell/rainbow/blob/master/src/prism.js
Apache-2.0
function _wrapCodeInSpan(name, code) { let className = name.replace(/\./g, ' '); const globalClass = options.globalClass; if (globalClass) { className += ` ${globalClass}`; } return `<span class="${className}">${code}</span>`; }
Takes a string of code and wraps it in a span tag based on the name @param {string} name name of the pattern (ie keyword.regex) @param {string} code block of code to wrap @param {string} globalClass class to apply to every span @return {string}
_wrapCodeInSpan ( name , code )
javascript
ccampbell/rainbow
src/prism.js
https://github.com/ccampbell/rainbow/blob/master/src/prism.js
Apache-2.0
function _processReplacements(code) { const positions = keys(replacements); for (const position of positions) { const replacement = replacements[position]; code = replaceAtPosition(position, replacement.replace, replacement.with, code); } return code; }
Process replacements in the string of code to actually update the markup @param {string} code the code to process replacements in @return {string}
_processReplacements ( code )
javascript
ccampbell/rainbow
src/prism.js
https://github.com/ccampbell/rainbow/blob/master/src/prism.js
Apache-2.0
function _cloneRegex(regex) { let flags = ''; if (regex.ignoreCase) { flags += 'i'; } if (regex.multiline) { flags += 'm'; } return new RegExp(regex.source, flags); }
It is so we can create a new regex object for each call to _processPattern to avoid state carrying over when running exec multiple times. The global flag should not be carried over because we are simulating it by processing the regex in a loop so we only care about the first match in each string. This also seems to improve performance quite a bit. @param {RegExp} regex @return {string}
_cloneRegex ( regex )
javascript
ccampbell/rainbow
src/prism.js
https://github.com/ccampbell/rainbow/blob/master/src/prism.js
Apache-2.0
function _processCodeWithPatterns(code, patterns) { for (const pattern of patterns) { let result = _processPattern(pattern, code); while (result) { result = _processPattern(pattern, result.remaining, result.offset); } } // We are done processing the patterns so we should actually replace // what needs to be replaced in the code. return _processReplacements(code); }
Processes a block of code using specified patterns @param {string} code @param {Array} patterns @return {string}
_processCodeWithPatterns ( code , patterns )
javascript
ccampbell/rainbow
src/prism.js
https://github.com/ccampbell/rainbow/blob/master/src/prism.js
Apache-2.0
function getPatternsForLanguage(language) { let patterns = options.patterns[language] || []; while (options.inheritenceMap[language]) { language = options.inheritenceMap[language]; patterns = patterns.concat(options.patterns[language] || []); } return patterns; }
Returns a list of regex patterns for this language @param {string} language @return {Array}
getPatternsForLanguage ( language )
javascript
ccampbell/rainbow
src/prism.js
https://github.com/ccampbell/rainbow/blob/master/src/prism.js
Apache-2.0
function _highlightBlockForLanguage(code, language, patterns) { currentLanguage = language; patterns = patterns || getPatternsForLanguage(language); return _processCodeWithPatterns(htmlEntities(code), patterns); }
Takes a string of code and highlights it according to the language specified @param {string} code @param {string} language @param {object} patterns optionally specify a list of patterns @return {string}
_highlightBlockForLanguage ( code , language , patterns )
javascript
ccampbell/rainbow
src/prism.js
https://github.com/ccampbell/rainbow/blob/master/src/prism.js
Apache-2.0
const _getReplacement = function(passedBlock, replaceBlock, matchName) { replacement = replaceAtPosition(indexOfGroup(match, groupKey), passedBlock, matchName ? _wrapCodeInSpan(matchName, replaceBlock) : replaceBlock, replacement); return; }; // If this is a string then this match is directly mapped // to selector so all we have to do is wrap it in a span // and continue. if (typeof group === 'string') { _getReplacement(block, block, group); return; } let localCode; const prism = new Prism(options); // If this is a sublanguage go and process the block using // that language if (language) { localCode = prism.refract(block, language); _getReplacement(block, localCode); return; } // The process group can be a single pattern or an array of // patterns. `_processCodeWithPatterns` always expects an array // so we convert it here. localCode = prism.refract(block, currentLanguage, groupToProcess.length ? groupToProcess : [groupToProcess]); _getReplacement(block, localCode, group.matches ? group.name : 0); } // If this pattern has sub matches for different groups in the regex // then we should process them one at a time by running them through // the _processGroup function to generate the new replacement. // // We use the `keys` function to run through them backwards because // the match position of earlier matches will not change depending // on what gets replaced in later matches. const groupKeys = keys(pattern.matches); for (const groupKey of groupKeys) { _processGroup(groupKey); } // Finally, call `onMatchSuccess` with the replacement return onMatchSuccess(replacement); } /** * Processes a block of code using specified patterns * * @param {string} code * @param {Array} patterns * @return {string} */ function _processCodeWithPatterns(code, patterns) { for (const pattern of patterns) { let result = _processPattern(pattern, code); while (result) { result = _processPattern(pattern, result.remaining, result.offset); } } // We are done processing the patterns so we should actually replace // what needs to be replaced in the code. return _processReplacements(code); } /** * Returns a list of regex patterns for this language * * @param {string} language * @return {Array} */ function getPatternsForLanguage(language) { let patterns = options.patterns[language] || []; while (options.inheritenceMap[language]) { language = options.inheritenceMap[language]; patterns = patterns.concat(options.patterns[language] || []); } return patterns; } /** * Takes a string of code and highlights it according to the language * specified * * @param {string} code * @param {string} language * @param {object} patterns optionally specify a list of patterns * @return {string} */ function _highlightBlockForLanguage(code, language, patterns) { currentLanguage = language; patterns = patterns || getPatternsForLanguage(language); return _processCodeWithPatterns(htmlEntities(code), patterns); } this.refract = _highlightBlockForLanguage; }
Takes the code block matched at this group, replaces it with the highlighted block, and optionally wraps it with a span with a name @param {string} passedBlock @param {string} replaceBlock @param {string|null} matchName
_getReplacement ( passedBlock , replaceBlock , matchName )
javascript
ccampbell/rainbow
src/prism.js
https://github.com/ccampbell/rainbow/blob/master/src/prism.js
Apache-2.0
function _processGroup(groupKey) { const block = match[groupKey]; // If there is no match here then move on if (!block) { return; } const group = pattern.matches[groupKey]; const language = group.language; /** * Process group is what group we should use to actually process * this match group. * * For example if the subgroup pattern looks like this: * * 2: { * 'name': 'keyword', * 'pattern': /true/g * } * * then we use that as is, but if it looks like this: * * 2: { * 'name': 'keyword', * 'matches': { * 'name': 'special', * 'pattern': /whatever/g * } * } * * we treat the 'matches' part as the pattern and keep * the name around to wrap it with later */ const groupToProcess = group.name && group.matches ? group.matches : group; /** * Takes the code block matched at this group, replaces it * with the highlighted block, and optionally wraps it with * a span with a name * * @param {string} passedBlock * @param {string} replaceBlock * @param {string|null} matchName */ const _getReplacement = function(passedBlock, replaceBlock, matchName) { replacement = replaceAtPosition(indexOfGroup(match, groupKey), passedBlock, matchName ? _wrapCodeInSpan(matchName, replaceBlock) : replaceBlock, replacement); return; }; // If this is a string then this match is directly mapped // to selector so all we have to do is wrap it in a span // and continue. if (typeof group === 'string') { _getReplacement(block, block, group); return; } let localCode; const prism = new Prism(options); // If this is a sublanguage go and process the block using // that language if (language) { localCode = prism.refract(block, language); _getReplacement(block, localCode); return; } // The process group can be a single pattern or an array of // patterns. `_processCodeWithPatterns` always expects an array // so we convert it here. localCode = prism.refract(block, currentLanguage, groupToProcess.length ? groupToProcess : [groupToProcess]); _getReplacement(block, localCode, group.matches ? group.name : 0); } // If this pattern has sub matches for different groups in the regex // then we should process them one at a time by running them through // the _processGroup function to generate the new replacement. // // We use the `keys` function to run through them backwards because // the match position of earlier matches will not change depending // on what gets replaced in later matches. const groupKeys = keys(pattern.matches); for (const groupKey of groupKeys) { _processGroup(groupKey); } // Finally, call `onMatchSuccess` with the replacement return onMatchSuccess(replacement); } /** * Processes a block of code using specified patterns * * @param {string} code * @param {Array} patterns * @return {string} */ function _processCodeWithPatterns(code, patterns) { for (const pattern of patterns) { let result = _processPattern(pattern, code); while (result) { result = _processPattern(pattern, result.remaining, result.offset); } } // We are done processing the patterns so we should actually replace // what needs to be replaced in the code. return _processReplacements(code); } /** * Returns a list of regex patterns for this language * * @param {string} language * @return {Array} */ function getPatternsForLanguage(language) { let patterns = options.patterns[language] || []; while (options.inheritenceMap[language]) { language = options.inheritenceMap[language]; patterns = patterns.concat(options.patterns[language] || []); } return patterns; } /** * Takes a string of code and highlights it according to the language * specified * * @param {string} code * @param {string} language * @param {object} patterns optionally specify a list of patterns * @return {string} */ function _highlightBlockForLanguage(code, language, patterns) { currentLanguage = language; patterns = patterns || getPatternsForLanguage(language); return _processCodeWithPatterns(htmlEntities(code), patterns); } this.refract = _highlightBlockForLanguage; } }
Helper function for processing a sub group @param {number} groupKey index of group @return {void}
_processGroup ( groupKey )
javascript
ccampbell/rainbow
src/prism.js
https://github.com/ccampbell/rainbow/blob/master/src/prism.js
Apache-2.0
function getAdditionalModulePaths(options = {}) { const baseUrl = options.baseUrl; // We need to explicitly check for null and undefined (and not a falsy value) because // TypeScript treats an empty string as `.`. if (baseUrl == null) { // If there's no baseUrl set we respect NODE_PATH // Note that NODE_PATH is deprecated and will be removed // in the next major release of create-react-app. const nodePath = process.env.NODE_PATH || ''; return nodePath.split(path.delimiter).filter(Boolean); } const baseUrlResolved = path.resolve(paths.appPath, baseUrl); // We don't need to do anything if `baseUrl` is set to `node_modules`. This is // the default behavior. if (path.relative(paths.appNodeModules, baseUrlResolved) === '') { return null; } // Allow the user set the `baseUrl` to `appSrc`. if (path.relative(paths.appSrc, baseUrlResolved) === '') { return [paths.appSrc]; } // If the path is equal to the root directory we ignore it here. // We don't want to allow importing from the root directly as source files are // not transpiled outside of `src`. We do allow importing them with the // absolute path (e.g. `src/Components/Button.js`) but we set that up with // an alias. if (path.relative(paths.appPath, baseUrlResolved) === '') { return null; } // Otherwise, throw an error. throw new Error( chalk.red.bold( "Your project's `baseUrl` can only be set to `src` or `node_modules`." + ' Create React App does not support other values at this time.' ) ); }
Get additional module paths based on the baseUrl of a compilerOptions object. @param {Object} options
getAdditionalModulePaths ( options = { } )
javascript
sanyuan0704/react-cloud-music
ts-music/config/modules.js
https://github.com/sanyuan0704/react-cloud-music/blob/master/ts-music/config/modules.js
MIT
function getWebpackAliases(options = {}) { const baseUrl = options.baseUrl; if (!baseUrl) { return {}; } const baseUrlResolved = path.resolve(paths.appPath, baseUrl); if (path.relative(paths.appPath, baseUrlResolved) === '') { return { src: paths.appSrc, }; } }
Get webpack aliases based on the baseUrl of a compilerOptions object. @param {*} options
getWebpackAliases ( options = { } )
javascript
sanyuan0704/react-cloud-music
ts-music/config/modules.js
https://github.com/sanyuan0704/react-cloud-music/blob/master/ts-music/config/modules.js
MIT
function getJestAliases(options = {}) { const baseUrl = options.baseUrl; if (!baseUrl) { return {}; } const baseUrlResolved = path.resolve(paths.appPath, baseUrl); if (path.relative(paths.appPath, baseUrlResolved) === '') { return { '^src/(.*)$': '<rootDir>/src/$1', }; } }
Get jest aliases based on the baseUrl of a compilerOptions object. @param {*} options
getJestAliases ( options = { } )
javascript
sanyuan0704/react-cloud-music
ts-music/config/modules.js
https://github.com/sanyuan0704/react-cloud-music/blob/master/ts-music/config/modules.js
MIT
function getAdditionalModulePaths(options = {}) { const baseUrl = options.baseUrl; // We need to explicitly check for null and undefined (and not a falsy value) because // TypeScript treats an empty string as `.`. if (baseUrl == null) { // If there's no baseUrl set we respect NODE_PATH // Note that NODE_PATH is deprecated and will be removed // in the next major release of create-react-app. const nodePath = process.env.NODE_PATH || ''; return nodePath.split(path.delimiter).filter(Boolean); } const baseUrlResolved = path.resolve(paths.appPath, baseUrl); // We don't need to do anything if `baseUrl` is set to `node_modules`. This is // the default behavior. if (path.relative(paths.appNodeModules, baseUrlResolved) === '') { return null; } // Allow the user set the `baseUrl` to `appSrc`. if (path.relative(paths.appSrc, baseUrlResolved) === '') { return [paths.appSrc]; } // Otherwise, throw an error. throw new Error( chalk.red.bold( "Your project's `baseUrl` can only be set to `src` or `node_modules`." + ' Create React App does not support other values at this time.' ) ); }
Get the baseUrl of a compilerOptions object. @param {Object} options
getAdditionalModulePaths ( options = { } )
javascript
sanyuan0704/react-cloud-music
config/modules.js
https://github.com/sanyuan0704/react-cloud-music/blob/master/config/modules.js
MIT
expectErrors(expectedErrors) { if (expectedErrors instanceof Array) { this.expectedErrors = this.expectedErrors.concat(expectedErrors); } else { this.expectedErrors.push(expectedErrors); } return this; }
Add expected error(s) for the test command. Input is an object or list of objects of the following form: { message: string, // optional regex stackTrace: string, //optional regex }
expectErrors ( expectedErrors )
javascript
angular/protractor
scripts/test/test_util.js
https://github.com/angular/protractor/blob/master/scripts/test/test_util.js
MIT
describe('synchronizing with pages that poll', () => { beforeEach(async () => { await browser.get('index.html#/polling'); }); it('avoids timeouts using waitForAngularEnabled set to false', async () => { const startButton = element(by.id('pollstarter')); const count = element(by.binding('count')); expect(await count.getText()).toEqual('0'); await startButton.click(); // Turn this on to see timeouts. await browser.waitForAngularEnabled(false); const textBefore = await count.getText(); expect(textBefore).toBeGreaterThan(-1); await browser.sleep(2000); const textAfter = await count.getText(); expect(textAfter).toBeGreaterThan(1); }); it('avoids timeouts using waitForAngularEnabled', async () => { const startButton = element(by.id('pollstarter')); const count = element(by.binding('count')); expect(await count.getText()).toEqual('0'); await startButton.click(); // Turn this off to see timeouts. await browser.waitForAngularEnabled(false); expect(await browser.waitForAngularEnabled()).toBeFalsy(); const textBefore = await count.getText(); expect(textBefore).toBeGreaterThan(-1); await browser.sleep(2000); const textAfter = await count.getText(); expect(textAfter).toBeGreaterThan(1); }); afterEach(async () => { // Remember to turn it back on when you're done! await browser.waitForAngularEnabled(true); }); });
These tests show how to turn off Protractor's synchronization when using applications which poll with $http or $timeout. A better solution is to switch to the angular $interval service if possible.
(anonymous)
javascript
angular/protractor
spec/basic/polling_spec.js
https://github.com/angular/protractor/blob/master/spec/basic/polling_spec.js
MIT
functions.waitForAngular = function(rootSelector, callback) { try { // Wait for both angular1 testability and angular2 testability. var testCallback = callback; // Wait for angular1 testability first and run waitForAngular2 as a callback var waitForAngular1 = function(callback) { if (window.angular) { var hooks = getNg1Hooks(rootSelector); if (!hooks){ callback(); // not an angular1 app } else{ if (hooks.$$testability) { hooks.$$testability.whenStable(callback); } else if (hooks.$injector) { hooks.$injector.get('$browser') .notifyWhenNoOutstandingRequests(callback); } else if (!rootSelector) { throw new Error( 'Could not automatically find injector on page: "' + window.location.toString() + '". Consider using config.rootEl'); } else { throw new Error( 'root element (' + rootSelector + ') has no injector.' + ' this may mean it is not inside ng-app.'); } } } else {callback();} // not an angular1 app }; // Wait for Angular2 testability and then run test callback var waitForAngular2 = function() { if (window.getAngularTestability) { if (rootSelector) { var testability = null; var el = document.querySelector(rootSelector); try{ testability = window.getAngularTestability(el); } catch(e){} if (testability) { testability.whenStable(testCallback); return; } } // Didn't specify root element or testability could not be found // by rootSelector. This may happen in a hybrid app, which could have // more than one root. var testabilities = window.getAllAngularTestabilities(); var count = testabilities.length; // No angular2 testability, this happens when // going to a hybrid page and going back to a pure angular1 page if (count === 0) { testCallback(); return; } var decrement = function() { count--; if (count === 0) { testCallback(); } }; testabilities.forEach(function(testability) { testability.whenStable(decrement); }); } else {testCallback();} // not an angular2 app }; if (!(window.angular) && !(window.getAngularTestability)) { // no testability hook throw new Error( 'both angularJS testability and angular testability are undefined.' + ' This could be either ' + 'because this is a non-angular page or because your test involves ' + 'client-side navigation, which can interfere with Protractor\'s ' + 'bootstrapping. See http://git.io/v4gXM for details'); } else {waitForAngular1(waitForAngular2);} // Wait for angular1 and angular2 // Testability hooks sequentially } catch (err) { callback(err.message); } };
Wait until Angular has finished rendering and has no outstanding $http calls before continuing. The specific Angular app is determined by the rootSelector. Asynchronous. @param {string} rootSelector The selector housing an ng-app @param {function(string)} callback callback. If a failure occurs, it will be passed as a parameter.
functions.waitForAngular ( rootSelector , callback )
javascript
angular/protractor
lib/clientsidescripts.js
https://github.com/angular/protractor/blob/master/lib/clientsidescripts.js
MIT
functions.findBindings = function(binding, exactMatch, using, rootSelector) { using = using || document; if (angular.getTestability) { return getNg1Hooks(rootSelector).$$testability. findBindings(using, binding, exactMatch); } var bindings = using.getElementsByClassName('ng-binding'); var matches = []; for (var i = 0; i < bindings.length; ++i) { var dataBinding = angular.element(bindings[i]).data('$binding'); if (dataBinding) { var bindingName = dataBinding.exp || dataBinding[0].exp || dataBinding; if (exactMatch) { var matcher = new RegExp('({|\\s|^|\\|)' + /* See http://stackoverflow.com/q/3561711 */ binding.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&') + '(}|\\s|$|\\|)'); if (matcher.test(bindingName)) { matches.push(bindings[i]); } } else { if (bindingName.indexOf(binding) != -1) { matches.push(bindings[i]); } } } } return matches; /* Return the whole array for webdriver.findElements. */ };
Find a list of elements in the page by their angular binding. @param {string} binding The binding, e.g. {{cat.name}}. @param {boolean} exactMatch Whether the binding needs to be matched exactly @param {Element} using The scope of the search. @param {string} rootSelector The selector to use for the root app element. @return {Array.<Element>} The elements containing the binding.
functions.findBindings ( binding , exactMatch , using , rootSelector )
javascript
angular/protractor
lib/clientsidescripts.js
https://github.com/angular/protractor/blob/master/lib/clientsidescripts.js
MIT
function findRepeaterRows(repeater, exact, index, using) { using = using || document; var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:']; var rows = []; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { rows.push(repeatElems[i]); } } } /* multiRows is an array of arrays, where each inner array contains one row of elements. */ var multiRows = []; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat-start'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { var elem = repeatElems[i]; var row = []; while (elem.nodeType != 8 || !repeaterMatch(elem.nodeValue, repeater)) { if (elem.nodeType == 1) { row.push(elem); } elem = elem.nextSibling; } multiRows.push(row); } } } var row = rows[index] || [], multiRow = multiRows[index] || []; return [].concat(row, multiRow); }
Find an array of elements matching a row within an ng-repeat. Always returns an array of only one element for plain old ng-repeat. Returns an array of all the elements in one segment for ng-repeat-start. @param {string} repeater The text of the repeater, e.g. 'cat in cats'. @param {boolean} exact Whether the repeater needs to be matched exactly @param {number} index The row index. @param {Element} using The scope of the search. @return {Array.<Element>} The row of the repeater, or an array of elements in the first row in the case of ng-repeat-start.
findRepeaterRows ( repeater , exact , index , using )
javascript
angular/protractor
lib/clientsidescripts.js
https://github.com/angular/protractor/blob/master/lib/clientsidescripts.js
MIT
function findAllRepeaterRows(repeater, exact, using) { using = using || document; var rows = []; var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:']; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { rows.push(repeatElems[i]); } } } for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat-start'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { var elem = repeatElems[i]; while (elem.nodeType != 8 || !repeaterMatch(elem.nodeValue, repeater)) { if (elem.nodeType == 1) { rows.push(elem); } elem = elem.nextSibling; } } } } return rows; }
Find all rows of an ng-repeat. @param {string} repeater The text of the repeater, e.g. 'cat in cats'. @param {boolean} exact Whether the repeater needs to be matched exactly @param {Element} using The scope of the search. @return {Array.<Element>} All rows of the repeater.
findAllRepeaterRows ( repeater , exact , using )
javascript
angular/protractor
lib/clientsidescripts.js
https://github.com/angular/protractor/blob/master/lib/clientsidescripts.js
MIT
function findRepeaterElement(repeater, exact, index, binding, using, rootSelector) { var matches = []; using = using || document; var rows = []; var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:']; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { rows.push(repeatElems[i]); } } } /* multiRows is an array of arrays, where each inner array contains one row of elements. */ var multiRows = []; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat-start'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { var elem = repeatElems[i]; var row = []; while (elem.nodeType != 8 || (elem.nodeValue && !repeaterMatch(elem.nodeValue, repeater))) { if (elem.nodeType == 1) { row.push(elem); } elem = elem.nextSibling; } multiRows.push(row); } } } var row = rows[index]; var multiRow = multiRows[index]; var bindings = []; if (row) { if (angular.getTestability) { matches.push.apply( matches, getNg1Hooks(rootSelector).$$testability.findBindings(row, binding)); } else { if (row.className.indexOf('ng-binding') != -1) { bindings.push(row); } var childBindings = row.getElementsByClassName('ng-binding'); for (var i = 0; i < childBindings.length; ++i) { bindings.push(childBindings[i]); } } } if (multiRow) { for (var i = 0; i < multiRow.length; ++i) { var rowElem = multiRow[i]; if (angular.getTestability) { matches.push.apply( matches, getNg1Hooks(rootSelector).$$testability.findBindings(rowElem, binding)); } else { if (rowElem.className.indexOf('ng-binding') != -1) { bindings.push(rowElem); } var childBindings = rowElem.getElementsByClassName('ng-binding'); for (var j = 0; j < childBindings.length; ++j) { bindings.push(childBindings[j]); } } } } for (var i = 0; i < bindings.length; ++i) { var dataBinding = angular.element(bindings[i]).data('$binding'); if (dataBinding) { var bindingName = dataBinding.exp || dataBinding[0].exp || dataBinding; if (bindingName.indexOf(binding) != -1) { matches.push(bindings[i]); } } } return matches; }
Find an element within an ng-repeat by its row and column. @param {string} repeater The text of the repeater, e.g. 'cat in cats'. @param {boolean} exact Whether the repeater needs to be matched exactly @param {number} index The row index. @param {string} binding The column binding, e.g. '{{cat.name}}'. @param {Element} using The scope of the search. @param {string} rootSelector The selector to use for the root app element. @return {Array.<Element>} The element in an array.
findRepeaterElement ( repeater , exact , index , binding , using , rootSelector )
javascript
angular/protractor
lib/clientsidescripts.js
https://github.com/angular/protractor/blob/master/lib/clientsidescripts.js
MIT
function findRepeaterColumn(repeater, exact, binding, using, rootSelector) { var matches = []; using = using || document; var rows = []; var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:']; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { rows.push(repeatElems[i]); } } } /* multiRows is an array of arrays, where each inner array contains one row of elements. */ var multiRows = []; for (var p = 0; p < prefixes.length; ++p) { var attr = prefixes[p] + 'repeat-start'; var repeatElems = using.querySelectorAll('[' + attr + ']'); attr = attr.replace(/\\/g, ''); for (var i = 0; i < repeatElems.length; ++i) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { var elem = repeatElems[i]; var row = []; while (elem.nodeType != 8 || (elem.nodeValue && !repeaterMatch(elem.nodeValue, repeater))) { if (elem.nodeType == 1) { row.push(elem); } elem = elem.nextSibling; } multiRows.push(row); } } } var bindings = []; for (var i = 0; i < rows.length; ++i) { if (angular.getTestability) { matches.push.apply( matches, getNg1Hooks(rootSelector).$$testability.findBindings(rows[i], binding)); } else { if (rows[i].className.indexOf('ng-binding') != -1) { bindings.push(rows[i]); } var childBindings = rows[i].getElementsByClassName('ng-binding'); for (var k = 0; k < childBindings.length; ++k) { bindings.push(childBindings[k]); } } } for (var i = 0; i < multiRows.length; ++i) { for (var j = 0; j < multiRows[i].length; ++j) { if (angular.getTestability) { matches.push.apply( matches, getNg1Hooks(rootSelector).$$testability.findBindings( multiRows[i][j], binding)); } else { var elem = multiRows[i][j]; if (elem.className.indexOf('ng-binding') != -1) { bindings.push(elem); } var childBindings = elem.getElementsByClassName('ng-binding'); for (var k = 0; k < childBindings.length; ++k) { bindings.push(childBindings[k]); } } } } for (var j = 0; j < bindings.length; ++j) { var dataBinding = angular.element(bindings[j]).data('$binding'); if (dataBinding) { var bindingName = dataBinding.exp || dataBinding[0].exp || dataBinding; if (bindingName.indexOf(binding) != -1) { matches.push(bindings[j]); } } } return matches; }
Find the elements in a column of an ng-repeat. @param {string} repeater The text of the repeater, e.g. 'cat in cats'. @param {boolean} exact Whether the repeater needs to be matched exactly @param {string} binding The column binding, e.g. '{{cat.name}}'. @param {Element} using The scope of the search. @param {string} rootSelector The selector to use for the root app element. @return {Array.<Element>} The elements in the column.
findRepeaterColumn ( repeater , exact , binding , using , rootSelector )
javascript
angular/protractor
lib/clientsidescripts.js
https://github.com/angular/protractor/blob/master/lib/clientsidescripts.js
MIT
functions.findByModel = function(model, using, rootSelector) { using = using || document; if (angular.getTestability) { return getNg1Hooks(rootSelector).$$testability. findModels(using, model, true); } var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:']; for (var p = 0; p < prefixes.length; ++p) { var selector = '[' + prefixes[p] + 'model="' + model + '"]'; var elements = using.querySelectorAll(selector); if (elements.length) { return elements; } } };
Find elements by model name. @param {string} model The model name. @param {Element} using The scope of the search. @param {string} rootSelector The selector to use for the root app element. @return {Array.<Element>} The matching elements.
functions.findByModel ( model , using , rootSelector )
javascript
angular/protractor
lib/clientsidescripts.js
https://github.com/angular/protractor/blob/master/lib/clientsidescripts.js
MIT
functions.findByOptions = function(optionsDescriptor, using) { using = using || document; var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:']; for (var p = 0; p < prefixes.length; ++p) { var selector = '[' + prefixes[p] + 'options="' + optionsDescriptor + '"] option'; var elements = using.querySelectorAll(selector); if (elements.length) { return elements; } } };
Find elements by options. @param {string} optionsDescriptor The descriptor for the option (i.e. fruit for fruit in fruits). @param {Element} using The scope of the search. @return {Array.<Element>} The matching elements.
functions.findByOptions ( optionsDescriptor , using )
javascript
angular/protractor
lib/clientsidescripts.js
https://github.com/angular/protractor/blob/master/lib/clientsidescripts.js
MIT
functions.findByButtonText = function(searchText, using) { using = using || document; var elements = using.querySelectorAll('button, input[type="button"], input[type="submit"]'); var matches = []; for (var i = 0; i < elements.length; ++i) { var element = elements[i]; var elementText; if (element.tagName.toLowerCase() == 'button') { elementText = element.textContent || element.innerText || ''; } else { elementText = element.value; } if (elementText.trim() === searchText) { matches.push(element); } } return matches; };
Find buttons by textual content. @param {string} searchText The exact text to match. @param {Element} using The scope of the search. @return {Array.<Element>} The matching elements.
functions.findByButtonText ( searchText , using )
javascript
angular/protractor
lib/clientsidescripts.js
https://github.com/angular/protractor/blob/master/lib/clientsidescripts.js
MIT
functions.findByCssContainingText = function(cssSelector, searchText, using) { using = using || document; if (searchText.indexOf('__REGEXP__') === 0) { var match = searchText.split('__REGEXP__')[1].match(/\/(.*)\/(.*)?/); searchText = new RegExp(match[1], match[2] || ''); }
Find elements by css selector and textual content. @param {string} cssSelector The css selector to match. @param {string} searchText The exact text to match or a serialized regex. @param {Element} using The scope of the search. @return {Array.<Element>} An array of matching elements.
functions.findByCssContainingText ( cssSelector , searchText , using )
javascript
angular/protractor
lib/clientsidescripts.js
https://github.com/angular/protractor/blob/master/lib/clientsidescripts.js
MIT
functions.testForAngular = function(attempts, ng12Hybrid, asyncCallback) { var callback = function(args) { setTimeout(function() { asyncCallback(args); }, 0);
Tests whether the angular global variable is present on a page. Retries in case the page is just loading slowly. Asynchronous. @param {number} attempts Number of times to retry. @param {boolean} ng12Hybrid Flag set if app is a hybrid of angular 1 and 2 @param {function({version: ?number, message: ?string})} asyncCallback callback
callback ( args )
javascript
angular/protractor
lib/clientsidescripts.js
https://github.com/angular/protractor/blob/master/lib/clientsidescripts.js
MIT
webdriver.ActionSequence = function() {};
Class for defining sequences of complex user interactions. @external webdriver.ActionSequence @see http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/actions_exports_ActionSequence.html
webdriver.ActionSequence ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.TouchSequence = function() {};
Class for defining sequences of user touch interactions. @external webdriver.TouchSequence @see http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_TouchSequence.html
webdriver.TouchSequence ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver = function() {};
Protractor's `browser` object is a wrapper for `selenium-webdriver` WebDriver. It inherits call of WebDriver's methods, but only the methods most useful to Protractor users are documented here. A full list of all functions available on WebDriver can be found in the selenium-webdriver <a href="http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_WebDriver.html">documentation</a> @constructor
webdriver.WebDriver ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.actions = function() {};
Creates a sequence of user actions using this driver. The sequence will not be scheduled for execution until {@link webdriver.ActionSequence#perform} is called. See the selenium webdriver docs <a href="http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/actions_exports_ActionSequence.html"> for more details on action sequences</a>. Mouse actions do not work on Chrome with the HTML5 Drag and Drop API due to a known <a href="https://bugs.chromium.org/p/chromedriver/issues/detail?id=841"> Chromedriver issue</a> @example // Dragging one element to another. browser.actions(). mouseDown(element1). mouseMove(element2). mouseUp(). perform(); // You can also use the `dragAndDrop` convenience action. browser.actions(). dragAndDrop(element1, element2). perform(); // Instead of specifying an element as the target, you can specify an offset // in pixels. This example double-clicks slightly to the right of an element. browser.actions(). mouseMove(element). mouseMove({x: 50, y: 0}). doubleClick(). perform(); @returns {!webdriver.ActionSequence} A new action sequence for this instance.
webdriver.WebDriver.prototype.actions ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.touchActions = function() {};
Creates a new touch sequence using this driver. The sequence will not be scheduled for execution until {@link actions.TouchSequence#perform} is called. See the selenium webdriver docs <a href="http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_TouchSequence.html"> for more details on touch sequences</a>. @example browser.touchActions(). tap(element1). doubleTap(element2). perform(); @return {!webdriver.TouchSequence} A new touch sequence for this instance.
webdriver.WebDriver.prototype.touchActions ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.executeScript = function(script, var_args) {};
Schedules a command to execute JavaScript in the context of the currently selected frame or window. The script fragment will be executed as the body of an anonymous function. If the script is provided as a function object, that function will be converted to a string for injection into the target window. Any arguments provided in addition to the script will be included as script arguments and may be referenced using the {@code arguments} object. Arguments may be a boolean, number, string, or {@linkplain WebElement}. Arrays and objects may also be used as script arguments as long as each item adheres to the types previously mentioned. The script may refer to any variables accessible from the current window. Furthermore, the script will execute in the window's context, thus {@code document} may be used to refer to the current document. Any local variables will not be available once the script has finished executing, though global variables will persist. If the script has a return value (i.e. if the script contains a return statement), then the following steps will be taken for resolving this functions return value: - For a HTML element, the value will resolve to a {@linkplain WebElement} - Null and undefined return values will resolve to null</li> - Booleans, numbers, and strings will resolve as is</li> - Functions will resolve to their string representation</li> - For arrays and objects, each member item will be converted according to the rules above @example var el = element(by.module('header')); var tag = browser.executeScript('return arguments[0].tagName', el); expect(tag).toEqual('h1'); @param {!(string|Function)} script The script to execute. @param {...*} var_args The arguments to pass to the script. @return {!promise.Promise<T>} A promise that will resolve to the scripts return value. @template T
webdriver.WebDriver.prototype.executeScript ( script , var_args )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.executeAsyncScript = (script, var_args) => {};
Schedules a command to execute asynchronous JavaScript in the context of the currently selected frame or window. The script fragment will be executed as the body of an anonymous function. If the script is provided as a function object, that function will be converted to a string for injection into the target window. Any arguments provided in addition to the script will be included as script arguments and may be referenced using the {@code arguments} object. Arguments may be a boolean, number, string, or {@code WebElement}. Arrays and objects may also be used as script arguments as long as each item adheres to the types previously mentioned. Unlike executing synchronous JavaScript with {@link #executeScript}, scripts executed with this function must explicitly signal they are finished by invoking the provided callback. This callback will always be injected into the executed function as the last argument, and thus may be referenced with {@code arguments[arguments.length - 1]}. The following steps will be taken for resolving this functions return value against the first argument to the script's callback function: - For a HTML element, the value will resolve to a {@link WebElement} - Null and undefined return values will resolve to null - Booleans, numbers, and strings will resolve as is - Functions will resolve to their string representation - For arrays and objects, each member item will be converted according to the rules above @example // Example 1 // Performing a sleep that is synchronized with the currently selected window var start = new Date().getTime(); browser.executeAsyncScript( 'window.setTimeout(arguments[arguments.length - 1], 500);'). then(function() { console.log( 'Elapsed time: ' + (new Date().getTime() - start) + ' ms'); }); // Example 2 // Synchronizing a test with an AJAX application: var button = element(by.id('compose-button')); button.click(); browser.executeAsyncScript( 'var callback = arguments[arguments.length - 1];' + 'mailClient.getComposeWindowWidget().onload(callback);'); browser.switchTo().frame('composeWidget'); element(by.id('to')).sendKeys('[email protected]'); // Example 3 // Injecting a XMLHttpRequest and waiting for the result. In this example, // the inject script is specified with a function literal. When using this // format, the function is converted to a string for injection, so it should // not reference any symbols not defined in the scope of the page under test. browser.executeAsyncScript(function() { var callback = arguments[arguments.length - 1]; var xhr = new XMLHttpRequest(); xhr.open("GET", "/resource/data.json", true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { callback(xhr.responseText); } }; xhr.send(''); }).then(function(str) { console.log(JSON.parse(str)['food']); }); @param {!(string|Function)} script The script to execute. @param {...*} var_args The arguments to pass to the script. @return {!promise.Promise<T>} A promise that will resolve to the scripts return value. @template T
webdriver.WebDriver.prototype.executeAsyncScript
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.call = function(fn, opt_scope, var_args) {};
Schedules a command to execute a custom function within the context of webdriver's control flow. Most webdriver actions are asynchronous, but the control flow makes sure that commands are executed in the order they were received. By running your function in the control flow, you can ensure that it is executed before/after other webdriver actions. Additionally, Protractor will wait until the control flow is empty before deeming a test finished. @example var logText = function(el) { return el.getText().then((text) => { console.log(text); }); }; var counter = element(by.id('counter')); var button = element(by.id('button')); // Use `browser.call()` to make sure `logText` is run before and after // `button.click()` browser.call(logText, counter); button.click(); browser.call(logText, counter); @param {function(...): (T|promise.Promise<T>)} fn The function to execute. @param {Object=} opt_scope The object in whose scope to execute the function (i.e. the `this` object for the function). @param {...*} var_args Any arguments to pass to the function. If any of the arguments are promised, webdriver will wait for these promised to resolve and pass the resulting value onto the function. @return {!promise.Promise<T>} A promise that will be resolved with the function's result. @template T
webdriver.WebDriver.prototype.call ( fn , opt_scope , var_args )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.wait = function() {};
Schedules a command to wait for a condition to hold or {@link webdriver.promise.Promise promise} to be resolved. This function blocks WebDriver's control flow, not the javascript runtime. It will only delay future webdriver commands from being executed (e.g. it will cause Protractor to wait before sending future commands to the selenium server), and only when the webdriver control flow is enabled. This function returnes a promise, which can be used if you need to block javascript execution and not just the control flow. See also {@link ExpectedConditions} *Example:* Suppose you have a function, `startTestServer`, that returns a promise for when a server is ready for requests. You can block a `WebDriver` client on this promise with: @example var started = startTestServer(); browser.wait(started, 5 * 1000, 'Server should start within 5 seconds'); browser.get(getServerUrl()); @param {!(webdriver.promise.Promise<T>| webdriver.until.Condition<T>| function(!webdriver.WebDriver): T)} condition The condition to wait on, defined as a promise, condition object, or a function to evaluate as a condition. @param {number=} opt_timeout How long to wait for the condition to be true. Will default 30 seconds, or to the jasmineNodeOpts.defaultTimeoutInterval in your protractor.conf.js file. @param {string=} opt_message An optional message to use if the wait times out. @returns {!webdriver.promise.Promise<T>} A promise that will be fulfilled with the first truthy value returned by the condition function, or rejected if the condition times out.
webdriver.WebDriver.prototype.wait ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.sleep = function() {};
Schedules a command to make the driver sleep for the given amount of time. @param {number} ms The amount of time, in milliseconds, to sleep. @returns {!webdriver.promise.Promise.<void>} A promise that will be resolved when the sleep has finished.
webdriver.WebDriver.prototype.sleep ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.getPageSource = function() {};
Schedules a command to retrieve the current page's source. The page source returned is a representation of the underlying DOM: do not expect it to be formatted or escaped in the same way as the response sent from the web server. @return {!promise.Promise<string>} A promise that will be resolved with the current page source.
webdriver.WebDriver.prototype.getPageSource ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.close = function() {};
Schedules a command to close the current window. @return {!promise.Promise<void>} A promise that will be resolved when this command has completed.
webdriver.WebDriver.prototype.close ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.getCurrentUrl = function() {};
Schedules a command to retrieve the URL of the current page. @returns {!webdriver.promise.Promise.<string>} A promise that will be resolved with the current URL.
webdriver.WebDriver.prototype.getCurrentUrl ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.getTitle = function() {};
Schedules a command to retrieve the current page's title. @returns {!webdriver.promise.Promise.<string>} A promise that will be resolved with the current page's title.
webdriver.WebDriver.prototype.getTitle ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.takeScreenshot = function() {};
Schedule a command to take a screenshot. The driver makes a best effort to return a screenshot of the following, in order of preference: <ol> <li>Entire page <li>Current window <li>Visible portion of the current frame <li>The screenshot of the entire display containing the browser </ol> @returns {!webdriver.promise.Promise.<string>} A promise that will be resolved to the screenshot as a base-64 encoded PNG.
webdriver.WebDriver.prototype.takeScreenshot ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebDriver.prototype.switchTo = function() {}
Used to switch WebDriver's focus to a frame or window (e.g. an alert, an iframe, another window). See [WebDriver's TargetLocator Docs](http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_TargetLocator.html) for more information. @example browser.switchTo().frame(element(by.tagName('iframe')).getWebElement()); @return {!TargetLocator} The target locator interface for this instance.
webdriver.WebDriver.prototype.switchTo ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebElement = function(driver, id) {};
Protractor's ElementFinders are wrappers for selenium-webdriver WebElement. A full list of all functions available on WebElement can be found in the selenium-webdriver <a href="http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_WebElement.html">documentation</a>. @param {!webdriver.WebDriver} driver The webdriver driver or the parent WebDriver instance for this element. @param {!(webdriver.promise.Promise.<webdriver.WebElement.Id>| webdriver.WebElement.Id)} id The server-assigned opaque ID for the underlying DOM element. @constructor
webdriver.WebElement ( driver , id )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebElement.prototype.getDriver = function() {};
Gets the parent web element of this web element. @view <ul class="pet"> <li class="dog">Dog</li> <li class="cat">Cat</li> </ul> @example // Using getDriver to find the parent web element to find the cat li var liDog = element(by.css('.dog')).getWebElement(); var liCat = liDog.getDriver().findElement(by.css('.cat')); @returns {!webdriver.WebDriver} The parent driver for this instance.
webdriver.WebElement.prototype.getDriver ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT
webdriver.WebElement.prototype.getId = function() {};
Gets the WebDriver ID string representation for this web element. @view <ul class="pet"> <li class="dog">Dog</li> <li class="cat">Cat</li> </ul> @example // returns the dog web element var dog = element(by.css('.dog')).getWebElement(); expect(dog.getId()).not.toBe(undefined); @returns {!webdriver.promise.Promise.<webdriver.WebElement.Id>} A promise that resolves to this element's JSON representation as defined by the WebDriver wire protocol. @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
webdriver.WebElement.prototype.getId ( )
javascript
angular/protractor
lib/selenium-webdriver/webdriver.js
https://github.com/angular/protractor/blob/master/lib/selenium-webdriver/webdriver.js
MIT