text
stringlengths
2
1.05M
(function(mask, Compo){ // source vars var __Compo = typeof Compo !== 'undefined' ? Compo : (mask.Compo || global.Compo), __dom_addEventListener = __Compo.Dom.addEventListener, __registerHandler = mask.registerHandler, __registerAttr = mask.registerAttrHandler, __registerUtil = mask.registerUtil, domLib = __Compo.config.getDOMLibrary(); // end:source vars // source utils/ // source object var obj_callFn; (function () { obj_callFn = function (obj, path, args) { var end = path.lastIndexOf('.'); if (end === -1) { return call(obj, path, args); } var host = obj, i = -1; while (host != null && i !== end) { var start = i; i = path.indexOf('.', i); var key = path.substring(start + 1, i); host = host[key]; } return call(host, path.substring(end + 1), args); }; function call(obj, key, args) { var fn = null; if (obj != null) fn = obj[key]; if (typeof fn !== 'function') { console.error('Not a function', key); return null; } return fn.apply(obj, args); } }()); // end:source object // source object_observe var obj_addObserver, obj_hasObserver, obj_removeObserver, obj_lockObservers, obj_unlockObservers, obj_ensureObserversProperty, obj_addMutatorObserver, obj_removeMutatorObserver ; (function(){ (function () { obj_addObserver = function(obj, property, cb) { if (obj == null) { log_error('Not possible to add the observer for "' + property + '" as current model is undefined.'); return; } // closest observer var parts = property.split('.'), imax = parts.length, i = -1, x = obj; if (pushClosest(obj[parts[0]], parts, 1, cb)) { /* We have added a callback as close as possible to the observle property owner * But also add the cb to myself to listen different object path level setters */ var cbs = pushListener_(obj, property, cb); if (cbs.length === 1) { var arr = parts.splice(0, i); if (arr.length !== 0) attachProxy_(obj, property, cbs, arr, true); } if (parts.length > 1) { obj_defineCrumbs(obj, parts); } return; } var cbs = pushListener_(obj, property, cb); if (cbs.length === 1) attachProxy_(obj, property, cbs, parts, true); var val = obj_getProperty(obj, property), mutators = getSelfMutators(val); if (mutators != null) { objMutator_addObserver( val, mutators, cb ); } }; function pushClosest(ctx, parts, i, cb) { if (ctx == null) { return false; } if (i < parts.length - 1 && pushClosest(ctx[parts[i]], parts, i + 1, cb)) { return true; } var obs = ctx[prop_OBS]; if (obs == null) { return false; } var prop = toProp(parts, i); var arr = obs[prop]; if (arr == null) { // fix [obj.test](hosts) var proxy = obs[prop_PROXY]; if (proxy != null && proxy[prop] === true) { pushListener_(ctx, prop, cb); return true; } return false; } pushListener_(ctx, prop, cb); return true; } }()); obj_hasObserver = function(obj, property, callback){ // nested observer var parts = property.split('.'), imax = parts.length, i = -1, x = obj; while ( ++i < imax ) { x = x[parts[i]]; if (x == null) break; if (x[prop_OBS] != null) { if (obj_hasObserver(x, parts.slice(i + 1).join('.'), callback)) return true; break; } } var obs = obj[prop_OBS]; if (obs == null || obs[property] == null) return false; return arr_contains(obs[property], callback); }; obj_removeObserver = function(obj, property, callback) { if (obj == null) { log_error('Not possible to remove the observer for "' + property + '" as current model is undefined.'); return; } // nested observer var parts = property.split('.'), imax = parts.length, i = -1, x = obj; while ( ++i < imax ) { x = x[parts[i]]; if (x == null) break; if (x[prop_OBS] != null) { obj_removeObserver(x, parts.slice(i + 1).join('.'), callback); break; } } var obs = obj_getObserversProperty(obj, property); if (obs != null) { if (callback === void 0) { // callback not provided -> remove all observers obs.length = 0; } else { arr_remove(obs, callback); } } var val = obj_getProperty(obj, property), mutators = getSelfMutators(val); if (mutators != null) objMutator_removeObserver(val, mutators, callback) }; obj_lockObservers = function(obj) { var obs = obj[prop_OBS]; if (obs != null) obs[prop_DIRTY] = {}; }; obj_unlockObservers = function(obj) { var obs = obj[prop_OBS], dirties = obs == null ? null : obs[prop_DIRTY]; if (dirties == null) return; obs[prop_DIRTY] = null; var prop, cbs, val, imax, i; for(prop in dirties) { cbs = obj[prop_OBS][prop]; imax = cbs == null ? 0 : cbs.length; if (imax === 0) continue; i = -1; val = prop === prop_MUTATORS ? obj : obj_getProperty(obj, prop) ; while ( ++i < imax ) { cbs[i](val); } } }; var obj_getObserversProperty = function (obj, type){ var obs = obj[prop_OBS]; return obs == null ? null : obs[type]; }; obj_ensureObserversProperty = function(obj, type){ var obs = obj[prop_OBS]; if (obs == null) { obs = { __dirty: null, __dfrTimeout: null, __mutators: null, __rebinders: {}, __proxies: {} }; defineProp_(obj, '__observers', { value: obs, enumerable: false }); } if (type == null) return obs; var arr = obs[type]; return arr == null ? (obs[type] = []) : arr ; }; var obj_ensureRebindersProperty = function(obj){ var hash = obj[prop_REBINDERS]; if (hash == null) { hash = {}; defineProp_(obj, prop_REBINDERS, { value: hash, enumerable: false }); } return hash; }; obj_addMutatorObserver = function(obj, cb){ var mutators = getSelfMutators(obj); if (mutators != null) objMutator_addObserver(obj, mutators, cb); }; obj_removeMutatorObserver = function(obj, cb){ objMutator_removeObserver(obj, null, cb); }; // PRIVATE var prop_OBS = '__observers', prop_MUTATORS = '__mutators', prop_TIMEOUT = '__dfrTimeout', prop_DIRTY = '__dirty', prop_REBINDERS = '__rebinders', prop_PROXY = '__proxies'; var defineProp_ = Object.defineProperty; //Resolve object, or if property do not exists - create function ensureProperty_(obj, chain) { var i = -1, imax = chain.length - 1, key ; while ( ++i < imax ) { key = chain[i]; if (obj[key] == null) obj[key] = {}; obj = obj[key]; } return obj; } function getSelfMutators(obj) { if (obj == null || typeof obj !== 'object') return null; if (typeof obj.length === 'number' && typeof obj.slice === 'function') return MUTATORS_.Array; if (typeof obj.toUTCString === 'function') return MUTATORS_.Date; return null; } var MUTATORS_ = { Array: { throttle: false, methods: [ // native mutators 'push', 'unshift', 'splice', 'pop', 'shift', 'reverse', 'sort', // collection mutators 'remove' ] }, Date: { throttle: true, methods: [ 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', ] } }; function attachProxy_(obj, property, cbs, chain) { var length = chain.length; if (length > 1) { if (obj_defineCrumbs(obj, chain) === false) { return; } } // TODO: ensure is not required, as defineCrumbs returns false when path contains null value */ var parent = length > 1 ? ensureProperty_(obj, chain) : obj, key = chain[length - 1], currentVal = parent[key]; if ('length' === key) { var mutators = getSelfMutators(parent); if (mutators != null) { objMutator_addObserver( parent, mutators, function(){ var imax = cbs.length, i = -1 ; while ( ++i < imax ) { cbs[i].apply(null, arguments); } }); return currentVal; } } var obs = obj_ensureObserversProperty(parent); var hash = obs[prop_PROXY]; if (hash[key] === true) return; hash[key] = true; defineProp_(parent, key, { get: function() { return currentVal; }, set: function(x) { if (x === currentVal) return; var oldVal = currentVal; currentVal = x; var i = 0, imax = cbs.length, mutators = getSelfMutators(x); if (mutators != null) { for(; i < imax; i++) { objMutator_addObserver( x, mutators, cbs[i] ); } } if (obj[prop_OBS][prop_DIRTY] != null) { obj[prop_OBS][prop_DIRTY][property] = 1; return; } for (i = 0; i < imax; i++) { cbs[i](x); } obj_sub_notifyListeners(obj, property, oldVal); obj_deep_notifyListeners(obj, chain, oldVal, currentVal, cbs); }, configurable: true, enumerable : true }); return currentVal; } /* return false, when path contains null values */ function obj_defineCrumbs(obj, chain) { var rebinder = obj_crumbRebindDelegate(obj), path = '', key; var imax = chain.length - 1, i = 0, x = obj; for(; i < imax; i++) { key = chain[i]; path += key + '.'; obj_defineCrumb(path, x, key, rebinder); x = x[key]; if (x == null) { return false; } } return true; } function obj_defineCrumb(path, obj, key, rebinder) { var cbs = obj[prop_OBS] && obj[prop_OBS][key]; if (cbs != null) { return; } var value = obj[key], old; var hash = obj_ensureRebindersProperty(obj); var set = hash[key]; if (set != null) { if (set[path] == null) { set[path] = rebinder; } return; } set = hash[key] = {}; set[path] = rebinder; defineProp_(obj, key, { get: function() { return value; }, set: function(x) { if (x === value) return; old = value; value = x; for (var _path in set) { set[_path](_path, old); } }, configurable: true, enumerable : true }); } function obj_sub_notifyListeners(obj, path, oldVal) { var obs = obj[prop_OBS]; if (obs == null) return; for(var prop in obs) { if (prop.indexOf(path + '.') !== 0) continue; var cbs = obs[prop].slice(0), imax = cbs.length, i = 0, oldProp, cb; if (imax === 0) continue; var val = obj_getProperty(obj, prop); for (i = 0; i < imax; i++) { cb = cbs[i]; obj_removeObserver(obj, prop, cb); if (oldVal != null && typeof oldVal === 'object') { oldProp = prop.substring(path.length + 1); obj_removeObserver(oldVal, oldProp, cb); } } for (i = 0; i < imax; i++){ cbs[i](val); } for (i = 0; i < imax; i++){ obj_addObserver(obj, prop, cbs[i]); } } } var obj_deep_notifyListeners; (function () { obj_deep_notifyListeners = function (obj, chain, oldVal, currentVal, fns) { var i = 0, imax = chain.length, ctx = obj, arr = fns.slice(0); do { ctx = ctx[chain[i]]; if (ctx == null) { return; } var obs = ctx[prop_OBS]; if (obs == null) { continue; } var prop = toProp(chain, i + 1); var cbs = obs[prop]; if (cbs == null) { continue; } for (var j = 0; j < cbs.length; j++) { var cb = cbs[j] if (arr.indexOf(cb) !== -1) { continue; } cb(currentVal); arr.push(cb); } } while(++i < imax - 1); }; }()); function toProp(arr, start) { var str = '', imax = arr.length, i = start - 1; while(++i < imax){ if (i !== start) str += '.'; str += arr[i]; } return str; } function obj_crumbRebindDelegate(obj) { return function(path, oldValue){ obj_crumbRebind(obj, path, oldValue); }; } function obj_crumbRebind(obj, path, oldValue) { var obs = obj[prop_OBS]; if (obs == null) return; for (var prop in obs) { if (prop.indexOf(path) !== 0) continue; var cbs = obs[prop].slice(0), imax = cbs.length, i = 0; if (imax === 0) continue; var val = obj_getProperty(obj, prop), oldProp = prop.substring(path.length), oldVal = obj_getProperty(oldValue, oldProp); for (i = 0; i < imax; i++) { var cb = cbs[i]; obj_removeObserver(obj, prop, cb); if (oldValue != null && typeof oldValue === 'object') { obj_removeObserver(oldValue, oldProp, cb); } } if (oldVal !== val) { for (i = 0; i < imax; i++){ cbs[i](val); } } for (i = 0; i < imax; i++){ obj_addObserver(obj, prop, cbs[i]); } } } // Create Collection - Check If Exists - Add Listener function pushListener_(obj, property, cb) { var obs = obj_ensureObserversProperty(obj, property); if (arr_contains(obs, cb) === false) obs.push(cb); return obs; } var objMutator_addObserver, objMutator_removeObserver; (function(){ objMutator_addObserver = function(obj, mutators, cb){ var methods = mutators.methods, throttle = mutators.throttle, obs = obj_ensureObserversProperty(obj, prop_MUTATORS); if (obs.length === 0) { var imax = methods.length, i = -1, method, fn; while( ++i < imax ){ method = methods[i]; fn = obj[method]; if (fn == null) continue; obj[method] = objMutator_createWrapper_( obj , fn , method , throttle ); } } obs[obs.length++] = cb; }; objMutator_removeObserver = function(obj, mutators, cb){ var obs = obj_getObserversProperty(obj, prop_MUTATORS); if (obs == null) { return; } if (cb === void 0) { obs.length = 0; return; } arr_remove(obs, cb); }; function objMutator_createWrapper_(obj, originalFn, method, throttle) { var fn = throttle === true ? callDelayed : call; return function() { return fn( obj, originalFn, method, _Array_slice.call(arguments) ); }; } function call(obj, original, method, args) { var cbs = obj_ensureObserversProperty(obj, prop_MUTATORS), result = original.apply(obj, args); tryNotify(obj, cbs, method, args, result); return result; } function callDelayed(obj, original, method, args) { var cbs = obj_ensureObserversProperty(obj, prop_MUTATORS), result = original.apply(obj, args); var obs = obj[prop_OBS]; if (obs[prop_TIMEOUT] != null) return result; obs[prop_TIMEOUT] = setTimeout(function(){ obs[prop_TIMEOUT] = null; tryNotify(obj, cbs, method, args, result); }); return result; } function tryNotify(obj, cbs, method, args, result){ if (cbs.length === 0) return; var obs = obj[prop_OBS]; if (obs[prop_DIRTY] != null) { obs[prop_DIRTY][prop_MUTATORS] = 1; return; } var imax = cbs.length, i = -1, x; while ( ++i < imax ){ x = cbs[i]; if (typeof x === 'function') { x(obj, method, args, result); } } } }()); }()); // end:source object_observe // source date var date_ensure; (function(){ date_ensure = function(val){ if (val == null || val === '') return null; var date = val; var type = typeof val; if (type === 'string') { date = new Date(val); if (rgx_es5Date.test(date) && val.indexOf('Z') === -1) { // adjust to local time (http://es5.github.io/x15.9.html#x15.9.1.15) val.setMinutes(val.getTimezoneOffset()); } } if (type === 'number') { date = new Date(val); } return isNaN(date) === false && typeof date.getFullYear === 'function' ? date : null ; }; var rgx_es5Date = /^\d{4}\-\d{2}/; }()); // end:source date // source dom var dom_removeElement, dom_removeAll, dom_insertAfter, dom_insertBefore, dom_hideEl, dom_hideAll, dom_showEl, dom_showAll; (function(){ dom_removeElement = function(el) { var parent = el.parentNode; if (parent == null) { return el; } return parent.removeChild(el); }; dom_removeAll = function(arr) { arr_each(arr, dom_removeElement); }; dom_hideEl = function(el){ if (el != null) { el.style.display = 'none'; } }; dom_hideAll = function(arr) { arr_each(arr, dom_hideEl); }; dom_showEl = function(el){ if (el != null) { el.style.display = ''; } }; dom_showAll = function(arr) { arr_each(arr, dom_showEl); }; dom_insertAfter = function(el, anchor) { return anchor.parentNode.insertBefore(el, anchor.nextSibling); }; dom_insertBefore = function(el, anchor) { return anchor.parentNode.insertBefore(el, anchor); }; }()); // end:source dom // source compo var compo_fragmentInsert, compo_render, compo_renderChildren, compo_renderElements, compo_dispose, compo_disposeChildren, compo_inserted, compo_attachDisposer, compo_hasChild, compo_getScopeFor, compo_transferChildren ; (function(){ compo_fragmentInsert = function(compo, index, fragment, placeholder) { if (compo.components == null) { return dom_insertAfter(fragment, placeholder || compo.placeholder); } var compos = compo.components, anchor = null, insertBefore = true, imax = compos.length, i = index - 1; if (anchor == null) { while (++i < imax) { var arr = compos[i].elements; if (arr != null && arr.length !== 0) { anchor = arr[0]; break; } } } if (anchor == null) { insertBefore = false; i = index < imax ? index : imax ; while (--i > -1) { var arr = compos[i].elements; if (arr != null && arr.length !== 0) { anchor = arr[arr.length - 1]; break; } } } if (anchor == null) { anchor = placeholder || compo.placeholder; } if (insertBefore) { return dom_insertBefore(fragment, anchor); } return dom_insertAfter(fragment, anchor); }; compo_render = function(parentCtr, template, model, ctx, container) { return mask.render(template, model, ctx, container, parentCtr); }; compo_renderChildren = function(compo, anchor, model){ var fragment = document.createDocumentFragment(); compo.elements = compo_renderElements( compo.nodes, model || compo.model, compo.ctx, fragment, compo ); dom_insertBefore(fragment, anchor); compo_inserted(compo); }; compo_renderElements = function(nodes, model, ctx, el, ctr){ if (nodes == null){ return null; } var arr = []; builder_build(nodes, model, ctx, el, ctr, arr); return arr; }; compo_dispose = function(compo, parent) { if (compo == null) return false; if (compo.elements != null) { dom_removeAll(compo.elements); compo.elements = null; } __Compo.dispose(compo); var compos = (parent && parent.components) || (compo.parent && compo.parent.components); if (compos == null) { log_error('Parent Components Collection is undefined'); return false; } return arr_remove(compos, compo); }; compo_disposeChildren = function(compo){ var els = compo.elements; if (els != null) { dom_removeAll(els); compo.elements = null; } var compos = compo.components; if (compos != null) { var imax = compos.length, i = -1; while (++i < imax){ Compo.dispose(compos[i]); } compos.length = 0; } }; compo_inserted = function(compo) { __Compo.signal.emitIn(compo, 'domInsert'); }; compo_attachDisposer = function(ctr, disposer) { if (typeof ctr.dispose === 'function') { var previous = ctr.dispose; ctr.dispose = function(){ disposer.call(this); previous.call(this); }; return; } ctr.dispose = disposer; }; compo_hasChild = function(compo, compoName){ var arr = compo.components; if (arr == null || arr.length === 0) { return false; } var imax = arr.length, i = -1; while (++i < imax) { if (arr[i].compoName === compoName) { return true; } } return false; }; compo_getScopeFor = function(ctr, path){ var key = path; var i = path.indexOf('.'); if (i !== -1) { key = path.substring(0, i); if (key.charCodeAt(key.length - 1) === 63 /*?*/) { key = key.slice(0, -1); } } while (ctr != null) { if (ctr.scope != null && ctr.scope.hasOwnProperty(key)) { return ctr.scope; } ctr = ctr.parent; } return null; }; compo_transferChildren = function(compo){ var x = { elements: compo.elements, components: compo.components }; compo.elements = compo.components = null; return x; }; }()); // end:source compo // source expression var expression_eval, expression_eval_strict, expression_evalStatements, expression_bind, expression_unbind, expression_createBinder, expression_createListener, expression_callFn, expression_parse, expression_varRefs, expression_getHost ; (function(){ var Expression = mask.Utils.Expression; expression_eval_strict = Expression.eval; expression_parse = Expression.parse; expression_varRefs = Expression.varRefs; expression_evalStatements = Expression.evalStatements; expression_eval = function(expr, model, ctx, ctr, node){ var x = expression_eval_strict(expr, model, ctx, ctr, node); return x == null ? '' : x; }; expression_bind = function(expr, model, ctx, ctr, cb) { if (expr === '.') { if (model != null) { obj_addMutatorObserver(model, cb); } return; } toggleExpressionsBindings( obj_addObserver, expr, model, ctr, cb ); }; expression_unbind = function(expr, model, ctr, cb) { if (expr === '.') { if (model != null) { obj_removeMutatorObserver(model, cb); } return; } toggleExpressionsBindings( obj_removeObserver, expr, model, ctr, cb ); }; function toggleExpressionsBindings (fn, expr, model, ctr, cb) { var mix = expression_varRefs(expr, model, null, ctr); if (mix == null) return null; if (typeof mix === 'string') { _toggleObserver(fn, model, ctr, mix, cb); return; } var arr = mix, imax = arr.length, i = -1; while (++i < imax) { var accs = arr[i]; if (typeof accs === 'string') if (accs.charCodeAt(0) === 95 /*_*/ && accs.charCodeAt(0) === 46 /*.*/) { continue; } else if (typeof accs === 'object') { if (accs.ref === '_') { continue; } } _toggleObserver(fn, model, ctr, accs, cb); } } expression_callFn = function (accessor, model, ctx, ctr, args) { var tuple = expression_getHost( accessor, model, ctx, ctr ); if (tuple != null) { var obj = tuple[0], path = tuple[1]; return obj_callFn(obj, path, args); } return null; }; /** * expression_bind only fires callback, if some of refs were changed, * but doesnt supply new expression value **/ expression_createBinder = function(expr, model, ctx, ctr, fn) { return expression_createListener(function(){ var value = expression_eval(expr, model, ctx, ctr); var args = _Array_slice.call(arguments); args[0] = value; fn.apply(this, args); }); }; expression_createListener = function(callback){ var locks = 0; return function(){ if (++locks > 1) { locks = 0; log_warn('<listener:expression> concurrent binder'); return; } callback.apply(this, _Array_slice.call(arguments)); locks--; } }; (function () { // [ObjectHost, Property] var tuple = [null, null]; expression_getHost = function (accessor, model, ctx, ctr) { var result = get(accessor, model, ctx, ctr); if (result == null || result[0] == null) { error_withCompo('Observable host is undefined or is not allowed: ' + accessor.toString(), ctr); return null; } return result; }; function get(accessor, model, ctx, ctr) { if (accessor == null) return; if (typeof accessor === 'object') { var obj = expression_eval_strict(accessor.accessor, model, null, ctr); if (obj == null || typeof obj !== 'object') { return null; } tuple[0] = obj; tuple[1] = accessor.ref; return tuple; } var property = accessor, parts = property.split('.'), imax = parts.length; if (imax > 1) { var first = parts[0]; if (first === 'this' || first === '$c' || first === '$') { // Controller Observer var owner = _getObservable_Controller(ctr, parts[1]); var cutIdx = first.length + 1; tuple[0] = owner; tuple[1] = property.substring(cutIdx); return tuple; } if (first === '$scope') { // Controller Observer var scope = _getObservable_Scope(ctr, parts[1]); var cutIdx = 6 + 1; tuple[0] = scope; tuple[1] = property.substring(cutIdx); return tuple; } } var obj = null; if (_isDefined(model, parts[0])) { obj = model; } if (obj == null) { obj = _getObservable_Scope(ctr, parts[0]); } if (obj == null) { obj = model; } tuple[0] = obj; tuple[1] = property; return tuple; } }()); function _toggleObserver(mutatorFn, model, ctr, accessor, callback) { var tuple = expression_getHost(accessor, model, null, ctr); if (tuple == null) return; var obj = tuple[0], property = tuple[1]; if (obj == null) return; mutatorFn(obj, property, callback); } function _getObservable_Controller(ctr_, key) { var ctr = ctr_; while(ctr != null){ if (_isDefined(ctr, key)) return ctr; ctr = ctr.parent; } return ctr; } function _getObservable_Scope(ctr_, property, imax) { var ctr = ctr_, scope; while(ctr != null){ scope = ctr.scope; if (_isDefined(scope, property)) { return scope; } ctr = ctr.parent; } return null; } function _isDefined(obj_, key_){ var key = key_; if (key.charCodeAt(key.length - 1) === 63 /*?*/) { key = key.slice(0, -1); } return obj_ != null && key in obj_; } }()); // end:source expression // source signal var signal_parse, signal_create ; (function(){ signal_parse = function(str, isPiped, defaultType) { var signals = str.split(';'), set = [], i = 0, imax = signals.length, x, signalName, type, signal; for (; i < imax; i++) { x = signals[i].split(':'); if (x.length !== 1 && x.length !== 2) { log_error('Too much ":" in a signal def.', signals[i]); continue; } type = x.length === 2 ? x[0] : defaultType; signalName = x[x.length === 2 ? 1 : 0]; signal = signal_create(signalName.trim(), type, isPiped); if (signal != null) { set.push(signal); } } return set; }; signal_create = function(signal, type, isPiped) { if (isPiped !== true) { return { signal: signal, type: type }; } var index = signal.indexOf('.'); if (index === -1) { log_error('No pipe name in a signal', signal); return null; } return { signal: signal.substring(index + 1), pipe: signal.substring(0, index), type: type }; }; }()); // end:source signal // end:source utils/ // source binders/ var Binders = {}; (function(){ // source ./IBinder.js var IBinder = class_create({ constructor: function (exp, model, ctr) { this.exp = exp; this.ctr = ctr; this.model = model; this.cb = null; }, bind: function(cb){ this.cb = cb; // we have here no access to the ctx, so pass null this.on(this.exp, this.model, null, this.ctr, cb); }, dispose: function(){ this.off(this.exp, this.model, this.ctr, this.cb); this.exp = this.model = this.ctr = this.cb = null; } }); // end:source ./IBinder.js // source ./ExpressionBinder.js Binders.ExpressionBinder = class_create(IBinder, { on: expression_bind, off: expression_unbind }); // end:source ./ExpressionBinder.js // source ./EventEmitterBinder.js /* * "expression, ...args" * expression: to get the IEventEmitter */ (function(){ Binders.EventEmitterBinder = class_create(IBinder, { on: function(exp, model, ctx, ctr, cb){ call('on', exp, model, ctr, cb); }, off: function(exp, model, ctr, cb){ call('off', exp, model, ctr, cb); }, }); function call (method, expr, model, ctr, cb) { var arr = expression_evalStatements(expr, model, null, ctr); var observable = arr.shift(); if (observable == null || observable[method] == null) { log_error('Method is undefined on observable: ' + method); return; } arr.push(cb); observable[method].apply(observable, arr); } }()); // end:source ./EventEmitterBinder.js // source ./RxBinder.js /* * "expression, ...args" * expression: to get the RxObservable {subscribe:IDisposable} */ Binders.RxBinder = class_create(IBinder, { stream: null, on: function call (expr, model, ctr, cb) { var arr = expression_evalStatements(expr, model, null, ctr); var stream = arr.shift(); if (stream == null || stream.subscribe == null) { error_withCompo('Subscribe method is undefined on RxObservable', ctr); return; } arr.push(cb); this.stream = stream.subscribe.apply(stream, arr); }, off: function(){ if (this.stream == null) { return; } this.stream.dispose(); }, }); // end:source ./RxBinder.js }()); // end:source binders/ // source DomObjectTransport var DomObjectTransport; (function(){ var objectWay = { get: function(provider, expression) { var getter = provider.objGetter; if (getter == null) { return expression_eval( expression , provider.model , provider.ctx , provider.ctr ); } var ctr = provider.ctr.parent, model = provider.model; return expression_callFn( getter, provider.model, provider.ctx, ctr, [ expression, model, ctr ] ); }, set: function(obj, property, value, provider) { var setter = provider.objSetter; if (setter == null) { obj_setProperty(obj, property, value); return; } var ctr = provider.ctr.parent, model = provider.model; return expression_callFn( setter, provider.model, provider.ctx, ctr, [ value, property, model, ctr ] ); } }; var domWay = { get: function(provider) { var getter = provider.domGetter; if (getter == null) { return obj_getProperty(provider, provider.property); } var ctr = provider.ctr.parent; if (isValidFn_(ctr, getter, 'Getter') === false) { return null; } return ctr[getter](provider.element); }, set: function(provider, value) { var setter = provider.domSetter; if (setter == null) { obj_setProperty(provider, provider.property, value); return; } var ctr = provider.ctr.parent; if (isValidFn_(ctr, setter, 'Setter') === false) { return; } ctr[setter](value, provider.element); } }; var DateTimeDelegate = { domSet: function(format){ return function(prov, val){ var date = date_ensure(val); prov.element.value = date == null ? '' : format(date); } }, objSet: function(extend){ return function(obj, prop, val){ var date = date_ensure(val); if (date == null) return; var target = obj_getProperty(obj, prop); if (target == null) { obj_setProperty(obj, prop, date); return; } if (target.getFullYear == null || isNaN(target)) { target = date_ensure(target) || date; extend(target, date); obj_setProperty(obj, prop, target); return; } extend(target, date); } } }; DomObjectTransport = { // generic objectWay: objectWay, domWay: domWay, SELECT: { get: function(provider) { var el = provider.element, i = el.selectedIndex; if (i === -1) return ''; var opt = el.options[i], val = opt.getAttribute('value'); return val == null ? opt.getAttribute('name') /* obsolete */ : val ; }, set: function(provider, val) { var el = provider.element, options = el.options, imax = options.length, opt, x, i; for(i = 0; i < imax; i++){ opt = options[i]; x = opt.getAttribute('value'); if (x == null) x = opt.getAttribute('name'); /* jshint eqeqeq: false */ if (x == val) { /* jshint eqeqeq: true */ el.selectedIndex = i; return; } } log_warn('Value is not an option', val); } }, SELECT_MULT: { get: function(provider) { return coll_map(provider.element.selectedOptions, function(x){ return x.value; }); }, set: function(provider, mix) { coll_each(provider.element.options, function(el){ el.selected = false; }); if (mix == null) { return; } var arr = is_ArrayLike(mix) ? mix : [ mix ]; coll_each(arr, function(val){ var els = provider.element.options, imax = els.length, i = -1; while (++i < imax) { /* jshint eqeqeq: false */ if (els[i].value == val) { /* jshint eqeqeq: true */ els[i].selected = true; } } log_warn('Value is not an option', val); }); } }, DATE: { domWay: { get: domWay.get, set: function(prov, val){ var date = date_ensure(val); prov.element.value = date == null ? '' : formatDate(date); } }, objectWay: { get: objectWay.get, set: DateTimeDelegate.objSet(function(a, b){ var offset = a.getTimezoneOffset(); a.setFullYear(b.getFullYear()); a.setMonth(b.getMonth()); a.setDate(b.getDate()); var diff = offset - a.getTimezoneOffset(); if (diff !== 0) { var h = (diff / 60) | 0; a.setHours(a.getHours() + h); } }) } }, TIME: { domWay: { get: domWay.get, set: DateTimeDelegate.domSet(formatTime) }, objectWay: { get: objectWay.get, set: DateTimeDelegate.objSet(function(a, b){ a.setHours(b.getHours()); a.setMinutes(b.getMinutes()); a.setSeconds(b.getSeconds()); }) } }, MONTH: { domWay: { get: domWay.get, set: DateTimeDelegate.domSet(formatMonth) }, objectWay: { get: objectWay.get, set: DateTimeDelegate.objSet(function(a, b){ a.setFullYear(b.getFullYear()); a.setMonth(b.getMonth()); }) } }, RADIO: { domWay: { get: function(provider){ var el = provider.element; return el.checked ? el.value : null; }, set: function(provider, value){ var el = provider.element; el.checked = el.value === value; } }, } }; function isValidFn_(obj, prop, name) { if (obj== null || typeof obj[prop] !== 'function') { log_error('BindingProvider. Controllers accessor.', name, 'should be a function. Property:', prop); return false; } return true; } function getAccessorObject_(provider, accessor) { var ctr = provider.ctr.parent; if (ctr[accessor] != null) return ctr; var model = provider.model; if (model[accessor] != null) return model; log_error('BindingProvider. Accessor `', accessor, '`should be a function'); return null; } function formatDate(date) { var YYYY = date.getFullYear(), MM = date.getMonth() + 1, DD = date.getDate(); return YYYY + '-' + (MM < 10 ? '0' : '') + (MM) + '-' + (DD < 10 ? '0' : '') + (DD) ; } function formatTime(date) { var H = date.getHours(), M = date.getMinutes(); return H + ':' + (M < 10 ? '0' : '') + (M) ; } function formatMonth(date) { var YYYY = date.getFullYear(), MM = date.getMonth() + 1; return YYYY + '-' + (MM < 10 ? '0' : '') + (MM); } }()); // end:source DomObjectTransport // source ValidatorProvider var ValidatorProvider, Validators; (function() { var class_INVALID = '-validate__invalid'; ValidatorProvider = { getFnFromModel: fn_fromModelWrapp, getFnByName: fn_byName, validate: validate, validateUi: function(fns, val, ctr, el, oncancel) { var error = validate(fns, val, ctr); if (error != null) { ui_notifyInvalid(el, error, oncancel); return error; } ui_clearInvalid(el); return null; } }; function validate(fns, val, ctr) { if (fns == null) { return null; } var imax = fns.length, i = -1, error, fn; while ( ++i < imax ){ fn = fns[i]; if (fn == null) { continue; } error = fn(val, ctr); if (error != null) { if (is_String(error)) { return { message: error, actual: val }; } if (error.actual == null) { error.actual = val; } return error; } } } function fn_fromModel(model, prop) { if (is_Object(model) === false) { return null; } var Validate = model.Validate; if (Validate != null) { var fn = null; if (is_Function(fn = Validate)) { return fn; } if (is_Function(fn = Validate[prop])) { return fn; } } var i = prop.indexOf('.'); if (i !== -1) { return fn_fromModel( model[prop.substring(0, i)], prop.substring(i+1) ); } return null; } function fn_fromModelWrapp(model, prop) { var fn = fn_fromModel(model, prop); if (fn == null) { return null; } return function(){ var mix = fn.apply(model, arguments), message, error; if (mix == null) { return null; } if (is_String(mix)) { return { message: mix, property: prop, ctx: model }; } mix.property = prop; mix.ctx = model; return mix; }; } function fn_byName(name, param, message) { var Delegate = Validators[name]; if (Delegate == null) { log_error('Invalid validator', name, 'Supports:', Object.keys(Validators)); return null; } var fn = Delegate(param); return function(val, ctr){ var mix = fn(val, ctr); if (mix == null || mix === true) { return null; } if (mix === false) { return message || ('Check failed: `' + name + '`'); } if (is_String(mix) && mix.length !== 0) { return mix; } return null; }; } function ui_notifyInvalid(el, error, oncancel) { var message = error.message || error; var next = domLib(el).next('.' + class_INVALID); if (next.length === 0) { next = domLib('<div>') .addClass(class_INVALID) .html('<span></span><button>&otimes;</button>') .insertAfter(el); } return next .children('button') .off() .on('click', function() { next.hide(); oncancel && oncancel(); }) .end() .children('span').text(message) .end() .show(); } function ui_clearInvalid(el) { return domLib(el).next('.' + class_INVALID).hide(); } Validators = { match: function (match) { return function (str){ return new RegExp(match).test(str); }; }, unmatch: function (unmatch) { return function (str){ return !(new RegExp(unmatch).test(str)); }; }, minLength: function (min) { return function (str){ return str.length >= parseInt(min, 10); }; }, maxLength: function (max) { return function (str){ return str.length <= parseInt(max, 10); }; }, check: function (condition, node){ return function (str){ return expression_eval('x' + condition, node.model, {x: str}, node); }; } }; }()); // end:source ValidatorProvider // source BindingProvider var CustomProviders, BindingProvider; (function() { CustomProviders = {}; BindingProvider = class_create({ validations: null, constructor: function BindingProvider(model, element, ctr, bindingType) { if (bindingType == null) { bindingType = 'dual'; var name = ctr.compoName; if (name === ':bind' || name === 'bind') { bindingType = 'single'; } } var attr = ctr.attr; this.ctr = ctr; this.ctx = null; this.model = model; this.element = element; this.value = attr.value; this.property = attr.property; this.domSetter = attr['dom-setter'] || attr.setter; this.domGetter = attr['dom-getter'] || attr.getter; this.objSetter = attr['obj-setter']; this.objGetter = attr['obj-getter']; this.mapToObj = attr['map-to-obj']; this.mapToDom = attr['map-to-dom']; this.changeEvent = attr['change-event'] || 'change'; /* Convert to an instance, e.g. Number, on domchange event */ this['typeof'] = attr['typeof'] || null; this.dismiss = 0; this.bindingType = bindingType; this.log = false; this.signal_domChanged = null; this.signal_objectChanged = null; this.locked = false; var isCompoBinder = ctr.node.parent.tagName === ctr.parent.compoName; if (isCompoBinder && (element.nodeType !== 1 || element.tagName !== 'INPUT')) { if (this.domSetter == null) this.domSetter = 'setValue'; if (this.domGetter == null) this.domGetter = 'getValue'; if (attr['dom-slot'] == null) attr['dom-slot'] = 'input'; } if (this.property == null && this.domGetter == null) { switch (element.tagName) { case 'INPUT': // Do not use .type accessor, as some browsers do not support e.g. date var type = element.getAttribute('type'); if ('checkbox' === type) { this.property = 'element.checked'; break; } else if ('date' === type || 'time' === type || 'month' === type) { var x = DomObjectTransport[type.toUpperCase()]; this.domWay = x.domWay; this.objectWay = x.objectWay; } else if ('number' === type) { this['typeof'] = 'Number'; } else if ('radio' === type) { var x = DomObjectTransport.RADIO; this.domWay = x.domWay; break; } this.property = 'element.value'; break; case 'TEXTAREA': this.property = 'element.value'; break; case 'SELECT': this.domWay = element.multiple ? DomObjectTransport.SELECT_MULT : DomObjectTransport.SELECT; break; default: this.property = 'element.innerHTML'; break; } } if (attr['log']) { this.log = true; if (attr.log !== 'log') { this.logExpression = attr.log; } } // Send signal on OBJECT or DOM change if (attr['x-signal']) { var signals = signal_parse(attr['x-signal'], null, 'dom'), i = signals.length; while (--i > -1) { var signal = signals[i], signalType = signal && signal.type; if (signalType !== 'dom' && signalType !== 'object') { log_error('Signal typs is not supported', signal); continue; } this['signal_' + signalType + 'Changed'] = signal.signal; } } // Send PIPED signal on OBJECT or DOM change if (attr['x-pipe-signal']) { var signals = signal_parse(attr['x-pipe-signal'], true, 'dom'), i = signals.length; while (--i > -1) { var signal = signals[i], signalType = signal && signal.type; if (signalType !== 'dom' && signalType !== 'object') { log_error('Pipe type is not supported', signal); continue; } this['pipe_' + signalType + 'Changed'] = signal; } } var domSlot = attr['dom-slot']; if (domSlot != null) { this.slots = {}; // @hack - place dualb. provider on the way of a signal // var parent = ctr.parent, newparent = parent.parent; parent.parent = this; this.parent = newparent; this.slots[domSlot] = function(sender, value) { this.domChanged(sender, value); }; } /* * @obsolete: attr name : 'x-pipe-slot' */ var pipeSlot = attr['object-pipe-slot'] || attr['x-pipe-slot']; if (pipeSlot) { var str = pipeSlot, index = str.indexOf('.'), pipeName = str.substring(0, index), signal = str.substring(index + 1); this.pipes = {}; this.pipes[pipeName] = {}; this.pipes[pipeName][signal] = function() { this.objectChanged(); }; __Compo.pipe.addController(this); } var expression = attr.expression || ctr.expression; if (expression) { this.expression = expression; if (this.value == null && bindingType !== 'single') { var refs = expression_varRefs(this.expression); if (typeof refs === 'string') { this.value = refs; } else { log_warn('Please set value attribute in DualBind Control.'); } } return; } this.expression = this.value; }, dispose: function() { expression_unbind(this.expression, this.model, this.ctr, this.binder); }, objectChanged: function(x) { if (this.dismiss-- > 0) { return; } if (this.locked === true) { log_warn('Concurance change detected', this); return; } this.locked = true; if (x == null || this.objGetter != null) { x = this.objectWay.get(this, this.expression); } if (this.mapToDom != null) { x = expression_callFn( this.mapToDom, this.model, null, this.ctr, [x] ); } this.domWay.set(this, x); if (this.log) { console.log('[BindingProvider] objectChanged -', x); } if (this.signal_objectChanged) { __Compo.signal.emitOut(this.ctr, this.signal_objectChanged, this.ctr, [x]); } if (this.pipe_objectChanged) { var pipe = this.pipe_objectChanged; __Compo.pipe(pipe.pipe).emit(pipe.signal); } this.locked = false; }, domChanged: function(event, val_) { if (this.locked === true) { log_warn('Concurance change detected', this); return; } this.locked = true; var value = val_; if (value == null) value = this.domWay.get(this); var typeof_ = this['typeof']; if (typeof_ != null) { var Converter = window[typeof_]; value = Converter(value); } if (this.mapToObj != null) { value = expression_callFn( this.mapToObj, this.model, null, this.ctr, [value] ); } var error = this.validate(value); if (error == null) { this.dismiss = 1; var tuple = expression_getHost(this.value, this.model, null, this.ctr.parent); if (tuple != null) { var obj = tuple[0], prop = tuple[1]; this.objectWay.set(obj, prop, value, this); } this.dismiss = 0; if (this.log) { console.log('[BindingProvider] domChanged -', value); } if (this.signal_domChanged != null) { __Compo.signal.emitOut(this.ctr, this.signal_domChanged, this.ctr, [value]); } if (this.pipe_domChanged != null) { var pipe = this.pipe_domChanged; __Compo.pipe(pipe.pipe).emit(pipe.signal); } } this.locked = false; }, addValidation: function(mix) { if (this.validations == null) { this.validations = []; } if (is_Array(mix)) { this.validations = this.validations.concat(mix); return; } this.validations.push(mix); }, validate: function(val) { var fns = this.validations, ctr = this.ctr, el = this.element; if (fns == null || fns.length === 0) { return null; } var val_ = arguments.length !== 0 ? val : this.domWay.get(this); return ValidatorProvider.validateUi( fns, val_, ctr, el, this.objectChanged.bind(this) ); }, objectWay: DomObjectTransport.objectWay, domWay: DomObjectTransport.domWay, }); obj_extend(BindingProvider, { create: function(model, el, ctr, bindingType) { /* Initialize custom provider */ var type = ctr.attr.bindingProvider, CustomProvider = type == null ? null : CustomProviders[type], provider; if (typeof CustomProvider === 'function') { return new CustomProvider(model, el, ctr, bindingType); } provider = new BindingProvider(model, el, ctr, bindingType); if (CustomProvider != null) { obj_extend(provider, CustomProvider); } return provider; }, bind: function(provider) { return apply_bind(provider); } }); function apply_bind(provider) { var expr = provider.expression, model = provider.model, onObjChanged = provider.objectChanged = provider.objectChanged.bind(provider); provider.binder = expression_createBinder(expr, model, provider.ctx, provider.ctr, onObjChanged); expression_bind(expr, model, provider.ctx, provider.ctr, provider.binder); if (provider.bindingType === 'dual') { var attr = provider.ctr.attr; if (!attr['dom-slot'] && !attr['change-pipe-event']) { var element = provider.element, eventType = provider.changeEvent, onDomChange = provider.domChanged.bind(provider); __dom_addEventListener(element, eventType, onDomChange); } if (provider.objectWay.get(provider, provider.expression) == null) { // object has no value, so check the dom setTimeout(function() { if (provider.domWay.get(provider)) // and apply when exists provider.domChanged(); }); return provider; } } // trigger update provider.objectChanged(); return provider; } obj_extend(BindingProvider, { addObserver: obj_addObserver, removeObserver: obj_removeObserver }); }()); // end:source BindingProvider // source handlers/ // source visible /** * visible handler. Used to bind directly to display:X/none * * attr = * check - expression to evaluate * bind - listen for a property change */ function VisibleHandler() {} __registerHandler(':visible', VisibleHandler); VisibleHandler.prototype = { constructor: VisibleHandler, refresh: function(model, container) { container.style.display = expression_eval(this.attr.check, model) ? '' : 'none'; }, renderStart: function(model, cntx, container) { this.refresh(model, container); if (this.attr.bind) { obj_addObserver(model, this.attr.bind, this.refresh.bind(this, model, container)); } } }; // end:source visible // source validate var ValidationCompo; (function() { var class_INVALID = '-validate-invalid'; ValidationCompo = class_create({ attr: null, element: null, validators: null, constructor: function(){ this.validators = []; }, renderStart: function(model, ctx, container) { this.element = container; var prop = this.attr.value; if (prop) { var fn = ValidatorProvider.getFnFromModel(model, prop); if (fn != null) { this.validators.push(fn); } } }, /** * @param input - {control specific} - value to validate * @param element - {HTMLElement} - (optional, @default this.element) - * Invalid message is schown(inserted into DOM) after this element * @param oncancel - {Function} - Callback function for canceling * invalid notification */ validate: function(val, el, oncancel) { var element = el == null ? this.element : el, value = val; if (arguments.length === 0) { value = obj_getProperty(this.model, this.attr.value); } if (this.validators.length === 0) { this.initValidators(); } var fns = this.validators, type = this.attr.silent ? 'validate' : 'validateUi' ; return ValidatorProvider[type]( fns, value, this, element, oncancel ); }, initValidators: function() { var attr = this.attr, message = this.attr.message, isDefault = message == null if (isDefault) { message = 'Invalid value of `' + this.attr.value + '`'; } for (var key in attr) { switch (key) { case 'message': case 'value': case 'getter': case 'silent': continue; } if (key in Validators === false) { log_error('Unknown Validator:', key, this); continue; } var str = isDefault ? (message + ' Validation: `' + key + '`') : message var fn = ValidatorProvider.getFnByName(key, attr[key], str); if (fn != null) { this.validators.push(fn); } } } }); __registerHandler(':validate', ValidationCompo); __registerHandler(':validate:message', Compo({ template: 'div.' + class_INVALID + ' { span > "~[bind:message]" button > "~[cancel]" }', onRenderStart: function(model){ if (typeof model === 'string') { model = { message: model }; } if (!model.cancel) { model.cancel = 'cancel'; } this.model = model; }, compos: { button: '$: button', }, show: function(message, oncancel){ var that = this; this.model.message = message; this.compos.button.off().on(function(){ that.hide(); oncancel && oncancel(); }); this.$.show(); }, hide: function(){ this.$.hide(); } })); }()); // end:source validate // source validate_group function ValidateGroup() {} __registerHandler(':validate:group', ValidateGroup); ValidateGroup.prototype = { constructor: ValidateGroup, validate: function() { var validations = getValidations(this); for (var i = 0, x, length = validations.length; i < length; i++) { x = validations[i]; if (!x.validate()) { return false; } } return true; } }; function getValidations(component, out){ if (out == null){ out = []; } if (component.components == null){ return out; } var compos = component.components; for(var i = 0, x, length = compos.length; i < length; i++){ x = compos[i]; if (x.compoName === 'validate'){ out.push(x); continue; } getValidations(x); } return out; } // end:source validate_group // if BROWSER // source bind /** * Mask Custom Tag Handler * attr = * attr: {String} - attribute name to bind * prop: {Stirng} - property name to bind * - : {default} - innerHTML */ (function() { function Bind() {} __registerHandler(':bind', Bind); __registerHandler( 'bind', Bind); Bind.prototype = { constructor: Bind, renderEnd: function(els, model, cntx, container){ this.provider = BindingProvider.create(model, container, this, 'single'); BindingProvider.bind(this.provider); }, dispose: function(){ if (this.provider && typeof this.provider.dispose === 'function') { this.provider.dispose(); } } }; }()); // end:source bind // source dualbind /** * Mask Custom Handler * * 2 Way Data Model binding * * * attr = * value: {string} - property path in object * ?property : {default} 'element.value' - value to get/set from/to HTMLElement * ?changeEvent: {default} 'change' - listen to this event for HTMLELement changes * * ?setter: {string} - setter function of a parent controller * ?getter: {string} - getter function of a parent controller * * */ var DualbindCompo = class_create({ renderEnd: function(elements, model, ctx, container) { this.provider = BindingProvider.create(model, container, this); var compos = this.components; if (compos != null) { var imax = compos.length, i = -1, x; while ( ++i < imax ){ x = compos[i]; if (x.compoName === ':validate') { this.provider.addValidation(x.validations); } } } if (this.attr['no-validation'] == null) { var fn = ValidatorProvider.getFnFromModel(model, this.provider.value); if (fn != null) { this.provider.addValidation(fn); } } BindingProvider.bind(this.provider); }, dispose: function() { var dispose = this.provider && this.provider.dispose; if (dispose != null) { dispose.call(this.provider); } }, validate: function(){ return this.provider && this.provider.validate(); }, handlers: { attr: { 'x-signal': function() {} } } }); __registerHandler(':dualbind', DualbindCompo); __registerHandler( 'dualbind', DualbindCompo); // end:source dualbind // endif // end:source handlers/ // source utilities/ // source bind /** * Mask Custom Utility - for use in textContent and attribute values */ (function(){ function attr_strReplace(attrValue, currentValue, newValue) { if (!attrValue) return newValue; if (currentValue == null || currentValue === '') return attrValue + ' ' + newValue; return attrValue.replace(currentValue, newValue); } function refresherDelegate_NODE(el){ return function(value) { el.textContent = value; }; } /** Attributes */ function refresherDelegate_ATTR(el, attrName, currentValue) { var current_ = currentValue; return function(value){ var currentAttr = el.getAttribute(attrName), attr = attr_strReplace(currentAttr, current_, value); if (attr == null || attr === '') { el.removeAttribute(attrName); } else { el.setAttribute(attrName, attr); } current_ = value; }; } function refresherDelegate_ATTR_COMPO(ctr, attrName, currentValue) { var current_ = currentValue; return function(val){ if (current_ === val) { return; } current_ = val; var fn = ctr.setAttribute; if (is_Function(fn)) { fn.call(ctr, attrName, val); return; } ctr.attr[attrName] = val; }; } function refresherDelegate_ATTR_PROP(element, attrName, currentValue) { return function(value){ switch(typeof element[attrName]) { case 'boolean': currentValue = element[attrName] = !!value; return; case 'number': currentValue = element[attrName] = Number(value); return; case 'string': currentValue = element[attrName] = attr_strReplace(element[attrName], currentValue, value); return; default: log_warn('Unsupported elements property type', attrName); return; } }; } /** Properties */ function refresherDelegate_PROP_NODE(el, property, currentValue) { return function(value){ obj_setProperty(el, property, value); }; } function refresherDelegate_PROP_COMPO(ctr, property, currentValue) { var current_ = currentValue; return function(val){ if (current_ === val) { return; } current_ = val; obj_setProperty(ctr, property, val); }; } function create_refresher(type, expr, element, currentValue, attrName, ctr) { if ('node' === type) { return refresherDelegate_NODE(element); } if ('attr' === type) { switch(attrName) { case 'value': case 'disabled': case 'checked': case 'selected': case 'selectedIndex': if (attrName in element) { return refresherDelegate_ATTR_PROP(element, attrName, currentValue); } } return refresherDelegate_ATTR(element, attrName, currentValue); } if ('prop' === type) { return refresherDelegate_PROP_NODE(element, attrName, currentValue); } if ('compo-attr' === type) { return refresherDelegate_ATTR_COMPO(ctr, attrName, currentValue) } if ('compo-prop' === type) { return refresherDelegate_PROP_COMPO(ctr, attrName, currentValue) } throw Error('Unexpected binder type: ' + type); } function bind (current, expr, model, ctx, element, ctr, attrName, type){ var refresher = create_refresher(type, expr, element, current, attrName, ctr), binder = expression_createBinder(expr, model, ctx, ctr, refresher); expression_bind(expr, model, ctx, ctr, binder); compo_attachDisposer(ctr, function(){ expression_unbind(expr, model, ctr, binder); }); } __registerUtil('bind', { mode: 'partial', current: null, element: null, nodeRenderStart: function(expr, model, ctx, el, ctr, type, node){ var current = expression_eval(expr, model, ctx, ctr, node); // though we apply value's to `this` context, but it is only for immediat use // in .node() function, as `this` context is a static object that share all bind // utils this.element = document.createTextNode(current); return (this.current = current); }, node: function(expr, model, ctx, container, ctr){ var el = this.element, val = this.current; bind( val , expr , model , ctx , el , ctr , null , 'node' ); this.element = null; this.current = null; return el; }, attrRenderStart: function(expr, model, ctx, el, ctr, type, node){ return (this.current = expression_eval(expr, model, ctx, ctr, node)); }, attr: function(expr, model, ctx, element, controller, attrName, type){ bind( this.current, expr, model, ctx, element, controller, attrName, type); return this.current; } }); }()); // end:source bind // end:source utilities/ // source attributes/ // source xxVisible __registerAttr('xx-visible', function(node, attrValue, model, ctx, el, ctr) { var binder = expression_createBinder(attrValue, model, ctx, ctr, function(value){ el.style.display = value ? '' : 'none'; }); expression_bind(attrValue, model, ctx, ctr, binder); compo_attachDisposer(ctr, function(){ expression_unbind(attrValue, model, ctr, binder); }); if (!expression_eval(attrValue, model, ctx, ctr, node)) { el.style.display = 'none'; } }); // end:source xxVisible // source xToggle /** * Toggle value with ternary operator on an event. * * button x-toggle='click: foo === "bar" ? "zet" : "bar" > 'Toggle' */ __registerAttr('x-toggle', 'client', function(node, attrValue, model, ctx, el, ctr){ var event = attrValue.substring(0, attrValue.indexOf(':')), expression = attrValue.substring(event.length + 1), ref = expression_varRefs(expression); if (typeof ref !== 'string') { // assume is an array ref = ref[0]; } __dom_addEventListener(el, event, function(){ var val = expression_eval(expression, model, ctx, ctr, node); obj_setProperty(model, ref, val); }); }); // end:source xToggle // source xClassToggle /** * Toggle Class Name * * button x-toggle='click: selected' */ __registerAttr('x-class-toggle', 'client', function(node, attrVal, model, ctx, element){ var event = attrVal.substring(0, attrVal.indexOf(':')), klass = attrVal.substring(event.length + 1).trim(); __dom_addEventListener(element, event, function(){ domLib(element).toggleClass(klass); }); }); // end:source xClassToggle // end:source attributes/ // source statements/ (function(){ var custom_Statements = mask.getStatement(); // source 1.utils.js var _getNodes, _renderPlaceholder, _compo_initAndBind, els_toggleVisibility ; (function(){ _getNodes = function(name, node, model, ctx, controller){ return custom_Statements[name].getNodes(node, model, ctx, controller); }; _renderPlaceholder = function(staticCompo, compo, container){ var placeholder = staticCompo.placeholder; if (placeholder == null) { placeholder = document.createComment(''); container.appendChild(placeholder); } compo.placeholder = placeholder; }; _compo_initAndBind = function(compo, node, model, ctx, container, controller) { compo.parent = controller; compo.model = model; compo.ctx = ctx; compo.refresh = fn_proxy(compo.refresh, compo); compo.binder = expression_createBinder( compo.expr || compo.expression, model, ctx, controller, compo.refresh ); expression_bind(compo.expr || compo.expression, model, ctx, controller, compo.binder); }; (function(){ els_toggleVisibility = function(mix, state){ if (mix == null) return; if (is_Array(mix)) { _arr(mix, state); return; } _single(mix, state); }; function _single(el, state) { el.style.display = state ? '' : 'none'; } function _arr(els, state) { var imax = els.length, i = -1; while (++i < imax) _single(els[i], state); } }()); }()); // end:source 1.utils.js // source 2.if.js (function(){ __registerHandler('+if', { placeholder: null, meta: { serializeNodes: true }, render: function(model, ctx, container, ctr, children){ var node = this, nodes = _getNodes('if', node, model, ctx, ctr), index = 0, next = node; while(next.nodes !== nodes){ index++; next = node.nextSibling; if (next == null || next.tagName !== 'else') { index = null; break; } } this.attr['switch-index'] = index; return compo_renderElements(nodes, model, ctx, container, ctr, children); }, renderEnd: function(els, model, ctx, container, ctr){ var compo = new IFStatement(), index = this.attr['switch-index']; _renderPlaceholder(this, compo, container); return initialize( compo , this , index , els , model , ctx , container , ctr ); }, serializeNodes: function(current){ var nodes = [ current ]; while (true) { current = current.nextSibling; if (current == null || current.tagName !== 'else') { break; } nodes.push(current); } return mask.stringify(nodes); } }); function IFStatement() {} IFStatement.prototype = { compoName: '+if', ctx : null, model : null, controller : null, index : null, Switch : null, binder : null, refresh: function() { var currentIndex = this.index, model = this.model, ctx = this.ctx, ctr = this.controller, switch_ = this.Switch, imax = switch_.length, i = -1; while ( ++i < imax ){ var node = switch_[i].node; var expr = node.expression; if (expr == null) break; if (expression_eval(expr, model, ctx, ctr, node)) break; } if (currentIndex === i) return; if (currentIndex != null) els_toggleVisibility(switch_[currentIndex].elements, false); if (i === imax) { this.index = null; return; } this.index = i; var current = switch_[i]; if (current.elements != null) { els_toggleVisibility(current.elements, true); return; } var nodes = current.node.nodes, frag = document.createDocumentFragment(), owner = { components: [], parent: ctr }, els = compo_renderElements(nodes, model, ctx, frag, owner); dom_insertBefore(frag, this.placeholder); current.elements = els; compo_inserted(owner); if (ctr.components == null) { ctr.components = []; } ctr.components.push.apply(ctr.components, owner.components); }, dispose: function(){ var switch_ = this.Switch, imax = switch_.length, i = -1, x, expr; while( ++i < imax ){ x = switch_[i]; expr = x.node.expression; if (expr) { expression_unbind( expr, this.model, this.controller, this.binder ); } x.node = null; x.elements = null; } this.controller = null; this.model = null; this.ctx = null; } }; function initialize(compo, node, index, elements, model, ctx, container, ctr) { compo.model = model; compo.ctx = ctx; compo.controller = ctr; compo.refresh = fn_proxy(compo.refresh, compo); compo.binder = expression_createListener(compo.refresh); compo.index = index; compo.Switch = [{ node: node, elements: null }]; expression_bind(node.expression, model, ctx, ctr, compo.binder); while (true) { node = node.nextSibling; if (node == null || node.tagName !== 'else') break; compo.Switch.push({ node: node, elements: null }); if (node.expression) expression_bind(node.expression, model, ctx, ctr, compo.binder); } if (index != null) { compo.Switch[index].elements = elements; } return compo; } }()); // end:source 2.if.js // source 3.switch.js (function(){ var $Switch = custom_Statements['switch'], attr_SWITCH = 'switch-index' ; var _nodes, _index; __registerHandler('+switch', { meta: { serializeNodes: true }, serializeNodes: function(current){ return mask.stringify(current); }, render: function(model, ctx, container, ctr, children){ var value = expression_eval(this.expression, model, ctx, ctr); resolveNodes(value, this.nodes, model, ctx, ctr); var nodes = _nodes, index = _index; if (nodes == null) { return null; } this.attr[attr_SWITCH] = index; return compo_renderElements(nodes, model, ctx, container, ctr, children); }, renderEnd: function(els, model, ctx, container, ctr){ var compo = new SwitchStatement(), index = this.attr[attr_SWITCH]; _renderPlaceholder(this, compo, container); return initialize( compo , this , index , els , model , ctx , container , ctr ); } }); function SwitchStatement() {} SwitchStatement.prototype = { compoName: '+switch', ctx: null, model: null, controller: null, index: null, nodes: null, Switch: null, binder: null, refresh: function(value) { var compo = this, Switch = compo.Switch, model = compo.model, ctx = compo.ctx, ctr = compo.controller ; resolveNodes(value, compo.nodes, model, ctx, ctr); var nodes = _nodes, index = _index; if (index === compo.index) { return; } if (compo.index != null) { els_toggleVisibility(Switch[compo.index], false); } compo.index = index; if (index == null) { return; } var elements = Switch[index]; if (elements != null) { els_toggleVisibility(elements, true); return; } var result = mask.render(nodes, model, ctx, null, ctr); Switch[index] = result.nodeType === Node.DOCUMENT_FRAGMENT_NODE ? _Array_slice.call(result.childNodes) : result ; dom_insertBefore(result, compo.placeholder); }, dispose: function(){ expression_unbind( this.expr, this.model, this.controller, this.binder ); this.controller = null; this.model = null; this.ctx = null; var switch_ = this.Switch, key, els, i, imax ; for(key in switch_) { els = switch_[key]; if (els == null) continue; imax = els.length; i = -1; while ( ++i < imax ){ if (els[i].parentNode != null) els[i].parentNode.removeChild(els[i]); } } } }; function resolveNodes(val, nodes, model, ctx, ctr) { _nodes = $Switch.getNodes(val, nodes, model, ctx, ctr); _index = null; if (_nodes == null) return; var imax = nodes.length, i = -1; while( ++i < imax ){ if (nodes[i].nodes === _nodes) break; } _index = i === imax ? null : i; } function initialize(compo, node, index, elements, model, ctx, container, ctr) { compo.ctx = ctx; compo.expr = node.expression; compo.model = model; compo.controller = ctr; compo.index = index; compo.nodes = node.nodes; compo.refresh = fn_proxy(compo.refresh, compo); compo.binder = expression_createBinder( compo.expr, model, ctx, ctr, compo.refresh ); compo.Switch = new Array(node.nodes.length); if (index != null) { compo.Switch[index] = elements; } expression_bind(node.expression, model, ctx, ctr, compo.binder); return compo; } }()); // end:source 3.switch.js // source 4.with.js (function(){ __registerHandler('+with', { meta: { serializeNodes: true }, rootModel: null, render: function(model, ctx, container, ctr){ var expr = this.expression, nodes = this.nodes, val = expression_eval_strict( expr, model, ctx, ctr ) ; this.rootModel = model; return compo_renderElements(nodes, val, ctx, container, ctr); }, onRenderStartClient: function(model, ctx){ this.rootModel = model; this.model = expression_eval_strict( this.expression, model, ctx, this ); }, renderEnd: function(els, model_, ctx, container, ctr){ var model = this.rootModel || model_, compo = new WithStatement(this); compo.elements = els; compo.model = model; compo.parent = ctr; compo.refresh = fn_proxy(compo.refresh, compo); compo.binder = expression_createBinder( compo.expr, model, ctx, ctr, compo.refresh ); expression_bind( compo.expr, model, ctx, ctr, compo.binder ); _renderPlaceholder(this, compo, container); return compo; } }); function WithStatement(node){ this.expr = node.expression; this.nodes = node.nodes; } WithStatement.prototype = { compoName: '+with', elements: null, binder: null, model: null, parent: null, refresh: function(model){ compo_disposeChildren(this); compo_renderChildren(this, this.placeholder, model); }, dispose: function(){ expression_unbind( this.expr, this.model, this.parent, this.binder ); this.parent = null; this.model = null; this.ctx = null; } }; }()); // end:source 4.with.js // source 5.visible.js (function(){ var $Visible = custom_Statements['visible']; __registerHandler('+visible', { meta: { serializeNodes: true }, render: function(model, ctx, container, ctr, childs){ return build(this.nodes, model, ctx, container, ctr); }, renderEnd: function(els, model, ctx, container, ctr){ var compo = new VisibleStatement(this); compo.elements = els; compo.model = model; compo.parent = ctr; compo.refresh = fn_proxy(compo.refresh, compo); compo.binder = expression_createBinder( compo.expr, model, ctx, ctr, compo.refresh ); expression_bind(compo.expr, model, ctx, ctr, compo.binder); compo.refresh(); return compo; } }); function VisibleStatement(node){ this.expr = node.expression; this.nodes = node.nodes; } VisibleStatement.prototype = { compoName: '+visible', elements: null, binder: null, model: null, parent: null, refresh: function(){ var isVisible = expression_eval( this.expr, this.model, this.ctx, this ); $Visible.toggle(this.elements, isVisible); }, dispose: function(){ expression_unbind( this.expr, this.model, this.parent, this.binder ); this.parent = null; this.model = null; this.ctx = null; } }; function build(nodes, model, ctx, container, ctr){ var els = []; builder_build(nodes, model, ctx, container, ctr, els); return els; } }()); // end:source 5.visible.js // source 6.listen.js (function(){ __registerHandler('listen', class_create({ disposed: false, placeholder: null, compoName: 'listen', show: null, hide: null, binder: null, meta: { serializeNodes: true, attributes: { animatable: false, on: false, rx: false, } }, renderEnd: function(els, model, ctx, container, ctr){ _renderPlaceholder(this, this, container); var fn = Boolean(this.attr.animatable) ? this.refreshAni : this.refreshSync; this.refresh = fn_proxy(fn, this); this.elements = els; var Ctor = this.getBinder(); this.binder = new Ctor(this.expression, model, this); this.binder.bind(this.refresh); }, getBinder: function(){ if (this.attr.on) { return Binders.EventEmitterBinder; } if (this.attr.rx) { return Binders.RxBinder; } return Binders.ExpressionBinder; }, dispose: function(){ this.binder.dispose(); this.disposed = true; this.elements = null; this.parent = null; this.model = null; this.ctx = null; }, refresh: function(){ throw new Error('Should be defined'); }, refreshSync: function(){ compo_disposeChildren(this); this.create(); }, create: function(){ compo_renderChildren(this, this.placeholder); }, refreshAni: function(){ var x = compo_transferChildren(this); var me = this; var show = me.getAni('show'); var hide = me.getAni('hide'); if (this.attr.animatable === 'parallel') { show.start(me.create()); hide.start(x.elements, function(){ compo_dispose(x); }); return; } hide.start(x.elements, function(){ if (me.disposed === true) { return; } compo_dispose(x); show.start(me.create()); }); }, getAni: function (name) { var x = this[name]; if (x != null) { return x; } var ani = Compo.child('Animation#' + name); if (ani != null) { return (this[name] = ani.start.bind(ani)); } }, })); }()); // end:source 6.listen.js // source loop/exports.js (function(){ // source utils.js var arr_createRefs, list_sort, list_update, list_remove; (function() { arr_createRefs = function(array){ var imax = array.length, i = -1; while ( ++i < imax ){ //create references from values to distinguish the models var x = array[i]; switch (typeof x) { case 'string': case 'number': case 'boolean': array[i] = Object(x); break; } } }; list_sort = function(self, array){ var compos = self.node.components, i = 0, imax = compos.length, j = 0, jmax = null, element = null, compo = null, fragment = document.createDocumentFragment(), sorted = []; for (; i < imax; i++) { compo = compos[i]; if (compo.elements == null || compo.elements.length === 0) continue; for (j = 0, jmax = compo.elements.length; j < jmax; j++) { element = compo.elements[j]; element.parentNode.removeChild(element); } } outer: for (j = 0, jmax = array.length; j < jmax; j++) { for (i = 0; i < imax; i++) { if (array[j] === self._getModel(compos[i])) { sorted[j] = compos[i]; continue outer; } } console.warn('No Model Found for', array[j]); } for (i = 0, imax = sorted.length; i < imax; i++) { compo = sorted[i]; if (compo.elements == null || compo.elements.length === 0) { continue; } for (j = 0, jmax = compo.elements.length; j < jmax; j++) { element = compo.elements[j]; fragment.appendChild(element); } } self.components = self.node.components = sorted; dom_insertBefore(fragment, self.placeholder); }; list_update = function(self, deleteIndex, deleteCount, insertIndex, rangeModel){ var node = self.node, compos = node.components ; if (compos == null) compos = node.components = [] var prop1 = self.prop1, prop2 = self.prop2, type = self.type, ctx = self.ctx, ctr = self.node ; if (deleteIndex != null && deleteCount != null) { var i = deleteIndex, length = deleteIndex + deleteCount; if (length > compos.length) length = compos.length; for (; i < length; i++) { if (compo_dispose(compos[i], node)){ i--; length--; } } } if (insertIndex != null && rangeModel && rangeModel.length) { var i = compos.length, imax, fragment = self._build(node, rangeModel, ctx, ctr), new_ = compos.splice(i) ; compo_fragmentInsert(node, insertIndex, fragment, self.placeholder); compos.splice.apply(compos, [insertIndex, 0].concat(new_)); i = 0; imax = new_.length; for(; i < imax; i++){ __Compo.signal.emitIn(new_[i], 'domInsert'); } } }; list_remove = function(self, removed){ var compos = self.components, i = compos.length; while(--i > -1){ var x = compos[i]; if (removed.indexOf(x.model) === -1) { continue; } compo_dispose(x, self.node); } }; }()); // end:source utils.js // source proto.js var LoopStatementProto = { ctx: null, model: null, parent: null, binder: null, refresh: function(value, method, args, result){ var i = 0, x, imax; var node = this.node, model = this.model, ctx = this.ctx, ctr = this.node ; if (method == null) { // this was new array/object setter and not an immutable function call var compos = node.components; if (compos != null) { var imax = compos.length, i = -1; while ( ++i < imax ){ if (compo_dispose(compos[i], node)){ i--; imax--; } } compos.length = 0; } var frag = this._build(node, value, ctx, ctr); dom_insertBefore(frag, this.placeholder); arr_each(node.components, compo_inserted); return; } var array = value; arr_createRefs(value); switch (method) { case 'push': list_update(this, null, null, array.length - 1, array.slice(array.length - 1)); break; case 'pop': list_update(this, array.length, 1); break; case 'unshift': list_update(this, null, null, 0, array.slice(0, 1)); break; case 'shift': list_update(this, 0, 1); break; case 'splice': var sliceStart = args[0], sliceRemove = args.length === 1 ? this.components.length : args[1], sliceAdded = args.length > 2 ? array.slice(args[0], args.length - 2 + args[0]) : null; list_update(this, sliceStart, sliceRemove, sliceStart, sliceAdded); break; case 'sort': case 'reverse': list_sort(this, array); break; case 'remove': if (result != null && result.length) list_remove(this, result); break; } }, dispose: function(){ expression_unbind( this.expr || this.expression, this.model, this.parent, this.binder ); } }; // end:source proto.js // source for.js (function(){ var For = custom_Statements['for'], attr_PROP_1 = 'for-prop-1', attr_PROP_2 = 'for-prop-2', attr_TYPE = 'for-type', attr_EXPR = 'for-expr' ; __registerHandler('+for', { meta: { serializeNodes: true }, serializeNodes: function(node){ return mask.stringify(node); }, render: function(model, ctx, container, ctr, children){ var directive = For.parseFor(this.expression), attr = this.attr; attr[attr_PROP_1] = directive[0]; attr[attr_PROP_2] = directive[1]; attr[attr_TYPE] = directive[2]; attr[attr_EXPR] = directive[3]; var value = expression_eval_strict(directive[3], model, ctx, ctr); if (value == null) return; if (is_Array(value)) arr_createRefs(value); For.build( value, directive, this.nodes, model, ctx, container, this, children ); }, renderEnd: function(els, model, ctx, container, ctr){ var compo = new ForStatement(this, this.attr); _renderPlaceholder(this, compo, container); _compo_initAndBind(compo, this, model, ctx, container, ctr); return compo; }, getHandler: function(name, model){ return For.getHandler(name, model); } }); function initialize(compo, node, els, model, ctx, container, ctr) { compo.parent = ctr; compo.model = model; compo.refresh = fn_proxy(compo.refresh, compo); compo.binder = expression_createBinder( compo.expr, model, ctx, ctr, compo.refresh ); expression_bind(compo.expr, model, ctx, ctr, compo.binder); } function ForStatement(node, attr) { this.prop1 = attr[attr_PROP_1]; this.prop2 = attr[attr_PROP_2]; this.type = attr[attr_TYPE]; this.expr = attr[attr_EXPR]; if (node.components == null) node.components = []; this.node = node; this.components = node.components; } ForStatement.prototype = { compoName: '+for', model: null, parent: null, refresh: LoopStatementProto.refresh, dispose: LoopStatementProto.dispose, _getModel: function(compo) { return compo.scope[this.prop1]; }, _build: function(node, model, ctx, component) { var nodes = For.getNodes(node.nodes, model, this.prop1, this.prop2, this.type); return builder_build(nodes, this.model, ctx, null, component); } }; }()); // end:source for.js // source each.js (function(){ var Each = custom_Statements['each']; var EachBinded = { meta: { serializeNodes: true }, serializeNodes: function(node){ return mask.stringify(node); }, //modelRef: null, render: function(model, ctx, container, ctr, children){ //this.modelRef = this.expression; var array = expression_eval(this.expression, model, ctx, ctr); if (array == null) return; arr_createRefs(array); build( this.nodes, array, ctx, container, this, children ); }, renderEnd: function(els, model, ctx, container, ctr){ var compo = new EachStatement(this, this.attr); _renderPlaceholder(this, compo, container); _compo_initAndBind(compo, this, model, ctx, container, ctr); return compo; } }; var EachItem = class_create({ compoName: 'each::item', scope: null, model: null, modelRef: null, parent: null, // if BROWSER renderStart: null, // endif renderEnd: function(els) { this.elements = els; }, dispose: function(){ if (this.elements != null) { this.elements.length = 0; this.elements = null; } } }); var EachStatement = class_create(LoopStatementProto, { compoName: '+each', constructor: function EachStatement(node, attr) { this.expression = node.expression; this.nodes = node.nodes; if (node.components == null) node.components = []; this.node = node; this.components = node.components; }, _getModel: function(compo) { return compo.model; }, _build: function(node, model, ctx, component) { var fragment = document.createDocumentFragment(); build(node.nodes, model, ctx, fragment, component); return fragment; } }); // METHODS function build(nodes, array, ctx, container, ctr, elements) { var imax = array.length, nodes_ = new Array(imax), i = 0, node; for(; i < imax; i++) { node = createEachNode(nodes, i); builder_build(node, array[i], ctx, container, ctr, elements); } } function createEachNode(nodes, index){ var item = new EachItem; item.scope = { index: index }; return { type: Dom.COMPONENT, tagName: 'each::item', nodes: nodes, controller: function() { return item; } }; } // EXPORTS __registerHandler('each::item', EachItem); __registerHandler('+each', EachBinded); }()); // end:source each.js }()); // end:source loop/exports.js }()); // end:source statements/ // source exports obj_extend(mask, { Validators: Validators, registerValidator: function(type, fn) { Validators[type] = fn; }, BindingProviders: CustomProviders, registerBinding: function(name, Prov) { CustomProviders[name] = Prov; } }); // end:source exports // source api/utils obj_extend(mask.obj, { addObserver : obj_addObserver, removeObserver: obj_removeObserver, }); // end:source api/utils }(Mask, Compo));
var cursor : Texture2D; var cursorOffset : Vector2; /* function Start() { Screen.showCursor = false; } */ function OnGUI () { if(Screen.lockCursor) { GUI.depth = -999; //GUI.Label(Rect (Event.current.mousePosition.x - cursorOffset.x, Event.current.mousePosition.y - cursorOffset.y, cursor.width, cursor.height), cursor); GUI.Label(Rect (Screen.width / 2 - cursorOffset.x, Screen.height / 2 - cursorOffset.y, cursor.width, cursor.height), cursor); } }
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var cssLexer_1 = require("./cssLexer"); var BlockType; (function (BlockType) { BlockType[BlockType["Import"] = 0] = "Import"; BlockType[BlockType["Charset"] = 1] = "Charset"; BlockType[BlockType["Namespace"] = 2] = "Namespace"; BlockType[BlockType["Supports"] = 3] = "Supports"; BlockType[BlockType["Keyframes"] = 4] = "Keyframes"; BlockType[BlockType["MediaQuery"] = 5] = "MediaQuery"; BlockType[BlockType["Selector"] = 6] = "Selector"; BlockType[BlockType["FontFace"] = 7] = "FontFace"; BlockType[BlockType["Page"] = 8] = "Page"; BlockType[BlockType["Document"] = 9] = "Document"; BlockType[BlockType["Viewport"] = 10] = "Viewport"; BlockType[BlockType["Unsupported"] = 11] = "Unsupported"; })(BlockType = exports.BlockType || (exports.BlockType = {})); var CssAst = (function () { function CssAst(location) { this.location = location; } Object.defineProperty(CssAst.prototype, "start", { get: function () { return this.location.start; }, enumerable: true, configurable: true }); Object.defineProperty(CssAst.prototype, "end", { get: function () { return this.location.end; }, enumerable: true, configurable: true }); return CssAst; }()); exports.CssAst = CssAst; var CssStyleValueAst = (function (_super) { __extends(CssStyleValueAst, _super); function CssStyleValueAst(location, tokens, strValue) { var _this = _super.call(this, location) || this; _this.tokens = tokens; _this.strValue = strValue; return _this; } CssStyleValueAst.prototype.visit = function (visitor, context) { return visitor.visitCssValue(this); }; return CssStyleValueAst; }(CssAst)); exports.CssStyleValueAst = CssStyleValueAst; var CssRuleAst = (function (_super) { __extends(CssRuleAst, _super); function CssRuleAst(location) { return _super.call(this, location) || this; } return CssRuleAst; }(CssAst)); exports.CssRuleAst = CssRuleAst; var CssBlockRuleAst = (function (_super) { __extends(CssBlockRuleAst, _super); function CssBlockRuleAst(location, type, block, name) { if (name === void 0) { name = null; } var _this = _super.call(this, location) || this; _this.location = location; _this.type = type; _this.block = block; _this.name = name; return _this; } CssBlockRuleAst.prototype.visit = function (visitor, context) { return visitor.visitCssBlock(this.block, context); }; return CssBlockRuleAst; }(CssRuleAst)); exports.CssBlockRuleAst = CssBlockRuleAst; var CssKeyframeRuleAst = (function (_super) { __extends(CssKeyframeRuleAst, _super); function CssKeyframeRuleAst(location, name, block) { return _super.call(this, location, BlockType.Keyframes, block, name) || this; } CssKeyframeRuleAst.prototype.visit = function (visitor, context) { return visitor.visitCssKeyframeRule(this, context); }; return CssKeyframeRuleAst; }(CssBlockRuleAst)); exports.CssKeyframeRuleAst = CssKeyframeRuleAst; var CssKeyframeDefinitionAst = (function (_super) { __extends(CssKeyframeDefinitionAst, _super); function CssKeyframeDefinitionAst(location, steps, block) { var _this = _super.call(this, location, BlockType.Keyframes, block, mergeTokens(steps, ',')) || this; _this.steps = steps; return _this; } CssKeyframeDefinitionAst.prototype.visit = function (visitor, context) { return visitor.visitCssKeyframeDefinition(this, context); }; return CssKeyframeDefinitionAst; }(CssBlockRuleAst)); exports.CssKeyframeDefinitionAst = CssKeyframeDefinitionAst; var CssBlockDefinitionRuleAst = (function (_super) { __extends(CssBlockDefinitionRuleAst, _super); function CssBlockDefinitionRuleAst(location, strValue, type, query, block) { var _this = _super.call(this, location, type, block) || this; _this.strValue = strValue; _this.query = query; var firstCssToken = query.tokens[0]; _this.name = new cssLexer_1.CssToken(firstCssToken.index, firstCssToken.column, firstCssToken.line, cssLexer_1.CssTokenType.Identifier, _this.strValue); return _this; } CssBlockDefinitionRuleAst.prototype.visit = function (visitor, context) { return visitor.visitCssBlock(this.block, context); }; return CssBlockDefinitionRuleAst; }(CssBlockRuleAst)); exports.CssBlockDefinitionRuleAst = CssBlockDefinitionRuleAst; var CssMediaQueryRuleAst = (function (_super) { __extends(CssMediaQueryRuleAst, _super); function CssMediaQueryRuleAst(location, strValue, query, block) { return _super.call(this, location, strValue, BlockType.MediaQuery, query, block) || this; } CssMediaQueryRuleAst.prototype.visit = function (visitor, context) { return visitor.visitCssMediaQueryRule(this, context); }; return CssMediaQueryRuleAst; }(CssBlockDefinitionRuleAst)); exports.CssMediaQueryRuleAst = CssMediaQueryRuleAst; var CssAtRulePredicateAst = (function (_super) { __extends(CssAtRulePredicateAst, _super); function CssAtRulePredicateAst(location, strValue, tokens) { var _this = _super.call(this, location) || this; _this.strValue = strValue; _this.tokens = tokens; return _this; } CssAtRulePredicateAst.prototype.visit = function (visitor, context) { return visitor.visitCssAtRulePredicate(this, context); }; return CssAtRulePredicateAst; }(CssAst)); exports.CssAtRulePredicateAst = CssAtRulePredicateAst; var CssInlineRuleAst = (function (_super) { __extends(CssInlineRuleAst, _super); function CssInlineRuleAst(location, type, value) { var _this = _super.call(this, location) || this; _this.type = type; _this.value = value; return _this; } CssInlineRuleAst.prototype.visit = function (visitor, context) { return visitor.visitCssInlineRule(this, context); }; return CssInlineRuleAst; }(CssRuleAst)); exports.CssInlineRuleAst = CssInlineRuleAst; var CssSelectorRuleAst = (function (_super) { __extends(CssSelectorRuleAst, _super); function CssSelectorRuleAst(location, selectors, block) { var _this = _super.call(this, location, BlockType.Selector, block) || this; _this.selectors = selectors; _this.strValue = selectors.map(function (selector) { return selector.strValue; }).join(','); return _this; } CssSelectorRuleAst.prototype.visit = function (visitor, context) { return visitor.visitCssSelectorRule(this, context); }; return CssSelectorRuleAst; }(CssBlockRuleAst)); exports.CssSelectorRuleAst = CssSelectorRuleAst; var CssDefinitionAst = (function (_super) { __extends(CssDefinitionAst, _super); function CssDefinitionAst(location, property, value) { var _this = _super.call(this, location) || this; _this.property = property; _this.value = value; return _this; } CssDefinitionAst.prototype.visit = function (visitor, context) { return visitor.visitCssDefinition(this, context); }; return CssDefinitionAst; }(CssAst)); exports.CssDefinitionAst = CssDefinitionAst; var CssSelectorPartAst = (function (_super) { __extends(CssSelectorPartAst, _super); function CssSelectorPartAst(location) { return _super.call(this, location) || this; } return CssSelectorPartAst; }(CssAst)); exports.CssSelectorPartAst = CssSelectorPartAst; var CssSelectorAst = (function (_super) { __extends(CssSelectorAst, _super); function CssSelectorAst(location, selectorParts) { var _this = _super.call(this, location) || this; _this.selectorParts = selectorParts; _this.strValue = selectorParts.map(function (part) { return part.strValue; }).join(''); return _this; } CssSelectorAst.prototype.visit = function (visitor, context) { return visitor.visitCssSelector(this, context); }; return CssSelectorAst; }(CssSelectorPartAst)); exports.CssSelectorAst = CssSelectorAst; var CssSimpleSelectorAst = (function (_super) { __extends(CssSimpleSelectorAst, _super); function CssSimpleSelectorAst(location, tokens, strValue, pseudoSelectors, operator) { var _this = _super.call(this, location) || this; _this.tokens = tokens; _this.strValue = strValue; _this.pseudoSelectors = pseudoSelectors; _this.operator = operator; return _this; } CssSimpleSelectorAst.prototype.visit = function (visitor, context) { return visitor.visitCssSimpleSelector(this, context); }; return CssSimpleSelectorAst; }(CssSelectorPartAst)); exports.CssSimpleSelectorAst = CssSimpleSelectorAst; var CssPseudoSelectorAst = (function (_super) { __extends(CssPseudoSelectorAst, _super); function CssPseudoSelectorAst(location, strValue, name, tokens, innerSelectors) { var _this = _super.call(this, location) || this; _this.strValue = strValue; _this.name = name; _this.tokens = tokens; _this.innerSelectors = innerSelectors; return _this; } CssPseudoSelectorAst.prototype.visit = function (visitor, context) { return visitor.visitCssPseudoSelector(this, context); }; return CssPseudoSelectorAst; }(CssSelectorPartAst)); exports.CssPseudoSelectorAst = CssPseudoSelectorAst; var CssBlockAst = (function (_super) { __extends(CssBlockAst, _super); function CssBlockAst(location, entries) { var _this = _super.call(this, location) || this; _this.entries = entries; return _this; } CssBlockAst.prototype.visit = function (visitor, context) { return visitor.visitCssBlock(this, context); }; return CssBlockAst; }(CssAst)); exports.CssBlockAst = CssBlockAst; var CssStylesBlockAst = (function (_super) { __extends(CssStylesBlockAst, _super); function CssStylesBlockAst(location, definitions) { var _this = _super.call(this, location, definitions) || this; _this.definitions = definitions; return _this; } CssStylesBlockAst.prototype.visit = function (visitor, context) { return visitor.visitCssStylesBlock(this, context); }; return CssStylesBlockAst; }(CssBlockAst)); exports.CssStylesBlockAst = CssStylesBlockAst; var CssStyleSheetAst = (function (_super) { __extends(CssStyleSheetAst, _super); function CssStyleSheetAst(location, rules) { var _this = _super.call(this, location) || this; _this.rules = rules; return _this; } CssStyleSheetAst.prototype.visit = function (visitor, context) { return visitor.visitCssStyleSheet(this, context); }; return CssStyleSheetAst; }(CssAst)); exports.CssStyleSheetAst = CssStyleSheetAst; var CssUnknownRuleAst = (function (_super) { __extends(CssUnknownRuleAst, _super); function CssUnknownRuleAst(location, ruleName, tokens) { var _this = _super.call(this, location) || this; _this.ruleName = ruleName; _this.tokens = tokens; return _this; } CssUnknownRuleAst.prototype.visit = function (visitor, context) { return visitor.visitCssUnknownRule(this, context); }; return CssUnknownRuleAst; }(CssRuleAst)); exports.CssUnknownRuleAst = CssUnknownRuleAst; var CssUnknownTokenListAst = (function (_super) { __extends(CssUnknownTokenListAst, _super); function CssUnknownTokenListAst(location, name, tokens) { var _this = _super.call(this, location) || this; _this.name = name; _this.tokens = tokens; return _this; } CssUnknownTokenListAst.prototype.visit = function (visitor, context) { return visitor.visitCssUnknownTokenList(this, context); }; return CssUnknownTokenListAst; }(CssRuleAst)); exports.CssUnknownTokenListAst = CssUnknownTokenListAst; function mergeTokens(tokens, separator) { if (separator === void 0) { separator = ''; } var mainToken = tokens[0]; var str = mainToken.strValue; for (var i = 1; i < tokens.length; i++) { str += separator + tokens[i].strValue; } return new cssLexer_1.CssToken(mainToken.index, mainToken.column, mainToken.line, mainToken.type, str); } exports.mergeTokens = mergeTokens;
import { Box, Container, Grid, makeStyles, Typography } from "@material-ui/core"; import React from "react"; import TeamCard from "../TeamCard"; const mentorList = [ { image: "assets/members/amit.png", name: "Amit Kumar", }, { image: "assets/members/anuj.png", name: "Anuj Garg", }, { image: "assets/members/kunal.png", name: "Kunal Kushwaha ", }, { image: "assets/members/ganga.png", name: "Ganga Chaturvedi", }, { image: "assets/members/ekta.png", name: "Ekta Mishra", }, { image: "assets/members/abhishek.jpg", name: "Abhishek Kumar", }, { image: "assets/members/nityanand.png", name: "Nityanand Rai", }, { image: "assets/members/vasu.jpeg", name: "Vasudev Singhal", }, { image: "assets/members/bharat.png", name: "Bharat Kumar", }, ]; function MentorSection() { const classes = useStyles(); return ( <Box pt={10} className={classes.root}> <Container className={classes.titleContainer}> <Box> <Typography variant="h1" className={classes.subTitle}> Our team member </Typography> <Box mt={3}> <Typography variant="h5"> These are the people who work every day to create great learning content that will help you in growing your skills . </Typography> </Box> </Box> </Container> <Container className={classes.gridContainer}> <Grid spacing={3} align="center" container justify="center"> {mentorList.map((items, index) => ( <TeamCard key={index} image={items.image} name={items.name} /> ))} </Grid> </Container> </Box> ); } const useStyles = makeStyles((theme) => ({ root: { minHeight: 750, }, titleContainer: { textAlign: "center", }, gridContainer: { marginTop: theme.spacing(10), maxWidth: "85%", [theme.breakpoints.between("md")]: { maxWidth: "none", }, [theme.breakpoints.down("lg")]: { maxWidth: "none", }, }, subTitle: { color: theme.palette.primary.main, }, })); export default MentorSection;
const userAdapter = require('./../adapter'); const logger = require('./../../../infrastructure/logger'); const { safeUser } = require('./../../../utils'); const searchV2 = async (req, res) => { try { const users = await userAdapter.getUsers(req.body.ids.split(','), req.header('x-correlation-id')); if (!users) { return res.status(404).send(); } return res.send(users.map(user => safeUser(user))); } catch (e) { logger.error(e); return res.status(500).send(e); } }; module.exports = searchV2;
import React from 'react'; export default function SvgCustomPay(props) { return ( <svg width="1em" height="1em" viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg" {...props} > <path fillRule="evenodd" clipRule="evenodd" d="M656.3 781.3H343.8c-69.1 0-125-56-125-125V343.8c0-69.1 55.9-125 125-125h312.5c69 0 125 55.9 125 125v312.5c-.1 68.9-56.1 124.9-125 125zm-312.5-500c-34.6 0-62.5 27.9-62.5 62.5v312.5c0 34.5 27.9 62.5 62.5 62.5h312.5c34.5 0 62.5-28 62.5-62.5V343.8c0-34.6-28-62.5-62.5-62.5H343.8zM515.7 650v-23.2c60.7-4.9 94.4-34.6 94.4-83 0-41.2-24.5-66.7-72.7-76l-21.8-4.1v-56.8c15.1 2.1 26.7 14.4 27.8 29.7H605c-.5-43.6-35-74.3-89.3-79.5v-25h-26.4v25c-59.1 4.2-93.2 33.9-93.2 81.3 0 40.1 24.5 66.5 71.4 76.7l21.9 4.8v58.9c-17.6-.2-32.3-13.3-34.6-30.7h-63.6c.1 46.9 36.2 76 98.1 79.1V650h26.4zm31.8-98.6c0 15.6-11.9 26-31.8 27.5v-54.6c21.4 4 31.8 13 31.8 27.1zm-87.2-119.2c1.1-15 14-26.4 29-25.6v52c-18.9-3.9-29-13-29-26.4z" /> </svg> ); }
require([ "jquery", "public/assets/javascripts/lib/components/lightbox.js" ], function($, LightBox) { "use strict"; describe("LightBox", function() { var lightbox; beforeEach(function() { loadFixtures("lightbox.html"); lightbox = new LightBox({ customClass: "lightbox-foo" }); }); describe("Initialisation", function() { it("is defined", function() { expect(lightbox).toBeDefined(); }); it("found the lightbox", function() { expect(lightbox.$lightbox.length).toBe(1); }); it("found the lightbox opener", function() { expect(lightbox.$opener.length).toBe(1); }); it("extends the flyout functionality", function() { expect(lightbox.listenToFlyout).toBeDefined(); }); it("should extend asEventEmitter functionality", function() { expect(lightbox.trigger).toBeDefined(); }); it("should extend viewport_helper functionality", function() { expect(lightbox.viewport).toBeDefined(); }); it("defines a way to render the contents", function() { expect(lightbox._renderContent).toBeDefined(); }); it("defines a way to fetch the contents via ajax", function() { expect(lightbox._fetchContent).toBeDefined(); }); }); describe("Open/Close", function() { beforeEach(function() { loadFixtures("lightbox.html"); jasmine.Clock.useMock(); lightbox = new LightBox({ showPreloader: true }); $("#js-row--content").trigger(":lightbox/open"); }); it("should have css classes", function() { jasmine.Clock.tick(301); expect($("#js-lightbox")).toHaveClass("is-active is-visible"); expect($("html")).toHaveClass("lightbox--open"); }); it("should close and clean the lightbox", function() { $("#js-row--content").trigger(":flyout/close"); jasmine.Clock.tick(301); expect($("#js-lightbox")).not.toHaveClass("content-ready"); expect($("#js-lightbox")).not.toHaveClass("is-active"); expect($("html")).not.toHaveClass("lightbox--open"); }); }); describe("Functionality", function() { beforeEach(function() { jasmine.Clock.useMock(); }); it("can update the lightbox contents", function() { $("#js-row--content").trigger(":lightbox/renderContent", "Test content here."); jasmine.Clock.tick(301); expect($(".js-lightbox-content").html()).toBe("Test content here."); expect($("#js-lightbox")).toHaveClass("content-ready"); }); it("can add a custom class to the lightbox", function() { expect($("#js-lightbox")).toHaveClass("lightbox-foo"); }); }); describe("Preloader", function() { beforeEach(function() { lightbox = new LightBox({ showPreloader: true }); }); it("should append the preloader HTML", function() { expect(lightbox.$lightbox.find(".preloader").length).toBe(1); }); }); }); });
//// [derivedClassOverridesPublicMembers.ts] var x: { foo: string; } var y: { foo: string; bar: string; } class Base { a: typeof x; b(a: typeof x) { } get c() { return x; } set c(v: typeof x) { } d: (a: typeof x) => void; static r: typeof x; static s(a: typeof x) { } static get t() { return x; } static set t(v: typeof x) { } static u: (a: typeof x) => void; constructor(a: typeof x) { } } class Derived extends Base { a: typeof y; b(a: typeof y) { } get c() { return y; } set c(v: typeof y) { } d: (a: typeof y) => void; static r: typeof y; static s(a: typeof y) { } static get t() { return y; } static set t(a: typeof y) { } static u: (a: typeof y) => void; constructor(a: typeof y) { super(x) } } var d: Derived = new Derived(y); var r1 = d.a; var r2 = d.b(y); var r3 = d.c; var r3a = d.d; d.c = y; var r4 = Derived.r; var r5 = Derived.s(y); var r6 = Derived.t; var r6a = Derived.u; Derived.t = y; class Base2 { [i: string]: Object; [i: number]: typeof x; } class Derived2 extends Base2 { [i: string]: typeof x; [i: number]: typeof y; } var d2: Derived2; var r7 = d2['']; var r8 = d2[1]; //// [derivedClassOverridesPublicMembers.js] var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var x; var y; var Base = (function () { function Base(a) { } Base.prototype.b = function (a) { }; Object.defineProperty(Base.prototype, "c", { get: function () { return x; }, set: function (v) { }, enumerable: true, configurable: true }); Base.s = function (a) { }; Object.defineProperty(Base, "t", { get: function () { return x; }, set: function (v) { }, enumerable: true, configurable: true }); return Base; }()); var Derived = (function (_super) { __extends(Derived, _super); function Derived(a) { return _super.call(this, x) || this; } Derived.prototype.b = function (a) { }; Object.defineProperty(Derived.prototype, "c", { get: function () { return y; }, set: function (v) { }, enumerable: true, configurable: true }); Derived.s = function (a) { }; Object.defineProperty(Derived, "t", { get: function () { return y; }, set: function (a) { }, enumerable: true, configurable: true }); return Derived; }(Base)); var d = new Derived(y); var r1 = d.a; var r2 = d.b(y); var r3 = d.c; var r3a = d.d; d.c = y; var r4 = Derived.r; var r5 = Derived.s(y); var r6 = Derived.t; var r6a = Derived.u; Derived.t = y; var Base2 = (function () { function Base2() { } return Base2; }()); var Derived2 = (function (_super) { __extends(Derived2, _super); function Derived2() { return _super.apply(this, arguments) || this; } return Derived2; }(Base2)); var d2; var r7 = d2['']; var r8 = d2[1];
/* jQWidgets v2.7.0 (2013-Feb-08) Copyright (c) 2011-2013 jQWidgets. License: http://jqwidgets.com/license/ */ (function(a){a.jqx.jqxWidget("jqxListBox","",{});a.extend(a.jqx._jqxListBox.prototype,{defineInstance:function(){this.disabled=false;this.width=null;this.height=null;this.items=new Array();this.multiple=false;this.selectedIndex=-1;this.selectedIndexes=new Array();this.source=null;this.scrollBarSize=15;this.enableHover=true;this.enableSelection=true;this.visualItems=new Array();this.groups=new Array();this.equalItemsWidth=true;this.itemHeight=-1;this.visibleItems=new Array();this.emptyGroupText="Group";this.checkboxes=false;this.hasThreeStates=false;this.autoHeight=false;this.autoItemsHeight=false;this.roundedcorners=true;this.touchMode="auto";this.displayMember="";this.valueMember="";this.searchMode="startswithignorecase";this.incrementalSearch=true;this.incrementalSearchDelay=700;this.allowDrag=false;this.allowDrop=true;this.dropAction="default";this.touchModeStyle="auto";this.keyboardNavigation=true;this.enableMouseWheel=true;this.multipleextended=false;this.emptyString="null";this.rtl=false;this.rendered=null;this.renderer=null;this.events=["select","unselect","change","checkChange","dragStart","dragEnd","bindingComplete"]},createInstance:function(b){this.render()},render:function(){this.element.innerHTML="";var b=this;this.host.addClass(this.toThemeProperty("jqx-listbox"));this.host.addClass(this.toThemeProperty("jqx-reset"));this.host.addClass(this.toThemeProperty("jqx-rc-all"));this.host.addClass(this.toThemeProperty("jqx-widget"));this.host.addClass(this.toThemeProperty("jqx-widget-content"));var f=false;if(this.width!=null&&this.width.toString().indexOf("%")!=-1){this.host.width(this.width);f=true}if(this.height!=null&&this.height.toString().indexOf("%")!=-1){this.host.height(this.height);if(this.host.height()==0){this.host.height(200)}f=true}if(this.width!=null&&this.width.toString().indexOf("px")!=-1){this.host.width(this.width)}else{if(this.width!=undefined&&!isNaN(this.width)){this.host.width(this.width)}}if(this.height!=null&&this.height.toString().indexOf("px")!=-1){this.host.height(this.height)}else{if(this.height!=undefined&&!isNaN(this.height)){this.host.height(this.height)}}var c=a("<div style='-webkit-appearance: none; background: transparent; outline: none; width:100%; height: 100%; align:left; border: 0px; padding: 0px; margin: 0px; left: 0px; top: 0px; valign:top; position: relative;'><div style='-webkit-appearance: none; border: none; background: transparent; outline: none; width:100%; height: 100%; padding: 0px; margin: 0px; align:left; left: 0px; top: 0px; valign:top; position: relative;'><div id='listBoxContent' style='-webkit-appearance: none; border: none; background: transparent; outline: none; border: none; padding: 0px; overflow: hidden; margin: 0px; align:left; valign:top; left: 0px; top: 0px; position: absolute;'/><div id='verticalScrollBar"+this.element.id+"' style='align:left; valign:top; left: 0px; top: 0px; position: absolute;'/><div id='horizontalScrollBar"+this.element.id+"' style='align:left; valign:top; left: 0px; top: 0px; position: absolute;'/><div id='bottomRight' style='align:left; valign:top; left: 0px; top: 0px; border: none; position: absolute;'/></div></div>");this._addInput();if(!this.host.attr("tabIndex")){this.host.attr("tabIndex",1)}this.host.append(c);var e=this.host.find("#verticalScrollBar"+this.element.id);if(!e.jqxScrollBar){alert("jqxscrollbar.js is not loaded.");return}this.vScrollBar=e.jqxScrollBar({vertical:true,rtl:this.rtl,theme:this.theme,touchMode:this.touchMode,largestep:parseInt(this.host.height())/2});var d=this.host.find("#horizontalScrollBar"+this.element.id);this.hScrollBar=d.jqxScrollBar({vertical:false,rtl:this.rtl,touchMode:this.touchMode,theme:this.theme});this.content=this.host.find("#listBoxContent");this.content[0].id="listBoxContent"+this.element.id;this.bottomRight=this.host.find("#bottomRight").addClass(this.toThemeProperty("jqx-listbox-bottomright"));this.bottomRight[0].id="bottomRight"+this.element.id;this.vScrollBar.css("visibility","inherit");this.hScrollBar.css("visibility","inherit");this.vScrollInstance=a.data(this.vScrollBar[0],"jqxScrollBar").instance;this.hScrollInstance=a.data(this.hScrollBar[0],"jqxScrollBar").instance;if(this.isTouchDevice()){var g=a("<div class='overlay' style='-webkit-appearance: none; border: none; background: transparent; outline: none; border: none; padding: 0px; overflow: hidden; margin: 0px; align:left; valign:top; left: 0px; top: 0px; position: absolute;'></div>");this.content.parent().append(g);this.overlayContent=this.host.find(".overlay")}this._updateTouchScrolling();this.host.addClass("jqx-disableselect");if(this.host.jqxDragDrop){jqxListBoxDragDrop()}},_addInput:function(){var b=this.host.attr("name");if(!b){b=this.element.id}else{this.host.attr("name","")}this.input=a("<input type='hidden'/>");this.host.append(this.input);this.input.attr("name",b)},_updateTouchScrolling:function(){var b=this;if(this.isTouchDevice()){b.enableHover=false;var c=this.overlayContent?this.overlayContent:this.content;a(c).off(a.jqx.mobile.getTouchEventName("touchstart")+".touchScroll");a(c).off(a.jqx.mobile.getTouchEventName("touchmove")+".touchScroll");a(c).off(a.jqx.mobile.getTouchEventName("touchend")+".touchScroll");a(c).off("touchcancel.touchScroll");a.jqx.mobile.touchScroll(c,b.vScrollInstance.max,function(f,e){if(b.vScrollBar.css("visibility")!="hidden"){var d=b.vScrollInstance.value;b.vScrollInstance.setPosition(d+e);b._lastScroll=new Date()}if(b.hScrollBar.css("visibility")!="hidden"){var d=b.hScrollInstance.value;b.hScrollInstance.setPosition(d+f);b._lastScroll=new Date()}},this.element.id);if(b.vScrollBar.css("visibility")!="visible"&&b.hScrollBar.css("visibility")!="visible"){a.jqx.mobile.setTouchScroll(false,this.element.id)}else{a.jqx.mobile.setTouchScroll(true,this.element.id)}}},isTouchDevice:function(){var b=a.jqx.mobile.isTouchDevice();if(this.touchMode==true){b=true;a.jqx.mobile.setMobileSimulator(this.element)}else{if(this.touchMode==false){b=false}}if(b&&this.touchModeStyle!=false){this.scrollBarSize=10}if(b){this.host.addClass(this.toThemeProperty("jqx-touch"))}return b},beginUpdate:function(){this.updatingListBox=true},endUpdate:function(){this.updatingListBox=false;this._addItems();this._renderItems()},beginUpdateLayout:function(){this.updating=true},resumeUpdateLayout:function(){this.updating=false;this.vScrollInstance.value=0;this._render(false)},propertyChangedHandler:function(b,c,e,d){if(this.isInitialized==undefined||this.isInitialized==false){return}if(c=="source"||c=="checkboxes"){b.clearSelection();b.refresh()}if(c=="scrollBarSize"||c=="equalItemsWidth"){if(d!=e){b._updatescrollbars()}}if(c=="disabled"){b._renderItems()}if(c=="touchMode"||c=="rtl"){b._removeHandlers();b.vScrollBar.jqxScrollBar({touchMode:d});b.hScrollBar.jqxScrollBar({touchMode:d});b._updateTouchScrolling();b._addHandlers();b._render(false)}if(!this.updating){if(c=="width"||c=="height"){setTimeout(function(){b.vScrollInstance.value=0;if(c=="width"){if(e!=d){b.host.width(d);b._updatescrollbars();b._renderItems()}}else{if(e!=d){b.host.height(d);if(b.items){if(b.items.length>0&&b.virtualItemsCount*b.items[0].height<d){b._render(false)}else{b._updatescrollbars();b._renderItems()}}}}},1)}}if(c=="theme"){if(e!=d){b.hScrollBar.jqxScrollBar({theme:b.theme});b.vScrollBar.jqxScrollBar({theme:b.theme});b.host.removeClass();b.host.addClass(b.toThemeProperty("jqx-listbox"));b.host.addClass(b.toThemeProperty("jqx-widget"));b.host.addClass(b.toThemeProperty("jqx-widget-content"));b.host.addClass(b.toThemeProperty("jqx-reset"));b.host.addClass(b.toThemeProperty("jqx-rc-all"));b.refresh()}}if(c=="selectedIndex"){b.clearSelection();b.selectIndex(d,true)}if(c=="displayMember"||c=="valueMember"){if(e!=d){var f=b.selectedIndex;b.refresh();b.selectedIndex=f;b.selectedIndexes[f]=f}b._renderItems()}if(c=="autoHeight"){if(e!=d){b._render(false)}else{b._updatescrollbars();b._renderItems()}}},loadFromSelect:function(i){if(i==null){return}var c="#"+i;var f=a(c);if(f.length>0){var e=f.find("option");var b=f.find("optgroup");var d=0;var h=-1;var g=new Array();a.each(e,function(){var k=b.find(this).length>0;var m=null;if(this.text!=this.value&&(this.label==null||this.label=="")){this.label=this.text}var l={disabled:this.disabled,value:this.value,label:this.label,title:this.title,originalItem:this};var j=a.jqx.browser.msie&&a.jqx.browser.version<8;if(j){if(l.value==""&&this.text!=null&&this.text.length>0){l.value=this.text}}if(k){m=b.find(this).parent()[0].label;l.group=m}if(this.selected){h=d}g[d]=l;d++});this.source=g;this.fromSelect=true;this.clearSelection();this.selectedIndex=h;this.selectedIndexes[this.selectedIndex]=this.selectedIndex;this.refresh()}},invalidate:function(){this._cachedItemHtml=[];this._renderItems()},refresh:function(c){var b=this;if(this.vScrollBar==undefined){return}this._cachedItemHtml=[];this.visibleItems=new Array();var d=function(e){if(e==true){if(b.selectedIndex!=-1){var f=b.selectedIndex;b.selectedIndex=-1;b._stopEvents=true;b.selectIndex(f,false,true);if(b.selectedIndex==-1){b.selectedIndex=f}b._stopEvents=false}}};if(this.itemswrapper!=null){this.itemswrapper.remove();this.itemswrapper=null}if(a.jqx.dataAdapter&&this.source!=null&&this.source._source){this.databind(this.source);d(c);return}this.items=this.loadItems(this.source);this._render(false,c==true);d(c)},_render:function(c,b){this._addItems();this._renderItems();this.vScrollInstance.setPosition(0);this._cachedItemHtml=new Array();if(c==undefined||c){if(this.items!=undefined&&this.items!=null){if(this.selectedIndex>=0&&this.selectedIndex<this.items.length){this.selectIndex(this.selectedIndex,true,true,true)}}}if(this.allowDrag&&this._enableDragDrop){this._enableDragDrop();if(this.isTouchDevice()){this._removeHandlers();if(this.overlayContent){this.overlayContent.remove();this.overlayContent=null}this._updateTouchScrolling();this._addHandlers();return}}this._updateTouchScrolling();if(this.rendered){this.rendered()}if(this.ready){this.ready()}},_createID:function(){var b=Math.random()+"";b=b.replace(".","");b="99"+b;b=b/1;while(this.items[b]){b=Math.random()+"";b=b.replace(".","");b=b/1}return"listitem"+b},_hitTest:function(c,f){var e=parseInt(this.vScrollInstance.value);var b=this._searchFirstVisibleIndex(f+e,this.renderedVisibleItems);if(this.renderedVisibleItems[b]!=undefined&&this.renderedVisibleItems[b].isGroup){return null}if(this.renderedVisibleItems.length>0){var d=this.renderedVisibleItems[this.renderedVisibleItems.length-1];if(d.height+d.top<f+e){return null}}b=this._searchFirstVisibleIndex(f+e);return this.visibleItems[b];return null},_searchFirstVisibleIndex:function(e,f){if(e==undefined){e=parseInt(this.vScrollInstance.value)}var c=0;if(f==undefined||f==null){f=this.visibleItems}var b=f.length;while(c<=b){mid=parseInt((c+b)/2);var d=f[mid];if(d==undefined){break}if(d.initialTop>e&&d.initialTop+d.height>e){b=mid-1}else{if(d.initialTop<e&&d.initialTop+d.height<=e){c=mid+1}else{return mid;break}}}return 0},_renderItems:function(){if(this.items==undefined||this.items.length==0){this.visibleItems=new Array();return}if(this.updatingListBox==true){return}var E=this.vScrollInstance;var h=this.hScrollInstance;var g=parseInt(E.value);var f=parseInt(h.value);if(this.rtl){if(this.hScrollBar[0].style.visibility!="hidden"){f=h.max-f}}var z=this.items.length;var K=this.host.width();var I=parseInt(this.content[0].style.width);var b=I+parseInt(h.max);var o=parseInt(this.vScrollBar[0].style.width)+2;if(this.vScrollBar[0].style.visibility=="hidden"){o=0}if(this.hScrollBar[0].style.visibility!="visible"){b=I}var j=this._getVirtualItemsCount();var J=new Array();var D=0;var C=parseInt(this.element.style.height)+2;if(this.element.style.height.indexOf("%")!=-1){C=this.host.outerHeight()}if(isNaN(C)){C=0}var r=0;var q=0;var N=0;if(E.value==0||this.visibleItems.length==0){for(var p=0;p<this.items.length;p++){var v=this.items[p];if(v.visible){v.top=-g;v.initialTop=-g;if(!v.isGroup&&v.visible){this.visibleItems[q++]=v;v.visibleIndex=q-1}this.renderedVisibleItems[N++]=v;v.left=-f;var c=v.top+v.height;if(c>=0&&v.top-v.height<=C){J[D++]={index:p,item:v}}g-=v.height}}}var k=g>0?this._searchFirstVisibleIndex(this.vScrollInstance.value,this.renderedVisibleItems):0;var L=0;D=0;var w=this.vScrollInstance.value;var H=0;while(L<100+C){var v=this.renderedVisibleItems[k];if(v==undefined){break}if(v.visible){v.left=-f;var c=v.top+v.height-w;if(c>=0&&v.initialTop-w-v.height<=2*C){J[D++]={index:k,item:v}}}k++;if(v.visible){L+=v.initialTop-w+v.height-L}H++;if(H>this.items.length-1){break}}var m=this.toThemeProperty("jqx-listitem-state-normal")+" "+this.toThemeProperty("jqx-item");var i=this.toThemeProperty("jqx-listitem-state-group");var M=this.toThemeProperty("jqx-listitem-state-disabled")+" "+this.toThemeProperty("jqx-fill-state-disabled");var A=0;var l=this;for(var p=0;p<this.visualItems.length;p++){var B=this.visualItems[p];var G=function(){var y=B[0].firstChild;if(l.checkboxes){y=B[0].lastChild}if(y!=null){y.style.visibility="hidden";y.className=""}if(l.checkboxes&&l.host.jqxCheckBox){var O=B.find(".chkbox");O.css({visibility:"hidden"})}};if(p<J.length){var v=J[p].item;if(v.initialTop-w>=C){G();continue}var x=a(B[0].firstChild);if(this.checkboxes){x=a(B[0].lastChild)}if(x.length==0){continue}if(x[0]==null){continue}x[0].className="";x[0].style.display="block";x[0].style.visibility="inherit";var n="";if(!v.isGroup&&!this.selectedIndexes[v.index]>=0){n=m}else{n=i}if(v.disabled||this.disabled){n+=" "+M}if(this.roundedcorners){n+=" "+this.toThemeProperty("jqx-rc-all")}x[0].className=n;if(this.renderer){if(!v.key){v.key=this.generatekey()}if(!this._cachedItemHtml){this._cachedItemHtml=new Array()}if(this._cachedItemHtml[v.key]){if(x[0].innerHTML!=this._cachedItemHtml[v.key]){x[0].innerHTML=this._cachedItemHtml[v.key]}}else{var u=this.renderer(v.index,v.label,v.value);x[0].innerHTML=u;this._cachedItemHtml[v.key]=x[0].innerHTML}}else{if(v.html!=null&&v.html.toString().length>0){x[0].innerHTML=v.html}else{if(v.label!=null||v.value!=null){if(v.label!=null){if(x[0].innerHTML!==v.label){x[0].innerHTML=v.label}if(v.label==""){x[0].innerHTML=this.emptyString;if(this.emptyString==""){x[0].style.height=(v.height-8)+"px"}}}else{if(x[0].innerHTML!==v.value){x[0].innerHTML=v.value}else{if(v.label==""){x[0].innerHTML=" "}}}}else{if(v.label==""||v.label==null){x[0].innerHTML="";x[0].style.height=(v.height-8)+"px"}}}}B[0].style.left=v.left+"px";B[0].style.top=v.initialTop-w+"px";v.element=x[0];if(v.title){x[0].title=v.title}if(this.equalItemsWidth&&!v.isGroup){if(r==0){var d=parseInt(b);var t=parseInt(x.outerWidth())-parseInt(x.width());d-=t;var F=1;if(F!=null){F=parseInt(F)}else{F=0}d-=2*F;r=d;if(this.checkboxes&&this.host.jqxCheckBox&&this.hScrollBar[0].style.visibility=="hidden"){r-=18}}if(I>this.virtualSize.width){x[0].style.width=r+"px";v.width=r}else{x[0].style.width=-4+this.virtualSize.width+"px";v.width=this.virtualSize.width-4}}else{if(x.width()<this.host.width()){x.width(this.host.width()-2)}}if(this.rtl){x[0].style.textAlign="right"}if(this.autoItemsHeight){x[0].style.whiteSpace="normal";x.width(r);v.width=r}A=0;if(this.checkboxes&&this.host.jqxCheckBox&&!v.isGroup){if(A==0){A=(v.height-16)/2;A++}var e=a(B.children()[0]);e[0].item=v;if(!this.rtl){if(x[0].style.left!="18px"){x[0].style.left="18px"}}else{if(x[0].style.left!="0px"){x[0].style.left="0px"}}if(this.rtl){e.css("left",8+v.width+"px")}e.css("top",A+"px");e.css({display:"block",visibility:"inherit"});var s=e.jqxCheckBox("checked");if(s!=v.checked){e.jqxCheckBox({checked:v.checked,disabled:v.disabled})}else{e.jqxCheckBox({disabled:v.disabled})}}else{if(this.checkboxes&&this.host.jqxCheckBox){var e=a(B.children()[0]);e.css({display:"none",visibility:"inherit"})}}if(this.selectedIndexes[v.visibleIndex]>=0&&!v.disabled){x.addClass(this.toThemeProperty("jqx-listitem-state-selected"));x.addClass(this.toThemeProperty("jqx-fill-state-pressed"))}}else{G()}}},generatekey:function(){var b=function(){return(((1+Math.random())*65536)|0).toString(16).substring(1)};return(b()+b()+"-"+b()+"-"+b()+"-"+b()+"-"+b()+b()+b())},_calculateVirtualSize:function(){var o=0;var m=2;var g=0;var n=a("<span></span>");var h=0;var i=this.host.outerHeight();a(document.body).append(n);var e=this.items.length;var j=this.host.width();if(this.autoItemsHeight){j-=10;if(this.vScrollBar.css("visibility")!="hidden"){j-=20}}if(this.renderer||this.groups.length>1||(e>0&&this.items[0].html!=null)){for(var g=0;g<e;g++){var q=this.items[g];if(q.isGroup&&(q.label==""&&q.html=="")){continue}if(!q.visible){continue}var d="";if(!q.isGroup){d+=this.toThemeProperty("jqx-listitem-state-normal jqx-rc-all")}else{d+=this.toThemeProperty("jqx-listitem-state-group jqx-rc-all")}d+=" "+this.toThemeProperty("jqx-fill-state-normal");if(this.isTouchDevice()){d+=" "+this.toThemeProperty("jqx-touch")}if(this.equalItemsWidth){n.css("float","left")}n[0].className=d;if(this.autoItemsHeight){n[0].style.whiteSpace="normal";var b=this.checkboxes?-20:0;n[0].style.width=(b+j)+"px"}if(this.renderer){var k=this.renderer(q.index,q.label,q.value);n[0].innerHTML=k}else{if(q.html!=null&&q.html.toString().length>0){n[0].innerHTML=q.html}else{if(q.label!=null||q.value!=null){if(q.label!=null){n[0].innerHTML=q.label;if(q.label==""){n[0].innerHTML="Empty"}}else{n[0].innerHTML=q.value}}}}var p=n.outerHeight();var r=n.outerWidth();if(this.itemHeight>-1){p=this.itemHeight}q.height=p;q.width=r;m+=p;o=Math.max(o,r);if(m<=i){h++}}}else{var m=0;var l=0;var c="";var s=0;var f=0;for(var g=0;g<e;g++){var q=this.items[g];if(q.isGroup&&(q.label==""&&q.html=="")){continue}if(!q.visible){continue}var d="";if(g==0){d+=this.toThemeProperty("jqx-listitem-state-normal jqx-rc-all");d+=" "+this.toThemeProperty("jqx-fill-state-normal");d+=" "+this.toThemeProperty("jqx-widget");d+=" "+this.toThemeProperty("jqx-listbox");d+=" "+this.toThemeProperty("jqx-widget-content");if(this.isTouchDevice()){d+=" "+this.toThemeProperty("jqx-touch")}if(this.equalItemsWidth){n.css("float","left")}n[0].className=d;if(this.autoItemsHeight){n[0].style.whiteSpace="normal";var b=this.checkboxes?-20:0;n[0].style.width=(b+j)+"px"}if(q.html==null&&(q.label==""||q.label==null)){n[0].innerHTML="Item"}else{if(q.html!=null&&q.html.toString().length>0){n[0].innerHTML=q.html}else{if(q.label!=null||q.value!=null){if(q.label!=null){n[0].innerHTML=q.label}else{n[0].innerHTML=q.value}}}}var p=n.outerHeight();if(this.itemHeight>-1){p=this.itemHeight}l=p}if(s!=undefined){f=s}if(q.html!=null&&q.html.toString().length>0){s=Math.max(s,q.html.toString().length);if(f!=s){c=q.html}}else{if(q.label!=null){s=Math.max(s,q.label.length);if(f!=s){c=q.label}}else{if(q.value!=null){s=Math.max(s,q.value.length);if(f!=s){c=q.value}}}}q.height=l;m+=l;if(m<=i){h++}}n[0].innerHTML=c;o=n.outerWidth()}m+=2;if(h<10){h=10}n.remove();return{width:o,height:m,itemsPerPage:h}},_getVirtualItemsCount:function(){if(this.virtualItemsCount==0){var b=parseInt(this.host.height())/5;if(b>this.items.length){b=this.items.length}return b}else{return this.virtualItemsCount}},_addItems:function(i){if(this.updatingListBox==true){return}if(this.items==undefined||this.items.length==0){this.virtualSize={width:0,height:0,itemsPerPage:0};this._updatescrollbars();this.renderedVisibleItems=new Array();if(this.itemswrapper){this.itemswrapper.children().remove()}return}if(i==false){var l=this._calculateVirtualSize();var m=l.itemsPerPage*2;if(this.autoHeight){m=this.items.length}this.virtualItemsCount=Math.min(m,this.items.length);var g=this;var f=l.width;this.virtualSize=l;this._updatescrollbars();return}var o=this;var h=0;this.visibleItems=new Array();this.renderedVisibleItems=new Array();this._removeHandlers();if(this.allowDrag&&this._enableDragDrop){this.itemswrapper=null}if(this.itemswrapper==null){this.content[0].innerHTML="";this.itemswrapper=a('<div style="outline: 0 none; overflow:hidden; width:100%; position: relative;"></div>');this.itemswrapper.height(2*this.host.height());this.content.append(this.itemswrapper)}var l=this._calculateVirtualSize();var m=l.itemsPerPage*2;if(this.autoHeight){m=this.items.length}this.virtualItemsCount=Math.min(m,this.items.length);var g=this;var f=l.width;this.virtualSize=l;this.itemswrapper.width(Math.max(this.host.width(),17+l.width));var j=this.itemswrapper.children().length;for(var k=j;k<this.virtualItemsCount;k++){var n=this.items[k];var b=a("<div style='-ms-touch-action: none; border: none; width:100%; height: 100%; align:left; valign:top; position: absolute;'><span style='-ms-touch-action: none;' id='spanElement'></span></div>");b[0].id=o._createID();if(this.allowDrag&&this._enableDragDrop){b.addClass("draggable")}b.appendTo(this.itemswrapper);if(this.checkboxes&&this.host.jqxCheckBox){var e=a('<div style="background-color: transparent; padding: 0; margin: 0; position: absolute; float: left; width: 16px; height: 16px;" class="chkbox"/>');b.css("float","left");var c=a(b[0].firstChild);c.css("float","left");b.prepend(e);e.jqxCheckBox({hasInput:false,checked:n.checked,animationShowDelay:0,animationHideDelay:0,disabled:n.disabled,enableContainerClick:false,keyboardCheck:false,hasThreeStates:this.hasThreeStates,theme:this.theme});n.checkBoxElement=e[0];var d=function(s,r){var p=s.owner.element.item;if(p!=null){var q=s.args;if(r){g.checkIndex(p.index,true)}else{if(p.checked==false){g.uncheckIndex(p.index,true)}else{if(p.hasThreeStates&&g.hasThreeStates){if(r==false){g.uncheckIndex(p.index,true)}else{g.indeterminateIndex(p.index,true)}}else{g.uncheckIndex(p.index,true)}}}}g.focused=true};e.jqxCheckBox("updated",d)}b[0].style.height=n.height+"px";b[0].style.top=h+"px";h+=n.height;this.visualItems[k]=b}this._addHandlers();this._updatescrollbars();if(this.autoItemsHeight){var l=this._calculateVirtualSize();var m=l.itemsPerPage*2;if(this.autoHeight){m=this.items.length}this.virtualItemsCount=Math.min(m,this.items.length);var g=this;var f=l.width;this.virtualSize=l;this._updatescrollbars()}if(a.jqx.browser.msie&&a.jqx.browser.version<8){this.host.attr("hideFocus",true);this.host.find("div").attr("hideFocus",true)}},_updatescrollbars:function(){var l=this.virtualSize.height;var j=this.virtualSize.width;var f=this.vScrollInstance;var e=this.hScrollInstance;this._arrange();var k=false;if(l>this.host.outerHeight()){var b=0;if(j>this.host.outerWidth()){b=this.hScrollBar.outerHeight()+2}var d=f.max;f.max=2+parseInt(l)+b-parseInt(this.host.height());if(this.vScrollBar[0].style.visibility!="inherit"){this.vScrollBar[0].style.visibility="inherit";k=true}if(d!=f.max){f._arrange()}}else{if(this.vScrollBar[0].style.visibility!="hidden"){this.vScrollBar[0].style.visibility="hidden";k=true;f.setPosition(0)}}var h=0;if(this.vScrollBar[0].style.visibility!="hidden"){h=this.scrollBarSize+6}var g=this.checkboxes?20:0;if(this.autoItemsHeight){this.hScrollBar[0].style.visibility="hidden"}else{if(j>=this.host.outerWidth()-h-g){var i=e.max;if(this.vScrollBar[0].style.visibility=="inherit"){e.max=g+h+parseInt(j)-this.host.width()+4}else{e.max=g+parseInt(j)-this.host.width()+6}if(this.hScrollBar[0].style.visibility!="inherit"){this.hScrollBar[0].style.visibility="inherit";k=true}if(i!=e.max){e._arrange()}if(this.vScrollBar[0].style.visibility=="inherit"){f.max=2+parseInt(l)+this.hScrollBar.outerHeight()+2-parseInt(this.host.height())}}else{if(this.hScrollBar[0].style.visibility!="hidden"){this.hScrollBar[0].style.visibility="hidden";k=true}}}e.setPosition(0);if(k){this._arrange()}if(this.itemswrapper){this.itemswrapper.width(Math.max(this.host.width(),17+j));this.itemswrapper.height(2*this.host.height())}var c=this.isTouchDevice();if(c){if(this.vScrollBar.css("visibility")!="visible"&&this.hScrollBar.css("visibility")!="visible"){a.jqx.mobile.setTouchScroll(false,this.element.id)}else{a.jqx.mobile.setTouchScroll(true,this.element.id)}}},clear:function(){this.source=null;this.clearSelection();this.refresh()},clearSelection:function(b){for(indx=0;indx<this.selectedIndexes.length;indx++){this.selectedIndexes[indx]=-1}this.selectedIndex=-1;if(b!=false){this._renderItems()}},unselectIndex:function(b,c){if(isNaN(b)){return}this.selectedIndexes[b]=-1;if(c==undefined||c==true){this._renderItems();this._raiseEvent("1",{index:b})}this._updateInputSelection();this._raiseEvent("2",{index:b,item:this.getItem(b)})},getItem:function(c){if(c==-1||isNaN(c)){return null}var b=null;var d=a.each(this.items,function(){if(this.index==c){b=this;return false}});return b},getVisibleItem:function(b){if(b==-1||isNaN(b)){return null}return this.visibleItems[b]},checkIndex:function(b,c,e){if(!this.checkboxes||!this.host.jqxCheckBox){return}if(isNaN(b)){return}if(b<0||b>=this.visibleItems.length){return}if(this.visibleItems[b]!=null&&this.visibleItems[b].disabled){return}if(this.disabled){return}var d=this.getItem(b);if(this.groups.length>0){var d=this.getVisibleItem(b)}if(d!=null){var f=a(d.checkBoxElement);d.checked=true;if(c==undefined||c==true){this._updateCheckedItems()}}if(e==undefined||e==true){this._raiseEvent(3,{label:d.label,value:d.value,checked:true,item:d})}},getCheckedItems:function(){if(!this.checkboxes||!this.host.jqxCheckBox){return null}var b=new Array();if(this.items==undefined){return}a.each(this.items,function(){if(this.checked){b[b.length]=this}});return b},checkAll:function(b){if(!this.checkboxes||!this.host.jqxCheckBox){return}if(this.disabled){return}a.each(this.items,function(){this.checked=true});this._updateCheckedItems();if(b==undefined||b==true){this._raiseEvent(3,{checked:true})}},uncheckAll:function(b){if(!this.checkboxes||!this.host.jqxCheckBox){return}if(this.disabled){return}a.each(this.items,function(){this.checked=false});this._updateCheckedItems();if(b==undefined||b==true){this._raiseEvent(3,{checked:false})}},uncheckIndex:function(b,c,e){if(!this.checkboxes||!this.host.jqxCheckBox){return}if(isNaN(b)){return}if(b<0||b>=this.visibleItems.length){return}if(this.visibleItems[b]!=null&&this.visibleItems[b].disabled){return}if(this.disabled){return}var d=this.getItem(b);if(this.groups.length>0){var d=this.getVisibleItem(b)}if(d!=null){var f=a(d.checkBoxElement);d.checked=false;if(c==undefined||c==true){this._updateCheckedItems()}}if(e==undefined||e==true){this._raiseEvent(3,{label:d.label,value:d.value,checked:false,item:d})}},indeterminateIndex:function(b,c,e){if(!this.checkboxes||!this.host.jqxCheckBox){return}if(isNaN(b)){return}if(b<0||b>=this.visibleItems.length){return}if(this.visibleItems[b]!=null&&this.visibleItems[b].disabled){return}if(this.disabled){return}var d=this.getItem(b);if(this.groups.length>0){var d=this.getVisibleItem(b)}if(d!=null){var f=a(d.checkBoxElement);d.checked=null;if(c==undefined||c==true){this._updateCheckedItems()}}if(e==undefined||e==true){this._raiseEvent(3,{checked:null})}},getSelectedIndex:function(){return this.selectedIndex},getSelectedItems:function(){var b=this.getItems();var e=this.selectedIndexes;var d=[];for(var c in e){if(e[c]!=-1){d[d.length]=b[c]}}return d},getSelectedItem:function(){return this.getItem(this.selectedIndex)},_updateCheckedItems:function(){var b=this.selectedIndex;this.clearSelection(false);var c=this.getCheckedItems();this.selectedIndex=b;this._renderItems();var d=a.data(this.element,"hoveredItem");if(d!=null){a(d).addClass(this.toThemeProperty("jqx-listitem-state-hover"));a(d).addClass(this.toThemeProperty("jqx-fill-state-hover"))}this._updateInputSelection()},getItemByValue:function(d){if(this.visibleItems==null){return}if(this.itemsByValue){return this.itemsByValue[a.trim(d).split(" ").join("")]}var b=this.visibleItems;for(var c=0;c<b.length;c++){if(b[c].value==d){return b[c];break}}},checkItem:function(c){if(c!=null){if(c.index==undefined){var b=this.getItemByValue(c);if(b){c=b}}return this.checkIndex(c.index,true)}return false},uncheckItem:function(c){if(c!=null){if(c.index==undefined){var b=this.getItemByValue(c);if(b){c=b}}return this.uncheckIndex(c.index,true)}return false},indeterminateItem:function(c){if(c!=null){if(c.index==undefined){var b=this.getItemByValue(c);if(b){c=b}}return this.indeterminateIndex(c.index,true)}return false},selectItem:function(c){if(c!=null){if(c.index==undefined){var b=this.getItemByValue(c);if(b){c=b}}return this.selectIndex(c.index,true)}return false},unselectItem:function(c){if(c!=null){if(c.index==undefined){var b=this.getItemByValue(c);if(b){c=b}}return this.unselectIndex(c.index,true)}return false},selectIndex:function(j,q,c,d,m,b){if(isNaN(j)){return}if(j<-1||j>=this.visibleItems.length){return}if(this.visibleItems[j]!=null&&this.visibleItems[j].disabled){return}if(this.disabled){return}if(!this.multiple&&!this.multipleextended&&this.selectedIndex==j&&!d){return}if(this.checkboxes){this._updateCheckedItems();return}this.focused=true;var p=false;if(this.selectedIndex!=j){p=true}var o=this.selectedIndex;if(this.selectedIndex==j&&!this.multiple){o=-1}if(m==undefined){m="none"}var h=this.getItem(j);var r=this.getItem(o);if(this.visibleItems&&this.items&&this.visibleItems.length!=this.items.length){h=this.getVisibleItem(j);r=this.getVisibleItem(o)}if(d!=undefined&&d){this._raiseEvent("1",{index:o,type:m,item:r,originalEvent:b});this.selectedIndex=j;this.selectedIndexes[o]=-1;this.selectedIndexes[j]=j;this._raiseEvent("0",{index:j,type:m,item:h,originalEvent:b})}else{var l=this;var e=function(s,w,u,v,t,i){l._raiseEvent("1",{index:w,type:u,item:v,originalEvent:i});l.selectedIndex=s;l.selectedIndexes[w]=-1;w=s;l.selectedIndexes[s]=s;l._raiseEvent("0",{index:s,type:u,item:t,originalEvent:i})};var k=function(s,w,u,v,t,i){if(l.selectedIndexes[s]==undefined||l.selectedIndexes[s]==-1){l.selectedIndexes[s]=s;l.selectedIndex=s;l._raiseEvent("0",{index:s,type:u,item:t,originalEvent:i})}else{w=l.selectedIndexes[s];l.selectedIndexes[s]=-1;l.selectedIndex=-1;l._raiseEvent("1",{index:w,type:u,item:v,originalEvent:i})}};if(this.multipleextended){if(!this._shiftKey&&!this._ctrlKey){if(m!="keyboard"&&m!="mouse"){k(j,o,m,r,h,b);l._clickedIndex=j}else{this.clearSelection(false);l._clickedIndex=j;e(j,o,m,r,h,b)}}else{if(this._ctrlKey){if(m=="keyboard"){this.clearSelection(false);l._clickedIndex=j}k(j,o,m,r,h,b)}else{if(this._shiftKey){if(l._clickedIndex==undefined){l._clickedIndex=o}var f=Math.min(l._clickedIndex,j);var n=Math.max(l._clickedIndex,j);this.clearSelection(false);for(var g=f;g<=n;g++){l.selectedIndexes[g]=g;l._raiseEvent("0",{index:g,type:m,item:this.getVisibleItem(g),originalEvent:b})}if(m!="keyboard"){l.selectedIndex=l._clickedIndex}else{l.selectedIndex=j}}}}}else{if(this.multiple){k(j,o,m,r,h,b)}else{e(j,o,m,r,h,b)}}}if(c==undefined||c==true){this._renderItems()}if(q!=undefined&&q!=null&&q==true){this.ensureVisible(j)}this._raiseEvent("2",{index:j,item:h,oldItem:r});this._updateInputSelection();return p},_updateInputSelection:function(){if(this.input){if(this.selectedIndex==-1){this.input.val("")}else{if(this.items[this.selectedIndex]!=undefined){this.input.val(this.items[this.selectedIndex].value)}}if(this.multiple||this.multipleextended||this.checkboxes){var b=!this.checkboxes?this.getSelectedItems():this.getCheckedItems();var d="";for(var c=0;c<b.length;c++){if(undefined!=b[c]){if(c==b.length-1){d+=b[c].value}else{d+=b[c].value+","}}}this.input.val(d)}}},isIndexInView:function(c){if(isNaN(c)){return false}if(!this.items){return false}if(c<0||c>=this.items.length){return false}var d=this.vScrollInstance.value;var e=this.visibleItems[this.selectedIndex];if(e==undefined){return true}var b=e.initialTop;var f=e.height;if(b-d<0||b-d+f>=this.host.outerHeight()){return false}return true},_itemsInPage:function(){var b=0;var c=this;a.each(this.items,function(){if((this.initialTop+this.height)>=c.content.height()){return false}b++});return b},_firstItemIndex:function(){if(this.visibleItems!=null){if(this.visibleItems[0].isGroup){return this._nextItemIndex(0)}else{return 0}}return -1},_lastItemIndex:function(){if(this.visibleItems!=null){if(this.visibleItems[this.visibleItems.length-1].isGroup){return this._prevItemIndex(this.visibleItems.length-1)}else{return this.visibleItems.length-1}}return -1},_nextItemIndex:function(b){for(indx=b+1;indx<this.visibleItems.length;indx++){if(this.visibleItems[indx]){if(!this.visibleItems[indx].disabled&&!this.visibleItems[indx].isGroup){return indx}}}return -1},_prevItemIndex:function(b){for(indx=b-1;indx>=0;indx--){if(this.visibleItems[indx]){if(!this.visibleItems[indx].disabled&&!this.visibleItems[indx].isGroup){return indx}}}return -1},_getMatches:function(g,d){if(g==undefined||g.length==0){return -1}if(d==undefined){d=0}var b=this.getItems();var f=this;var c=-1;var e=0;a.each(b,function(h){var k="";if(!this.isGroup){if(this.label){k=this.label}else{if(this.value){k=this.value}else{if(this.title){k=this.title}else{k="jqxItem"}}}var j=false;switch(f.searchMode){case"containsignorecase":j=a.jqx.string.containsIgnoreCase(k,g);break;case"contains":j=a.jqx.string.contains(k,g);break;case"equals":j=a.jqx.string.equals(k,g);break;case"equalsignorecase":j=a.jqx.string.equalsIgnoreCase(k,g);break;case"startswith":j=a.jqx.string.startsWith(k,g);break;case"startswithignorecase":j=a.jqx.string.startsWithIgnoreCase(k,g);break;case"endswith":j=a.jqx.string.endsWith(k,g);break;case"endswithignorecase":j=a.jqx.string.endsWithIgnoreCase(k,g);break}if(j&&this.visibleIndex>=d){c=this.visibleIndex;return false}}});return c},findItems:function(e){var b=this.getItems();var d=this;var c=0;var f=new Array();a.each(b,function(g){var j="";if(!this.isGroup){if(this.label){j=this.label}else{if(this.value){j=this.value}else{if(this.title){j=this.title}else{j="jqxItem"}}}var h=false;switch(d.searchMode){case"containsignorecase":h=a.jqx.string.containsIgnoreCase(j,e);break;case"contains":h=a.jqx.string.contains(j,e);break;case"equals":h=a.jqx.string.equals(j,e);break;case"equalsignorecase":h=a.jqx.string.equalsIgnoreCase(j,e);break;case"startswith":h=a.jqx.string.startsWith(j,e);break;case"startswithignorecase":h=a.jqx.string.startsWithIgnoreCase(j,e);break;case"endswith":h=a.jqx.string.endsWith(j,e);break;case"endswithignorecase":h=a.jqx.string.endsWithIgnoreCase(j,e);break}if(h){f[c++]=this}}});return f},_handleKeyDown:function(b){var o=b.keyCode;var p=this;var j=p.selectedIndex;var d=p.selectedIndex;var l=false;if(!this.keyboardNavigation||!this.enableSelection){return}var i=function(){if(p.multiple){p.clearSelection(false)}};if(b.altKey){o=-1}if(p.incrementalSearch){var q=-1;if(!p._searchString){p._searchString=""}if((o==8||o==46)&&p._searchString.length>=1){p._searchString=p._searchString.substr(0,p._searchString.length-1)}var c=String.fromCharCode(o);var k=(!isNaN(parseInt(c)));if((o>=65&&o<=97)||k||o==8||o==32||o==46){if(!b.shiftKey){c=c.toLocaleLowerCase()}var n=1+p.selectedIndex;if(o!=8&&o!=32&&o!=46){if(p._searchString.length>0&&p._searchString.substr(0,1)==c){n=1+p.selectedIndex}else{p._searchString+=c}}if(o==32){p._searchString+=" "}var h=this._getMatches(p._searchString,n);q=h;if(q==p._lastMatchIndex||q==-1){var h=this._getMatches(p._searchString,0);q=h}p._lastMatchIndex=q;if(q>=0){i();p.selectIndex(q,false,false,false,"keyboard",b);var e=p.isIndexInView(q);if(!e){p.ensureVisible(q)}else{p._renderItems()}}}if(p._searchTimer!=undefined){clearTimeout(p._searchTimer)}if(o==27||o==13){p._searchString=""}p._searchTimer=setTimeout(function(){p._searchString=""},p.incrementalSearchDelay);if(q>=0){return}}if(this.checkboxes){return true}if(o==33){var g=p._itemsInPage();if(p.selectedIndex-g>=0){i();p.selectIndex(d-g,false,false,false,"keyboard",b)}else{i();p.selectIndex(p._firstItemIndex(),false,false,false,"keyboard",b)}p._searchString=""}if(o==32&&this.checkboxes){var f=this.getItem(j);if(f!=null){p._updateItemCheck(f,j);b.preventDefault()}p._searchString=""}if(o==36){i();p.selectIndex(p._firstItemIndex(),false,false,false,"keyboard",b);p._searchString=""}if(o==35){i();p.selectIndex(p._lastItemIndex(),false,false,false,"keyboard",b);p._searchString=""}if(o==34){var g=p._itemsInPage();if(p.selectedIndex+g<p.visibleItems.length){i();p.selectIndex(d+g,false,false,false,"keyboard",b)}else{i();p.selectIndex(p._lastItemIndex(),false,false,false,"keyboard",b)}p._searchString=""}if(o==38){p._searchString="";if(p.selectedIndex>0){var m=p._prevItemIndex(p.selectedIndex);if(m!=p.selectedIndex&&m!=-1){i();p.selectIndex(m,false,false,false,"keyboard",b)}else{return true}}else{return false}}else{if(o==40){p._searchString="";if(p.selectedIndex+1<p.visibleItems.length){var m=p._nextItemIndex(p.selectedIndex);if(m!=p.selectedIndex&&m!=-1){i();p.selectIndex(m,false,false,false,"keyboard",b)}else{return true}}else{return false}}}if(o==35||o==36||o==38||o==40||o==34||o==33){var e=p.isIndexInView(p.selectedIndex);if(!e){p.ensureVisible(p.selectedIndex)}else{p._renderItems()}return false}return true},_updateItemCheck:function(b,c){if(b.checked==true){b.checked=(b.hasThreeStates&&this.hasThreeStates)?null:false}else{b.checked=b.checked!=null}switch(b.checked){case true:this.checkIndex(c);break;case false:this.uncheckIndex(c);break;default:this.indeterminateIndex(c);break}},wheel:function(d,c){if(c.autoHeight||!c.enableMouseWheel){d.returnValue=true;return true}var e=0;if(!d){d=window.event}if(d.originalEvent&&d.originalEvent.wheelDelta){d.wheelDelta=d.originalEvent.wheelDelta}if(d.wheelDelta){e=d.wheelDelta/120}else{if(d.detail){e=-d.detail/3}}if(e){var b=c._handleDelta(e);if(b){if(d.preventDefault){d.preventDefault()}if(d.originalEvent!=null){d.originalEvent.mouseHandled=true}if(d.stopPropagation!=undefined){d.stopPropagation()}}if(b){b=false;d.returnValue=b;return b}else{return false}}if(d.preventDefault){d.preventDefault()}d.returnValue=false},_handleDelta:function(d){var c=this.vScrollInstance.value;if(d<0){this.scrollDown()}else{this.scrollUp()}var b=this.vScrollInstance.value;if(c!=b){return true}return false},focus:function(){try{this.focused=true;this.host.focus();var c=this;setTimeout(function(){c.host.focus()},10)}catch(b){}},_removeHandlers:function(){var b=this;this.removeHandler(a(document),"keydown.listbox"+this.element.id);this.removeHandler(a(document),"keyup.listbox"+this.element.id);this.removeHandler(this.vScrollBar,"valuechanged");this.removeHandler(this.hScrollBar,"valuechanged");this.removeHandler(this.host,"mousewheel");this.removeHandler(this.host,"keydown");this.removeHandler(this.content,"mouseleave");this.removeHandler(this.content,"focus");this.removeHandler(this.content,"blur");this.removeHandler(this.host,"focus");this.removeHandler(this.host,"blur");this.removeHandler(this.content,"mouseenter");this.removeHandler(this.content,"mouseup");this.removeHandler(this.content,"mousedown");this.removeHandler(this.content,"touchend");if(this._mousemovefunc){this.removeHandler(this.content,"mousemove",this._mousemovefunc);this._mousemovefunc=null}else{this.removeHandler(this.content,"mousemove")}if(a.jqx.browser.msie){this.removeHandler(this.content,"selectstart")}if(this.overlayContent){this.removeHandler(this.overlayContent,a.jqx.mobile.getTouchEventName("touchend"))}},_addHandlers:function(){var j=this;this.focused=false;var k=false;var i=0;var f=null;var i=0;var b=0;var g=new Date();var d=this.isTouchDevice();if((this.width!=null&&this.width.toString().indexOf("%")!=-1)||(this.height!=null&&this.height.toString().indexOf("%")!=-1)){a(window).off("resize."+this.element.id);a(window).on("resize."+this.element.id,function(){j._arrange();if(j.host.height()!=j._oldheight||j.host.width()!=j._oldwidth){var l=j.host.width()!=j._oldwidth;j._oldwidth=j.host.width();j._oldheight=j.host.height();if(j.autoItemsHeight){j._render(false)}else{if(j.items){if(j.items.length>0&&j.virtualItemsCount*j.items[0].height<j._oldheight){j._render(false)}else{var m=j.vScrollInstance.value;j._updatescrollbars();j._renderItems();if(m<j.vScrollInstance.max){j.vScrollInstance.setPosition(m)}else{j.vScrollInstance.setPosition(j.vScrollInstance.max)}}}}}})}this.addHandler(this.vScrollBar,"valuechanged",function(l){if(a.jqx.browser.msie&&a.jqx.browser.version>9){setTimeout(function(){j._renderItems()},1)}else{j._renderItems()}});this.addHandler(this.hScrollBar,"valuechanged",function(){j._renderItems()});this.addHandler(this.host,"mousewheel",function(l){j.wheel(l,j)});this.addHandler(a(document),"keydown.listbox"+this.element.id,function(l){j._ctrlKey=l.ctrlKey;j._shiftKey=l.shiftKey});this.addHandler(a(document),"keyup.listbox"+this.element.id,function(l){j._ctrlKey=l.ctrlKey;j._shiftKey=l.shiftKey});this.addHandler(this.host,"keydown",function(l){return j._handleKeyDown(l)});this.addHandler(this.content,"mouseleave",function(l){j.focused=false;var m=a.data(j.element,"hoveredItem");if(m!=null){a(m).removeClass(j.toThemeProperty("jqx-listitem-state-hover"));a(m).removeClass(j.toThemeProperty("jqx-fill-state-hover"));a.data(j.element,"hoveredItem",null)}});this.addHandler(this.content,"focus",function(l){j.host.addClass(j.toThemeProperty("jqx-fill-state-focus"));j.focused=true});this.addHandler(this.content,"blur",function(l){j.focused=false;j.host.removeClass(j.toThemeProperty("jqx-fill-state-focus"))});this.addHandler(this.host,"focus",function(l){j.host.addClass(j.toThemeProperty("jqx-fill-state-focus"));j.focused=true});this.addHandler(this.host,"blur",function(l){j.host.removeClass(j.toThemeProperty("jqx-fill-state-focus"))});this.addHandler(this.content,"mouseenter",function(l){j.focused=true});var c=a.jqx.utilities.hasTransform(this.host);if(this.enableSelection){var e=j.isTouchDevice();var h=!e?"mousedown":"touchend";if(this.overlayContent){this.addHandler(this.overlayContent,a.jqx.mobile.getTouchEventName("touchend"),function(n){if(!j.enableSelection){return true}if(e){j._newScroll=new Date();if(j._newScroll-j._lastScroll<500){return true}}var r=a.jqx.mobile.getTouches(n);var q=r[0];if(q!=undefined){var s=j.host.offset();var p=parseInt(q.pageX);var t=parseInt(q.pageY);if(j.touchmode==true){p=parseInt(q._pageX);t=parseInt(q._pageY)}p=p-s.left;t=t-s.top;var u=j._hitTest(p,t);if(u!=null&&!u.isGroup){if(j.checkboxes){var m=a(u.element).offset();var l=parseInt(m.left);if(!j.rtl){if(p<=l+20){if(u.checked){j.uncheckIndex(u.visibleIndex)}else{j.checkIndex(u.visibleIndex)}}}else{var o=j.hScrollBar.css("visibility")!="hidden"?j.hScrollInstance.max:j.host.width();if(p<=j.host.width()-20){j._updateItemCheck(u,u.visibleIndex)}}}if(u.html.indexOf("href")!=-1){setTimeout(function(){j.selectIndex(u.visibleIndex,false,true,false,"mouse",n)},100)}else{j.selectIndex(u.visibleIndex,false,true,false,"mouse",n)}}}})}else{this.addHandler(this.content,h,function(l){if(!j.enableSelection){return true}if(e){j._newScroll=new Date();if(j._newScroll-j._lastScroll<500){return false}}j.focused=true;if(!j.isTouchDevice()){j.host.focus()}if(l.target.id!=("listBoxContent"+j.element.id)&&j.itemswrapper[0]!=l.target){var p=l.target;var v=a(p).offset();var o=j.host.offset();if(c){var m=a.jqx.mobile.getLeftPos(p);var r=a.jqx.mobile.getTopPos(p);v.left=m;v.top=r;m=a.jqx.mobile.getLeftPos(j.element);r=a.jqx.mobile.getTopPos(j.element);o.left=m;o.top=r}var q=parseInt(v.top)-parseInt(o.top);var t=parseInt(v.left)-parseInt(o.left);var u=j._hitTest(t,q);if(u!=null&&!u.isGroup){var n=function(x,w){if(!j._shiftKey){j._clickedIndex=x.visibleIndex}if(!j.checkboxes){j.selectIndex(x.visibleIndex,false,true,false,"mouse",w)}else{j.selectedIndex=x.visibleIndex;if(j.rtl){var y=j.hScrollBar.css("visibility")!="hidden"?j.hScrollInstance.max:j.host.width();if(t<=j.host.width()-20){j._updateItemCheck(x,x.visibleIndex)}}else{if(t+j.hScrollInstance.value>=20){j._updateItemCheck(x,x.visibleIndex)}}}};if(!u.disabled){if(u.html.indexOf("href")!=-1){setTimeout(function(){n(u,l)},100)}else{n(u,l)}}}if(h=="mousedown"){var s=false;if(l.which){s=(l.which==3)}else{if(l.button){s=(l.button==2)}}if(s){return true}return false}}return true})}this.addHandler(this.content,"mouseup",function(l){j.vScrollInstance.handlemouseup(j,l)});if(a.jqx.browser.msie){this.addHandler(this.content,"selectstart",function(l){return false})}}var d=this.isTouchDevice();if(this.enableHover&&!d){this._mousemovefunc=function(l){if(d){return true}if(!j.enableHover){return true}var n=a.jqx.browser.msie==true&&a.jqx.browser.version<9?0:1;if(l.target==null){return true}if(j.disabled){return true}j.focused=true;var p=j.vScrollInstance.isScrolling();if(!p&&l.target.id!=("listBoxContent"+j.element.id)){if(j.itemswrapper[0]!=l.target){var r=l.target;var z=a(r).offset();var q=j.host.offset();if(c){var m=a.jqx.mobile.getLeftPos(r);var t=a.jqx.mobile.getTopPos(r);z.left=m;z.top=t;m=a.jqx.mobile.getLeftPos(j.element);t=a.jqx.mobile.getTopPos(j.element);q.left=m;q.top=t}var s=parseInt(z.top)-parseInt(q.top);var u=parseInt(z.left)-parseInt(q.left);var w=j._hitTest(u,s);if(w!=null&&!w.isGroup&&!w.disabled){var o=a.data(j.element,"hoveredItem");if(o!=null){a(o).removeClass(j.toThemeProperty("jqx-listitem-state-hover"));a(o).removeClass(j.toThemeProperty("jqx-fill-state-hover"))}a.data(j.element,"hoveredItem",w.element);var v=a(w.element);v.addClass(j.toThemeProperty("jqx-listitem-state-hover"));v.addClass(j.toThemeProperty("jqx-fill-state-hover"))}}}};this.addHandler(this.content,"mousemove",this._mousemovefunc)}},_arrange:function(){var c=null;var k=null;var h=this;var f=function(n){n=h.host.height();if(n==0){n=200;h.host.height(n)}return n};if(this.width!=null&&this.width.toString().indexOf("px")!=-1){c=this.width}else{if(this.width!=undefined&&!isNaN(this.width)){c=this.width}}if(this.height!=null&&this.height.toString().indexOf("px")!=-1){k=this.height}else{if(this.height!=undefined&&!isNaN(this.height)){k=this.height}}if(this.width!=null&&this.width.toString().indexOf("%")!=-1){this.host.width(this.width);c=this.host.width()}if(this.height!=null&&this.height.toString().indexOf("%")!=-1){this.host.height(this.height);k=f(k)}var j=this.host.css("border-width");if(j==null){j=0}if(c!=null){c=parseInt(c);if(parseInt(this.element.style.width)!=parseInt(this.width)){this.host.width(this.width)}}if(!this.autoHeight){if(k!=null){k=parseInt(k);if(parseInt(this.element.style.height)!=parseInt(this.height)){this.host.height(this.height);f(k)}}}else{if(this.virtualSize){if(this.hScrollBar.css("visibility")!="hidden"){this.host.height(this.virtualSize.height+parseInt(this.scrollBarSize)+3);this.height=this.virtualSize.height+parseInt(this.scrollBarSize)+3}else{this.host.height(this.virtualSize.height);this.height=this.virtualSize.height}}}var b=this.scrollBarSize;if(isNaN(b)){b=parseInt(b);if(isNaN(b)){b="17px"}else{b=b+"px"}}b=parseInt(b);var g=4;var m=2;var i=0;if(this.vScrollBar){if(this.vScrollBar[0].style.visibility!="hidden"){i=b+g}else{this.vScrollInstance.setPosition(0)}}else{return}if(this.hScrollBar){if(this.hScrollBar[0].style.visibility!="hidden"){m=b+g}else{this.hScrollInstance.setPosition(0)}}else{return}if(this.autoItemsHeight){this.hScrollBar[0].style.visibility="hidden";m=0}var l=parseInt(k)-g-b;if(l<0){l=0}this.hScrollBar.height(b);this.hScrollBar.css({top:l+"px",left:"0px"});this.hScrollBar.width(c-b-g+"px");if(i==0){this.hScrollBar.width(c-2)}if(b!=parseInt(this.vScrollBar[0].style.width)){this.vScrollBar.width(b)}if((parseInt(k)-m)!=parseInt(this.vScrollBar[0].style.height)){this.vScrollBar.height(parseInt(k)-m+"px")}this.vScrollBar.css({left:parseInt(c)-parseInt(b)-g+"px",top:"0px"});var e=this.vScrollInstance;e.disabled=this.disabled;e._arrange();var d=this.hScrollInstance;d.disabled=this.disabled;d._arrange();if((this.vScrollBar[0].style.visibility!="hidden")&&(this.hScrollBar[0].style.visibility!="hidden")){this.bottomRight.css("visibility","inherit");this.bottomRight.css({left:1+parseInt(this.vScrollBar.css("left")),top:1+parseInt(this.hScrollBar.css("top"))});if(this.rtl){this.bottomRight.css({left:0})}this.bottomRight.width(parseInt(b)+3);this.bottomRight.height(parseInt(b)+3)}else{this.bottomRight.css("visibility","hidden")}if(parseInt(this.content[0].style.width)!=(parseInt(c)-i)){this.content.width(parseInt(c)-i)}if(this.rtl){this.vScrollBar.css({left:0+"px",top:"0px"});this.hScrollBar.css({left:this.vScrollBar.width()+2+"px"});if(this.vScrollBar[0].style.visibility!="hidden"){this.content.css("margin-left",4+this.vScrollBar.width())}else{this.content.css("margin-left",0);this.hScrollBar.css({left:"0px"})}}if(parseInt(this.content[0].style.height)!=(parseInt(k)-m)){this.content.height(parseInt(k)-m)}if(this.overlayContent){this.overlayContent.width(parseInt(c)-i);this.overlayContent.height(parseInt(k)-m)}},ensureVisible:function(d){var c=this.isIndexInView(d);if(!c){if(d<0){return}if(this.autoHeight){var b=a.data(this.vScrollBar[0],"jqxScrollBar").instance;b.setPosition(0)}else{for(indx=0;indx<this.visibleItems.length;indx++){var e=this.visibleItems[indx];if(e.visibleIndex==d&&!e.isGroup){var b=a.data(this.vScrollBar[0],"jqxScrollBar").instance;b.setPosition(e.initialTop);break}}}}this._renderItems()},scrollDown:function(){if(this.vScrollBar.css("visibility")=="hidden"){return false}var b=this.vScrollInstance;if(b.value+b.largestep<=b.max){b.setPosition(b.value+b.largestep);return true}else{b.setPosition(b.max);return true}return false},scrollUp:function(){if(this.vScrollBar.css("visibility")=="hidden"){return false}var b=this.vScrollInstance;if(b.value-b.largestep>=b.min){b.setPosition(b.value-b.largestep);return true}else{if(b.value!=b.min){b.setPosition(b.min);return true}}return false},databind:function(h){this.records=new Array();var d=h._source?true:false;var i=new a.jqx.dataAdapter(h,{autoBind:false});if(d){i=h;h=h._source}var g=function(j){if(h.type!=undefined){i._options.type=h.type}if(h.formatdata!=undefined){i._options.formatData=h.formatdata}if(h.contenttype!=undefined){i._options.contentType=h.contenttype}if(h.async!=undefined){i._options.async=h.async}};var c=function(o,p){var r=function(s){if(typeof s==="string"){var u=s;var v=s}else{var v=s[o.valueMember];var u=s[o.displayMember]}var t=new a.jqx._jqxListBox.item();t.label=u;t.value=v;t.html="";t.visible=true;t.originalItem=s;t.group="";t.groupHtml="";t.disabled=false;t.hasThreeStates=true;return t};if(p!=undefined){var j=i._changedrecords[0];if(j){a.each(i._changedrecords,function(){var s=this.index;var t=this.record;if(p!="remove"){var u=r(t)}switch(p){case"update":o.updateAt(u,s);break;case"add":o.insertAt(u,s);break;case"remove":o.removeAt(s);break}});return}}o.records=i.records;var l=o.records.length;o.items=new Array();o.itemsByValue=new Array();for(var k=0;k<l;k++){var m=o.records[k];var n=r(m);n.index=k;o.items[k]=n;var q=n.value;if(n.value==""||n.value==null){q=k}o.itemsByValue[a.trim(q).split(" ").join("")]=n}o._render();o._raiseEvent("6")};g(this);var f=this;switch(h.datatype){case"local":case"array":default:if(h.localdata!=null){i.unbindBindingUpdate(this.element.id);i.dataBind();c(this);i.bindBindingUpdate(this.element.id,function(j){c(f,j)})}break;case"json":case"jsonp":case"xml":case"xhtml":case"script":case"text":case"csv":case"tab":if(h.localdata!=null){i.unbindBindingUpdate(this.element.id);i.dataBind();c(this);i.bindBindingUpdate(this.element.id,function(){c(f)});return}var e={};if(i._options.data){a.extend(i._options.data,e)}else{if(h.data){a.extend(e,h.data)}i._options.data=e}var b=function(){c(f)};i.unbindDownloadComplete(f.element.id);i.bindDownloadComplete(f.element.id,b);i.dataBind()}},loadItems:function(m){if(m==null){this.groups=new Array();this.items=new Array();this.visualItems=new Array();return}var s=this;var k=0;var d=0;var b=0;this.groups=new Array();this.items=new Array();this.visualItems=new Array();var e=new Array();this.itemsByValue=new Array();a.map(m,function(v){if(v==undefined){return null}var j=new a.jqx._jqxListBox.item();var w=v.group;var i=v.groupHtml;var x=v.title;if(x==null||x==undefined){x=""}if(w==null||w==undefined){w=""}if(i==null||i==undefined){i=""}if(!s.groups[w]){s.groups[w]={items:new Array(),index:-1,caption:w,captionHtml:i};k++;var t=k+"jqxGroup";s.groups[t]=s.groups[w];d++;s.groups.length=d}var u=s.groups[w];u.index++;u.items[u.index]=j;if(typeof v==="string"){j.label=v;j.value=v}else{if(v.label==null&&v.value==null&&v.html==null&&v.group==null&&v.groupHtml==null){j.label=v.toString();j.value=v.toString()}else{j.label=v.label||v.value;j.value=v.value||v.label}}if(typeof v!="string"){if(s.displayMember!=""){if(v[s.displayMember]){j.label=v[s.displayMember]}}if(s.valueMember!=""){j.value=v[s.valueMember]}}j.hasThreeStates=v.hasThreeStates!=undefined?v.hasThreeStates:true;j.originalItem=v;j.title=x;j.html=v.html||"";if(v.html&&v.html!=""){if(x&&x!=""){}}j.group=w;j.checked=v.checked||false;j.groupHtml=v.groupHtml||"";j.disabled=v.disabled||false;j.visible=v.visible||true;j.index=b;e[b]=j;b++;return j});var c=new Array();var o=0;if(this.fromSelect==undefined||this.fromSelect==false){for(var h=0;h<d;h++){var k=h+1;var n=k+"jqxGroup";var q=this.groups[n];if(q==undefined||q==null){break}if(h==0&&q.caption==""&&q.captionHtml==""&&d<=1){for(var g=0;g<q.items.length;g++){var p=q.items[g].value;if(q.items[g].value==""||q.items[g].value==null){p=g}this.itemsByValue[a.trim(p).split(" ").join("")]=q.items[g]}return q.items}else{var l=new a.jqx._jqxListBox.item();l.isGroup=true;l.label=q.caption;if(q.caption==""&&q.captionHtml==""){q.caption=this.emptyGroupText;l.label=q.caption}l.html=q.captionHtml;c[o]=l;var p=l.value;if(l.value==""||l.value==null){p=o}s.itemsByValue[a.trim(p).split(" ").join("")]=l;o++}for(var f=0;f<q.items.length;f++){c[o]=q.items[f];o++}}}else{var o=0;var r=new Array();a.each(e,function(){if(!r[this.group]){if(this.group!=""){var i=new a.jqx._jqxListBox.item();i.isGroup=true;i.label=this.group;c[o]=i;o++;r[this.group]=true}}c[o]=this;var j=this.value;if(this.value==""||this.value==null){j=o-1}s.itemsByValue[a.trim(j).split(" ").join("")]=this;o++})}return c},_mapItem:function(c){var b=new a.jqx._jqxListBox.item();if(typeof c==="string"){b.label=c;b.value=c}else{if(typeof c==="number"){b.label=c.toString();b.value=c.toString()}else{b.label=c.label||c.value;b.value=c.value||c.label}}if(b.label==undefined&&b.value==undefined&&b.html==undefined){b.label=b.value=c}b.html=c.html||"";b.group=c.group||"";b.title=c.title||"";b.groupHtml=c.groupHtml||"";b.disabled=c.disabled||false;b.visible=c.visible||true;return b},addItem:function(b){return this.insertAt(b,this.items?this.items.length:0)},updateAt:function(d,c){if(d!=null){var b=this._mapItem(d);this.items[c].value=b.value;this.items[c].label=b.label;this.items[c].html=b.html;this.items[c].disabled=b.disabled}this._cachedItemHtml=[];this._renderItems();if(this.rendered){this.rendered()}},insertAt:function(k,f){if(k==null){return false}this._cachedItemHtml=[];if(this.items==undefined||this.items.length==0){this.source=new Array();this.refresh();var g=this._mapItem(k);g.index=0;this.items[this.items.length]=g;this._addItems(true);this._renderItems();if(this.rendered){this.rendered()}if(this.allowDrag&&this._enableDragDrop){this._enableDragDrop()}return false}var g=this._mapItem(k);if(f==-1||f==undefined||f==null||f>=this.items.length){g.index=this.items.length;this.items[this.items.length]=g}else{var c=new Array();var j=0;var e=false;var h=0;for(var b=0;b<this.items.length;b++){if(this.items[b].isGroup==false){if(h>=f&&!e){c[j++]=g;g.index=f;h++;e=true}}c[j]=this.items[b];if(!this.items[b].isGroup){c[j].index=h;h++}j++}this.items=c}this.visibleItems=new Array();this.renderedVisibleItems=new Array();var d=a.data(this.vScrollBar[0],"jqxScrollBar").instance;var i=d.value;d.setPosition(0);if((this.allowDrag&&this._enableDragDrop)||(this.virtualSize&&this.virtualSize.height<10+this.host.height())){this._addItems(true)}else{this._addItems(false)}this._renderItems();if(this.allowDrag&&this._enableDragDrop){this._enableDragDrop()}d.setPosition(i);if(this.rendered){this.rendered()}return true},removeAt:function(g){if(g<0||g>this.items.length-1){return false}var d=this.items[g].height;this.items.splice(g,1);var c=new Array();var j=0;var e=false;var h=0;for(var b=0;b<this.items.length;b++){c[j]=this.items[b];if(!this.items[b].isGroup){c[j].index=h;h++}j++}this.items=c;var f=a.data(this.vScrollBar[0],"jqxScrollBar").instance;var f=a.data(this.vScrollBar[0],"jqxScrollBar").instance;var i=f.value;f.setPosition(0);this.visibleItems=new Array();this.renderedVisibleItems=new Array();if(this.items.length>0){if(this.virtualSize){this.virtualSize.height-=d;var k=this.virtualSize.itemsPerPage*2;if(this.autoHeight){k=this.items.length}this.virtualItemsCount=Math.min(k,this.items.length)}this._updatescrollbars()}else{this._addItems()}this._renderItems();if(this.allowDrag&&this._enableDragDrop){this._enableDragDrop()}if(this.vScrollBar.css("visibility")!="hidden"){f.setPosition(i)}else{f.setPosition(0)}if(this.rendered){this.rendered()}return true},removeItem:function(b){this.removeAt(b.index)},getItems:function(){return this.items},disableAt:function(b){if(!this.items){return false}if(b<0||b>this.items.length-1){return false}this.items[b].disabled=true;this._renderItems();return true},enableAt:function(b){if(!this.items){return false}if(b<0||b>this.items.length-1){return false}this.items[b].disabled=false;this._renderItems();return true},destroy:function(){this._removeHandlers();this.vScrollBar.jqxScrollBar("destroy");this.hScrollBar.jqxScrollBar("destroy");this.vScrollBar.remove();this.hScrollBar.remove();this.host.removeClass("jqx-listbox jqx-rc-all");this.host.remove()},_raiseEvent:function(f,c){if(this._stopEvents==true){return true}if(c==undefined){c={owner:null}}var d=this.events[f];args=c;args.owner=this;this._updateInputSelection();var e=new jQuery.Event(d);e.owner=this;e.args=args;if(this.host!=null){var b=this.host.trigger(e)}return b}})})(jQuery);(function(a){a.jqx._jqxListBox.item=function(){var b={group:"",groupHtml:"",selected:false,isGroup:false,highlighted:false,value:null,label:"",html:null,visible:true,disabled:false,element:null,width:null,height:null,initialTop:null,top:null,left:null,title:"",index:-1,checkBoxElement:null,originalItem:null,checked:false,visibleIndex:-1};return b}})(jQuery);
import React, { Component } from 'react'; import PropTypes from 'prop-types' import {connect } from 'react-redux'; import {getCustomers} from '../../store/actions/customer' import './customers.css'; class Customers extends Component { static propTypes = { getCustomers: PropTypes.func.isRequired, customers: PropTypes.array.isRequired } static defaultProps = { customers: [] } componentWillMount() { this.props.getCustomers(); } render() { return ( <div> <h2>Customers</h2> <ul> {this.props.customers.map(customer => <li key={customer._id}>{customer.firstname} {customer.lastname}</li> )} </ul> </div> ); } } const mapStateToProps = (state) => ({ customers: state.customers }) const dispatchToProps = (dispatch) => ({ getCustomers: () => dispatch(getCustomers()) }) export default connect(mapStateToProps, dispatchToProps)(Customers);
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ const alwaysImportedTests = [require.resolve('../test/functional/config.js')]; const onlyNotInCoverageTests = [ require.resolve('../test/reporting/configs/chromium_api.js'), require.resolve('../test/reporting/configs/chromium_functional.js'), require.resolve('../test/reporting/configs/generate_api.js'), require.resolve('../test/functional_with_es_ssl/config.ts'), require.resolve('../test/functional/config_security_basic.js'), require.resolve('../test/api_integration/config_security_basic.js'), require.resolve('../test/api_integration/config.js'), require.resolve('../test/alerting_api_integration/basic/config.ts'), require.resolve('../test/alerting_api_integration/spaces_only/config.ts'), require.resolve('../test/alerting_api_integration/security_and_spaces/config.ts'), require.resolve('../test/detection_engine_api_integration/security_and_spaces/config.ts'), require.resolve('../test/plugin_api_integration/config.ts'), require.resolve('../test/plugin_functional/config.ts'), require.resolve('../test/kerberos_api_integration/config.ts'), require.resolve('../test/kerberos_api_integration/anonymous_access.config.ts'), require.resolve('../test/saml_api_integration/config.ts'), require.resolve('../test/token_api_integration/config.js'), require.resolve('../test/oidc_api_integration/config.ts'), require.resolve('../test/oidc_api_integration/implicit_flow.config.ts'), require.resolve('../test/pki_api_integration/config.ts'), require.resolve('../test/login_selector_api_integration/config.ts'), require.resolve('../test/encrypted_saved_objects_api_integration/config.ts'), require.resolve('../test/spaces_api_integration/spaces_only/config.ts'), require.resolve('../test/spaces_api_integration/security_and_spaces/config_trial.ts'), require.resolve('../test/spaces_api_integration/security_and_spaces/config_basic.ts'), require.resolve('../test/saved_object_api_integration/security_and_spaces/config_trial.ts'), require.resolve('../test/saved_object_api_integration/security_and_spaces/config_basic.ts'), require.resolve('../test/saved_object_api_integration/security_only/config_trial.ts'), require.resolve('../test/saved_object_api_integration/security_only/config_basic.ts'), require.resolve('../test/saved_object_api_integration/spaces_only/config.ts'), require.resolve('../test/ui_capabilities/security_and_spaces/config.ts'), require.resolve('../test/ui_capabilities/security_only/config.ts'), require.resolve('../test/ui_capabilities/spaces_only/config.ts'), require.resolve('../test/upgrade_assistant_integration/config.js'), require.resolve('../test/licensing_plugin/config.ts'), require.resolve('../test/licensing_plugin/config.public.ts'), require.resolve('../test/licensing_plugin/config.legacy.ts'), ]; require('@kbn/plugin-helpers').babelRegister(); require('@kbn/test').runTestsCli([ ...alwaysImportedTests, ...(!!process.env.CODE_COVERAGE ? [] : onlyNotInCoverageTests), ]);
/** * Bio component that queries for data * with Gatsby's useStaticQuery component * * See: https://www.gatsbyjs.org/docs/use-static-query/ */ import React from "react" import { Link, useStaticQuery, graphql } from "gatsby" import Image from "gatsby-image" import { rhythm } from "../utils/typography" const Bio = () => { const data = useStaticQuery(graphql` query BioQuery { avatar: file(absolutePath: { regex: "/profile-pic.jpg/" }) { childImageSharp { fixed(width: 50, height: 50) { ...GatsbyImageSharpFixed } } } site { siteMetadata { author, email, position, github } } } `) const { author, email, github, position } = data.site.siteMetadata return ( <div style={{ display: `flex`, marginBottom: rhythm(1), }} > <Link style={{ boxShadow: `none`, height: 50 }} to={`about`} title="About me"> <Image fixed={data.avatar.childImageSharp.fixed} alt={author} style={{ marginRight: rhythm(1 / 2), marginBottom: 0, minWidth: 50, borderRadius: `100%`, }} imgStyle={{ borderRadius: `50%`, }} /> </Link> <p style={{ marginBottom: '0.875rem', overflow: 'hidden' }}> A personal blog of <Link to="about" title="About me"><strong>{author}</strong></Link>, {position}. <br></br> <a href={`mailto:${email}`} style={{ color: 'var(--textGrey)', boxShadow: 'none', display: 'inline-block', marginRight: '0.8rem' }}>📧 {email}</a> <a href={github} style={{ color: 'var(--textGrey)', boxShadow: 'none', display: 'inline-block', marginRight: '0.8rem' }} target="_blank">⚡ Github</a> {/* <a href="https://kongfandong.cn/howdy" style={{ color: 'var(--textGrey)', boxShadow: 'none', display: 'inline-block', marginRight: '0.8rem' }} target="_blank" title="个人组件库Howdyjs">🏳️‍🌈 Howdyjs</a> */} </p> </div> ) } export default Bio
'use strict'; "use strict"; const jws = require('jws'); const { exec } = require('child_process'); const { readFileSync } = require('fs'); const path = require('path'); // Configuration file location for IBM Cloud CLI. // This will contain the current IAM tokens for the user. const DEFAULT_CONFIG_LOCATION = `.bluemix/config.json` // This class handles retrieving authentication tokens for IAM namespaces on IBM Cloud Functions. // Tokens are parsed from the configuration file used by the IBM Cloud CLI. // If tokens have expired, the CLI command `ibmcloud iam oauth-tokens` is executed. // This will automatically refresh the tokens in the configuration. module.exports = class CliTokenManager { constructor(_exec = exec, _readFile = readFileSync) { this.exec = _exec this.readFile = _readFile this.refresh_command = 'ibmcloud iam oauth-tokens' } getAuthHeader () { const to_header = token => `Bearer ${token}` const token = this.readTokenFromConfig() if (this.isTokenExpired(token)) { return this.refreshToken().then(to_header) } return Promise.resolve(to_header(token)) } refreshToken () { return new Promise((resolve, reject) => { this.exec(this.refresh_command, error => { if (error) { const err_message = `IAM token from IBM Cloud CLI configuration file (.bluemix/config.json) has expired. ` + `Refresh failed using CLI command (ibmcloud iam oauth-tokens). Check error message for details: ${error}` return reject(new Error(err_message)) } resolve(this.readTokenFromConfig()) }); }) } // IAM Tokens stored under the IAMToken field in configuration. readTokenFromConfig (configPath = CliTokenManager.configFilePath()) { const contents = this.readFile(configPath, 'utf-8') const config = JSON.parse(contents) const [prefix, token] = config.IAMToken.split(' ') return token } isTokenExpired (token) { const decoded = jws.decode(token, { json: true }) const expiry_time = decoded.payload.exp const now = Math.floor(Date.now() / 1000) return expiry_time <= now } // Support both platforms for configuration files. static configFilePath (config_file = DEFAULT_CONFIG_LOCATION) { const home_dir = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']; const config_path = path.format({ dir: home_dir, base: config_file }); return config_path } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '../../core/dom_extension/dom_extension.js'; import '../../Images/Images.js'; import * as Platform from '../../core/platform/platform.js'; // eslint-disable-line rulesdir/es_modules_import Platform.runOnWindowLoad(() => { if (!window.opener) { return; } // @ts-ignore TypeScript doesn't know about `Emulation` on `Window`. const app = window.opener.Emulation.AdvancedApp.instance(); app.deviceModeEmulationFrameLoaded(document); }); //# sourceMappingURL=device_mode_emulation_frame.js.map
import React from 'react'; import { createPortal } from 'react-dom'; import { Spin } from 'antd'; import PropTypes from 'prop-types'; import './style/index.less'; /** * MyLoading 组件 * @param {string} tip - loading的文本描述 * @param {string} size - size控制Spin的大小 * @param {boolean} loading - loading控制是否展示 * @param {boolean} inner - inner控制是否局部挂载 * @author: zhangsiyi@biosan.cn */ const MyLoading = ({ tip = '', size = '', loading = false, inner = false }) => { if (loading) { return inner ? ( <div className={'bs-inner-loading-container'}> <Spin size={size || 'small'} className={'bs-loading'} /> </div> ) : ( createPortal( <div className={'bs-loading-container'}> <Spin tip={tip} size={size || 'large'} className={'bs-loading'} /> </div>, document.querySelector('body') ) ); } return null; }; MyLoading.propTypes = { tip: PropTypes.string, size: PropTypes.string, loading: PropTypes.bool, inner: PropTypes.bool }; export default MyLoading;
var MolViewer = function(customConfig, customInfo) { /** * http://www.w3.org/wiki/JavaScript_best_practices * configuration options */ var config = { CSS : { IDs : { parentDivId : '', jmolcontent : 'divJmolcontent', btnReset : 'btnReset', viewOptions : 'viewOptions', PfamDomains : 'PfamDomains', CDDdomains : 'CDDdomains', protSeq : 'protSeq', divSeqTitle : 'divSeqTitle', divSeqContainner : 'divSeqContainner', btnCDDtryAgain : 'btnCDDtryAgain', btnPfamTryAgain : 'btnPfamTryAgain', divMenu : 'divMenu', divMain : 'divMain', divBottomWrapper: 'divBottomWrapper', jsMolViewer : 'oMolViewer' }, names : { rdFeature : 'feature' } }, /* * Application settings */ application : { //the name to use to create the jmol object jMolObject : 'myJmol', // pfamUrlBar : 'http://bar.utoronto.ca/~gfucile/cdd3d/cgi-bin/PfamAnnot.cgi', // pfamUrlDev : 'ProxyServlet', // pfamParams : 'FASTAseq', // cddUrlBar : 'http://bar.utoronto.ca/~gfucile/cdd3d/cgi-bin/CDDannot.cgi', // cddUrlDev : 'ProxyServlet', // cddParams : 'FASTAseq', // defaultLoadScript : "isDssp = false;set defaultVDW babel;"+ "select protein or nucleic;cartoons Only;color \"#C9C9C9\";frank OFF;set disablePopupMenu true;"+ "select *;zoom 70;translate x 5;translate y -5;display !water;", pickCallback : "pickCallback", // resetColorsScript : 'select not (protein or nucleic); color cpk; select protein or nucleic; color \'#C9C9C9\';', //'load "http://bar.utoronto.ca/eplant_legacy/java/Phyre2-Models/Phyre2_AT1G01200.1.pdb"' load: 'load =2HHB' } } /** * initial JSmol setup */ var Info = { height : '100%', width : '100%', use : "HTML5", //to use the php from my server http://104.197.50.15/myphptest/php/jsmol.php serverURL : "http://chemapps.stolaf.edu/jmol/jsmol/php/jsmol.php", src : null, LoadStructCallback : config.CSS.IDs.jsMolViewer+".setControls", script: "set defaultLoadScript '" + config.application.defaultLoadScript + "';"+config.application.load, debug : false, disableJ2SLoadMonitor : true, disableInitialConsole : true,//If set true, avoids the display of messages ('console') in the Jmol panel while the Jmol object is being built initially. addSelectionOptions : false //if you want to display, below the Jmol object, a menu with options for loading structures from public databases } // Merge object2 into object1, recursively if(customConfig) $.extend(true, config, customConfig); if(customInfo) $.extend(true, Info, customInfo); var res; var myJmolOb; var xhrPool = []; //holds ajax request functions (to abort if necessary). http://jsfiddle.net/s4pbn/3/ var mySequence = {}; //holds info from each residue var codeArray = {'ALA':'A','ARG':'R','ASN':'N','ASP':'D','CYS':'C','GLU':'E', 'GLN':'Q','GLY':'G','HIS':'H','ILE':'I','LEU':'L','LYS':'K','MET':'M', 'PHE':'F','PRO':'P','SER':'S','THR':'T','TRP':'W','TYR':'Y','VAL':'V'}; var pDiv; /** * Load jsmol viewer with supplied params */ function init() { pDiv = jq(config.CSS.IDs.parentDivId)+" "; //just to make the var name shorter console.log('initializing MolViewer'); //abort all running ajax requests xhrPool.abortAll = function() { console.log('aborting all ajax requests'); $(this).each(function(idx, jqXHR) { jqXHR.abort(); }); $.xhrPool = []; }; //default values for all ajax requests $.ajaxSetup({ beforeSend: function(jqXHR) { xhrPool.push(jqXHR); }, complete: function(jqXHR) { var index = xhrPool.indexOf(jqXHR); if (index > -1) { xhrPool.splice(index, 1); } } }); //create and put the jsmol on screen //http://wiki.jmol.org/index.php/Jmol_JavaScript_Object/Functions Jmol.setDocument(0); Jmol.getApplet(config.application.jMolObject, Info);// creates the object but does not insert it myJmolOb = window[config.application.jMolObject];//used to have a reference to jMol object created above //-------to work at jsmol from an iframe. Pass as param the structure you want to load. Jim from BAR requested it //example: http://localhost:8080/testjsmol/index29.html?loadpdb=4QCD var structure = getQueryStringByName('loadpdb'); if(structure){ Jmol.script(myJmolOb, "load ="+structure); } //example: //http://localhost:8080/testjsmol/index29.html?loadfile=http://bar.utoronto.ca/eplant_legacy/java/Phyre2-Models/Phyre2_AT1G01200.1.pdb var structure = getQueryStringByName('loadfile'); if(structure){ Jmol.script(myJmolOb, "load \""+structure+"\""); } //-------hack end $(pDiv+jq(config.CSS.IDs.jmolcontent)).html(Jmol.getAppletHtml(myJmolOb));//insert the object in the page //then add controls for Options $(pDiv+"input:radio[name="+config.CSS.names.rdFeature+"]").change(function(event) { resetJsmolColors(); switch($(this).val()) { case 'hydro': Jmol.script(myJmolOb, 'select hydrophobic; color mediumblue; '+ 'select polar; color red;wireframe 0.0; spacefill 0.0; select charged; color "#FFFF00";'); break; case 'temp': Jmol.script(myJmolOb, 'select all; color relativeTemperature; '); break; default: break; } }); $(pDiv+jq(config.CSS.IDs.btnReset)).click(function(e) { reloadModel(); }); //set PickCallback function to run when user clicks on the model Jmol.script(myJmolOb, "set PickCallback '"+config.CSS.IDs.jsMolViewer+"."+config.application.pickCallback+"';"); return myJmolOb; } /** * callback method - set all controls related with jsmol protein structure */ function setControls(a,b,c,d,e,f,g,h){ var aa = '' + a; var bb = '' + b; var cc = '' + c; var dd = '' + d; var ee = '' + ee; var ff = '' + ff; var gg = '' + gg; var hh = '' + hh; //console.log('aa: '+aa+'\n'+'bb: '+bb+'\n'+'cc: '+cc+'\n'+'dd: '+dd+'\n'+'ee: '+ee+'\n'+'ff: '+ff+'\n'+'gg: '+gg+'\n'+'hh: '+hh); if(cc != 'zapped'){//avoid call twice, happens when load a new file using the input field var theSeq = Jmol.evaluateVar( myJmolOb, "show('residues')" ); res = theSeq.split("\n");//global var mySequence.sequenceArray = res; //holds array sequence one letter code console.log('res: '+res); var seqToShow =''; //transform 3 letter in 1 letter to call ajax var fullseq = ''; for (var i=0; i<res.length; i++) { var matches = res[i].match(/\[(.*?)\]/); if (matches) { if(codeArray[matches[1]]) fullseq += codeArray[matches[1]]; } } console.log("1letterseq: "+fullseq); mySequence.fullseq = fullseq; //ajax call get Pfam domains ajaxGetPfamDomains(fullseq); //ajax call get CDD domains ajaxGetCDDfeatures(fullseq); for (var i=0; i<res.length; i++) { var res1letter =''; for (var x in codeArray){ if(res[i].indexOf(x) > -1){ res1letter = codeArray[x]; mySequence[res[i]]={oneLetterCode:codeArray[x],threeLetterCode:x,selected:false}; break; } } if(res1letter.length){//only aminoacids, skip anything else (hem, h2o, etc) seqToShow += "<span class='sequence deselected icon hint--top hint--success hint-rounded' id=\'"+res[i]+"\' data-hint=\'"+res[i]+"\' onclick=\'"+config.CSS.IDs.jsMolViewer+".setResidue(this);\'>"+res1letter+"</span>"; } } //add space on both sides to show both sequence ends var fadeWidth = $('#fadeLeft, #fadeRight').width(); var spanExtraSpace = "<span class='alignment' style='width: "+(fadeWidth/2)+"px;' ></span>"; seqToShow = spanExtraSpace + seqToShow + spanExtraSpace; $(jq(config.CSS.IDs.divSeqTitle)).empty().append('Sequence'); $(pDiv+jq(config.CSS.IDs.protSeq)).empty().append(seqToShow); //avoid left menu overlaps the bottom div setMenuMaxHeight(); }else{//load a new structure takes time so remove all options from the older structure to avoid use old controls to interact with the new loaded structure $(pDiv+jq(config.CSS.IDs.PfamDomains)).empty(); $(pDiv+jq(config.CSS.IDs.CDDdomains)).empty(); $(pDiv+jq(config.CSS.IDs.viewOptions)).empty(); $(pDiv+jq(config.CSS.IDs.protSeq)).empty(); } Eplant.Views.MoleculeView.loadedFunctions[this.config.callback](); //if(Eplant.Views.MoleculeView.fisrtLoad && Eplant.Views.MoleculeView.fisrtLoadDfd) Eplant.Views.MoleculeView.fisrtLoadDfd.resolve(); } /** * pickCallback method */ function pickCallback(a,b,c,d,e,f,g,h){ var aa = '' + a; var bb = '' + b; var cc = '' + c; var dd = '' + d; var ee = '' + ee; var ff = '' + ff; var gg = '' + gg; var hh = '' + hh; console.log('aa: '+aa+'\n'+'bb: '+bb+'\n'+'cc: '+cc+'\n'+'dd: '+dd+'\n'+'ee: '+ee+'\n'+'ff: '+ff+'\n'+'gg: '+gg+'\n'+'hh: '+hh); var clicked = bb.split('.')[0];//get everything until first "." if(mySequence[clicked]){ setResidue(clicked); }else{ console.log('ERROR: molViewer didnt find the clicked element: '+ clicked); } } /** * Get param from browser url */ function getQueryStringByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } /** * update max-height property from left options menu to avoid overlap the * fixed div (divBottomWrapper) at the bottom */ function setMenuMaxHeight() { var outerHeight = $(pDiv+jq(config.CSS.IDs.divBottomWrapper)).outerHeight(true); var docHeight = $(pDiv+ jq("divMainJsmol")).height();//TODO fix $(pDiv+ jq(config.CSS.IDs.divMenu)).css('max-height',docHeight - outerHeight ); } /** * */ function ajaxGetCDDfeatures(fullseq){ console.log('calling CDD ajax'); $(pDiv+jq(config.CSS.IDs.CDDdomains)).empty().append("<span class='loading'>Loading CDD features</span>"); $.ajax({ type: 'POST', dataType: 'json', url: config.application.cddUrlBar, timeout: 25000, data: { "url" : config.application.cddUrlBar,"FASTAseq": fullseq }, cache: false, success: function(data, textStatus, jqXHR){ console.log('fullseq '+fullseq+ " url " + config.application.cddUrlBar); $(pDiv+jq(config.CSS.IDs.CDDdomains)).empty(); console.log('cdd result from json:\n'+JSON.stringify(data)); if(Object.keys(data).length==0){//empty $(pDiv+jq(config.CSS.IDs.CDDdomains)).append("<span> No features found</span> <br/>"); }else{ $.each(data, function(key, value) { var numberPattern = /\d+/g;//only numbers var arIndex = value.match( numberPattern );//hold the indexes console.log('arIndex '+arIndex); for(x in arIndex){ console.log('x '+x+' arIndex '+arIndex[x]); } //change spaces to _ and removes non letters or non numbers to use as ids var keyId = key.replace(/ /g, "_").replace(/[^a-zA-Z0-9-_]/g, ''); $(pDiv+jq(config.CSS.IDs.CDDdomains)).append("<span id='"+config.CSS.IDs.parentDivId+keyId +"span' class='radioMenu'><input type='radio' id='"+config.CSS.IDs.parentDivId+keyId+"' name='"+config.CSS.names.rdFeature+"' value='TODO' style='' ><label for='"+config.CSS.IDs.parentDivId+keyId+"'>"+ key+" (" +value+")</label></span>"); $(jq(config.CSS.IDs.parentDivId+keyId)).click(function(e) { setResiduesByIndexes(e, arIndex); }); }); } }, error: function(xhr, textStatus, errorThrown){ console.log('cdd request failed: '+xhr.responseText+'. textStatus: '+textStatus); if(textStatus==="abort") { $(pDiv+jq(config.CSS.IDs.CDDdomains)).empty(); }else if(textStatus==="timeout") { $(pDiv+jq(config.CSS.IDs.CDDdomains)).empty().append("<span style='white-space: normal;'>CDD features loading error. Try again?</span><br> <button class='greenbutton' id='"+config.CSS.IDs.btnCDDtryAgain+"' style='margin: 10px;'>Try again</button>"); $(pDiv+jq(config.CSS.IDs.btnCDDtryAgain)).click(function(e) { ajaxGetCDDfeatures(mySequence.fullseq); }); }else{ $(pDiv+jq(config.CSS.IDs.CDDdomains)).empty().append("<span style='white-space: normal;'>CDD features loading error. Try again?</span><br> <button class='greenbutton' id='"+config.CSS.IDs.btnCDDtryAgain+"' style='margin: 10px;'>Try again</button>"); $(pDiv+jq(config.CSS.IDs.btnCDDtryAgain)).click(function(e) { ajaxGetCDDfeatures(mySequence.fullseq); }); } } }); } /** * */ function ajaxGetPfamDomains(fullseq){ console.log('calling pfam at bar.utoronto.ca'); $(pDiv+jq(config.CSS.IDs.PfamDomains)).empty().append("<span class='loading' >Loading Pfam domains</span>"); $.ajax({ type: 'POST', dataType: 'json', url: config.application.pfamUrlBar, timeout: 25000, data: {"FASTAseq" : fullseq, "url" : config.application.pfamUrlBar}, cache: false, success: function(data, textStatus, jqXHR ){ $(pDiv+jq(config.CSS.IDs.PfamDomains)).empty(); console.log('pfam result from json:'); console.log(JSON.stringify(data)); if(Object.keys(data).length==0){//empty $(pDiv+jq(config.CSS.IDs.PfamDomains)).append("<span> Error loading domains</span> <br/>"); }else{ $.each(data, function(key, value) { console.log( 'key: '+key + " value:" + value +' PfamAnnot: '+value.PfamAnnot+' startIndex: '+value.startIndex+ ' endIndex: '+value.endIndex+' Expect: '+value.Expect+' domainName: '+value.domainName ); key = key.replace(/\./g,"");//removes dot from the key $(pDiv+jq(config.CSS.IDs.PfamDomains)).append("<span id='"+config.CSS.IDs.parentDivId+key+"span' class='radioMenu'><input type='radio' id='"+config.CSS.IDs.parentDivId+key +"' name='"+config.CSS.names.rdFeature+"' value='TODO' style=''><label for='"+config.CSS.IDs.parentDivId+key +"'>" + value.PfamAnnot+": " + value.startIndex+" - " + value.endIndex+" ("+value.domainName+")</label></span>"); $(jq(config.CSS.IDs.parentDivId+key)).on("click", function(){ setColorByRange(value.startIndex, value.endIndex); }); }); } }, error: function(xhr, textStatus, errorThrown){ console.log('Pfam request failed: '+xhr.responseText+'. textStatus: '+textStatus); if(textStatus==="abort") { $(pDiv+jq(config.CSS.IDs.PfamDomains)).empty(); }else if(textStatus==="timeout") { $(pDiv+jq(config.CSS.IDs.PfamDomains)).empty().append("<span style='white-space: normal;'>Pfam domain loading error. Try again?</span><br> <button class='greenbutton' id='"+config.CSS.IDs.btnPfamTryAgain+"'>Try again</button>"); $(pDiv+jq(config.CSS.IDs.btnPfamTryAgain)).click(function(e) { ajaxGetPfamDomains(mySequence.fullseq); }); }else{ $(pDiv+jq(config.CSS.IDs.PfamDomains)).empty().append("<span style='white-space: normal;'>Pfam domain loading error. Try again?</span><br> <button class='greenbutton' id='"+config.CSS.IDs.btnPfamTryAgain+"'>Try again</button>"); $(pDiv+jq(config.CSS.IDs.btnPfamTryAgain)).click(function(e) { ajaxGetPfamDomains(mySequence.fullseq); }); } } }); } /** * */ function scrollLoggerToBottom(){ // http://www.w3schools.com/jsref/prop_element_scrollheight.asp //scroll to bottom $(pDiv+"#logger").scrollTop($(pDiv+'#logger').prop('scrollHeight')); } /** * select/unselect residue */ function setResidue(residueSpan) { var strResidue; if (jQuery.type(residueSpan) === "string") {//string strResidue = residueSpan; }else{ strResidue = $(residueSpan).attr("id") } //I'm getting the color from the first atom from the residue, I think that's enough var resColor = Jmol.evaluateVar( myJmolOb, "{"+strResidue+"}[0].color " ); if(mySequence[strResidue].selected){ $(jq(strResidue)).removeClass('selected'); $(jq(strResidue)).addClass('deselected'); Jmol.script(myJmolOb, 'select '+ strResidue +' ; color {'+mySequence[strResidue].previousColor+'};wireframe 0.0; spacefill off;'); mySequence[strResidue].selected=false; }else{ mySequence[strResidue].previousColor=resColor; $(jq(strResidue)).removeClass('deselected'); $(jq(strResidue)).addClass('selected'); Jmol.script(myJmolOb, 'select '+ strResidue +' and (sidechain or alpha); color "#99cc00";wireframe 0.3; spacefill off;'); mySequence[strResidue].selected=true; } } /** * set color of residues by index */ function setResiduesByIndexes(domainSpan, arrayOfIndexes) { var jsmolCommand = ''; //holds string command to send to jsmol resetJsmolColors(); console.log('arrayOfIndexes: '+arrayOfIndexes.constructor.name ); for (var i = 0; i < arrayOfIndexes.length; i++) { var y = arrayOfIndexes[i]; var residueSpan = res[arrayOfIndexes[i]]; jsmolCommand += 'select '+ residueSpan +' ; color "#CCE77B";'; } console.log("command to send to jsmol: "+ jsmolCommand); Jmol.script(myJmolOb, jsmolCommand); } /** * */ function resetJsmolColors(){ Jmol.script(myJmolOb, config.application.resetColorsScript);// } /** * set color by range */ function setColorByRange(startIndex, endIndex) { var jsmolCommand = ''; //holds string command to send to jsmol resetJsmolColors(); for(var i = startIndex-1; i<=endIndex-1; i++){ var residueSpan = res[i]; //I'm getting the color from the first atom from the residue, I think that's enough //Jmol.evaluateVar( myJmol, "{"+res[i]+" and *.CA}.color " );//get carbon alpha http://chemapps.stolaf.edu/jmol/docs/misc/atomInfo.txt var resColor = Jmol.evaluateVar( myJmolOb, "{"+residueSpan+"}[0].color " ); jsmolCommand += 'select '+ residueSpan +' ; color "#CCE77B";'; } console.log("command to send to jsmol: "+ jsmolCommand); Jmol.script(myJmolOb, jsmolCommand); } /** * takes care of escaping non valid ID characters and places a "#" at the beginning of the ID string: $( jq( "some.id" ) ) * http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/ */ function jq( myid ) { if(myid) return "#" + myid.replace( /(:|\.|\[|\]|,)/g, "\\$1" ); else return ""; } /** * Reloads current file, will trigger LoadStructCallback callback function * @param * @return */ function reloadModel(){ xhrPool.abortAll();//stop all ajax calls $(pDiv+"input:radio").attr("checked", false);//remove checked radios buttons Jmol.script(myJmolOb, 'load;');//load again the same structure } /** * put here functions and variables you want to be public */ return { showMessage : function() { // TODO }, Info : Info, config : config, init : init, scrollLoggerToBottom : scrollLoggerToBottom, ajaxGetPfamDomains : ajaxGetPfamDomains, ajaxGetCDDfeatures : ajaxGetCDDfeatures, setResidue : setResidue, setResiduesByIndexes : setResiduesByIndexes, resetJsmolColors : resetJsmolColors, setColorByRange : setColorByRange, jq : jq, reloadModel : reloadModel, setControls : setControls, xhrPool : xhrPool, mySequence : mySequence, myJmolOb : myJmolOb, pickCallback : pickCallback }; }; // ----------------------------------------- var oMolViewer; $(document).ready(function() { });
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Animated } from 'react-native'; import withTheme from '../../../Theme/withTheme'; import styles from './Undrline.styles'; class Underline extends Component { static propTypes = { color: PropTypes.string, value: PropTypes.oneOfType([ PropTypes.string, PropTypes.instanceOf(Animated.Value), ]), tabWidth: PropTypes.number, underlineHeight: PropTypes.number, }; static defaultProps = { underlineHeight: 2, }; render() { const { tabWidth, color, value, underlineHeight } = this.props; return ( <Animated.View useNativeDriver={true} style={[ styles.underline, { width: tabWidth, backgroundColor: color, transform: [{ translateX: value }], height: underlineHeight, }, ]} /> ); } } export default withTheme(Underline);
import iPol from '../ipol'; import AContainer from './acontainer'; import ASprite from './asprite'; import A9Slice from './a9slice'; import Fipps from './fippstext'; import { callMaybe, tapHandler } from './util'; export default function CButton(play, ctx, bs) { const { textures } = ctx; const mhud = textures['mhud']; let dLabel = new Fipps(this, ctx, { label: bs.label, size: bs.height * 0.3 }); let uiMargin = 8; let labelBounds = dLabel.container.bounds(); let dBg = new A9Slice(this, ctx, { width: labelBounds.width + uiMargin * 2.0, height: bs.height, tileWidth: 16, textures: mhud['rbutton'] }); let container = this.container = new AContainer(); const initContainer = () => { container.addChild(dBg); container.addChild(dLabel); dLabel.container.center(labelBounds.width + uiMargin * 2.0, bs.height); }; initContainer(); let iClick = new iPol(0, 0, { yoyo: 1 }); this.init = (data) => { }; const animateClick = () => { iClick.both(0, 1); }; const { events } = ctx; const handleTap = tapHandler(() => { callMaybe(bs.onTap); animateClick(); }, events, () => container.bounds()); this.update = delta => { iClick.update(delta / 100); handleTap(delta); this.container.update(delta); }; this.render = () => { let vClick = iClick.value(); let sExtend = 0.05 * vClick; container.scale(1-sExtend); this.container.render(); }; }
import fs from './fs' // List all files and folders within given diretory export function fsAPIgetItemByPath(path) { let components = path.split('/') const name = components.pop() const parent = components.join('/') fs.files.where({parent: parent, name: name}).first((item) => { return item }) }
/** * @private * Flyweight object to process the attributes of a sprite. * A single instance of the AttributeDefinition is created per sprite class. * See `onClassCreated` and `onClassExtended` callbacks * of the {@link Ext.draw.sprite.Sprite} for more info. */ Ext.define('Ext.draw.sprite.AttributeDefinition', { requires: [ 'Ext.draw.sprite.AttributeParser', 'Ext.draw.sprite.AnimationParser' ], config: { /** * @cfg {Object} defaults Defines the default values of attributes. */ defaults: { $value: {}, lazy: true }, /** * @cfg {Object} aliases Defines the alternative names for attributes. */ aliases: {}, /** * @cfg {Object} animationProcessors Defines the process used to animate between attributes. * One doesn't have to define animation processors for sprite attributes that use * predefined {@link #processors} from the {@link Ext.draw.sprite.AttributeParser} singleton. * For such attributes matching animation processors from the {@link Ext.draw.sprite.AnimationParser} * singleton will be used automatically. * However, if you have a custom processor for an attribute that should support * animation, you must provide a corresponding animation processor for it here. * For more information on animation processors please see {@link Ext.draw.sprite.AnimationParser} * documentation. */ animationProcessors: {}, /** * @cfg {Object} processors Defines the preprocessing used on the attributes. * One can define a custom processor function here or use the name of a predefined * processor from the {@link Ext.draw.sprite.AttributeParser} singleton. */ processors: { // A plus side of lazy initialization is that the 'processors' and 'defaults' will // only be applied for those sprite classes that are actually instantiated. $value: {}, lazy: true }, /** * @cfg {Object} dirtyTriggers * @deprecated Use the {@link #triggers} config instead. */ dirtyTriggers: {}, /** * @cfg {Object} triggers Defines which updaters have to be called when an attribute is changed. * For example, the config below indicates that the 'size' updater * of a {@link Ext.draw.sprite.Square square} sprite has to be called * when the 'size' attribute changes. * * triggers: { * size: 'size' // Use comma-separated values here if multiple updaters have to be called. * } // Note that the order is _not_ guaranteed. * * If any of the updaters to be called (triggered by the {@link Ext.draw.sprite.Sprite#setAttributes call) * set attributes themselves and those attributes have triggers defined for them, * then their updaters will be called after all current updaters finish execution. * * The updater functions themselves are defined in the {@link #updaters} config, * aside from the 'canvas' updater, which doesn't have to be defined and acts as a flag, * indicating that this attribute should be applied to a Canvas context (or whatever emulates it). * @since 5.1.0 */ triggers: {}, /** * @cfg {Object} updaters Defines the postprocessing used by the attribute. * Inside the updater function 'this' refers to the sprite that the attributes belong to. * In case of an instancing sprite 'this' will refer to the instancing template. * The two parameters passed to the updater function are the attributes object * of the sprite or instance, and the names of attributes that triggered this updater call. * * The example below shows how the 'size' updater changes other attributes * of a {@link Ext.draw.sprite.Square square} sprite sprite when its 'size' attribute changes. * * updaters: { * size: function (attr) { * var size = attr.size; * this.setAttributes({ // Changes to these attributes will trigger the 'path' updater. * x: attr.x - size, * y: attr.y - size, * height: 2 * size, * width: 2 * size * }); * } * } */ updaters: {} }, inheritableStatics: { /** * @private * Processor declaration in the form of 'processorFactory(argument1,argument2,...)'. * E.g.: {@link Ext.draw.sprite.AttributeParser#enums enums}, * {@link Ext.draw.sprite.AttributeParser#limited limited}. */ processorFactoryRe: /^(\w+)\(([\w\-,]*)\)$/ }, // The sprite class for which AttributeDefinition instance is created. spriteClass: null, constructor: function (config) { var me = this; me.initConfig(config); }, applyDefaults: function (defaults, oldDefaults) { oldDefaults = Ext.apply(oldDefaults || {}, this.normalize(defaults)); return oldDefaults; }, applyAliases: function (aliases, oldAliases) { return Ext.apply(oldAliases || {}, aliases); }, applyProcessors: function (processors, oldProcessors) { this.getAnimationProcessors(); // Apply custom animation processors first. var result = oldProcessors || {}, defaultProcessor = Ext.draw.sprite.AttributeParser, processorFactoryRe = this.self.processorFactoryRe, animationProcessors = {}, anyAnimationProcessors, name, match, fn; for (name in processors) { fn = processors[name]; if (typeof fn === 'string') { match = fn.match(processorFactoryRe); if (match) { // enums(... , limited(... or something of that nature. fn = defaultProcessor[match[1]].apply(defaultProcessor, match[2].split(',')); } else if (defaultProcessor[fn]) { // Names of animation parsers match the names of attribute parsers. animationProcessors[name] = fn; anyAnimationProcessors = true; fn = defaultProcessor[fn]; } } //<debug> if (!Ext.isFunction(fn)) { Ext.raise(this.spriteClass.$className + ": processor '" + name + "' has not been found."); } //</debug> result[name] = fn; } if (anyAnimationProcessors) { this.setAnimationProcessors(animationProcessors); } return result; }, applyAnimationProcessors: function (animationProcessors, oldAnimationProcessors) { var parser = Ext.draw.sprite.AnimationParser, name, item; if (!oldAnimationProcessors) { oldAnimationProcessors = {}; } for (name in animationProcessors) { item = animationProcessors[name]; if (item === 'none') { oldAnimationProcessors[name] = null; } else if (Ext.isString(item) && !(name in oldAnimationProcessors)) { if (item in parser) { // The while loop is used to resolve aliases, e.g. `num: 'number'`, // where `number` maps to a parser object or is an alias too. while (Ext.isString(parser[item])) { item = parser[item]; } oldAnimationProcessors[name] = parser[item]; } } else if (Ext.isObject(item)) { oldAnimationProcessors[name] = item; } } return oldAnimationProcessors; }, updateDirtyTriggers: function (dirtyTriggers) { this.setTriggers(dirtyTriggers); }, applyTriggers: function (triggers, oldTriggers) { if (!oldTriggers) { oldTriggers = {}; } for (var name in triggers) { oldTriggers[name] = triggers[name].split(','); } return oldTriggers; }, applyUpdaters: function (updaters, oldUpdaters) { return Ext.apply(oldUpdaters || {}, updaters); }, batchedNormalize: function (batchedChanges, keepUnrecognized) { if (!batchedChanges) { return {}; } var processors = this.getProcessors(), aliases = this.getAliases(), translation = batchedChanges.translation || batchedChanges.translate, normalized = {}, i, ln, name, val, rotation, scaling, matrix, subVal, split; if ('rotation' in batchedChanges) { rotation = batchedChanges.rotation; } else { rotation = ('rotate' in batchedChanges) ? batchedChanges.rotate : undefined; } if ('scaling' in batchedChanges) { scaling = batchedChanges.scaling; } else { scaling = ('scale' in batchedChanges) ? batchedChanges.scale : undefined; } if (typeof scaling !== 'undefined') { if (Ext.isNumber(scaling)) { normalized.scalingX = scaling; normalized.scalingY = scaling; } else { if ('x' in scaling) { normalized.scalingX = scaling.x; } if ('y' in scaling) { normalized.scalingY = scaling.y; } if ('centerX' in scaling) { normalized.scalingCenterX = scaling.centerX; } if ('centerY' in scaling) { normalized.scalingCenterY = scaling.centerY; } } } if (typeof rotation !== 'undefined') { if (Ext.isNumber(rotation)) { rotation = Ext.draw.Draw.rad(rotation); normalized.rotationRads = rotation; } else { if ('rads' in rotation) { normalized.rotationRads = rotation.rads; } else if ('degrees' in rotation) { if (Ext.isArray(rotation.degrees)) { normalized.rotationRads = Ext.Array.map(rotation.degrees, function (deg) { return Ext.draw.Draw.rad(deg); }); } else { normalized.rotationRads = Ext.draw.Draw.rad(rotation.degrees); } } if ('centerX' in rotation) { normalized.rotationCenterX = rotation.centerX; } if ('centerY' in rotation) { normalized.rotationCenterY = rotation.centerY; } } } if (typeof translation !== 'undefined') { if ('x' in translation) { normalized.translationX = translation.x; } if ('y' in translation) { normalized.translationY = translation.y; } } if ('matrix' in batchedChanges) { matrix = Ext.draw.Matrix.create(batchedChanges.matrix); split = matrix.split(); normalized.matrix = matrix; normalized.rotationRads = split.rotation; normalized.rotationCenterX = 0; normalized.rotationCenterY = 0; normalized.scalingX = split.scaleX; normalized.scalingY = split.scaleY; normalized.scalingCenterX = 0; normalized.scalingCenterY = 0; normalized.translationX = split.translateX; normalized.translationY = split.translateY; } for (name in batchedChanges) { val = batchedChanges[name]; if (typeof val === 'undefined') { continue; } else if (Ext.isArray(val)) { if (name in aliases) { name = aliases[name]; } if (name in processors) { normalized[name] = []; for (i = 0, ln = val.length; i < ln; i++) { subVal = processors[name].call(this, val[i]); if (typeof subVal !== 'undefined') { normalized[name][i] = subVal; } } } else if (keepUnrecognized){ normalized[name] = val; } } else { if (name in aliases) { name = aliases[name]; } if (name in processors) { val = processors[name].call(this, val); if (typeof val !== 'undefined') { normalized[name] = val; } } else if (keepUnrecognized){ normalized[name] = val; } } } return normalized; }, /** * Normalizes the changes given via their processors before they are applied as attributes. * * @param {Object} changes The changes given. * @param {Boolean} keepUnrecognized If 'true', unknown attributes will be passed through as normalized values. * @return {Object} The normalized values. */ normalize: function (changes, keepUnrecognized) { if (!changes) { return {}; } var processors = this.getProcessors(), aliases = this.getAliases(), translation = changes.translation || changes.translate, normalized = {}, name, val, rotation, scaling, matrix, split; if ('rotation' in changes) { rotation = changes.rotation; } else { rotation = ('rotate' in changes) ? changes.rotate : undefined; } if ('scaling' in changes) { scaling = changes.scaling; } else { scaling = ('scale' in changes) ? changes.scale : undefined; } if (translation) { if ('x' in translation) { normalized.translationX = translation.x; } if ('y' in translation) { normalized.translationY = translation.y; } } if (typeof scaling !== 'undefined') { if (Ext.isNumber(scaling)) { normalized.scalingX = scaling; normalized.scalingY = scaling; } else { if ('x' in scaling) { normalized.scalingX = scaling.x; } if ('y' in scaling) { normalized.scalingY = scaling.y; } if ('centerX' in scaling) { normalized.scalingCenterX = scaling.centerX; } if ('centerY' in scaling) { normalized.scalingCenterY = scaling.centerY; } } } if (typeof rotation !== 'undefined') { if (Ext.isNumber(rotation)) { rotation = Ext.draw.Draw.rad(rotation); normalized.rotationRads = rotation; } else { if ('rads' in rotation) { normalized.rotationRads = rotation.rads; } else if ('degrees' in rotation) { normalized.rotationRads = Ext.draw.Draw.rad(rotation.degrees); } if ('centerX' in rotation) { normalized.rotationCenterX = rotation.centerX; } if ('centerY' in rotation) { normalized.rotationCenterY = rotation.centerY; } } } if ('matrix' in changes) { matrix = Ext.draw.Matrix.create(changes.matrix); split = matrix.split(); // This will NOT update the transformation matrix of a sprite // with the given elements. It will attempt to extract the // individual transformation attributes from the transformation matrix // elements provided. Then the extracted attributes will be used by // the sprite's 'applyTransformations' method to calculate // the transformation matrix of the sprite. // It's not possible to recover all the information from the given // transformation matrix elements. Shearing and centers of rotation // and scaling are not recovered. // Ideally, this should work like sprite.transform([elements], true), // i.e. update the transformation matrix of a sprite directly, // without attempting to update sprite's transformation attributes. // But we are not changing the behavior (just yet) for compatibility // reasons. normalized.matrix = matrix; normalized.rotationRads = split.rotation; normalized.rotationCenterX = 0; normalized.rotationCenterY = 0; normalized.scalingX = split.scaleX; normalized.scalingY = split.scaleY; normalized.scalingCenterX = 0; normalized.scalingCenterY = 0; normalized.translationX = split.translateX; normalized.translationY = split.translateY; } for (name in changes) { val = changes[name]; if (typeof val === 'undefined') { continue; } if (name in aliases) { name = aliases[name]; } if (name in processors) { val = processors[name].call(this, val); if (typeof val !== 'undefined') { normalized[name] = val; } } else if (keepUnrecognized){ normalized[name] = val; } } return normalized; }, setBypassingNormalization: function (attr, modifierStack, changes) { return modifierStack.pushDown(attr, changes); }, set: function (attr, modifierStack, changes) { changes = this.normalize(changes); return this.setBypassingNormalization(attr, modifierStack, changes); } });
import LoveIllustration from './LoveIllustration'; export default LoveIllustration;
/** * Do not modify this file unless you have too * This file has UI handlers. */ // eslint-disable-next-line no-unused-vars function connect() { $('#connectButton').prop('disabled', true); var computation_id = $('#computation_id').val(); var party_count = parseInt($('#count').val()); if (isNaN(party_count)) { $('#output').append("<p class='error'>Party count must be a valid number!</p>"); $('#connectButton').prop('disabled', false); } else { var options = { party_count: party_count, decimal_digits: 2, integer_digits: 2, Zp: 32749 }; options.onError = function (error) { $('#output').append("<p class='error'>"+error+'</p>'); }; options.onConnect = function () { $('#button').attr('disabled', false); $('#output').append('<p>All parties Connected!</p>'); }; var hostname = window.location.hostname.trim(); var port = window.location.port; if (port == null || port === '') { port = '80'; } if (!(hostname.startsWith('http://') || hostname.startsWith('https://'))) { hostname = 'http://' + hostname; } if (hostname.endsWith('/')) { hostname = hostname.substring(0, hostname.length-1); } if (hostname.indexOf(':') > -1 && hostname.lastIndexOf(':') > hostname.indexOf(':')) { hostname = hostname.substring(0, hostname.lastIndexOf(':')); } hostname = hostname + ':' + port; // eslint-disable-next-line no-undef mpc.connect(hostname, computation_id, options); } } // eslint-disable-next-line no-unused-vars function submit() { var input = parseFloat($('#number').val()); if (isNaN(input)) { $('#output').append("<p class='error'>Input a valid number!</p>"); } else if (99 < input || input < -99) { $('#output').append("<p class='error'>Input a number between -100 and 100!</p>"); } else { $('#button').attr('disabled', true); $('#output').append('<p>Starting...</p>'); try { // eslint-disable-next-line no-undef var promise = mpc.compute(input); promise.then(handleResult); } catch (err) { $('#button').attr('disabled', false); $('#output').append("<p class='error'>"+err+'</p>'); } } } function handleResult(result) { $('#output').append('<p>Result is: ' + result.toString(10) + '</p>'); $('#button').attr('disabled', false); }
const webpack = require('webpack') const MemoryFS = require('memory-fs') const FS = require('fs') const webpackDevMiddleware = require('webpack-dev-middleware') const webpackHotMiddleware = require('webpack-hot-middleware') const VueCliConfiger = require('@vapper/configer-vue-cli') const Vapper = require('../lib/index') jest.mock('webpack') jest.mock('webpack-dev-middleware') jest.mock('webpack-hot-middleware') jest.mock('@vapper/configer-vue-cli') jest.mock('memory-fs') jest.mock('fs') // mock fs const mockMemoryFSReadFileSync = jest.fn() mockMemoryFSReadFileSync.mockReturnValue('{}') MemoryFS.mockImplementation(() => { return { readFileSync: mockMemoryFSReadFileSync } }) FS.readFileSync.mockReturnValue('{}') FS.statSync.mockReturnValue({ isFile: false }) // mock webpack const mockWebpackRun = jest.fn() const mockWebpackWatch = jest.fn() const mockTap = jest.fn((name, cb) => { cb() }) const compiler = { run: mockWebpackRun, watch: mockWebpackWatch, hooks: { done: { tap: mockTap } } } webpack.mockImplementation(() => { return compiler }) // mock middlewares webpackDevMiddleware.mockReturnValue({ fileSystem: new MemoryFS() }) webpackHotMiddleware.mockReturnValue('webpack-hot-middleware') // mock @vapper/configer-vue-cli const mockGetServerConfig = jest.fn() const mockServerConfig = { serverConfig: true } mockGetServerConfig.mockReturnValue(mockServerConfig) const mockGetClientConfig = jest.fn() const mockClientConfig = { serverConfig: true, output: { path: '/', publicPath: 'publicPath' } } mockGetClientConfig.mockReturnValue(mockClientConfig) VueCliConfiger.mockImplementation(() => { return { getServerConfig: mockGetServerConfig, getClientConfig: mockGetClientConfig } }) beforeEach(() => { webpack.mockClear() mockWebpackRun.mockClear() mockWebpackWatch.mockClear() mockTap.mockClear() webpackDevMiddleware.mockClear() webpackHotMiddleware.mockClear() mockGetClientConfig.mockClear() mockGetClientConfig.mockClear() mockMemoryFSReadFileSync.mockClear() FS.readFileSync.mockClear() }) describe('Dev mode: ', () => { test('Should be instantiated correctly', () => { const vapper = new Vapper({ mode: 'development' }) const builder = vapper.builder expect(mockGetServerConfig).toHaveBeenCalledTimes(1) expect(mockGetClientConfig).toHaveBeenCalledTimes(1) expect(builder.serverWebpackConfig).toEqual(mockServerConfig) expect(builder.clientWebpackConfig).toEqual(mockClientConfig) }) test('Webpack should be run correctly', async () => { const vapper = new Vapper({ mode: 'development' }) const builder = vapper.builder const mockEmitEvent = jest.fn() builder.on('change', mockEmitEvent) await builder.run() expect(webpack).toHaveBeenCalledTimes(2) expect(mockWebpackWatch).toHaveBeenNthCalledWith(1, {}, expect.any(Function)) expect(mockTap).toHaveBeenNthCalledWith(1, '@vapper', expect.any(Function)) expect(webpackDevMiddleware).toHaveBeenCalledWith(compiler, { publicPath: 'publicPath', logLevel: 'silent', noInfo: true }) expect(webpackHotMiddleware).toHaveBeenCalledWith(compiler, { log: false }) expect(mockTap).toHaveBeenNthCalledWith(2, '@vapper', expect.any(Function)) expect(mockEmitEvent).toHaveBeenCalledWith({ serverBundle: builder.serverBundle, clientManifest: builder.clientManifest }) }) }) describe('Prod mode: ', () => { test('Webpack should be run correctly', async () => { const vapper = new Vapper({ mode: 'production' }) const builder = vapper.builder const mockEmitEvent = jest.fn() builder.on('change', mockEmitEvent) await builder.run() expect(webpack).toHaveBeenCalledTimes(2) expect(mockWebpackWatch).not.toHaveBeenCalled() expect(mockWebpackRun).toHaveBeenCalledTimes(2) expect(mockTap).toHaveBeenNthCalledWith(1, '@vapper', expect.any(Function)) expect(mockTap).toHaveBeenNthCalledWith(2, '@vapper', expect.any(Function)) expect(mockEmitEvent).toHaveBeenCalledWith({ serverBundle: builder.serverBundle, clientManifest: builder.clientManifest }) }) })
/*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, immed: true */ /*global window: false */ /**! * @license FusionCharts JavaScript Library * Copyright FusionCharts Technologies LLP * License Information at <http://www.fusioncharts.com/license> * * @version fusioncharts/3.3.1-sr3.21100 * * @attributions (infers respective third-party copyrights) * Raphael 2.1.0 (modified as "Red Raphael") <http://raphaeljs.com/license.html> * SWFObject v2.2 (modified) <http://code.google.com/p/swfobject/> * JSON v2 <http://www.JSON.org/js.html> * jQuery 1.8.3 <http://jquery.com/> * Firebug Lite 1.3.0 <http://getfirebug.com/firebuglite> */ /** * FusionCharts Core Framework * This module contains the basic routines required by subsequent modules to * extend/scale or add functionality to the FusionCharts object. */ (function () { // In case FusionCharts object already exists, we skip this function. if (window.FusionCharts && window.FusionCharts.version) { return; } /** * @var {object} global The global variable would store all private methods * and properties available to each module. * * @var {object} modules For maintaining module information. */ var global = {}, win = window, doc = win.document, nav = win.navigator, modules = global.modules = {}, interpreters = global.interpreters = {}, objectToStringFn = Object.prototype.toString, isIE = /msie/i.test(nav.userAgent) && !win.opera, hasLoaded = /loaded|complete/, hasSVG = !!doc.createElementNS && !!doc.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGRect, mapLegacyDiscovered = false, // flag to keep track of legacy map script notifyLibraryInit = function () {// function to notify init of library var wasReady = global.ready; global.ready = true; if (global.raiseEvent) { global.readyNotified = true; global.raiseEvent('ready', { version: global.core.version, now: !wasReady }, global.core); } global.readyNow = !wasReady; }, // recursive function that copies one object into another. merge = function (obj1, obj2) { var item, str; //check whether obj2 is an array //if array then iterate through it's index //**** MOOTOOLS precution if (obj2 instanceof Array) { for (item = 0; item < obj2.length; item += 1) { if (typeof obj2[item] !== 'object') { obj1[item] = obj2[item]; } else { if (typeof obj1[item] !== 'object') { obj1[item] = obj2[item] instanceof Array ? [] : {}; } merge(obj1[item], obj2[item]); } } } else { for (item in obj2) { if (typeof obj2[item] === 'object') { str = objectToStringFn.call(obj2[item]); if (str === "[object Object]") { if (typeof obj1[item] !== 'object') { obj1[item] = {}; } merge(obj1[item], obj2[item]); } else if (str === "[object Array]") { if (!(obj1[item] instanceof Array)) { obj1[item] = []; } merge(obj1[item], obj2[item]); } else { obj1[item] = obj2[item]; } } else { obj1[item] = obj2[item]; } } } return obj1 }; /** * This method, when added to the prototype of an object, * allows shallow or deep extension of the object with another * object. */ global.extend = function (sink, source, proto, deep) { var item; // When 'proto' is marked as true, the methods and properties // of source is not added to the prototype of the sink. if (proto && sink.prototype) { sink = sink.prototype; } // If deep extend is specified, then we use the deep copy function // "merge" if (deep === true) { merge(sink, source); } // Copy all methods and properties of the object passed in parameter // to the object to which this function is attached. else { for (item in source) { sink[item] = source[item]; } } return sink; }; // Function that auto-generates a unique id. global.uniqueId = function () { return 'chartobject-' + (global.uniqueId.lastId += 1); }; global.uniqueId.lastId = 0; // Define the policy to create default parameters for the swfObject. // Values are in format [sourceOption, defaultValue] // This helps in building the initial FusionCharts object when new instances // are created from user parameters. global.policies = { /** * Contains all the customizable options that are * used by the library internally and has nothing to do with renderer * attributes, vars or parameters. * @type {object} options */ options: { swfSrcPath: ['swfSrcPath', undefined], product: ['product', 'v3'], insertMode: ['insertMode', 'replace'], safeMode: ['safeMode', true], overlayButton: ['overlayButton', undefined], containerBackgroundColor: ['backgroundColor', '#ffffff'], chartType: ['type', undefined] }, /** * @var attributes {object} Contains configurations pertaining to the * host (browser) environment. */ attributes: { lang: ['lang', 'EN'], 'class': ['className', 'FusionCharts'], id: ['id', undefined] }, /** * @var {Array} width configuration for width of the chart. * @var {Array} height configuration for height of the chart. * @var {Array} src specifies chart swf url */ width: ['width', '100%'], height: ['height', '100%'], src: ['swfUrl', ''] }; // Specifies the order in which the parameters of the new // FusionCharts objects are interpreted and converted to options object. interpreters.stat = ['swfUrl', 'id', 'width', 'height', 'debugMode', 'registerWithJS', 'backgroundColor', 'scaleMode', 'lang', 'detectFlashVersion', 'autoInstallRedirect'] /** * Allows the core to process an arguments object based on a set of policies * and construct an object out of it that is mapped exactly as respective * parameter policy defines. In other words, it uses an object and * creates another object or updates another object with values from the * original arguments object in a particular hierarchy and name that a set * of rules (policies) define. */ global.parsePolicies = function (obj, policies, options) { var prop, policy, value; // Iterate through the data policy and correspondingly create the // three stacks of parameters, attributes and flashVars for (policy in policies) { // Set just the policy object in case of single-level policy. if (global.policies[policy] instanceof Array) { value = options[policies[policy][0]]; obj[policy] = value === undefined ? policies[policy][1] : value; } else { // Define objects that would hold parameters for swfobject. Also // populate with variables from the parameters if (typeof obj[policy] !== 'object') { obj[policy] = {}; } // Set every sub-object for two-level policy for (prop in policies[policy]) { value = options[policies[policy][prop][0]]; obj[policy][prop] = value === undefined ? policies[policy][prop][1] : value; } } } }; /** * Parse commands (command interpretor) based on a specified interpreter * structure */ global.parseCommands = function (obj, interpreter, args) { var i, l; if (typeof interpreter === 'string') { interpreter = interpreters[interpreter] || []; } // Iterate through the arguments template and add the keys to the // options object while fetching corresponding values from arguments // array. for (i = 0, l = interpreter.length; i < l; i++) { obj[interpreter[i]] = args[i]; } return obj; }; global.core = function (command) { // This point onwards, we must check whether this is being used as a // constructor or not if (!(this instanceof global.core)) { // Allow private communication with modules. In case FusionCharts is // not called as constructor and it is passed an array that is marked // to do private communication, then share the global variable. if (arguments.length === 1 && command instanceof Array && command[0] === 'private') { // Prevent overwriting and duplicate execution of modules. if (modules[command[1]]) { return undefined; } modules[command[1]] = {}; // Check for module-specific information if (command[3] instanceof Array) { global.core.version[command[1]] = command[3]; } // Execute module function if (typeof command[2] === 'function') { return command[2].call(global, modules[command[1]]); } else { return global; } } // Allow using FusionCharts object to directly access its new items if (arguments.length === 1 && typeof command === 'string') { return global.core.items[command]; } // In case all above combination of arguments fail, we can unsafely // assume that user forgot the 'new' keyword. global.raiseError && global.raiseError(this, '25081840', 'run', '', new SyntaxError( "Use the \"new\" keyword while creating a new FusionCharts object")); } // Define a variable for iterative key in various loops and the // object variable that stores the options. var options = {}; /** * @var {object} __state maintains internal state related information. * @private */ this.__state = {}; // Check whether linear arguments are sent and convert it to object. if (arguments.length === 1 && typeof arguments[0] === 'object') { // If the above condition matches, then we can safely assume that // the first parameter is the options object. options = arguments[0]; } else { // Parse command interpreter policies global.parseCommands(options, interpreters.stat, arguments); // Do a special treatment of swfUrl (first argument) if (global.core.options.sensePreferredRenderer && options.swfUrl && options.swfUrl.match && !options.swfUrl.match(/[^a-z0-9]+/ig)) { options.type = options.swfUrl; } } // Incorporate the trailing object parameter as object-style // parameter input overrides. if (arguments.length > 1 && typeof arguments[arguments.length - 1] === 'object') { delete options[interpreters.stat[arguments.length - 1]]; global.extend(options, arguments[arguments.length - 1]); } // Set autogenerated chart-id in case one is not specified this.id = typeof options.id === 'undefined' ? this.id = global.uniqueId() : options.id; // Set dimension passed by user and subsequently validate the options. // - Remove trailing 'px' this.args = options; // If an item is created with same id, the previous item is disposed. if (global.core.items[this.id] instanceof global.core) { global.raiseWarning(this, '06091847', 'param', '', new Error('A FusionChart oject with the specified id \"' + this.id + '\" already exists. Renaming it to ' + (this.id = global.uniqueId()) )); } // Use the "type" attribute if provided and override swfUrl. if (options.type && options.type.toString) { // when type is provided, default renderer is JS unless overridden. if (!global.renderer.userSetDefault && (isIE || hasSVG)) { options.renderer = options.renderer || 'javascript'; } // The swfUrl is first compunded with swfSrcPath and if unavailable, // scriptBaseUri. options.swfUrl = (global.core.options.swfSrcPath || options.swfSrcPath || global.core.options.scriptBaseUri).replace(/\/\s*$/g, '') + '/' + options.type.replace(/\.swf\s*?$/ig, '') + '.swf'; } // Parse global policies. global.parsePolicies(this, global.policies, options); // Copy chart id to attributes this.attributes.id = this.id; // Set initial dimension of charts this.resizeTo(options.width, options.height, true); // Execute all constructors one after the other using events. global.raiseEvent('BeforeInitialize', options, this); // Add this object to the repository of objects within core object. global.core.items[this.id] = this; // Raise initialization event. global.raiseEvent('Initialized', options, this); return this; }; // Make the core extensible and reset the constructor of the object // for maintaining correct prototype chain. global.core.prototype = {}; // Reset constructor. global.core.prototype.constructor = global.core; global.extend(global.core, { id: 'FusionCharts', /** * The version of FusionCharts.js */ version: [3, 3, 1, 'sr3', 21100], // Add a container of all chart objects. This will allow easy returning // of FusionCharts objects through getChartFromId. items: {}, // Add an object to store options options: { sensePreferredRenderer: true }, // Add function to access the object created by renderers. getObjectReference: function (id) { return global.core.items[id].ref; } }, false); // Expose the core to the global scope. win.FusionCharts = global.core; // Check whether legacy FusionMaps already exists at this point in execution // time. If yes, then we need to perform routines to assimilate it. if (win.FusionMaps && win.FusionMaps.legacy) { global.core(['private', 'modules.core.geo', win.FusionMaps.legacy, win.FusionMaps.version]); mapLegacyDiscovered = true; } // If FusionMaps legacy was not discovered, we give it another shot after // the page has loaded. if (!(hasLoaded.test(doc.readyState) || doc.loaded)) { (function () { var _timer; function init() { // quit if this function has already been called if (arguments.callee.done) return; // flag this function so we don't do the same thing twice arguments.callee.done = true; // kill the timer if (_timer) clearTimeout(_timer); if (!mapLegacyDiscovered) { if (win.FusionMaps && win.FusionMaps.legacy) { global.core(['private', 'modules.core.geo', win.FusionMaps.legacy, win.FusionMaps.version]); } win.FusionMaps = global.core; } // Notify that library is ready for consumption. setTimeout(notifyLibraryInit, 1); }; function checkInit () { if (hasLoaded.test(doc.readyState)) { init(); // call the onload handler } else { _timer = setTimeout(checkInit, 10); } } if (doc.addEventListener) { doc.addEventListener("DOMContentLoaded", init, false); } else if (doc.attachEvent) { win.attachEvent("onLoad", init); } if (isIE) { try { if (win.location.protocol === 'https:') { doc.write('<script id="__ie_onload_fusioncharts" defer="defer" src="//:"><\/script>'); } else { doc.write('<script id="__ie_onload_fusioncharts" defer="defer" src="javascript:void(0)"><\/script>'); } var script = doc.getElementById("__ie_onload_fusioncharts"); script.onreadystatechange = function() { if (this.readyState == "complete") { init(); // call the onload handler } }; } catch (e) {} } if (/WebKit/i.test(nav.userAgent)) { // sniff _timer = setTimeout(checkInit, 10); } win.onload = function (callback) { return function () { init(); callback && callback.call && callback.call(win); }; }(win.onload); }()); } else { // already marking it ready means that notifier will let know that page // has already been loaded. global.ready = true; setTimeout(notifyLibraryInit, 1); } // In any case, we expose the latest core. If legacy overrides it on page // load, that would be handled win.FusionMaps = global.core; }()); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, immed: true */ /*global Array: false, FusionCharts, window: false */ /*members "*", BeforeDispose, BeforeInitialize, DataLoadCancelled, BeforeDataUpdate, DataLoadError, DataLoadRequestCancelled, DataLoadRequestCompleted, DataUpdateCancelled, DataLoadRequested, DataLoaded, DataXMLInvalid, Disposed, DrawComplete, FusionChartsEvents, Initialized, InvalidDataError, Loaded, DataUpdated NoDataToDisplay, Rendered, Resized, addEventListener, addListener, call, cancel, core, eventId, eventType, extend, items, lastEventId, length, listeners, push, raiseError, raiseEvent, removeEventListener, removeListener, sender, splice, stopPropagation, toLowerCase, triggerEvent */ /** * ----------------------------------------------------------------------------- * Event Handler Framework * This module allows FusionCharts to work with W3C Level 2 style events for * allowing multiple handlers per event and also to do event driven development * on a global or per-chart basis. * ----------------------------------------------------------------------------- */ (function () { // Try register the module with FusionCharts. var global = FusionCharts(['private', 'EventManager']); // Check whether the module has been already registered. If true, then // do not bother to re-register. if (global === undefined) { return; } // Collection of FusionCharts events window.FusionChartsEvents = { BeforeInitialize: 'beforeinitialize', Initialized: 'initialized', Loaded: 'loaded', BeforeRender: 'beforerender', Rendered: 'rendered', DataLoadRequested: 'dataloadrequested', DataLoadRequestCancelled: 'dataloadrequestcancelled', DataLoadRequestCompleted: 'dataloadrequestcompleted', BeforeDataUpdate: 'beforedataupdate', DataUpdateCancelled: 'dataupdatecancelled', DataUpdated: 'dataupdated', DataLoadCancelled: 'dataloadcancelled', DataLoaded: 'dataloaded', DataLoadError: 'dataloaderror', NoDataToDisplay: 'nodatatodisplay', DataXMLInvalid: 'dataxmlinvalid', InvalidDataError: 'invaliddataerror', DrawComplete: 'drawcomplete', Resized: 'resized', BeforeDispose: 'beforedispose', Disposed: 'disposed', Exported: 'exported' }; // A function to create an abstraction layer so that the try-catch / // error suppression of flash can be avoided while raising events. var managedFnCall = function (item, scope, event, args) { // We change the scope of the function with respect to the // object that raised the event. try { item[0].call(scope, event, args || {}); } catch (e) { // Call error in a separate thread to avoid stopping // of chart load. setTimeout(function () { throw e; }, 0); } }; // Function that executes all functions that are to be invoked upon trigger // of an event. var slotLoader = function (slot, event, args) { // If slot does not have a queue, we assume that the listener // was never added and halt method. if (!(slot instanceof Array)) { // Statutory W3C NOT preventDefault flag return; } // Initialize variables. var i = 0, scope; // Iterate through the slot and look for match with respect to // type and binding. for (; i < slot.length; i += 1) { // If there is a match found w.r.t. type and bind, we fire it. if (slot[i][1] === event.sender || slot[i][1] === undefined) { // Determine the sender of the event for global events. // The choice of scope differes depending on whether a // global or a local event is being raised. scope = slot[i][1] === event.sender ? event.sender : global.core; managedFnCall(slot[i], scope, event, args); // Check if the user wanted to detach the event if (event.detached === true) { slot.splice(i, 1); i -= 1; event.detached = false; } } // Check whether propagation flag is set to false and discontnue // iteration if needed. if (event.cancelled === true) { break; } } }; var EventTarget = { unpropagator: function () { return (this.cancelled = true) === false; }, detacher: function () { return (this.detached = true) === false; }, undefaulter: function () { return (this.prevented = true) === false; }, // Entire collection of listeners. listeners: {}, // The last raised event id. Allows to calculate the next event id. lastEventId: 0, addListener: function (type, listener, bind) { // In case type is sent as array, we recurse this function. if (type instanceof Array) { // We look into each item of the 'type' parameter and send it, // along with other parameters to a recursed addListener // method. for (var i = 0; i < type.length; i += 1) { EventTarget.addListener(type[i], listener, bind); } return; } // Validate the type parameter. Listener cannot be added without // valid type. if (typeof type !== 'string') { global.raiseError(bind || global.core, '03091549', 'param', '::EventTarget.addListener', new Error('Unspecified Event Type')); return; } // Listener must be a function. It will not eval a string. if (typeof listener !== 'function') { global.raiseError(bind || global.core, '03091550', 'param', '::EventTarget.addListener', new Error('Invalid Event Listener')); return; } // Desensitize the type case for user accessability. type = type.toLowerCase(); // If the insertion position does not have a queue, then create one. if (!(EventTarget.listeners[type] instanceof Array)) { EventTarget.listeners[type] = []; } // Add the listener to the queue. EventTarget.listeners[type].push([listener, bind]); }, removeListener: function (type, listener, bind) { var slot, i; // Listener must be a function. Else we have nothing to remove! if (typeof listener !== 'function') { global.raiseError(bind || global.core, '03091560', 'param', '::EventTarget.removeListener', new Error('Invalid Event Listener')); return; } // In case type is sent as array, we recurse this function. if (type instanceof Array) { // We look into each item of the 'type' parameter and send it, // along with other parameters to a recursed addListener // method. for (i = 0; i < type.length; i += 1) { EventTarget.removeListener(type[i], listener, bind); } return; } // Validate the type parameter. Listener cannot be removed without // valid type. if (typeof type !== 'string') { global.raiseError(bind || global.core, '03091559', 'param', '::EventTarget.removeListener', new Error('Unspecified Event Type')); return; } // Desensitize the type case for user accessability. type = type.toLowerCase(); // Create a reference to the slot for easy lookup in this method. slot = EventTarget.listeners[type]; // If slot does not have a queue, we assume that the listener // was never added and halt method. if (!(slot instanceof Array)) { return; } // Iterate through the slot and remove every instance of the // event handler. for (i = 0; i < slot.length; i += 1) { // Remove all instances of the listener found in the queue. if (slot[i][0] === listener && slot[i][1] === bind) { slot.splice(i, 1); i -= 1; } } }, // opts can have { async:true, omni:true } triggerEvent: function (type, sender, args, source, defaultFn) { // In case, event type is missing, dispatch cannot proceed. if (typeof type !== 'string') { global.raiseError(sender, '03091602', 'param', '::EventTarget.dispatchEvent', new Error('Invalid Event Type')); return undefined; } // Desensitize the type case for user accessability. type = type.toLowerCase(); // Model the event as per W3C standards. Add the function to cancel // event propagation by user handlers. Also append an incremental // event id. var event = { eventType: type, eventId: (EventTarget.lastEventId += 1), sender: sender || new Error('Orphan Event'), cancel: false, stopPropagation: this.unpropagator, prevented: false, preventDefault: this.undefaulter, detached: false, detachHandler: this.detacher }; // Add underlyingEvent object if (source) { event.originalEvent = source; } // Execute the functions present within the event slot (collection // of functions for a particular event). slotLoader(EventTarget.listeners[type], event, args); // Facilitate the call of a global event listener. slotLoader(EventTarget.listeners['*'], event, args); // Execute default action if (defaultFn && event.prevented === false) { managedFnCall(defaultFn, event.sender, event, args); } // Statutory W3C NOT preventDefault flag return true; } }; // Facilitate for raising events internally. global.raiseEvent = function (type, args, obj, sourceEvent, defaultFn) { return EventTarget.triggerEvent(type, obj, args, sourceEvent, defaultFn); }; // Extend the eventlisteners to internal global. global.addEventListener = function (type, listener) { return EventTarget.addListener(type, listener); }; global.removeEventListener = function (type, listener) { return EventTarget.removeListener(type, listener); }; // Add eventListener extensibility to FusionCharts object global.extend(global.core, { addEventListener: global.addEventListener, removeEventListener: global.removeEventListener }, false); // Add eventListener extensibility to FusionCharts prototype so that // individual FusionCharts objects can use per-chart events global.extend(global.core, { addEventListener: function (type, listener) { return EventTarget.addListener(type, listener, this); }, removeEventListener: function (type, listener) { return EventTarget.removeListener(type, listener, this); } }, true); // Cleanup on dispose global.addEventListener('BeforeDispose', function (e) { var type, i; // Iterate through all events in the collection of listeners for (type in EventTarget.listeners) { for (i = 0; i < EventTarget.listeners[type].length; i += 1) { // When a match is found, delete the listener from the // collection. if (EventTarget.listeners[type][i][1] === e.sender) { EventTarget.listeners[type].splice(i, 1); } } } }); // Raise library initialization event, if not already done. if (global.ready && !global.readyNotified) { global.readyNotified = true; global.raiseEvent('ready', { version: global.core.version, now: global.readyNow }, global.core); } }()); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, immed: true */ /*global Array: false, FusionCharts, window: false, console: false */ /*members _enableFirebugLite, appendChild, comp, console, core, createElement, currentOutputHelper, debugMode, enabled, event, eventId, eventType, extend, firebug, getElementsByTagName, id, impl, length, level, log, message, module, name, nature, onload, onreadystatechange, options, outputFailed, outputFormat, outputHandler, outputHelpers, outputTo, param, raiseError, raiseEvent, raiseWarning, range, readyState, run, scriptBaseUri, sender, setTimeout, source, src, text, toLowerCase, toString, type, undefined, verbose */ /** * ----------------------------------------------------------------------------- * FusionCharts JavaScript Library * Error Handler Framework * * This module allows other FusionCharts JavaScript Library modules to raise * error and warning messages. * ----------------------------------------------------------------------------- */ (function () { // Try register the module with FusionCharts. var global = FusionCharts(['private', 'ErrorHandler']); // Check whether the module has been already registered. If true, then // do not bother to re-register. if (global === undefined) { return; } // Set the default options for the default output helper. var DEFAULT_OUTPUT_HELPER = 'text'; /** * @var {object} errorNature is an enumeration containing possible error * types. This is used so that shorthand reference to .raiseError and * .raiseWarning can be expanded for easier user reference. */ var errorNatures = { type: 'TypeException', range: 'ValueRangeException', impl: 'NotImplementedException', param: 'ParameterException', run: 'RuntimeException', comp: 'DesignTimeError', 'undefined': 'UnspecifiedException' }; /** * This function raises the error event after appropriately formatting the * parameters. * @param {FusionCharts} sender * @param {string} id Is the error reference id. * @param {string} nature Is a cue as to what category of error is this. * The value of this param must be same as one of the "keys" within * the "errorNatures" collection. * @param {string} source Is a cue as to which object/module caused this * error. * @param {Error} err * @param {string} level Indicates whether this error event is an error * or warning event. Its values can be "Error" or "Warning". * * @type void */ var raiseEWEvent = function (sender, id, nature, source, err, level) { // We create a human-readable message for this error. var message = '#' + id + ' ' + (sender ? sender.id : 'unknown-source') + source + ' ' + level + ' >> '; // If err is sent as error object, we input more details to the error // object if (err instanceof Error) { err.name = errorNatures[nature]; err.module = 'FusionCharts' + source; err.level = level; // Update the error message. err.message = message + err.message; message = err.message; // Throw error in a separate scope so that the execution of this script // is not blocked. Do this only when debugMode is enabled window.setTimeout(function () { throw err; }, 0); } else { // Append the message string to the error message and sync with err. message = message + err; } // Prepare the event argument object. var args = { id: id, nature: errorNatures[nature], source: 'FusionCharts' + source, message: message }; // Raise the appropriate event. global.raiseEvent(level, args, sender); // Raise legacy events if (typeof window['FC_' + level] === 'function') { window['FC_' + level](args); } }; /** * This function raises an "Error" event based upon the parameters passed * to it. * @param {FusionCharts} sender * @param {string} id Is the error reference id. * @param {string} nature Is a cue as to what category of error is this. * The value of this param must be same as one of the "keys" within * the "errorNatures" collection. * @param {string} source Is a cue as to which object/module caused this * error. * @param {string} message * * @type void */ global.raiseError = function (sender, id, nature, source, message) { raiseEWEvent(sender, id, nature, source, message, 'Error'); }; /** * This function raises an "Warning" event based upon the parameters passed * to it. * @param {FusionCharts} sender * @param {string} id Is the error reference id. * @param {string} nature Is a cue as to what category of error is this. * The value of this param must be same as one of the "keys" within * the "errorNatures" collection. * @param {string} source Is a cue as to which object/module caused this * error. * @param {string} message * * @type void */ global.raiseWarning = function (sender, id, nature, source, message) { raiseEWEvent(sender, id, nature, source, message, 'Warning'); }; /** * @var {object} logger Conatins all routines pertaining to logging a debug * outout. */ var logger = { /** * @var {object} outputHelpers Is the collection of functions that calls * the outputTo function with arguments formatted in a specific manner. */ outputHelpers: { // Simple text output function. 'text': function (e, a) { var sender = (e.sender.id || e.sender).toString(); logger.outputTo('#' + e.eventId + ' [' + sender + '] fired "' + e.eventType + '" event. ' + (e.eventType === 'error' || e.eventType === 'warning' ? a.message : '')); }, // Function that calls the debugger method in typical FusionCharts // events argument format. 'event': function (e, a) { this.outputTo(e, a); }, // This function formats outputs with all details, and still, // maintaining human readable format. It is best used in conjunction // with an advanced JS console. 'verbose': function (e, a) { logger.outputTo(e.eventId, e.sender.id, e.eventType, a); } }, /** * @var {object} outputHandler Is the eventHandler that indirectly calls * the output function via output helpers whenever any event is raised. */ outputHandler: function (e, a) { // Verify whether the output function exists or not. if (typeof logger.outputTo !== 'function') { global.core.debugMode.outputFailed = true; return; } // Clear flag of data load fail upon reaching this line. global.core.debugMode.outputFailed = false; // Call the current outputHelper in order to invoke the // required function. logger.currentOutputHelper(e, a); }, /** * @var {function} currentOutputHelper Is the function that formats the * debug output if event format to different formats as arguments. * @var {function} outputTo Is the reference to the function that is * called when a debug event is raised. * @var {boolean} keeps a track whether the logger is enabled or not. */ currentOutputHelper: undefined, outputTo: undefined, enabled: false }; // Set the initial default output helper to the one specified as default. logger.currentOutputHelper = logger.outputHelpers[DEFAULT_OUTPUT_HELPER]; // Add debugMode API to FusionCharts core object, so that it can be accessed // by users globally. global.extend(global.core, { debugMode: { syncStateWithCharts: true, /** * Specifies how to format the output to the function that will * accept output from the debugger. * @id FusionCharts.debugMode.outputFormat * * @param {string} format Can be one of the accepted format names * such as "text", "verbose", "event". * * @type boolean */ outputFormat: function (format) { // Validate the parameter. if (format && typeof format.toLowerCase === 'function' && typeof logger.outputHelpers[format = format.toLowerCase()] === 'function') { // set the current output helper function to the one specified // in parameter logger.currentOutputHelper = logger.outputHelpers[format]; // Return "true" to users, indicating, output format // successfully updated. return true; } // In case validation fails, notify user that it failed by // returning false; return false; }, /** * Allows you to specify the function to which the debugger output * will be redirected. * @id FusionCharts.debugMode.outputTo * * @param {function} fn is the function to which the debugMode output * will be passed on. * * @type void */ outputTo: function (fn) { // Check whether the logger is a function or not. If it is a // function, we set a reference to it to be used later as the // logger function. if (typeof fn === 'function') { logger.outputTo = fn; } // In case user sends 'null' as the value of the logger function, // we can assume that user wants not to log any output. else if (fn === null) { global.core.debugMode.enabled(false); delete logger.outputTo; } }, /** * Enables, disables and configures the debugMode. * @FusionCHarts.edbugMode.enabled * * @param {boolean} state specifies whether to enable logging of * debug information. * @param {function} outputTo is the function to which the debugMode * output will be passed on. * @param {string} outputFormat Can be one of the accepted format names * such as "text", "verbose", "event". * * @return The current 'enable' state of the debugMode. * @type boolean */ enabled: function (state, outputTo, outputFormat) { // Allow object to be sent as configuration parameter. var config; // In case the first parameter is object and the only parameter, // we copy its contents to various linear parameters and save // a copy of the object for later use. if (typeof state === 'object' && arguments.length === 1) { config = state; state = config.state; outputTo = config.outputTo; outputFormat = config.outputFormat; } // In case user send in only one parameter and that too a // function, we can assume that he wants to use it as a logger // function and also enable logging. if (typeof state === 'function') { if (typeof outputTo === 'string' && (arguments.length === 2 || config)) { outputFormat = outputTo; } outputTo = state; state = true; } // In case user sends in a valid parameter to change the current // state of the debugger, we update the debugger state. if (typeof state === 'boolean' && state !== logger.enabled) { global.core[(logger.enabled = state) ? 'addEventListener' : 'removeEventListener']('*', logger.outputHandler); } // If user sends in a parameter for the logger parameter, we // set it to the logger function reference. if (typeof outputTo === 'function') { logger.outputTo = outputTo; } // Set output format if needed. global.core.debugMode.outputFormat(outputFormat); // Finally send the current debugger state to the user. return logger.enabled; }, /** * This method fetches FirebugLite component's code and adds it to * current page. Subsequently, on load of the script it enables * advanced console logging to it. * @id FusionCharts.debugMode._enableFirebugLite * * * @type void * @private true */ _enableFirebugLite: function () { // Check whether firebug already exists. if (window.console && window.console.firebug) { // If firebug already exists, we do not need to include any // script for firebu-lite and we simply enable logging to //console. global.core.debugMode.enabled(console.log, 'verbose'); return; } // Install firebug-lite within page by creating new 'script' // element and appending to page head. global.loadScript('firebug-lite.js', function () { global.core.debugMode.enabled(console.log, 'verbose'); }, '{ startOpened: true }'); } } }, false); }()); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, immed: true */ /*global window: false, Array, FusionCharts, Error: false */ FusionCharts(['private', 'modules.mantle.ajax', function () { var global = this, // define constants for future use. FUNCTION = 'function', MSXMLHTTP = 'Microsoft.XMLHTTP', MSXMLHTTP2 = 'Msxml2.XMLHTTP', GET = 'GET', POST = 'POST', XHREQERROR = 'XmlHttprequest Error', RUN = 'run', ERRNO = '1110111515A', win = window, // keep a local reference of window scope // Probe IE version version = parseFloat(navigator.appVersion.split("MSIE")[1]), ielt8 = (version >= 5.5 && version <= 7) ? true : false, // // Calculate flags. // Check whether the page is on file protocol. fileProtocol = win.location.protocol === 'file:', axObject = win.ActiveXObject, // Check if native xhr is present xhrNative = (!axObject || !fileProtocol) && win.XMLHttpRequest, // stats counters = { objects: 0, xhr: 0, requests: 0, success: 0, failure: 0, idle: 0 }, // Prepare function to retrieve compatible xmlhttprequest. newXmlHttpRequest = function() { var xmlhttp; // if xmlhttprequest is present as native, use it. if (xhrNative) { newXmlHttpRequest = function () { counters.xhr++; return new xhrNative(); }; return newXmlHttpRequest(); } // Use activeX for IE try { xmlhttp = new axObject(MSXMLHTTP2); newXmlHttpRequest = function () { counters.xhr++; return new axObject(MSXMLHTTP2); }; } catch (e) { try { xmlhttp = new axObject(MSXMLHTTP); newXmlHttpRequest = function () { counters.xhr++; return new axObject(MSXMLHTTP); }; } catch (e) { xmlhttp = false; } } return xmlhttp; }, // Ajax class. Ajax = global.ajax = function (success, error) { this.onSuccess = success; this.onError = error; this.open = false; counters.objects++; counters.idle++; }; Ajax.stats = function (type) { return type ? counters[type] : global.extend({}, counters); }; Ajax.prototype.headers = { 'If-Modified-Since': 'Sat, 29 Oct 1994 19:43:31 GMT', 'X-Requested-With': 'XMLHttpRequest', 'X-Requested-By': 'FusionCharts', 'Accept': 'text/plain, */*', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }; Ajax.prototype.transact = function (method, url, data, callbackArgs) { var wrapper = this, xmlhttp = wrapper.xmlhttp, headers = wrapper.headers, errorCallback = wrapper.onError, successCallback = wrapper.onSuccess, isPost = (method === POST), postData, i; if (!xmlhttp || ielt8) { xmlhttp = newXmlHttpRequest(); wrapper.xmlhttp = xmlhttp; } xmlhttp.onreadystatechange = function () { try { if (xmlhttp.readyState === 4) { if ((!xmlhttp.status && fileProtocol) || (xmlhttp.status >= 200 && xmlhttp.status < 300) || xmlhttp.status === 304 || xmlhttp.status === 1223 || xmlhttp.status === 0) { successCallback && successCallback(xmlhttp.responseText, wrapper, callbackArgs, url); counters.success++; } else if (errorCallback) { errorCallback(Error(XHREQERROR), wrapper, callbackArgs, url); counters.failure++; } counters.idle--; wrapper.open = false; } } catch (error) { if (errorCallback) { errorCallback(error, wrapper, callbackArgs, url); } if (window.FC_DEV_ENVIRONMENT) { setTimeout(function () { throw error; }, 0); } counters.failure++; } }; try { if (xmlhttp.overrideMimeType) { xmlhttp.overrideMimeType('text/plain'); } if (isPost) { xmlhttp.open(POST, url, true); if (typeof data === 'string') { postData = data; } else { postData = []; for (i in data) { postData.push(i + '=' + (data[i]+"") .replace(/\=/g, '%3D').replace(/\&/g, '%26')); } postData = postData.join('&'); } } else { xmlhttp.open(GET, url, true); postData = null; } for (i in headers) { xmlhttp.setRequestHeader(i, headers[i]); } xmlhttp.send(postData); counters.requests++; counters.idle++; wrapper.open = true; } catch (e) { global.raiseError(global.core, ERRNO, RUN, XHREQERROR, e.message); } return xmlhttp; }; Ajax.prototype.get = function (url, callbackArgs) { return this.transact(GET, url, undefined, callbackArgs); }; Ajax.prototype.post = function (url, data, callbackArgs) { return this.transact(POST, url, data, callbackArgs); }; Ajax.prototype.abort = function () { var instance = this, xmlhttp = instance.xmlhttp; instance.open = false; return xmlhttp && typeof xmlhttp.abort === FUNCTION && xmlhttp.readyState && xmlhttp.readyState !== 0 && xmlhttp.abort(); }; Ajax.prototype.dispose = function () { var instance = this; instance.open && instance.abort(); delete instance.onError; delete instance.onSuccess; delete instance.xmlhttp; delete instance.open; counters.objects--; return (instance = null); }; }]); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, immed: true */ /*global window: false, Array: false, FusionCharts: false, FusionChartsEvents: false, FusionChartsDataFormats: false*/ /** * Generic Runtime Module */ (function () { // Register the module with FusionCharts. var global = FusionCharts(['private', 'modules.mantle.runtime;1.1']); // Check whether the module has been already registered. If true, then // do not bother to re-register. if (global === undefined) { return; } // Set the FusionCharts filename possibilities as regular expression. var SCRIPT_NAME_REGEX = /(^|[\/\\])(fusioncharts\.js|fusioncharts\.debug\.js|fusioncharts\.core\.js|fusioncharts\.min\.js)([\?#].*)?$/ig, BLOCK_EXTERNAL_SCRIPT_LOADING = false, DISALLOW_CROSSDOMAIN_RESOURCE = false, SCRIPT_LOAD_TIMEOUTMS = 15000; /** * Function to determine the script base uri for a script name */ global.getScriptBaseUri = function (scriptNameRegex) { // Get a collection of all script nodes. var scripts = document.getElementsByTagName('script'), l = scripts.length, src, i; // Iterate through the script node collection and match whether its // 'src' attribute contains fusioncharts file name. for (i = 0; i < l; i += 1) { src = scripts[i].getAttribute('src'); if (!(src === undefined || src === null || src.match(scriptNameRegex) === null)) { return src.replace(scriptNameRegex, '$1'); } } return undefined; }; // Get the script base uri. (Regexp has been updated) global.core.options.scriptBaseUri = (function () { var baseUri = global.getScriptBaseUri(SCRIPT_NAME_REGEX); if (baseUri === undefined) { global.raiseError(FusionCharts, '1603111624', 'run', '>GenericRuntime~scriptBaseUri', 'Unable to locate FusionCharts script source location (URL).'); return ''; } return baseUri; }()); /** * Regular Expressions that helps to check XSS security loops. */ var checkBadChars = /[\\\"<>;&]/, hasProtocolDef = /^[^\S]*?(sf|f|ht)(tp|tps):\/\//i, LOAD_EVENTNAME = FusionChartsEvents.ExternalResourceLoad = 'externalresourceload', /** * To keep a track of scripts requested. * @type Object */ scriptsRequested = {}, /** * To keep a track of loaded script tags */ scriptTags = {}, /** * To keep a track of scripts loaded. * @type Object */ scriptsLoaded = {}, /** * Keep a track of load failure check * @type object */ scriptLoadFailureTimeout = {}; /** * Function that allows users to verify whether a string contains any XSS * unsafe code. This is used while setting various urls. * @param {string} str The string that has to be checked for XSS * @param {boolean} proto Specify whether to test any protocol definition */ global.isXSSSafe = function (str, proto) { if (proto && hasProtocolDef.exec(str) !== null) { return false; } return (checkBadChars.exec(str) === null); }; /** * Loads a JS using head script attach method */ global.loadScript = function (file, callback, scriptText, includeOnce, pathInFile) { // If file is not specified, we exit if (!file) { return false; } // Check security block. if (BLOCK_EXTERNAL_SCRIPT_LOADING === true) { global.raiseWarning(global.core, '04031935', 'run', '>genericRuntime~loadScript', 'External Script loading has been blocked'); return false; } var script, success = callback && callback.success || callback, failure = callback && callback.failure, path, src, eventArgs = { type: 'script', success: false }, notify = function () { // clear stalled 404 check scriptLoadFailureTimeout[src] = clearTimeout(scriptLoadFailureTimeout[src]); // execute callbacks eventArgs.success ? (success && success(file, src)) : (failure && failure(file, src)); global.raiseEvent(LOAD_EVENTNAME, eventArgs, global.core); }; // Prepare path. if (pathInFile) { path = ''; } else { path = global.core.options.scriptBaseUri; } // Prepare the full src src = path + file; // we do not allow XSS unsafe string if (!global.isXSSSafe(src, DISALLOW_CROSSDOMAIN_RESOURCE)) { src = typeof window.encodeURIComponent === 'function' ? window.encodeURIComponent(src) : window.escape(src); } // Update event arguments eventArgs.path = path; eventArgs.src = src; eventArgs.file = file; // Do not reload the script once loaded. if (scriptsLoaded[src] === true && includeOnce) { eventArgs.success = true; eventArgs.notReloaded = true; if (typeof callback === 'function') { callback(); global.raiseEvent(LOAD_EVENTNAME, eventArgs, global.core); } return true; } // Check whether this script has been already loaded once and whether // multiple inclusion is prevented. if (scriptsRequested[src] && includeOnce) { return false; } // Add the src to the lists of scripts loaded. scriptsRequested[src] = true; // If a script tag with same src exists, then we need to delete the // previous one if (scriptTags[src] && scriptTags[src].parentNode) { scriptTags[src].parentNode.removeChild(scriptTags[src]); } // Create the script element with its attributes. script = scriptTags[src] = document.createElement('script') // Set the script type to javaScript script.type = 'text/javascript'; // Set the prepared src as the script's src. script.src = src; // Set script inner text to what user passed as parameter. if (scriptText) { script[('\v' === 'v' ? 'text' : 'innerHTML')] = scriptText; } // Execute callback function when the script was loaded. if (typeof success === 'function') { scriptsLoaded[src] = false; scriptLoadFailureTimeout[src] = clearTimeout(scriptLoadFailureTimeout[src]); script.onload = function () { scriptsLoaded[src] = true; eventArgs.success = true; notify(); }; script.onerror = function () { scriptsLoaded[src] = false; scriptsRequested[src] = false; // in case of error cancel request notify(); }; script.onreadystatechange = function () { if (this.readyState === 'complete' || this.readyState === 'loaded') { scriptsLoaded[src] = true; eventArgs.success = true; notify(); } }; } // Append the script to the head of this page. document.getElementsByTagName('head')[0].appendChild(script); // Prepare the timeout check for script load failure if (typeof failure === 'function') { scriptLoadFailureTimeout[src]= setTimeout(function () { if (scriptsLoaded[src]) { return; } notify(); }, global.core.options.html5ResourceLoadTimeout || SCRIPT_LOAD_TIMEOUTMS); } return true; }; /** * Capitalizes first letter of a word */ global.capitalizeString = function (str, all) { return str ? str.replace(all ? (/(^|\s)([a-z])/g) : (/(^|\s)([a-z])/), function(m,p1,p2){ return p1 + p2.toUpperCase(); }) : str; }; /** * Function that safely deletes all items in a DOM element. */ var purgeDOM = global.purgeDOM = function (d) { var a = d.attributes, i, l, n; if (a) { for (i = a.length - 1; i >= 0; i -= 1) { n = a[i].name; if (typeof d[n] === 'function') { d[n] = null; } } } a = d.childNodes; if (a) { l = a.length; for (i = 0; i < l; i += 1) { purgeDOM(d.childNodes[i]); } } }, // Deconstruct policies. // Update the arguments with latest copy of all variables by // reverse engineering the policies. deconstructPolicySet = function (policies, options, obj) { var policy; for (policy in policies) { var prop; // Set just the policy object in case of single-level policy. if (policies[policy] instanceof Array) { options[policies[policy][0]] = obj[policy]; } else { // Copy the source of multi-level policies for (prop in policies[policy]) { options[policies[policy][prop][0]] = obj[policy][prop]; } } } }, lengthCleanupRegex = /[^\%\d]*$/ig, signatureMatchRegex = /^(FusionCharts|FusionWidgets|FusionMaps)/; global.extend(global.core, { // Add default object management prototype method to raise deletion // event. dispose: function () { // The event must be async in order to prevent integrity. global.raiseEvent('BeforeDispose', {}, this); // Call dispose on the renderer. Renderer should dispose between // the beforeDispose and disposed event. global.renderer.dispose(this); // Delete the reference of the item delete global.core.items[this.id]; // Raise a post-disposal event global.raiseEvent('Disposed', {}, this); // Remove all variables within this object, making this variable not // usable. for (var prop in this) { delete this[prop]; } }, clone: function (params, cloneParametersOnly) { // Create a copy of arguments of this object. var typeofParams = (typeof params), crcObjects = {}, options = global.extend({}, this.args, false, false); // Recreate construction parameters by reverse calculating the global // policies. deconstructPolicySet(global.policies, options, this); // Also deconstruct the rendere specific policies. deconstructPolicySet(global.renderer.getRendererPolicy(this.options.renderer), options, this); // Remove any specific parameters that if cloned will create issues. delete options.id; delete options.animate; delete options.stallLoad; crcObjects.link = options.link; // link was removed as it prevents deep cloning // Now, deep clone the entire object to separate both instances options = global.extend({}, options, false, false); // restore crc Objects options.link = crcObjects.link; switch (typeofParams) { // Override any of the options by parameters sent by user case 'object': global.extend(options, params); break; // In case user sends only one boolean param marking not to // create new chart. case 'boolean': cloneParametersOnly = params; break; } // Create new FusionCharts object from the computed options return cloneParametersOnly ? options: new global.core(options); }, isActive: function () { if (!this.ref || document.getElementById(this.id) !== this.ref || typeof this.ref.signature !== 'function') { return false; } try { return signatureMatchRegex.test(this.ref.signature()); } catch (e) { return false; } }, resizeTo: function (w, h, noUpdate) { var dimension = { width: w, height: h }; if (typeof arguments[0] === 'object') { dimension.width = arguments[0].width; dimension.height = arguments[0].height; noUpdate = h; } if (dimension.width && typeof dimension.width.toString === 'function') { this.width = dimension.width.toString().replace(lengthCleanupRegex, ''); } if (dimension.height && typeof dimension.height.toString === 'function') { this.height = dimension.height.toString().replace(lengthCleanupRegex, ''); } if (noUpdate !== true) { global.renderer.resize(this, dimension); } }, // Add function to get chart type name from SWF chartType: function (value) { var chartObj = this, src = chartObj.src, url; if (typeof value === 'string') { chartObj.src = value; chartObj.isActive() && chartObj.render(); } // Note that we need to replace 'fcmap_' when there. return (url = (url = src.substring(src.indexOf('.swf'), 0)) ? url : src).substring(url.lastIndexOf('/') + 1).toLowerCase() .replace(/^fcmap_/i, ''); } }, true); // Globally expose getChartFromId method. window.getChartFromId = window.getMapFromId = function (id) { global.raiseWarning(this, '11133001041', 'run', 'GenericRuntime~getObjectFromId()', 'Use of deprecated getChartFromId() or getMapFromId(). Replace ' + 'with "FusionCharts()" or FusionCharts.items[].'); return global.core.items[id] instanceof global.core ? global.core.items[id].ref : window.swfobject.getObjectById(id); }; }()); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, immed: true */ /*global Array: false, FusionCharts, RegExp: false, window: false FusionChartsDataFormats: true */ /*members FusionCharts, XMLURL, addEventListener, appendChild, apply, args, call, config, configure, containerElement, containerElementId, core, createElement, currentRendererName, dataFormat, extend, firstChild, getAttribute, getElementById, getElementsByTagName, getExternalInterfaceMethods, getRenderer, getRendererPolicy, hasChildNodes, id, init, initialized, insertMode, items, length, options, parsePolicies, policies, prototype, raiseError, raiseEvent, ref, register, removeChild, render, renderer, resize, sender, setAttribute, setCurrentRenderer, setDefault, slice, split, success, toLowerCase, toString, undefined, update, __state, rendering, dispose, events */ /** * ----------------------------------------------------------------------------- * Renderer Abstraction Framework * This module allows developers to abstract the entire rendering engine. This * helps in multiple implementations of FusionCharts in various technologies * such as flash, HTML5, etc. * ----------------------------------------------------------------------------- */ (function () { // Register the module with FusionCharts. var global = FusionCharts(['private', 'RendererManager']); // Check whether the module has been already registered. If true, then // do not bother to re-register. if (global === undefined) { return; } // Allow FusionCharts to accept parameter to specify where to render the // chart. global.policies.options.containerElementId = ['renderAt', undefined]; global.policies.options.renderer = ['renderer', undefined]; // Function to normalize dimension for style setting global.normalizeCSSDimension = function (width, height, container) { // optimize dimensions var w = width === undefined ? (container.offsetWidth || parseFloat(container.style.width)) : width, h = height === undefined ? (container.offsetHeight || parseFloat(container.style.height)) : height, p; // Do initial testing by setting dimensions container.style.width = w = w.toString ? w.toString() : '0'; container.style.height = h = h.toString ? h.toString() : '0'; if (w.match(/^\s*\d*\.?\d*\%\s*$/) && !w.match(/^\s*0\%\s*$/) && container.offsetWidth === 0) { p = container; while ((p = p.offsetParent)) { if (p.offsetWidth > 0) { w = (p.offsetWidth * parseFloat(w.match(/\d*/)[0]) / 100).toString(); break; } } } if (h.match(/^\s*\d*\.?\d*\%\s*$/) && !h.match(/^\s*0\%\s*$/) && container.offsetHeight <= 20) { p = container; while ((p = p.offsetParent)) { if (p.offsetHeight > 0) { h = (p.offsetHeight * parseFloat(h.match(/\d*/)[0]) / 100).toString(); break; } } } // Re-use variable 'p' to store the final dimensioms p = { width: (w.replace ? w.replace(/^\s*(\d*\.?\d*)\s*$/ig, '$1px') : w), height: (h.replace ? h.replace(/^\s*(\d*\.?\d*)\s*$/ig, '$1px') : h) }; // Finally apply the dimensions container.style.width = p.width; container.style.height = p.height; return p }; // Collection of renderers. var notDefined = function () { global.raiseError(this, '25081845', 'run', '::RendererManager', new Error('No active renderer')); return; }, renderers = { 'undefined': { render: notDefined, remove: notDefined, update: notDefined, resize: notDefined, config: notDefined, policies: {} } }, store = {}, // store which chart has what renderer // API to add renderer and also to set/get the current renderer. renderer = global.renderer = { register: function (name, obj) { // Validate parameters if (!name || typeof name.toString !== 'function') { throw "#03091436 ~renderer.register() Invalid value for renderer name."; } // Desensitize character case for renderer name name = name.toString().toLowerCase(); // Prevent addition of duplicate renderer if (renderers[name] !== undefined) { global.raiseError(global.core, '03091438', 'param', '::RendererManager>register', 'Duplicate renderer name specified in "name"'); return false; } // Add renderer to the collection of renderers. renderers[name] = obj; // Return true when a new renderer is successfully added. return true; }, // Flag that tracks whether user has updated the default value. userSetDefault: false, // Set the current renderer setDefault: function (name) { // Validate parameters if (!name || typeof name.toString !== 'function') { global.raiseError(global.core, '25081731', 'param', '::RendererManager>setDefault', 'Invalid renderer name specified in "name"'); return false; } // Validate the renderer name and see whether the parameter refers to a // valid renderer. // ALSO: Desensitize character case for renderer name. if (renderers[name = name.toString().toLowerCase()] === undefined) { global.raiseError(global.core, '25081733', 'range', '::RendererManager>setDefault', 'The specified renderer does not exist.'); return false; } // Mark auto-set default renderer. When user specifically sets // renderer, this flag needs to be overwritten. this.userSetDefault = false; // Set reference to the current renderer. global.policies.options.renderer = ['renderer', name]; return true; }, // Define a function that saves the reference to the embedded object // after it has been rendered. notifyRender: function (status) { // Lookup corresponding chartObject for the renderer notif. var chartObj = global.core.items[(status && status.id)]; // Check whether the render was successful. if (!chartObj || (status.success === false && !status.silent)) { global.raiseError(global.core.items[status.id], '25081850', 'run', '::RendererManager', new Error('There was an error rendering the chart. ' + 'Enable FusionCharts JS debugMode for more information.')); } // Lookup the FusionCharts object within its "items" repository. chartObj.ref = status.ref; // If the ref has been created, create a reverse reference. if (status.ref) { status.ref.FusionCharts = global.core.items[status.id]; } // Raise event that this chart has a DOM element global.raiseEvent('internal.DOMElementCreated', status, chartObj); }, protectedMethods: { options: true, attributes: true, src: true, ref: true, constructor: true, signature: true, link: true, addEventListener: true, removeEventListener: true }, getRenderer: function (name) { return renderers[name]; }, getRendererPolicy: function (name) { var policies = renderers[name].policies; return typeof policies === 'object' ? policies : {}; }, currentRendererName: function () { return global.policies.options.renderer[1]; }, update: function (obj) { store[obj.id].update.apply(obj, Array.prototype.slice.call(arguments, 1)); }, render: function (obj) { store[obj.id].render.apply(obj, Array.prototype.slice.call(arguments, 1)); }, remove: function (obj) { store[obj.id].remove.apply(obj, Array.prototype.slice.call(arguments, 1)); }, resize: function (obj) { store[obj.id].resize.apply(obj, Array.prototype.slice.call(arguments, 1)); }, config: function (obj) { store[obj.id].config.apply(obj, Array.prototype.slice.call(arguments, 1)); }, dispose: function (obj) { store[obj.id].dispose.apply(obj, Array.prototype.slice.call(arguments, 1)); } }; // This function allows users to make a generic call to external interface // of the chart via the FusionCharts object var eiCall = function (method) { return function () { // Verify whether the chart is valid object and then proceed. if (this.ref === undefined || this.ref === null || typeof this.ref[method] !== 'function') { // Raise error event to notify that a method on the renderer was // invoked while the renderer does not have such a method. global.raiseError(this, '25081617', 'run', '~' + method + '()', 'ExternalInterface call failed. Check whether chart has been rendered.'); return undefined; } return this.ref[method].apply(this.ref, arguments); }; }; // Constructor to add renderer functions global.addEventListener('BeforeInitialize', function (event) { // Reference to event sender. var obj = event.sender, item; // Check if construction has the default renderer name saved. if (typeof obj.options.renderer === 'string' && renderers[obj.options.renderer.toLowerCase()] === undefined) { obj.options.renderer = global.policies.options.renderer[1]; } // Desensitize the case of the parameter. obj.options.renderer = obj.options.renderer.toLowerCase(); // Keep a reference store[obj.id] = renderers[obj.options.renderer]; // Check whether this particular renderer has been rendered. if (store[obj.id].initialized !== true && typeof store[obj.id].init === 'function') { // Call the 'init' function on the renderer and set a flag. store[obj.id].init(); store[obj.id].initialized = true; } // Parse construction policies specific to this renderer. global.parsePolicies(obj, store[obj.id].policies || {}, obj.args); // Copy the prototype of the renderer specified in constructor to the // main object. for (var prop in store[obj.id].prototype) { obj[prop] = store[obj.id].prototype[prop]; } // Attach event liseners of the renderer to this object. for (item in store[obj.id].events) { obj.addEventListener(item, store[obj.id].events[item]); } }); global.addEventListener('Loaded', function (e) { // Store a reference to the chart swf HTML Node. var obj = e.sender, chartObj = e.sender.ref; // Clear the flag that keeps a track whether the chart is presently // in a 'rendering' state if (obj instanceof global.core) { delete obj.__state.rendering; } // Validate whether the chart swf node exists and that it has // the prerequisite externalInterface functions. if (chartObj === undefined || chartObj === null || typeof chartObj.getExternalInterfaceMethods !== 'function') { return; } // The externalInterfaceMethods names are parsed from CSV to // Array. var eiItems, i; // Check whether the external interface methods are being called or not. // If not, then there is an error (probably cross-domain). try { eiItems = chartObj.getExternalInterfaceMethods(); eiItems = typeof eiItems === 'string' ? eiItems.split(',') : []; } catch (err) { eiItems = []; global.raiseError(obj, '13111126041', 'run', 'RendererManager^Loaded', Error('Error while retrieving data from the chart-object.' + (err.message && err.message.indexOf('NPObject') >= 0 ? ' Possible cross-domain security restriction.' : ''))); } // We iterate through all the externalInterface method names and // create an extensible API object that is added to main // FusionCharts object as reference. for (i = 0; i < eiItems.length; i += 1) { // Copy method from renderer only when a local method does not exist if (obj[eiItems[i]] === undefined) { obj[eiItems[i]] = eiCall(eiItems[i]); } } }); // This function allows users to make a generic call from renderer // of the chart to main FusionCharts object. var jsCall = function (obj, prop) { // Check whether me if (typeof obj[prop] === 'function') { return function () { return obj[prop].apply(obj, arguments); }; } return obj[prop]; }; /** * Extend FusionCharts capabilities to swf HTMLNode object */ global.addEventListener('loaded', function (event, args) { var sender = event.sender; // Check whether the object was added to DOM or not. if (!sender.ref) { return; } // List the properties that are not to be extended. var ignore1 = global.renderer.protectedMethods, ignore2 = global.renderer.getRenderer(sender.options.renderer).protectedMethods, prop; // Iterate through the FusionCharts object and add its variables to the // HTMLNode object. for (prop in event.sender) { // Discontinue adding this object in case the property is marked to // be ignored. if (ignore2 && !(ignore1[prop] || ignore2[prop] || sender.ref[prop] !== undefined)) { try { sender.ref[prop] = jsCall(event.sender, prop); } catch (e) { } } } }); // ============================================================================ // Function that checks duplicate. var isDuplicateId = function (lookupId, container) { // Get the lookup element from the ID sent via parameter. var lookupElement = document.getElementById(lookupId), // Get the ID of the container element. containerId = container.getAttribute('id'); // Check whether the element exists or not. If it does not exist, it // implies that there cannot be any duplicate. if (lookupElement === null) { return false; } // In case chart's Id and container's Id is same then is duplicate. if (lookupId === containerId) { return true; } // Check whether the lookup element returned before is actually // inside container or not. var children = container.getElementsByTagName('*'); for (var i = 0; i < children.length; i += 1) { if (children[i] === lookupElement) { return false; } } // If the lookupElement is outside/before the container, it implies // that it is a duplicate. return true; }; global.extend(global.core, { render: function (containerElement) { // Dispose the renderer in case of re-render. This checks whether there // is any previous DOM element in case the chart is re-rendered and // correspondingly deletes it. (B#565) var ref, s; if ((ref = window[this.id]) && ref.FusionCharts && ref.FusionCharts === this || (ref = this.ref) && ref.FusionCharts && ref.FusionCharts === this) { global.renderer.dispose(this); } // Check IE-Safe variable name collision within Global Scope if (window[this.id] !== undefined) { global.raiseError(this, '25081843', 'comp', '.render', new Error('#25081843:IECompatibility() Chart ' + 'Id is same as a JavaScript variable name. Variable naming ' + 'error. Please use unique name for chart JS variable, ' + 'chart-id and container id.')); } // Create a blank element inside to mimic alternativecontent var insertMode = this.options.insertMode.toLowerCase() || 'replace', alt; // Procure containerElement from internal object options that has // been passed via parameters. if (containerElement === undefined) { containerElement = this.options.containerElementId; } // In case user sends the element id, we get the object from it if (typeof containerElement === 'string') { containerElement = document.getElementById(containerElement); } if (containerElement === undefined || containerElement === null) { global.raiseError(this, '03091456', 'run', '.render()', new Error("Unable to find the container DOM element.")); return this; } // Check duplicate rendering with same id if (isDuplicateId(this.id, containerElement)) { global.raiseError(this, '05102109', 'run', '.render()', new Error("A duplicate object already exists with the specific Id: " + this.id)); return this; } // Set the attribute of this element that will be replaced by // swfobject alt = document.createElement(this.options.containerElementType || 'span'); alt.setAttribute('id', this.id); // Clear the contents of the containerElement and subsequently // append the new alt content. if (insertMode !== 'append' && insertMode !== 'prepend') { while (containerElement.hasChildNodes()) { containerElement.removeChild(containerElement.firstChild); } } // Check whether we are to prepend this item or append. if (insertMode === 'prepend' && containerElement.firstChild) { containerElement.insertBefore(alt, containerElement.firstChild); } else { containerElement.appendChild(alt); } // Update the present container details in object. this.options.containerElement = containerElement; this.options.containerElementId = containerElement.id; // Set the chart element style property to make it display as an // inline-block element. if ((s = alt.style)) { s.position = 'relative'; s.textAlign = 'left'; s.lineHeight = '100%'; s.display = 'inline-block'; s.zoom = '1'; s.fontWeight = 'normal'; s.fontVariant = 'normal'; s.fontStyle = 'normal'; s.textDecoration = 'none'; s['*DISPLAY'] = 'inline'; } // Fix percentage width issues global.normalizeCSSDimension(this.width, this.height, alt); // Set state that the chart is rendering this.__state.rendering = true; // Raise event before rendering global.raiseEvent('BeforeRender', { container: containerElement, width: this.width, height: this.height, renderer: this.options.renderer }, this); // Call the current renderer. global.renderer.render(this, alt, global.renderer.notifyRender); // Return the fusioncharts object for chainability return this; }, remove: function () { global.renderer.remove(this); return this; // chain }, configure: function (key, value) { var hash; if (!key) { return; } else if (typeof key === 'string') { hash = {}; hash[key] = value; } else { hash = key; } global.renderer.config(this, hash); } }, true); global.extend(global.core, { setCurrentRenderer: function () { var ret = renderer.setDefault.apply(renderer, arguments); renderer.userSetDefault = true; // Mark this renderer as user set. return ret; }, getCurrentRenderer: function () { return renderer.currentRendererName.apply(renderer, arguments); }, /** * Render FusionCharts directly using the simplest one-line argument * parameter. * This function directly renders FusionCharts into the container * specified in arguments. */ render: function () { // The order in which to parse the linear parameters. var argsT = ['swfUrl', 'id', 'width', 'height', 'renderAt', 'dataSource', 'dataFormat'], params = {}, i; // If a FusionCharts object is sent to it, it calls render method of // it. if (arguments[0] instanceof global.core) { arguments[0].render(); return arguments[0]; } // Iterate through the linear parameters using the argument template // array defined above and create a parameter object out of it. for (i = 0; (i < arguments.length && i < argsT.length); i += 1) { params[argsT[i]] = arguments[i]; } // Incorporate the trailing object parameter as object-style // parameter input overrides. if (typeof arguments[arguments.length - 1] === 'object') { delete params[argsT[i - 1]]; global.extend(params, arguments[arguments.length - 1]); } // Pre-specify the 'xmlurl' format if (params.dataFormat === undefined) { params.dataFormat = FusionChartsDataFormats.XMLURL; } // Render a new FusionCharts out of the parameters and return the // object. return new global.core(params).render(); } }, false); }()); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, immed: true */ /*global window: false, Array, FusionCharts, Error: false */ /** * ----------------------------------------------------------------------------- * Data-Handler Abstraction Framework * This allows developers to dynamically integrate a data transcoder so that * FusionCharts core can seamlessly work with multiple formats for data * provisioning. * ----------------------------------------------------------------------------- */ (function () { // Register the module with FusionCharts. var global = FusionCharts(['private', 'DataHandlerManager']); // Check whether the module has been already registered. If true, then // do not bother to re-register. if (global === undefined) { return; } // Collection of Data Formats window.FusionChartsDataFormats = {}; // Store all data handlers here in a collection and also store all 'data' of // every chart in an object. /** * @var {object} cache stores the parsed JSON data as a cache location, so * that multiple calls to decode JSON does not involve redundant conversion. */ var SOURCENAME = 'XmlHttpRequest', handlers = global.transcoders = {}, dataStore = {}, cache = {}, isUrl = /url$/i, xmlhttpSuccess = function (responseText, wrapper, data, url) { // Allow cancellation of data loaing var cancelDLFlag = false, obj = data.obj, baseFormat = data.format, silent = data.silent; // Raise pre data-load event global.raiseEvent('DataLoadRequestCompleted', { source: SOURCENAME, url: url, data: responseText, dataFormat: baseFormat, cancelDataLoad: function () { cancelDLFlag = true; wrapper.abort(); this.cancelDataLoad = function () { return false; }; return true; }, xmlHttpRequestObject: wrapper.xhr }, obj); // Update the chart's dataStore with data received // from url. if (cancelDLFlag !== true) { // Set the chart's data received from url. obj.setChartData(responseText, baseFormat, silent); } else { // Raise post data load event . global.raiseEvent('DataLoadCancelled', { source: SOURCENAME, url: url, dataFormat: baseFormat, xmlHttpRequestObject: wrapper.xhr }, obj); } }, xmlhttpFailure = function (resp, wrapper, data, url) { // Compile argument for event. var obj = data.obj, eventArgs = { source: SOURCENAME, url: url, xmlHttpRequestObject: wrapper.xhr, error: resp, httpStatus: (wrapper.xhr && wrapper.xhr.status) ? wrapper.xhr.status : -1 }; // Raise data load error message. global.raiseEvent('DataLoadError', eventArgs, obj); // Call legacy event handler. if (typeof window.FC_DataLoadError === 'function') { window.FC_DataLoadError(obj.id, eventArgs); } }; // Allow data-related parameters to be passed in constructor global.policies.options.dataSource = ['dataSource', undefined]; global.policies.options.dataFormat = ['dataFormat', undefined]; global.policies.options.dataConfiguration = ['dataConfiguration', undefined]; global.policies.options.showDataLoadingMessage = ['showDataLoadingMessage', true]; // Expose Data handler and related management API. global.addDataHandler = function (name, obj) { if (typeof name !== 'string' || handlers[name.toLowerCase()] !== undefined) { global.raiseError(global.core, '03091606', 'param', '::DataManager.addDataHandler', new Error('Invalid Data Handler Name')); return; } var api = {}, lcaseName = name.toLowerCase(); // Add handler to collection handlers[lcaseName] = obj; obj.name = name; // Create Handler Direct Access API. This adds common fuctions for the // handler. api['set' + name + 'Url'] = function (url) { // unused param: [1]config return this.setChartDataUrl(url, name); }; api['set' + name + 'Data'] = function (data, config) { return this.setChartData(data, name, false, config); }; api['get' + name + 'Data'] = function () { return this.getChartData(name); }; // Add data formats to global formats collection window.FusionChartsDataFormats[name] = lcaseName; window.FusionChartsDataFormats[name + 'URL'] = lcaseName + 'URL'; // Extend FusionCharts objects global.extend(global.core, api, true); }; // Add constructor to initialize datastore or to clear any garbage. global.addEventListener('BeforeInitialize', function (event) { // Get short reference to the event sender. var obj = event.sender, dataSource = obj.options.dataSource; // Clear the dataStore, cache and xStore when new chart is created. dataStore[obj.id] = ''; cache[obj.id] = {}; // Set intitial data if present if (dataSource !== undefined && dataSource !== null) { obj.__state.dataSetDuringConstruction = true; // If data formay was not specified during construction, try // auto-detection. if (typeof obj.options.dataFormat !== 'string') { switch (typeof dataSource) { case "function": dataSource = obj.options.dataSource = dataSource(obj); obj.options.dataFormat = 'JSON'; break; case "string": obj.options.dataFormat = /^\s*?\{[\s\S]*\}\s*?$/g.test(obj.options.dataFormat) ? 'JSON' : 'XML'; break; case "object": obj.options.dataFormat = "JSON"; break; }; } obj.setChartData(dataSource, obj.options.dataFormat); } }); // Add method to make sure to delete all fusioncharts objects when // dispose method is invoked global.addEventListener('BeforeDispose', function (e) { var obj = e.sender; delete dataStore[e.sender.id]; delete cache[e.sender.id]; if (obj && obj.__state && obj.__state.dhmXhrObj) { obj.__state.dhmXhrObj.abort(); } }); // Add getter and setter to FusionCharts Objects global.extend(global.core, { setChartDataUrl: function (url, format, silent) { if (format === undefined || format === null || typeof format.toString !== 'function') { global.raiseError(global.core, '03091609', 'param', '.setChartDataUrl', new Error('Invalid Data Format')); return; } // Desensitize case of parameter. format = format.toString().toLowerCase(); /** * @var {Boolean} cancelDLRFlag is to allow users to flag that * data-load request has to be cancelled. */ var baseFormat, obj = this, // This is an out-of architecture implementation to specifically // look for FlashRenderer specific instruction. cancelDLRFlag = (obj.options && (obj.options.renderer === 'flash') && obj.options.useLegacyXMLTransport) || false, xhr; // Check whether the data-format has "url" at the end of it. // We compute the base format and update the format accordingly so // that format always ends with 'url' and the baseFormat contains real // format name. if (isUrl.test(format)) { baseFormat = format.slice(0, -3); } else { baseFormat = format; format = format + 'url'; } // Raise event to notify xmlhttprequest transaction start. global.raiseEvent('DataLoadRequested', { source: SOURCENAME, url: url, dataFormat: baseFormat, cancelDataLoadRequest: function () { cancelDLRFlag = true; global.raiseEvent('DataLoadRequestCancelled', { source: SOURCENAME, url: url, dataFormat: baseFormat }, obj); try { if (this.__state && this.__state.dhmXhrObj) { this.__state.dhmXhrObj.abort(); } } catch (e) { } this.cancelDataLoadRequest = function () { return false; }; return true; } }, obj); // In case cancel was hit even before this function reached here, // we then do not proceed. if (cancelDLRFlag) { if (this.__state && this.__state.dhmXhrObj) { try { this.__state.dhmXhrObj.abort(); } catch (e) { } } return; } // Update reference to data-source. this.options.dataSource = url; // Create an XMLHttpRequest object if it is not already if (!this.__state.dhmXhrObj) { this.__state.dhmXhrObj = new global.ajax(xmlhttpSuccess, xmlhttpFailure); } xhr = this.__state.dhmXhrObj; // Initiate XmlHttpRequest. xhr.get(typeof window.decodeURIComponent === 'function' ? window.decodeURIComponent(url) : window.unescape(url), { obj: this, format: baseFormat, silent: silent }); }, setChartData: function (data, format, silent) { // In case format is not a string, we raise an error if (format === undefined || format === null || typeof format.toString !== 'function') { global.raiseError(global.core, '03091610', 'param', '.setChartData', new Error('Invalid Data Format')); return; } // Desensitize case of parameter. format = format.toString().toLowerCase(); // Thebase format is set by truncating fetching method from the // formatg-string and then stored in 'baseFormat' variable. var baseFormat; // Check whether the data-format has "url" at the end of it. If true, // then we call the setChartDataUrl method and that in turn calls this // method as callback (marked as _recursed.) if (isUrl.test(format)) { this.setChartDataUrl(data, format, silent); return; } else { // When there is no trailing "url" in data-format, we assume that // the format provided is baseFormat itself. // Update the dataSource here only when we know that this call // was not recursed for dataurl purpose this.options.dataSource = data; baseFormat = format; } // Update chart's internal data-format options this.options.dataFormat = format; // Fetch the data-handler function from the dataHandler collection. var handler = handlers[baseFormat], parseResult, cancelDUFlag = false; // If the handler has been successfully fetched, execute it. if (typeof handler === 'undefined') { global.raiseError(global.core, '03091611', 'param', '.setChartData', new Error('Data Format not recognized')); return; } // Execute the parser and fetch the parsing result. Also check whether // the parser returns a valid object, if not, use a blank object. parseResult = handler.encode(data, this, this.options.dataConfiguration) || {}; // Updated the result so that it can be passed as event argument. parseResult.format = parseResult.dataFormat = baseFormat; // Add additional argument for events in parser result parseResult.dataSource = data; parseResult.cancelDataUpdate = function () { cancelDUFlag = true; this.cancelDataUpdate = function () { return false; }; return true; }; global.raiseEvent('BeforeDataUpdate', parseResult, this); delete parseResult.cancelDataUpdate; // Remove cancellation fn. // Update event only if it is not marked to be cancelled by user. if (cancelDUFlag === true) { global.raiseEvent('DataUpdateCancelled', parseResult, this); return; } // Save data within dataStore dataStore[this.id] = parseResult.data || ''; // Clear cache cache[this.id] = {}; // Raise data updation event if it is not marked as silent data // updating. if (silent !== true) { // stall this update if this is stuck in between a render and loading if (this.options.safeMode === true && this.__state.rendering === true && !this.isActive()) { this.__state.updatePending = parseResult; global.raiseWarning(this, '23091255', 'run', '::DataHandler~update', 'Renderer update was postponed due to async loading.'); } else { delete this.__state.updatePending; global.renderer.update(this, parseResult); } } // Clear any decision flag whether data is ready for chart to be // rendered. this.__state.dataReady = undefined; // DevNote: This event must not be raised asynchronously in order // to maintain integrity and timing of related codes. global.raiseEvent('DataUpdated', parseResult, this); }, getChartData: function (format, advanced) { // Variable to store a reference to the data-handler. var handler, parseResult; // Desensitize case of parameter and fetch the data-handler // function from the dataHandler collection within the validation // check itself. if (format === undefined || typeof format.toString !== 'function' || (handler = handlers[format = format.toString().toLowerCase()]) === undefined) { global.raiseError(this, '25081543', 'param', '~getChartData()', new Error('Unrecognized data-format specified in "format"')); return undefined; } // Check presence of cached data or call the decoder routine of // the data-handler and return the decoded data. parseResult = (typeof cache[this.id][format] === 'object') ? cache[this.id][format] : cache[this.id][format] = handler.decode(dataStore[this.id], this, this.options.dataConfiguration); // Return the eminent data (in advanced mode if needed. return Boolean(advanced) === true ? parseResult : parseResult.data; }, /** * Function returns whether the chart has it's data ready or not. */ dataReady: function () { return this.__state.dataReady; } }, true); // extend the prototype global.extend(global.core, { transcodeData: function (data, from, to, advanced, configuration) { // Validate parameters. if (!from || typeof from.toString !== 'function' || !to || typeof to.toString !== 'function' || handlers[(to = to.toString().toLowerCase())] === undefined || handlers[(from = from.toString().toLowerCase())] === undefined) { global.raiseError(this, '14090217', 'param', 'transcodeData()', new Error('Unrecognized data-format specified during transcoding.')); return undefined; } // Chain the decoder and encoder. var l1 = handlers[from].encode(data, this, configuration), l2 = handlers[to].decode(l1.data, this, configuration); // Carry the error. if (!(l2.error instanceof Error)) { l2.error = l1.error; } return advanced ? l2 : l2.data; } }, false); // Attach an event handler to clear the data cache when chart is disposed. global.addEventListener('Disposed', function (e) { delete cache[e.sender.id]; }); // Check for pending data updates global.addEventListener('Loaded', function (e) { var obj = e.sender; if (obj instanceof global.core && obj.__state.updatePending !== undefined) { global.renderer.update(obj, obj.__state.updatePending); delete obj.__state.updatePending; } }); // Check for event when renderer declares that there is no data global.addEventListener('NoDataToDisplay', function (e) { var obj = e.sender; obj.__state.dataReady = false; }); // Enumeration of charts that has exceptional implementation of 'getXMLData' // method. The value [dynamicDatRouter, dynamicAttributeRouter] // A reference of this enum is stored at global._interactiveCharts so that // it can be accessed by ChartAttributes module. This is done so that for // interactive charts, when data is fetched, we fetch the updated data and not // the initial data state. var interactiveCharts = global._interactiveCharts = { 'selectscatter': [true, false], 'dragcolumn2d': [true, true], 'dragarea': [true, true], 'dragline': [true, true], 'dragnode': [true, true] }; global.addEventListener('Loaded', function (event) { var obj = event.sender, state = obj.__state, transcoder, dataGetterName, transcoderName; // We specially address the getXMLData function of PowerCharts. // We check whether the loaded chart is one of the listed charts that // are known to have the anomalous implementation. if (obj.chartType && interactiveCharts[obj.chartType()] && interactiveCharts[obj.chartType()][0]) { // We set a modified getXXXData method that allows users to bypass // the JS method and use the flash method instead. for (transcoder in global.transcoders) { transcoderName = global.transcoders[transcoder].name; dataGetterName = 'get' + transcoderName + 'Data'; obj[dataGetterName] = function (format, protoHandler) { return function (fresh) { // obj redefined here so that on chart change, old obj // is not reused. var obj = this; if (fresh === false) { // check false positive return protoHandler.apply(obj); } else if (obj.ref.getUpdatedXMLData) { // for flash return global.core.transcodeData(obj.ref.getUpdatedXMLData(), 'xml', format); } else if (obj.getData) { // for js charts return obj.getData(format); } else { // if all fail, return stale data return protoHandler.apply(obj); } }; }(transcoder, obj.constructor.prototype[dataGetterName]); obj[dataGetterName]._dynamicdatarouter = true; // flag } state.dynamicDataRoutingEnabled = true; // flag } // Remove for other chart types if it was earlier inserted. else if (state.dynamicDataRoutingEnabled){ for (transcoder in global.transcoders) { transcoderName = global.transcoders[transcoder].name; dataGetterName = 'get' + transcoderName + 'Data'; if (obj.hasOwnProperty(dataGetterName) && obj[dataGetterName]._dynamicdatarouter) { delete obj[dataGetterName]; } } state.dynamicDataRoutingEnabled = false; } }); }()); /* SWFObject v2.2 <http://code.google.com/p/swfobject/> modified by FusionCharts Technologies LLP <http://www.fusioncharts.com/> Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> Copyright (c) for modifications 2010-2011 FusionCharts Technologies LLP. */var swfobject = window.swfobject = function () { var UNDEF = "undefined", OBJECT = "object", SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", EXPRESS_INSTALL_ID = "SWFObjectExprInst", ON_READY_STATE_CHANGE = "onreadystatechange", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], regObjArr = [], objIdArr = [], listenersArr = [], storedAltContent, storedAltContentId, storedCallbackFn, storedCallbackObj, isDomLoaded = false, isExpressInstallActive = false, dynamicStylesheet, dynamicStylesheetMedia, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function () { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled // Fix for /bug#462 //!// d = a.GetVariable("$version"); try { d = a.GetVariable("$version"); } catch (e) { } // End fix for /bug#462 if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return {w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac}; }(), /* Cross-browser onDomLoad - Will fire an event as soon as the DOM of a web page is loaded - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/ - Regular onload serves as fallback */ onDomLoad = function() { if (!ua.w3) {return;} if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically callDomLoadFunctions(); } if (!isDomLoaded) { if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false); } if (ua.ie && ua.win) { doc.attachEvent(ON_READY_STATE_CHANGE, function() { if (doc.readyState == "complete") { doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee); callDomLoadFunctions(); } }); if (win == top) { // if not inside an iframe (function(){ if (isDomLoaded) {return;} try { doc.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } } if (ua.wk) { (function(){ if (isDomLoaded) {return;} if (!/loaded|complete/.test(doc.readyState)) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } addLoadEvent(callDomLoadFunctions); } }(); function callDomLoadFunctions() { if (isDomLoaded) {return;} try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span")); t.parentNode.removeChild(t); } catch (e) {return;} isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Cross-browser onload - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/ - Will fire an event as soon as a web page including all of its assets are loaded */ function addLoadEvent(fn) { if (typeof win.addEventListener != UNDEF) { win.addEventListener("load", fn, false); } else if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("load", fn, false); } else if (typeof win.attachEvent != UNDEF) { addListener(win, "onload", fn); } else if (typeof win.onload == "function") { var fnOld = win.onload; win.onload = function() { fnOld(); fn(); }; } else { win.onload = fn; } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } else { matchVersions(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { // Fix for /bug#462 //!// var d = t.GetVariable("$version"); var d; try { d = t.GetVariable("$version"); } catch (e) { } // End fix for /bug#462 if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; matchVersions(); })(); } else { matchVersions(); } } /* Perform Flash Player and SWF version matching; static publishing only */ function matchVersions() { var rl = regObjArr.length; if (rl > 0) { for (var i = 0; i < rl; i++) { // for each registered object element var id = regObjArr[i].id; var cb = regObjArr[i].callbackFn; var cbObj = regObjArr[i].userData || {}; cbObj.success = false; cbObj.id = id; if (ua.pv[0] > 0) { var obj = getElementById(id); if (obj) { if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match! setVisibility(id, true); if (cb) { cbObj.success = true; cbObj.ref = getObjectById(id); cb(cbObj); } } else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported var att = {}; att.data = regObjArr[i].expressInstall; att.width = obj.getAttribute("width") || "0"; att.height = obj.getAttribute("height") || "0"; if (obj.getAttribute("class")) {att.styleclass = obj.getAttribute("class");} if (obj.getAttribute("align")) {att.align = obj.getAttribute("align");} // parse HTML object param element's name-value pairs var par = {}; var p = obj.getElementsByTagName("param"); var pl = p.length; for (var j = 0; j < pl; j++) { if (p[j].getAttribute("name").toLowerCase() != "movie") { par[p[j].getAttribute("name")] = p[j].getAttribute("value"); } } showExpressInstall(att, par, id, cb); } else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF displayAltContent(obj); if (cb) {cb(cbObj);} } } } else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content) setVisibility(id, true); if (cb) { var o = getObjectById(id); // test whether there is an HTML object element or not if (o && typeof o.SetVariable != UNDEF) { cbObj.success = true; cbObj.ref = o; } cb(cbObj); } } } } } function getObjectById(objectIdStr) { var o, r = null; /* ORIGINAL CODE o = getElementById(objectIdStr); if (o && o.nodeName == "OBJECT") { if (typeof o.SetVariable != UNDEF) { r = o; } else { var n = o.getElementsByTagName(OBJECT)[0]; if (n) { r = n; } } } */ /* fix for access embeds */ if (!(document.embeds && (o = document.embeds[objectIdStr]))) { if (!((o = getElementById(objectIdStr)) && o.nodeName == "OBJECT")) { o = window[objectIdStr]; } } if (!o) { return r; } if (typeof o.SetVariable != UNDEF) { r = o; } else { var n = o.getElementsByTagName(OBJECT)[0]; if (n) { r = n; } } /* fix for access embeds ends */ return r; } /* Requirements for Adobe Express Install - only one instance can be active at a time - fp 6.0.65 or higher - Win/Mac OS only - no Webkit engines older than version 312 */ function canExpressInstall() { return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312); } /* Show the Adobe Express Install dialog - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75 */ function showExpressInstall(att, par, replaceElemIdStr, callbackFn) { isExpressInstallActive = true; storedCallbackFn = callbackFn || null; storedCallbackObj = {success:false, id:replaceElemIdStr}; var obj = getElementById(replaceElemIdStr); if (obj) { if (obj.nodeName == "OBJECT") { // static publishing storedAltContent = abstractAltContent(obj); storedAltContentId = null; } else { // dynamic publishing storedAltContent = obj; storedAltContentId = replaceElemIdStr; } att.id = EXPRESS_INSTALL_ID; if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) {att.width = "310";} if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) {att.height = "137";} doc.title = doc.title.slice(0, 47) + " - Flash Player Installation"; var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn", fv = "MMredirectURL=" + win.location.toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title; if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + fv; } else { par.flashvars = fv; } // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work if (ua.ie && ua.win && obj.readyState != 4) { var newObj = createElement("div"); replaceElemIdStr += "SWFObjectNew"; newObj.setAttribute("id", replaceElemIdStr); obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } createSWF(att, par, replaceElemIdStr); } } /* Functions to abstract and display alternative content */ function displayAltContent(obj) { if (ua.ie && ua.win && obj.readyState != 4) { // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work var el = createElement("div"); obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content el.parentNode.replaceChild(abstractAltContent(obj), el); obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.replaceChild(abstractAltContent(obj), obj); } } function abstractAltContent(obj) { var ac = createElement("div"); if (ua.win && ua.ie) { ac.innerHTML = obj.innerHTML; } else { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var i = 0; i < cl; i++) { if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) { ac.appendChild(c[i].cloneNode(true)); } } } } } return ac; } /* Cross-browser dynamic SWF creation */ function createSWF(attObj, parObj, id) { var r, el = getElementById(id); if (ua.wk && ua.wk < 312) {return r;} if (el) { if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content attObj.id = el.id; } if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML var att = ""; for (var i in attObj) { if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries if (i.toLowerCase() == "data") { parObj.movie = attObj[i]; } else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword att += ' class="' + attObj[i] + '"'; } else if (i.toLowerCase() != "classid") { att += ' ' + i + '="' + attObj[i] + '"'; } } } var par = ""; for (var j in parObj) { if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries par += '<param name="' + j + '" value="' + parObj[j] + '" />'; } } el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>'; objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only) r = getElementById(attObj.id); } else { // well-behaving browsers var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); for (var m in attObj) { if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword o.setAttribute("class", attObj[m]); } else if (m.toLowerCase() != "classid") { // filter out IE specific attribute o.setAttribute(m, attObj[m]); } } } for (var n in parObj) { if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element createObjParam(o, n, parObj[n]); } } el.parentNode.replaceChild(o, el); r = o; } } return r; } function createObjParam(el, pName, pValue) { var p = createElement("param"); p.setAttribute("name", pName); p.setAttribute("value", pValue); el.appendChild(p); } /* Cross-browser SWF removal - Especially needed to safely and completely remove a SWF in Internet Explorer */ function removeSWF(id) { var obj = getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (ua.ie && ua.win) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } } function removeObjectInIE(id) { var obj = getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } /* Functions to optimize JavaScript compression */ function getElementById(id) { var el = null; try { el = doc.getElementById(id); } catch (e) {} return el; } function createElement(el) { return doc.createElement(el); } /* Updated attachEvent function for Internet Explorer - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks */ function addListener(target, eventType, fn) { target.attachEvent(eventType, fn); listenersArr[listenersArr.length] = [target, eventType, fn]; } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } /* Cross-browser dynamic CSS creation - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php */ function createCSS(sel, decl, media, newStyle) { if (ua.ie && ua.mac) {return;} var h = doc.getElementsByTagName("head")[0]; if (!h) {return;} // to also support badly authored HTML pages that lack a head element var m = (media && typeof media == "string") ? media : "screen"; if (newStyle) { dynamicStylesheet = null; dynamicStylesheetMedia = null; } if (!dynamicStylesheet || dynamicStylesheetMedia != m) { // create dynamic stylesheet + get a global reference to it var s = createElement("style"); s.setAttribute("type", "text/css"); s.setAttribute("media", m); dynamicStylesheet = h.appendChild(s); if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) { dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1]; } dynamicStylesheetMedia = m; } // add style rule if (ua.ie && ua.win) { if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) { dynamicStylesheet.addRule(sel, decl); } } else { if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) { dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}")); } } } function setVisibility(id, isVisible) { if (!autoHideShow) {return;} var v = isVisible ? "visible" : "hidden"; if (isDomLoaded && getElementById(id)) { getElementById(id).style.visibility = v; } else { createCSS("#" + id, "visibility:" + v); } } /* Filter to avoid XSS attacks */ function urlEncodeIfNecessary(s) { var regex = /[\\\"<>\.;]/; var hasBadChars = regex.exec(s) != null; return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s; } /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only) */ var cleanup = function() { if (ua.ie && ua.win) { window.attachEvent("onunload", function() { // remove listeners to avoid memory leaks var ll = listenersArr.length; for (var i = 0; i < ll; i++) { listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]); } // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect var il = objIdArr.length; for (var j = 0; j < il; j++) { removeSWF(objIdArr[j]); } // cleanup library's main closures to avoid memory leaks for (var k in ua) { ua[k] = null; } ua = null; for (var l in swfobject) { swfobject[l] = null; } swfobject = null; }); } }(); return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ FusionChartsModified: true, registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn, data) { var regObj = data || {}; if (ua.w3 && objectIdStr && swfVersionStr) { regObj.id = objectIdStr; regObj.swfVersion = swfVersionStr; regObj.expressInstall = xiSwfUrlStr; regObj.callbackFn = callbackFn; regObj.userData = data; regObjArr[regObjArr.length] = regObj; setVisibility(objectIdStr, false); } else if (callbackFn) { regObj.success = false; regObj.id = objectIdStr; callbackFn(regObj); } }, getObjectById: function(objectIdStr) { if (ua.w3) { return getObjectById(objectIdStr); } }, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn, data) { var callbackObj = data || {}; callbackObj.success = false; callbackObj.id = replaceElemIdStr; if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) { setVisibility(replaceElemIdStr, false); addDomLoadEvent(function() { widthStr += ""; // auto-convert to string heightStr += ""; var att = {}; if (attObj && typeof attObj === OBJECT) { for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs att[i] = attObj[i]; } } att.data = swfUrlStr; att.width = widthStr; att.height = heightStr; var par = {}; if (parObj && typeof parObj === OBJECT) { for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs par[j] = parObj[j]; } } if (flashvarsObj && typeof flashvarsObj === OBJECT) { for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + k + "=" + flashvarsObj[k]; } else { par.flashvars = k + "=" + flashvarsObj[k]; } } } if (hasPlayerVersion(swfVersionStr)) { // create SWF var obj = createSWF(att, par, replaceElemIdStr); if (att.id == replaceElemIdStr) { setVisibility(replaceElemIdStr, true); } callbackObj.success = true; callbackObj.ref = obj; } else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install att.data = xiSwfUrlStr; showExpressInstall(att, par, replaceElemIdStr, callbackFn); return; } else { // show alternative content setVisibility(replaceElemIdStr, true); } if (callbackFn) {callbackFn(callbackObj);} }); } else if (callbackFn) {callbackFn(callbackObj);} }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return {major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2]}; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) { if (ua.w3 && canExpressInstall()) { showExpressInstall(att, par, replaceElemIdStr, callbackFn); } }, removeSWF: function(objElemIdStr) { if (ua.w3) { removeSWF(objElemIdStr); } }, createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) { if (ua.w3) { createCSS(selStr, declStr, mediaStr, newStyleBoolean); } }, addDomLoadEvent: addDomLoadEvent, addLoadEvent: addLoadEvent, getQueryParamValue: function(param) { var q = doc.location.search || doc.location.hash; if (q) { if (/\?/.test(q)) {q = q.split("?")[1];} // strip question mark if (param == null) { return urlEncodeIfNecessary(q); } var pairs = q.split("&"); for (var i = 0; i < pairs.length; i++) { if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) { return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1))); } } } return ""; }, // For internal usage only expressInstallCallback: function() { if (isExpressInstallActive) { var obj = getElementById(EXPRESS_INSTALL_ID); if (obj && storedAltContent) { obj.parentNode.replaceChild(storedAltContent, obj); if (storedAltContentId) { setVisibility(storedAltContentId, true); if (ua.ie && ua.win) {storedAltContent.style.display = "block";} } if (storedCallbackFn) {storedCallbackFn(storedCallbackObj);} } isExpressInstallActive = false; } } }; }(); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, plusplus: true, bitwise: true, immed: true */ /*global Array: false, FusionCharts, window: false, FusionChartsDataFormats: false */ /** * Flash Renderer Module * This module is to add functionalities and interfaces for Flash-based * FusionCharts rendering. * * @include swfobject JavaScript Library to perform managed renedring of Flash * media objects. * * @since 1.0 */ FusionCharts(['private', 'modules.renderer.flash', function () { var global = this, win = window, doc = document, OBJECT = 'object', STRING = 'string', FUNCTION = 'function', isFunction = function (obj) { return (typeof obj === FUNCTION); }, urlEncode = win.encodeURIComponent ? function (str) { return win.encodeURIComponent(str); } : function (str) { return win.escape(str); }; // Fix for Firefox 4 dotted outline issue. try { global.swfobject = win.swfobject; win.swfobject.createCSS('object.FusionCharts:focus, embed.FusionCharts:focus', 'outline: none'); } catch (err) { } // Suppress any error caused. // Set flags for minimum version of flash-player needed. global.core.options.requiredFlashPlayerVersion = '8'; // The redirection URL global.core.options.flashInstallerUrl = 'http://get.adobe.com/flashplayer/'; // Message to show upon auto install redirect. global.core.options.installRedirectMessage = 'You need Adobe Flash ' + 'Player 8 (or above) to view the charts on this page. It is a free, ' + 'lightweight and safe installation from Adobe Systems Incorporated.' + '\n\nWould you like to go to Adobe\'s website and install Flash Player?'; /** * This method will check whether the browser has the requared * flash player version * @param {string} version [optional] the minimum version of the * flash player that is requared * @return {boolean} true if the browser has equal or greter version */ global.core.hasRequiredFlashVersion = function (version) { //if no version is provided then check for the FusionCharts //minimum requared version if (typeof version === 'undefined') { version = global.core.options.requiredFlashPlayerVersion; } // Check flash version. return win.swfobject ? win.swfobject.hasFlashPlayerVersion(version) : undefined; }; /** * Flag that keeps track whether the user has been once notified that Flash * is absent. This flag is checked before notifying users, in order to * prevent duplicate notifications on every chart. * @type boolan */ var noFlashRedirectNotified = false, // Regular expression to match whether a right trimmedstring ends with // percentage sign or not. isPercentRegex = /.*?\%\s*?$/g, // List of flashVars that needs to be always encoded alwaysEncodedFlashVars = { chartWidth: true, chartHeight: true, mapWidth: true, mapHeight: true }, // TODO: Not Implemented. probeParamsFromDOM = function (id) { // Get reference to the HTMLNode from the id that has been sent. To // ensure that object/embed elements are properly located, we use the // swfobject's getObjectById method. var ref = win.swfobject.getObjectById(id), i, l, paramName, tags, params = {}, parent, vars, attrs = {}; // We test whether an object was located or not. if (!ref && typeof ref.tagName !== STRING) { return undefined; } // Get the parentNode as container. For that we first test whether the // object has a parentNode or not. It has to be really really wierd to // not have a parentNode and yet reach this point in code. Still, we // do a check. if ((parent = ref.parentNode) && parent.tagName && parent.tagName.toLowerCase() === OBJECT && parent.parentNode) { // When we know that the parentNode of the object exists, we need to // check whether it is an embed element within object element. parent = parent.parentNode; } if (!parent) { return undefined; } params.renderAt = parent; // Get flashVars. First check whether there is any attribute within // the root tag named as flashVars as because this is the syntax for // <embed> tag. if (!(ref.tagName.toLowerCase() !== OBJECT && ref.getAttribute && (vars = ref.getAttribute('flashvars') || '')) && ref.hasChildNodes && ref.hasChildNodes()) { // When flashvars attribute is not found, we try to iterate through // the childnodes to find the <param> node that contains the // flashVars. tags = ref.childNodes; for (i = 0, l = tags.length; i < l; i += 1) { if (tags[i].tagName === 'PARAM' && (paramName = tags[i].getAttribute('name')) && paramName.toLowerCase() === 'flashvars') { vars = tags[i].getAttribute('value') || ''; } } } // Convert the flashVars attribute into flashVars object: // Split the attribute string with = and &. Then put the odd indices // as keys and evens as values if (vars && isFunction(vars.toString)) { vars = vars.split(/\=|&/g); params.flashVars = {}; for (i = 0, l = vars.length; i < l; i += 2) { params.flashVars[vars[i]] = vars[i + 1]; } } return params; }, /** * Event listener that updates local chart data when there has * been a remote data update on renderer. */ syncDataStore = function (e, a) { // Verify whether the event has been raised by JS or by Flash. // If event has been raised by JS, we do not need to do // anything further. // TODO: Filter out non-internal data-load event. if (a && a.source === 'XmlHttpRequest') { return; } // Reference to chartObj. var obj = e.sender; // Test whether the required functions are available. if (obj.ref && isFunction(obj.ref.dataInvokedOnSWF) && obj.ref.dataInvokedOnSWF() && isFunction(obj.ref.getXML)) { // Raise a warning for the same. global.raiseWarning(obj, '08300116', 'run', '::DataHandler~__fusioncharts_vars', 'Data was set in UTF unsafe manner'); // Silently update/sync the internal data of FusionCharts JS // objects with the new data that was directly sent to flash. obj.setChartData(win.unescape(e.sender.ref.getXML({ escaped: true })), FusionChartsDataFormats.XML, true); // Update the flashVars as well. obj.flashVars.dataXML = obj.getChartData(FusionChartsDataFormats.XML); // Since further data communication involves the presence of // data-xml in state, we remove the dataURL from flashVars and // keep XML fetched from chart. delete obj.flashVars.dataURL; } // Remove ebent handler association so that normal dataLoad is not // intercepted. e.sender.removeEventListener('DataLoaded', syncDataStore); }; // This code-block exposes a function that assists FusionCharts swf objects // to receive updated and accurate dimension information in case of // percentage size. win.__fusioncharts_dimension = (function () { // No point documenting this piece of unreadable code! In short, it // simply calculates the width of the chart based on the offsetWidth of // the container. Same is for height. return function (id) { var obj, parent; return !((obj = global.core(id)) instanceof global.core && obj.ref && (parent = obj.ref.parentNode)) ? {} : { width: parent.offsetWidth * (isPercentRegex.test(obj.width) ? parseInt(obj.width, 10) / 100 : 1), height: parent.offsetHeight * (isPercentRegex.test(obj.height) ? parseInt(obj.height, 10) / 100 : 1) }; }; }()); // Routines to manage state between SWF and FusionCharts JS Object win.__fusioncharts_vars = function (id, vars) { var obj = global.core.items[id], params, ref; // Verify whether corresponding FusionCharts object exists. if (!(obj instanceof global.core)) { // We check whether a flash movie was loaded by html-embed // method and we accordingly absorb it in our JS. setTimeout(function () { if (id !== undefined && (params = probeParamsFromDOM(id))) {/* // Reference to DOM object for sending "ref" value to the // renderer. ref = window.swfobject.getObjectById(id); // Mark in the parameters that this item was created using // HTMLEmbed Injection. params.htmlEmbedInjection = true; // Create a new FusionCharts object from the parameters that // has been probed. new global.core(params); // Register this object with swfObject routines. window.swfobject.registerObject(id, global.core.options.requiredFlashPlayerVersion, undefined, global.renderer.notifyRender);*/ } else { // Throw error when FusionCharts obj not found. global.raiseError(global.core, '25081621', 'run', '::FlashRenderer', 'FusionCharts Flash object is accessing flashVars of non-existent object.'); } }, 0); return false; } // When 'vars' parameter is sent, we sync the local vars object if (typeof vars === OBJECT) { // We check whether there was a direct update of data on SWF. In // case it is true, we proceed with datastore sync. if (obj.ref && isFunction(obj.ref.dataInvokedOnSWF) && obj.ref.dataInvokedOnSWF()) { // In case dataURL has been updated, we probe into an event that // updates local dataStore if (vars.dataURL !== undefined) { obj.addEventListener('DataLoaded', syncDataStore); } // Specifically unescape the dataXML updated else if (vars.dataXML !== undefined) { vars.dataXML = win.unescape(vars.dataXML); } obj.__state.flashUpdatedFlashVars = true; } else { // Clear data related variables to prevent sync with local // store. delete vars.dataURL; delete vars.dataXML; } // If corresponding FusionCharts object is found, we update the // vars. global.extend(obj.flashVars, vars); return true; } // Here we check whether data was set during construction, requires // special handling. if (obj.__state.dataSetDuringConstruction && obj.flashVars.dataXML === undefined && obj.options.dataSource !== undefined && typeof obj.options.dataFormat === STRING) { obj.flashVars.dataXML = obj.options.dataSource; } obj.__state.flashInvokedFlashVarsRequest = true; return obj.flashVars; }; // Bind EventTarget with the FusionCharts global event handler win.__fusioncharts_event = function (event, args) { // Create an abstraction layer so that the try-catch / error suppression // of flash can be avoided. setTimeout(function () { global.raiseEvent(event.type, args, global.core.items[event.sender]); }, 0); }; var onBeforeInitialize = function (event) { // Get short reference to the event sender. var obj = event.sender; // Filter objects that are generated by flash renderer only. if (obj.options.renderer !== 'flash') { return; } // Prevention is better than cure. So is precaution! if (obj.width === undefined) { obj.width = global.renderer.policies.flashVars.chartWidth[1]; } if (obj.height === undefined) { obj.height = global.renderer.policies.flashVars.chartHeight[1]; } if (obj.flashVars.DOMId === undefined) { obj.flashVars.DOMId = obj.id; } // Default flashVars that are to be set. global.extend(obj.flashVars, { registerWithJS: '1', chartWidth: obj.width, chartHeight: obj.height, InvalidXMLText: 'Invalid data.' }); // AutoInstallRedirect action routine. if (Boolean(obj.options.autoInstallRedirect) === true && !win.swfobject.hasFlashPlayerVersion( global.core.options.requiredFlashPlayerVersion.toString()) && noFlashRedirectNotified === false) { noFlashRedirectNotified = true; if (global.core.options.installRedirectMessage && win.confirm(global.core.options.installRedirectMessage)) { win.location.href = global.core.options.flashInstallerUrl; } } // Set initial state of charts if (obj.options.dataFormat === undefined && obj.options.dataSource === undefined) { obj.options.dataFormat = FusionChartsDataFormats.XMLURL; obj.options.dataSource = 'Data.xml'; } }; var renderer = { // Default data format supported by this renderer dataFormat: 'xml', init: function () { // When this renderer is invoked for the first time (init) we attach // the construction event handler. global.addEventListener('BeforeInitialize', onBeforeInitialize); }, policies: { // Add construction policies specific to ActiveX parameters. params: { scaleMode: ['scaleMode', 'noScale'], scale: ['scaleMode', 'noScale'], wMode: ['wMode', 'opaque'], menu: ['menu', undefined], bgColor: ['backgroundColor', '#ffffff'], allowScriptAccess: ['allowScriptAccess', 'always'], quality: ['quality', 'best'], swLiveConnect: ['swLiveConnect', undefined], base: ['base', undefined], align: ['align', undefined], salign: ['sAlign', undefined] }, /** * @var vars {object} Contains all the veriables that are local to every * renderer. This has a direct implication to the FlashVars of the * 'flash' renderer. */ flashVars: { lang: ['lang', 'EN'], debugMode: ['debugMode', undefined], scaleMode: ['scaleMode', 'noScale'], // Issue #1440 // @note: Deprecated and hardcoded in beforeinitialize event. // registerWithJS: ['registerWithJS', '1'], animation: ['animate', undefined] }, options: { autoInstallRedirect: ['autoInstallRedirect', false], useLegacyXMLTransport: ['_useLegacyXMLTransport', false] } }, render: function (container, callBack) { // Remove the 'animation' flag of the chart. if (Boolean(this.flashVars.animation) === true) { delete this.flashVars.animation; } // Check for valid 'src' attribute if (!this.src) { global.raiseError(this, '03102348', 'run', '::FlashRenderer.render', 'Could not find a valid "src" attribute. swfUrl or chart ' + 'type missing.'); } // Copy the flashVars and encodeURIComponent all of them before // sending to swfObject var encodedVars = {}, dataXML = this.flashVars.dataXML, dataURL = this.flashVars.dataURL, item, swfoData; global.extend(encodedVars, this.flashVars); // For backward compatibility, set the flashVar to have reference // to xml or xmlurl in case render is called while the charts are // flagged to be stalled. if (this.flashVars.stallLoad === true) { if (this.options.dataFormat === FusionChartsDataFormats.XML) { dataXML = this.options.dataSource; } if (this.options.dataFormat === FusionChartsDataFormats.XMLURL) { dataURL = this.options.dataSource; } } // Check if debugMode has been pre-enabled. if (global.core.debugMode.enabled() && global.core.debugMode.syncStateWithCharts && encodedVars.debugMode === undefined && this.options.safeMode) { encodedVars.debugMode = '1'; } // Store a copy of the currently rendered src value for later // use while comparing during update. this.__state.lastRenderedSrc = this.src; // Encode dataXML and dataURL encodedVars.dataXML = urlEncode(dataXML) || ''; // check XSS before saving URL request. if (global.isXSSSafe(dataURL)) { encodedVars.dataURL = dataURL || ''; } else { encodedVars.dataURL = urlEncode(dataURL) || ''; } // Encode width and height in case they have percentage. for (item in alwaysEncodedFlashVars) { if (encodedVars.hasOwnProperty(item)) { encodedVars[item] = urlEncode(encodedVars[item]); } } // Check for the presence of swfobject in window scope. It should be present // either provided externally by user or as part of stitched build. if (!(win.swfobject && win.swfobject.embedSWF && win.swfobject.FusionChartsModified)) { win.swfobject = global.swfobject; } // Prepare aditional renderer data that will be smoothly passed on // via callback. // Suppress raising error when no install redirect message has been // shown. if (noFlashRedirectNotified && !global.core.options.installRedirectMessage) { swfoData = {silent: true}; } if (win.swfobject && win.swfobject.embedSWF) { // Call swfobject API to render the chart win.swfobject.embedSWF(this.src, container.id, this.width, this.height, global.core.options.requiredFlashPlayerVersion, undefined, encodedVars, this.params, this.attributes, callBack, swfoData); } else { global.raiseError(this, '1113061611', 'run', 'FlashRenderer~render', Error('Could not find swfobject library or embedSWF API')); } }, // Listen to the dataUpdated event, so that charts can be re-rendered with // new data, when data is updated on JS variable post render update: function (vars) { // Point to direct SWFObject and also get the latest data var chart = this.ref, data = vars.data; // When updating states that dataXML has been updated // Update FlashVars this.flashVars.dataXML = data; // Check whether there was an error or not. if (vars.error === undefined) { // Call ExternalInterface method and update the data if (this.isActive() && isFunction(chart.setDataXML)) { // Check whether the chart-type has changed since last update. // If yes then we re-render the chart. if (this.src !== this.__state.lastRenderedSrc) { this.render(); } else { chart.setDataXML(data, false); } } else { // Remove the 'animation' flag of the chart while data was // updated during unavailability of SWF delete this.flashVars.dataURL; delete this.flashVars.animation; } } // Show error message. else { // Call ExternalInterface method to show message if (this.isActive() && isFunction(chart.showChartMessage)) { chart.showChartMessage('InvalidXMLText'); } else { // Remove the 'animation' flag of the chart while data was // updated during unavailability of SWF this.flashVars.dataXML = '<Invalid' + vars.format.toUpperCase() + '>'; delete this.flashVars.dataURL; delete this.flashVars.animation; } } }, // Handle renderer resize. resize: function () { // Updated flashVars with new dimension this.flashVars.chartWidth = this.width; this.flashVars.chartHeight = this.height; if (this.ref !== undefined) { // Set sizes of DOM elements. this.ref.width = this.width; this.ref.height = this.height; if (isFunction(this.ref.resize)) { // Force resize on charts. this.ref.resize(this.ref.offsetWidth, this.ref.offsetHeight); } } }, // Send chart configuration config: function (items) { global.extend(this.flashVars, items); }, dispose: function () { var container; // Managed removal of chart using swfObject library win.swfobject.removeSWF(this.id); // Proceed with disposal only when the HTML element exists. if ((container = this.ref)) { // Delete DOM element if (container.parentNode) { container.parentNode.removeChild(container); } } }, protectedMethods: { flashVars: true, params: true, setDataXML: true, setDataURL: true, hasRendered: true, getXML: true, getDataAsCSV: true, print: true, exportChart: true }, events: { Loaded: function (e) { var obj = e.sender; // Upon render completion, disable animation of the chart by updating the // 'animation' flag in flashVars. This fixes the issue of FusionCharts // loosing its state when it is re-rendered after being hidden. // Set disable animation flag for state management. obj.flashVars.animation = '0'; }, DataLoadRequested: function (event, args) { // Reference to event sender. var obj = event.sender, url = args.url, legacyTransport = false; // Do not use AJAX in case of local file protocol. if (args.dataFormat === FusionChartsDataFormats.XML && ( win.location.protocol === 'file:' && Boolean(obj.options.safeMode) || Boolean(obj.options.useLegacyXMLTransport))) { if (obj.ref) { if (obj.ref.setDataURL) { obj.ref.setDataURL(url, false); } else { global.raiseError(this, '0109112330', 'run', '>FlashRenderer^DataLoadRequested', Error('Unable to fetch URL due to security restriction on Flash Player. Update global security settings.')); } } else { // Update the flashVars with new URL obj.flashVars.dataURL = url; } // Stop further activities on this event. event.stopPropagation(); // Cancel the AJAX data-load request. legacyTransport = true; args.cancelDataLoadRequest(); obj.addEventListener('DataLoaded', syncDataStore); } // In case we have an active chart, we show the loading // message in chart itself. if (obj.ref && obj.showChartMessage) { delete obj.flashVars.stallLoad; if (obj.options.showDataLoadingMessage) { obj.ref.showChartMessage('XMLLoadingText'); } } // In case chart object is not available, we set a flashvar saying that // loading is to be stalled. else if (!legacyTransport) { obj.flashVars.stallLoad = true; } }, DataLoadRequestCancelled: function (event) { // Reference to event sender. var obj = event.sender; // In case we have an active chart, we hide the loading message in chart // itself. if (obj.ref && isFunction(obj.showChartMessage)) { obj.ref.showChartMessage(); } // In case chart object is not available, we set a flashvar saying that // loading is to be stalled. delete obj.flashVars.stallLoad; }, DataLoadError: function (event, args) { // Reference to event sender. var obj = event.sender; // On data load error, one needs to display "No Data To Display" on // charts. if (obj.ref && isFunction(obj.ref.showChartMessage) && args.source === 'XmlHttpRequest') { // Show Data Load Error Message. obj.ref.showChartMessage('LoadDataErrorText'); } else { delete obj.flashVars.dataURL;// = 'XmlHttpRequestDataLoadError: ' + args.url; obj.flashVars.dataXML = '<JSON parsing error>'; delete obj.flashVars.stallLoad; } }, DataLoadRequestCompleted: function (event, args) { // Reference to event sender. var obj = event.sender; // Process this event only when raised by AJAX data handler! if (args.source !== 'XmlHttpRequest') { return; } // Clear load prevention flag. delete obj.flashVars.stallLoad; } } }; // Add flash renderer legacy functions. renderer.prototype = { // Legacy function getSWFHTML: function () { // Create temporary elements and temporary access Id var outElm = doc.createElement('span'), inElm = doc.createElement('span'), tempId = 'RnVzaW9uQ2hhcnRz' + (new Date()).getTime(); // Create DOM hierarchy outElm.appendChild(inElm); // Specify temp access Id inElm.setAttribute('id', tempId); // Hide this element from user. outElm.style.display = 'none'; // Add the element to DOM. doc.getElementsByTagName('body')[0].appendChild(outElm); // Temporarily embed the swf in the above-created element. win.swfobject.embedSWF(this.src, tempId, this.width, this.height, '8.0.0', undefined, this.flashVars, this.params, this.attrs); // Get the HTML from the temp objects. var html = outElm.innerHTML.replace(tempId, this.id); // Clean up the dirty work. win.swfobject.removeSWF(tempId); outElm.parentNode.removeChild(outElm); // Return the HTML with its ID set to normal. return html; }, // Add legacy setTransparent function setTransparent: function (transparency) { // Sets chart to transparent mode when isTransparent (wMode) is true // (default). When no parameter is passed, we assume transparent to // be true. if (typeof transparency !== 'boolean' && transparency !== null) { transparency = true; } // Set the property. this.params.wMode = transparency === null ? 'window' : (transparency === true ? 'transparent' : 'opaque'); }, registerObject: function () { }, // Reference to deprecated "addVariable API" addVariable: function () { global.raiseWarning(this, '1012141919', 'run', 'FlashRenderer~addVariable()', 'Use of deprecated "addVariable()". Replace with "configure()".'); global.core.prototype.configure.apply(this, arguments); }, /** * Legacy function that simply calls setDataXML on JS object. * @id FusionCharts.setDataXML * * @param {string} xml The data as string in FusionCharts compatible XML * format. * * @type void * @deprecated */ setDataXML: function (xml) { global.raiseWarning(this, '11033001081', 'run', 'GenericRuntime~setDataXML()', 'Use of deprecated "setDataXML()". Replace with "setXMLData()".'); // Check whether the XML as parameter can be converted to // string or not and then send data to chart. if (xml === undefined || xml === null || !isFunction(xml.toString)) { // Notify using error event that invalid data was provided as xml. global.raiseError(this, '25081627', 'param', '~setDataXML', 'Invalid data type for parameter "xml"'); return; } // We check whether the renderer has setDataXML function, we set it. if (this.ref === undefined || this.ref === null || !isFunction(this.ref.setDataXML)) { this.setChartData(xml.toString(), FusionChartsDataFormats.XML); } else { // When direct XML updated API is available we use it to directly // do remote update of XML. this.ref.setDataXML(xml.toString()); } }, /** * @id FusionCharts.setDataURL * * @param {string} url * * @type void * @deprecated */ setDataURL: function (url) { global.raiseWarning(this, '11033001082', 'run', 'GenericRuntime~setDataURL()', 'Use of deprecated "setDataURL()". Replace with "setXMLUrl()".'); // Check whether the URL as parameter can be converted to // string or not. if (url === undefined || url === null || !isFunction(url.toString)) { // Notify using error event that invalid data was provided as xml. global.raiseError(this, '25081724', 'param', '~setDataURL', 'Invalid data type for parameter "url"'); return; } // We check whether the renderer has setDataURL function, we set it. if (this.ref === undefined || this.ref === null || !isFunction(this.ref.setDataURL)) { // For flash renderer, we set the flashVars, so that it is picked // up when chart renders. this.setChartData(url.toString(), FusionChartsDataFormats.XMLURL); } else { // When direct XML updated API is available we use it to directly // do remote update of XML. this.ref.setDataURL(url.toString()); } } }; // Add the renderer to FusionCharts core repository global.renderer.register('flash', renderer); // Set default renderer global.renderer.setDefault('flash'); }]); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, plusplus: true, bitwise: true, immed: true */ /*global Array: false, FusionCharts, RegExp: false, jQuery: false, window: false, $: true, FusionChartsDataFormats: false, FC_Loaded, FC_DataLoaded, FC_Rendered, FC_DrawComplete */ /** * This is the JavaScript Renderer bootstrap. Its basic functionalities are to * create interfaces between FusionCharts JS Renderer Manager and the renderer. * * @since 1.0 */ FusionCharts(['private', 'modules.renderer.js', function () { var global = this, win = window, doc = document, coreOptions = global.core.options, extendedCoreOptions = { html5ScriptNameSuffix: '.js', html5ScriptNamePrefix: 'FusionCharts.HC.', jQuerySourceFileName: 'jquery.min.js' }, /** * This flag sets whether the JavaScript renderer will be used primarily or * Flash renderer would be given priority if player exists. * @id SET_AS_PRIMARY_RENDERER * @type boolean * @const */ SET_AS_PRIMARY_RENDERER = false, LOADER_CSS_TEXT = 'display: inline-block; *zoom:1; *display:inline; width: 100%; ' + 'font-family: Verdana; font-size: 10px; color: #666666; text-align: center;', MODULE_NAME_BASE = 'modules.renderer.js-', isIE = /msie/i.test(navigator.userAgent) && !win.opera, hasSVG = !!doc.createElementNS && !!doc.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGRect, // Create the renderer object. renderer = function () {}, // Create an object in global that would store Renderer Library lib = global.hcLib = { cmdQueue: [] }, moduleCmdQueue = lib.moduleCmdQueue = { jquery: [], base: [], charts: [], powercharts: [], widgets: [], maps: [] }, moduleDependencies = lib.moduleDependencies = {}, /** * The enumeration of default filenames for each of the dependent * modules. * @type object * @constant */ moduleMeta = lib.moduleMeta = { jquery: 'jquery.min.js', base: 'FusionCharts.HC.js', charts: 'FusionCharts.HC.Charts.js', powercharts: 'FusionCharts.HC.PowerCharts.js', widgets: 'FusionCharts.HC.Widgets.js', maps: 'FusionCharts.HC.Maps.js' }, /** * Stores a list of modules that are blocked from loading. */ blockedModules = {}, /** * Find the relevant required module names from a given chart type. * * @param {string} type depermines the chart type (alias) that needs to * be looked up for dependent module names * * @type Array */ getDependentModuleName = lib.getDependentModuleName = function (type) { var modules = [], i, j; for (i in moduleDependencies) { if ((j = moduleDependencies[i][type]) === undefined) { continue; } modules[j] = i; } return modules; }, /** * Adds a dynamic dependency item */ injectModuleDependency = lib.injectModuleDependency = function (module, alias, order) { var isInjected = false; if (alias === undefined) { alias = module; } if (!moduleDependencies[module]) { moduleDependencies[module] = {}; if (!moduleCmdQueue[module]) { moduleCmdQueue[module] = []; lib.moduleMeta[module] = coreOptions.html5ScriptNamePrefix + alias + coreOptions.html5ScriptNameSuffix; } isInjected = true; } moduleDependencies[module][alias] = order || 0; return isInjected; // indicate alias already injected }, // Function that checks whether a particular module is loaded. hasModule = lib.hasModule = function (name) { var i, l; // In case we check presense of multiple modules. if (name instanceof Array) { for (i = 0, l = name.length; i < l; i += 1) { if (!Boolean(global.modules[MODULE_NAME_BASE + name]) || (name === 'jquery' && !Boolean(win.jQuery))) { return false; } } return true; } // Do special check for jQuery as it does not declare a specific module if (name === 'jquery') { return Boolean(win.jQuery); } return Boolean(global.modules[MODULE_NAME_BASE + name]); }, // Determine whether a chart-type needs a particular module. needsModule = lib.needsModule = function (name, type) { return (lib.moduleDependencies[name] && lib.moduleDependencies[name][type]) !== undefined; }, // Function to call the global loadScript function for loading an html5 // module. loadModule = lib.loadModule = function (name, success, failure, source) { // convert single string to array of one string. if (!(name instanceof Array)) { name = [name]; } var l = name.length, count = 0, loadFile = function () { // Proceed with callback when load completes. if (count >= l) { success && success(); return; } var metaKey = name[count], meta = moduleMeta[metaKey], userSrc; // Increment counter. count += 1; if (!metaKey) { failure && failure(metaKey); } // Check if module already exists else if (hasModule(metaKey)) { loadFile(); return; } // Check if loading has been blocked. If yes, then assume that // module exists. else if (blockedModules[metaKey]) { global.raiseError(source || global.core, '1112201445A', 'run', 'JavaScriptRenderer~loadModule() ', 'required resources are absent or blocked from loading.'); failure && failure(metaKey); return; } // If user has overridden file names. userSrc = (metaKey === 'jquery') ? // handle jquery legacy global.core.options.jQuerySourceFileName : global.core.options['html5' + global.capitalizeString(metaKey) + 'Src']; global.loadScript(userSrc == undefined ? meta : userSrc, { success: function () { // Even after successful load, we should check whether it // actually loaded the module. if (hasModule(metaKey)) { loadFile(); } else { failure && failure(metaKey); } }, failure: failure && function () { failure(metaKey); } }, undefined, true); }; loadFile(); }, /** * Execute renderer interface commands that are queued due to renderer * not being ready. */ executeWaitingCommands = lib.executeWaitingCommands = function (queue) { var item; // Iterate through all FusionCharts objects while ((item = queue.shift())) { // Now we execute 'command' on all charts that are waiting // for the renderer to get ready. if (typeof item === 'object') { renderer[item.cmd].apply(item.obj, item.args); } } }, /** * Remove all waiting commands for a specific chart-object */ cleanupWaitingCommands = lib.cleanupWaitingCommands = function (chart) { var type = chart.chartType(), modules = getDependentModuleName(type), module, requeue = [], queue, item; // Iterate through all modules that this chart is dependent on. while ((module = modules.shift())) { queue = moduleCmdQueue[module] || []; while ((item = queue.shift())) { // Check whether the scope object matches the one passed in params. if (typeof item === 'object' && item.obj !== chart) { requeue.push(item); } } // Restore re-queued items back in queue queue.concat(requeue); requeue = []; } }, clearStateEventHandler = function (event) { delete event.sender.jsVars._reflowData; event.sender.jsVars._reflowData = {}; //delete reflowclean delete event.sender.jsVars._reflowClean; }, // Messege configuration ChartMessage = function () { var api = function () {}; api.prototype = { "LoadDataErrorText": 'Error in loading data.', "XMLLoadingText": 'Retrieving data. Please wait', "InvalidXMLText": 'Invalid data.', "ChartNoDataText": 'No data to display.', "ReadingDataText": 'Reading data. Please wait', "ChartNotSupported": 'Chart type not supported.', "PBarLoadingText": '', "LoadingText": 'Loading chart. Please wait', "RenderChartErrorText": 'Unable to render chart.' }; return api.prototype.constructor = api; }(), showLoadingMessage = function (chart, container) { var vars = chart.jsVars, msgs = vars.msgStore; if (container && chart.options.showLoadingMessage) { // Show loading message as HTML block since HTML5 renderer is not // loaded yet. container.innerHTML = '<small style="'+ LOADER_CSS_TEXT + ' padding-top: ' + ((parseInt(container.style.height, 10) / 2) - 5) +'px">' + (msgs.PBarLoadingText || msgs.LoadingText) + '</small>'; // Set the container's background color only when // transparent mode is not set. container.style.backgroundColor = vars.transparent ? 'transparent' : (chart.options.containerBackgroundColor || '#ffffff'); } }; // Define default configuration options pertaining to HTML5 renderer. global.extend(global.core.options, extendedCoreOptions); // Create the renderer interface functions global.extend(renderer, { dataFormat: 'json', ready: false, policies: { jsVars: { // userModules: ['dependentModules', []] // enable if needed }, options: { // Shows messages while chart is loading JS files. showLoadingMessage: ['showLoadingMessage', true] } }, init: function () { /** * @algorithm * 1. Load external libraries (jQuery -> Renderer) * 2. After loading is completed, render the queued charts. */ // jQuery MUST be loaded in order to proceed. (Include Once is set // to true in order to avoid loop.) if (!win.jQuery) { loadModule('jquery', function () { // if jQuery was loaded by FusionCharts, we would like to // set it to noConflict mode and then re-assign it to $ // value if no other script is using $. jQuery.noConflict(); if (win.$ === undefined) { win.$ = jQuery; } // call init again after jQuery is loaded. renderer.init(); }, undefined, global.core); return; } // Now that jQuery exists, we know that 'base' has to be loaded. Had // base been loaded, this function would not have had existed. if (!hasModule('base')) { loadModule('base', function () { // All scripts are loaded, hence renderer is ready renderer.ready = true; // Clear any object that has been waiting for render executeWaitingCommands(lib.cmdQueue); }, undefined, global.core); return; } // If code is here, implies renderer is ready renderer.ready = true; }, // This is almost a stub render function as its job is to queue objects. render: function (container) { // Show message in HTML form showLoadingMessage(this, container); // As renderer is not ready, push it to queue lib.cmdQueue.push({ cmd: 'render', obj: this, args: arguments }); }, update: function () { // As renderer is not ready, push it to queue lib.cmdQueue.push({ cmd: 'update', obj: this, args: arguments }); }, resize: function () { lib.cmdQueue.push({ cmd: 'resize', obj: this, args: arguments }); }, dispose: function () { var queue = lib.cmdQueue, i, l; // Since renderer is not ready, we clear the command queue for (i = 0, l = queue.length; i < l; i += 1) { // We remove commands specific to this particular object. if (queue[i].obj === this) { queue.splice(i, 1); l -= 1; // subtract length as item was removed i -= 1; } } }, load: function () { lib.cmdQueue.push({ cmd: 'load', obj: this, args: arguments }); }, config: function (items, optionalValue) { var item, vars = this.jsVars, msgs = vars.msgStore, cfg = vars.cfgStore; if (typeof items === 'string' && arguments.length > 1) { item = items; items = {}; items[item] = optionalValue; } // store data at respective places. for (item in items) { // if the config is part of chart messages, we store it there. if (msgs[item] !== undefined) { msgs[item] = items[item]; } // otherwise we store it to the config store. else { cfg[item.toLowerCase()] = items[item]; } } }, protectedMethods: { }, events: { BeforeInitialize: function (event) { var sender = event.sender, vars = sender.jsVars, chartType = this.chartType(), userArg; vars.fcObj = sender; vars.msgStore = vars.msgStore || new ChartMessage(); vars.cfgStore = vars.cfgStore || {}; vars.previousDrawCount = -1; vars.drawCount = 0; vars._reflowData = {}; // validate user-defined dependent module names if (!(vars.userModules instanceof Array)) { userArg = vars.userModules; vars.userModules = []; if (typeof userArg === 'string') { vars.userModules = vars.userModules.concat(userArg.split(',')); } } // check presence of API if (!lib.chartAPI || !lib.chartAPI[chartType]) { vars.needsLoaderCall = true; } }, Initialized: function (event) { var chart = event.sender, vars = chart.jsVars; if (vars.needsLoaderCall) { delete vars.needsLoaderCall; // Request load of the specific chart module renderer.load.call(chart); } }, BeforeDataUpdate: clearStateEventHandler, BeforeDispose: clearStateEventHandler, BeforeRender: function (event) { var chart = event.sender, vars = chart.jsVars; delete vars.drLoadAttempted; delete vars.waitingModule; delete vars.waitingModuleError; clearStateEventHandler.apply(this, arguments); }, DataLoadRequested: function (event, args) { // Reference to event sender. var obj = event.sender, vars = obj.jsVars; delete vars.loadError; // In case we have an active chart, we show the loading // message in chart itself. if (obj.ref && obj.options.showDataLoadingMessage) { if (vars.hcObj && !vars.hasNativeMessage && vars.hcObj.showLoading) { vars.hcObj.showMessage(vars.msgStore.XMLLoadingText); } else if (obj.ref.showChartMessage) { obj.ref.showChartMessage('XMLLoadingText'); } else { vars.stallLoad = true; } } else { vars.stallLoad = true; } }, DataLoadRequestCompleted: function (event) { // Reference to event sender. var obj = event.sender, vars = obj.id; // Clear load prevention flags. delete vars.stallLoad; }, DataLoadError: function (event) { // Reference to event sender. var obj = event.sender, vars = obj.jsVars; // On data load error, one needs to display "No Data To Display" // on charts. delete vars.stallLoad; vars.loadError = true; if (obj.ref && typeof obj.ref.showChartMessage === 'function') { obj.ref.showChartMessage('LoadDataErrorText'); } clearStateEventHandler.apply(this, arguments); } }, // Not required for interface, but needed for runtime definition of // chartAPI '_call': function (fn, args, scope) { fn.apply(scope || win, args || []); } }); // Add functions that will be inherited by every chart instance created out // of this instance. global.extend(renderer.prototype, { getSWFHTML: function () { global.raiseWarning(this, '11090611381', 'run', 'JavaScriptRenderer~getSWFHTML()', 'getSWFHTML() is not supported for JavaScript charts.'); }, addVariable: function () { global.raiseWarning(this, '11090611381', 'run', 'JavaScriptRenderer~addVariable()', 'Use of deprecated "addVariable()". Replace with "configure()".'); global.core.prototype.configure.apply(this, arguments); }, getXML: function () { global.raiseWarning(this, '11171116291', 'run', 'JavaScriptRenderer~getXML()', 'Use of deprecated "getXML()". Replace with "getXMLData()".'); return this.getXMLData.apply(this, arguments); }, setDataXML: function () { global.raiseWarning(this, '11171116292', 'run', 'JavaScriptRenderer~setDataXML()', 'Use of deprecated "setDataXML()". Replace with "setXMLData()".'); return this.setXMLData.apply(this, arguments); }, setDataURL: function () { global.raiseWarning(this, '11171116293', 'run', 'JavaScriptRenderer~setDataURL()', 'Use of deprecated "SetDataURL()". Replace with "setXMLUrl()".'); return this.setXMLUrl.apply(this, arguments); }, hasRendered: function () { return this.jsVars.hcObj && this.jsVars.hcObj.hasRendered; }, setTransparent: function (transparency) { var vars; if (!(vars = this.jsVars)) { return; } // Sets chart to transparent mode when isTransparent (wMode) is true // (default). When no parameter is passed, we assume transparent to // be true. if (typeof transparency !== 'boolean' && transparency !== null) { transparency = true; } // Set the property. vars.transparent = transparency === null ? false : (transparency === true ? true : false); } }) global.extend(global.core, { /** * Provide API for auto fall-back to JS chart when no flash is installed. */ _fallbackJSChartWhenNoFlash: function () { // Check flash version. if (!win.swfobject.hasFlashPlayerVersion(global.core.options.requiredFlashPlayerVersion)) { // If flash version is missing, we fallback to javascript global.renderer.setDefault('javascript'); } }, /** * Specify to enable JavaScript renderer as default, based on browser * userAgent. * @param {string} str Is the regular expression used to detect browser * userAgent * * @note: Regexp for Apple Devices: /\(iPhone;|\(iPod;|\(iPad;/i */ _enableJSChartsForSelectedBrowsers: function (str) { // str is a required parameter. If not set, we exit this function. if (str === undefined || str === null) { return; } // Register the js renderer in case we have iPad or iPhone and flash // for rest. global.renderer.setDefault((new RegExp(str).test(navigator.userAgent)) ? 'javascript' : 'flash'); }, /** * Let user specify not to load specific external scripts. * @param {object} flags is the object that specifies which external * script is not to be loadd. * * @example * // Prevent FusionCharts from loading its own jQuery * if (FusionCharts._doNotLoadHTML5ExternalScript) { * FusionCharts._doNotLoadHTML5ExternalScript({ jQuery: false })] * } */ _doNotLoadExternalScript: function (flags) { var item, srcKey; for (item in flags) { srcKey = item.toLowerCase(); if (moduleMeta[srcKey]) { blockedModules[srcKey] = Boolean(flags[item]); } } }, _preloadJSChartModule: function (name) { throw "NotImplemented()"; } }); // Add the renderer to FusionCharts core repository global.renderer.register('javascript', renderer); // In case JavaScript is configured to be set as primary renderer, check for // SVG support or IE browser. if (SET_AS_PRIMARY_RENDERER && (hasSVG || isIE)) { global.renderer.setDefault('javascript'); } // Otherwise check for Flash support and finally fall back to JavaScript. else if (win.swfobject && win.swfobject.hasFlashPlayerVersion && !win.swfobject.hasFlashPlayerVersion(global.core.options.requiredFlashPlayerVersion)) { global.raiseWarning(global.core, '1204111846', 'run', 'JSRenderer', 'Switched to JavaScript as default rendering due to absence of required Flash Player.'); // If flash version is missing, we fallback to javascript global.renderer.setDefault('javascript'); } }]); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, immed: true */ /*global FusionCharts */ /*members addDataHandler, data, decode, encode, error */ /** * ----------------------------------------------------------------------------- * XML Data Handler Stub Module * ----------------------------------------------------------------------------- * This module contains the XML transcoder. This module adds the 'XML' data * handler. */ (function () { // Register the module with FusionCharts. var global = FusionCharts(['private', 'XMLDataHandler']); // Check whether the module has been already registered. If true, then // do not bother to re-register. if (global === undefined) { return; } /** * Function to convert a variable into a FusionCharts data-handler API * compatible object. * * @param {variant} data can be anything. * @type object */ var stubCoder = function (data) { // We do not need to normalize the data while encoding as because // the data is saved in JS scope and is now not sent via flashVars. return { data: data, error: undefined }; }; // Add Abstract data handler as because when the primary data-type is XML, // it requires a transparent transcoder that has nothing to do. global.addDataHandler('XML', { encode: stubCoder, decode: stubCoder }); }()); /*jslint evil: true, strict: false, regexp: false */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. var JSON; if (!JSON) { JSON = {}; } (function () { "use strict"; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }());/*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, immed: true */ /*global Array: false, FusionCharts, RegExp: false, window: false */ /** * JSON Data-Handler Module * This module performs the routines involved to transcode FusionCharts XML and * JSON. The module depends upon json2.js component from json.org and the same * has been included * * @since 3.2 * @build 2400 */ (function () { // Register the module with FusionCharts. var global = FusionCharts(['private', 'JSON_DataHandler']); // Check whether the module has been already registered. If true, then // do not bother to re-register. if (global === undefined) { return; } if (window.JSON === undefined) { global.raiseError(this, '1113062012', 'run', 'JSONDataHandler', Error('Could not find library support for JSON parsing.')); } // Add policy to allow safe XML parsing in IE using XML Islands global.core.options.allowIESafeXMLParsing = ['_allowIESafeXMLParsing', true]; var COMPACTDATAMODE = 'compactdatamode', STRING = 'string', FUNCTION = 'function', OBJECT = 'object', /** * Trims a long string at lightning fast speed of less than an ms! * @param {string} str is the string to be trimmed. * @type string */ fastTrim = function (str) { str = str.replace(/^\s\s*/, ''); var ws = /\s/, i = str.length; while (ws.test(str.charAt(i -= 1))) {} return str.slice(0, i + 1); }, XSSEncode = function (s) { if (s === null || s === undefined || typeof s.toString !== FUNCTION) { return ''; } // do we convert to numerical or html entity? s = s.toString() .replace(/&/g, '&amp;') .replace(/\'/g, '&#39;') //no HTML equivalent as &apos is not cross browser supported .replace(/\"/g, '&quot;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); return s; }; var xml2json = (function () { var rules = { /** * @var {object} arr contains the nodeNames that are marked to be * expanded as an array. * * There are two ways of defining the type: * (a) in case the node is not constrained under a specific parent, * we simply specify <code>nodeName: true</code> * */ arr: { set: true, trendlines: true, vtrendlines: true, line: { trendlines: true, vtrendlines: true }, data: true, dataset: true, lineset : true, categories: true, category: true, //styles: true, // uncomment this to disable support for compact style syntax. linkeddata: true, // For application and definition, though we know that they are // always under <styles>, yet we cannot specify that here as these // two are in 'group' rule. application: true, definition: true, // PowerCharts group of rules axis: true, connectors: true, connector: {connectors: true}, trendset: true, row: {rows: true}, column: {columns: true}, label: {labels: true}, // Widgets specific rules color: {colorrange: true}, // +powercharts dial: {dials: true}, pointer: {pointers: true}, point: {trendpoints: true}, process: {processes: true}, // gantt task: {tasks: true}, // gantt milestone: {milestones: true}, // gantt datacolumn: {datatable: true}, // gantt text: {datacolumn: true}, // gantt item: {legend: true}, // gantt alert: {alerts: true}, // alert manager groups: {annotations: true}, //annot items: {groups: true}, // annot // maps shapes: true, shape: {shapes: true}, entitydef: true, // map entity: {entitydef: true} }, /** * @var {object} tag contains nodeNames that are to be transformed * to a different nodeName as specified within this rule's meta. * @note supports comparison with base object. */ tag: { chart: 'linkedchart', map: 'linkedmap', set: 'data', vline: { chart: 'data', graph: 'data', // legacy dataset: 'data', categories: 'category', linkedchart: 'data' }, apply: { application: 'application' }, style: { definition: 'definition' }, marker: { // map application: 'application', definition: 'definition' }, entity: { // map entitydef: 'entitydef', data: 'data' }, shape: { // map and powercharts shapes: 'shapes' }, connector: { // map and powercharts connectors: { chart: 'connector', linkedchart: 'connector', map: 'connectors', linkedmap: 'connectors' } }, // annotations annotationgroup: { annotations: 'groups' }, annotation: { groups: 'items' } }, /** * @var {object} attr is the rule that defines the default * JSON variables to add in case a particular XML nodeName is found */ attr: { vline: { vline: 'true' } }, /** * @var {object} ins contains nodeNames, that are treated as source * of attributes for a grand-child with same name as that of the * child. */ ins: { chart: true, map: true, graph: true }, /** * @var {object} dsv contains nodeNames that are specially expected * to be delimiter separated textnodes. Useful for "compactDataMode". */ dsv: { dataset: 'data', categories: 'category' }, /** * @var {object} text rule specifies the nodes that are always * treated as text node and appended to its parent with specified * name. * * When specified as an array, it denotes that the text values are * to be accumulated within a sibling array with specified name under * a specified parent. * * When enclosed in an object it specifies the parent restriction. * * NOTE: That for allowing text rule to work, to append it parent * we need to insert corresponding item in "group" rule. * * @code * nodeName: equivalentJSONKey // simple key: 'value' result */ text: { target: 'target', value: 'value' }, /** * @var {object} group specifies which are the tags that are to * be promoted/inserted into its parent node (as in rule meta). */ group: { styles: { definition: true, application: true }, chart: { value: true, // widgets target: true // widgets }, graph: { // legacy value: true, // legacy widgets target: true // legacy widgets }, linkedchart: { value: true, // widgets target: true // widgets }, // maps markers: { definition: true, application: true, shapes: true, connectors: true }, map: { entitydef: true, data: true }, linkedmap: { entitydef: true, data: true } } }; var XML_CHILDNODE = 1, XML_TEXTNODE = 3; var parse = { append: function (childObj, obj, nodeName, parentNodeName) { // Before we append the childNode returned from the // previous recursion, we need to decide whether to // simply put that object with the nodeName as key, or // whether there is a qualification of 'arr' rule, by // which we push the data onto parent array. if (rules.arr[nodeName] && (rules.arr[nodeName] === true || rules.arr[nodeName][parentNodeName] === true)) { if (!(obj[nodeName] instanceof Array)) { obj[nodeName] = []; } obj[nodeName].push(childObj); } else { obj[nodeName] = childObj; } }, child: function (obj, children, parentNodeName, baseObj) { var i, nodeName, childNode, childObj, temp, rule; // Iterate through the children and parse it depending upon its // nodeType for (i = 0; i < children.length; i += 1) { // Retain reference to the child node childNode = children[i]; // Desensitize the case of the nodeName nodeName = childNode.nodeName.toLowerCase(); // When the child object is a child node, we need to recurse // onto it and also separately parse its attributes. switch (childNode.nodeType) { case XML_CHILDNODE: // Parse the attributes of the XML Node. childObj = parse.attr(childNode.attributes); rule = rules.ins[nodeName]; if (rule === true) { // In case 'ins' rule is matched, we transfer the // parsed attributes to a grand-child having the node // name of child and rename the child to the new name // specified in the meta of 'tag' rule. temp = childObj; childObj = {}; childObj[nodeName] = temp; temp = undefined; } // Apply the "attr" rule to add defalt flag variables. rule = rules.attr[nodeName] if (typeof rule === OBJECT) { global.extend(childObj, rule); } // Parse the tag rule. rule = rules.tag[nodeName] if (rule) { // Apply nodeName transformation 'tag' rule with // base-parent-child relationship. if (typeof rule === OBJECT && typeof rule[parentNodeName] === OBJECT) { temp = undefined; for (temp in rule[parentNodeName]) { if (baseObj[temp]) { nodeName = rule[parentNodeName][temp]; break; } } } // Apply nodeName transformation 'tag' rule with // parent-child relationship. else if (typeof rule === OBJECT && typeof rule[parentNodeName] === STRING) { nodeName = rule[parentNodeName]; } // Apply nodeName transformation 'tag' rule with parent // independent relationship. else if (typeof rule === STRING) { nodeName = rule; } } // We now need to parse the rest of the childnodes as // recursed into this function. if (childNode.childNodes.length) { // Match the group rule. To check whether we need to append // the parsed children or treat the parsed children as siblings. rule = rules.group[parentNodeName]; if (rule && rule[nodeName]) { parse.child(obj, childNode.childNodes, nodeName, baseObj); } else { parse.child(childObj, childNode.childNodes, nodeName, baseObj); } } // Append the computed childObject to parent depending // upon whether it has to be appended to an array or as // a child object. // Note: We append only when the "group" rule was not matched rule = rules.group[parentNodeName]; if (!(rule && rule[nodeName])) { parse.append(childObj, obj, nodeName, parentNodeName); } /*else { if (nodeName === 'entity' && parentNodeName === 'entitydef') { if (!obj.i) {obj.i = 1} else {obj.i++} } }*/ break; // In case the child object is a text node and meets some // other requirements, we parse it as textNode case XML_TEXTNODE: // Parse mandatory text-node rule. rule = rules.text[parentNodeName]; if (rule) { nodeName = rule; childObj = childNode.data; // Append the computed childObject to parent depending // upon whether it has to be appended to an array or as // a child object. parse.append(childObj, obj, nodeName, parentNodeName); } // Parse compact-data mode / optional text-node rule rule = rules.dsv[parentNodeName]; if (typeof rule === STRING && baseObj.chart && parseInt(baseObj.chart[COMPACTDATAMODE], 10)) { // Create text node nodeName = rule; childObj = childNode.data; // Since this is DSV type text node, it is directly // appended to the object. obj[nodeName] = obj[nodeName] ? obj[nodeName] + childObj : childObj; } break; } // end switching based on node-type } }, attr: function (attrObj) { var i, obj = {}; // Check whether a valid xml attr NamedNode is passed. if (!attrObj || !attrObj.length) { return obj; } // Iterate through the attribute list and populate the return // object with the nodeValues. for (i = 0; i < attrObj.length; i += 1) { obj[attrObj[i].nodeName.toLowerCase()] = attrObj[i].value || attrObj[i].nodeValue; } // Finally return the converted object. return obj; } }; var parser = function (xml) { var jsonObj = {}, xmlDoc, root, rootName, newNode, nodeEle, rootAttrs, childNodes, i; // Validate parameters to check that xml can be converted into a string. if (typeof xml !== OBJECT && typeof xml.toString !== FUNCTION) { parser.errorObject = new TypeError('xml2json.parse()'); return jsonObj; } xml = xml.toString() .replace(/<\!--[\s\S]*?-->/g, '') // remove xml comments .replace(/<\?xml[\s\S]*?\?>/ig, '') // remove xml definition //.replace(/\<\!\[cdata[\s\S]*?\]\]\>/ig, '') // remove CDATA //.replace(/(=\s*?\"[\s\S]*?\")(\w)/ig, '$1 $2') // fix whitespace attr with quot //.replace(/(=\s*?\'[\s\S]*?\')(\w)/ig, '$1 $2') // fix whitespace attr with apos .replace(/&(?!([^;\n\r]+?;))/g, '&amp;$1'); // fix ampersand xml = fastTrim(xml); // Check whether unwanted data like undefined, null blank string etc. if (!xml) { //parser.errorObject = new TypeError('xml2json.parse()'); return jsonObj; } // Get XML Parser object depending upon browser capability and // subsequently load xml string. try { if (window.DOMParser) { xmlDoc = (new window.DOMParser()).parseFromString(xml, "text/xml"); } else { // Internet Explorer if (document.body && global.core.options.allowIESafeXMLParsing) { // Check if xml islands can be used var xmlElem = document.createElement("xml"); xmlElem.innerHTML = xml; document.body.appendChild(xmlElem); xmlDoc = xmlElem.XMLDocument; document.body.removeChild(xmlElem); xmlElem = null; } else { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(xml); } } if (!(xmlDoc && xmlDoc.childNodes && xmlDoc.childNodes.length === 1 && (root = xmlDoc.childNodes[0]) && root.nodeName && (rootName = root.nodeName.toLowerCase()) && (rootName === 'chart' || rootName === 'map' || rootName === 'graph'))) { parser.errorObject = new TypeError('xml2json.parse()'); return jsonObj; } else if (rootName === 'graph') { newNode = xmlDoc.createElement('chart'); rootAttrs = root.attributes; i = (rootAttrs && rootAttrs.length) || 0; while (i--) { newNode.setAttribute(rootAttrs[i].name, rootAttrs[i].value); rootAttrs.removeNamedItem(rootAttrs[i].name); } childNodes = root.childNodes; i = (childNodes && childNodes.length) || 0; if (i) { i -= 1; nodeEle = root.removeChild(childNodes[i]); newNode.appendChild(nodeEle); } while (i--) { nodeEle = root.removeChild(childNodes[i]); newNode.insertBefore(nodeEle, newNode.firstChild); } xmlDoc.replaceChild(newNode, root); root = newNode; } } catch (e) { parser.errorObject = e; } if (root) { // Do initial attribute parsing if (root.attributes) { jsonObj[rootName] = parse.attr(root.attributes); } // Parse all childNodes. if (root.childNodes) { parse.child(jsonObj, root.childNodes, rootName, jsonObj); } // Delete error flag. delete parser.errorObject; } else { parser.errorObject = new TypeError('xml2json.parse()'); } return jsonObj; }; return function (xml) { // Clear error flags of parser. delete parser.errorObject; // Call JSON2XML parser to retrieve the parsed data. var jsonData = parser(xml); // Compile a return object for encoding function. return { data: jsonData, error: parser.errorObject }; }; }()); /** * This function accepts a JSON string or object and converts it to * FusionCharts data XML. * @type string * */ var json2xml = (function () { /** * This function verifies whether an */ var rules = { /** * @var {object} items Collection of rules that are required to convert * JSON to FusionCharts XML. * * @note The rules are in the form: * ruleType: { namespace: { nodeName: ruleMeta } } */ items: { /** * @var {object} explode Comprises of JSON attributes that needs to * be converted to a particular set of nodes. Generally the value of * such attributes/properties are an array of objects. Each object * in these arrays are converted to a particular XML node specified * within the rule meta. */ explode: { data: 'set', groups: { annotations: 'annotationgroup' }, items: { groups: 'annotation' } }, /** * @var {object} text Comprises of JSON keys that are to be * always treated as text-node */ text: { chart: { target: 'target', value: 'value' }, graph: { // legacy target: 'target', value: 'value' } }, /** * @var {object} dsv contains nodeNames that are specially expected * to be delimiter separated textnodes. Useful for "compactDataMode". */ dsv: { dataset: { data: 'dataset' }, categories: { category: 'categories' } }, /** * @var {object} attr Comprises of JSON attributes whose values are * always added to the XML attributes of its namespace. Such nodes * generally are object containing strings. The keys within them * are to be converted to XML attributes and the values become XML * attribute values. * */ attr: { chart: { chart: 'chart' }, graph: { // legacy graph: 'graph' }, map: { map: 'map' }, linkedmap: { map: 'map' }, linkedchart : { chart: 'chart' } }, /** * @var {object} group Comprises of JSON attributes whose children * are to be grouped under a particular node. The parentNode where * it has to be grouped are specified in the rule meta. */ group: { styles: { definition: 'style', application: 'apply' }, map: { data: 'entity', entitydef: 'entity' }, markers: { // for maps definition: 'marker', application: 'marker', shapes: 'shape', connectors: 'connector' } } }, /** * This method verifies whether a name-item pair qualifies for a * rule or not. If so, it also returns the meta information of the * qualified rule. * @type string * * @param {string} rule is the name of the rule that you want to * verify. There must be a corresponding rule group in the items * object. * @param {variant} item * @param {variant} namespace */ qualify: function (rule, item, namespace) { return typeof this.items[rule][namespace] === OBJECT ? this.items[rule][namespace][item] : this.items[rule][namespace]; } }; /** * This function accepts a JSON object and converts it to FusionCharts * data xml. * * @param obj {object} JSON object to be parsed. * @param namespace {string} is the parent/root namespace within which * the JSON object is contained. */ var parser = function (obj, namespace, namespaceparent, flags) { // Initialize variables that stores the current namespace's XML // construction parameters. /** * @var {string} attrString The serialized set of attributes key:value * pairs generated for this namespace. * @var {string} innerXML The innerXML of the node generated in this NS. * @var {string} nodeName The current node name devised from the NS. * @var {string} outerXML The outer XML generated for this JSON tree. * @var {string} item The current child being processed within an NS. * @var {string} lcaseItem The case desensitized current node item. * @var {string} lcaseNS The case desensitized namespace. */ var attrString = '', innerXML = '', nodeName = '', outerXML = '', item, lowerItem, qualifier; // Desensitize case of namespace. if (namespace && typeof namespace.toLowerCase === 'function') { namespace = namespace.toLowerCase(); } // Special root namespace flag setting if (namespaceparent === undefined && obj[namespace]) { for (item in obj[namespace]) { lowerItem = item.toLowerCase(); if (lowerItem === COMPACTDATAMODE) { flags.applyDSV = (obj[namespace][item] == 1); } } } // In case the object is an array, apply explosion rule. if (obj instanceof Array) { // Iterate through every item within the array and expand it. for (item = 0; item < obj.length; item += 1) { // If the value of the node is string we expand its contents // into the content of the node for COMPACT_MODE data if (typeof obj[item] === STRING) { outerXML += XSSEncode(obj[item]); } // If the node is not string, we process its contents as // another node. else { outerXML += parser(obj[item], namespace, namespaceparent, flags); } } } // For any other data-type other than Array we iterate through the // contents of the variable and parse each node. else { for (item in obj) { // Store a lower-case version of this lowerItem = item.toLowerCase(); // Parse "group" rule. Here, we test whether we are to group // a JSON Array under a particular XML node. // @example where this rule matches x for y: // x: [a, b, c] is <y><x a /><x b /><x c/></y> if (obj[item] instanceof Array && (qualifier = rules.qualify('group', lowerItem, namespace))) { innerXML += '<' + lowerItem + '>' + parser(obj[item], qualifier, namespace, flags) + '</' + lowerItem + '>'; } // Parse "attr" rule. Here we test whether to use the items // within a particular item as the XML attributes of the // parent namespace. else if (typeof obj[item] === OBJECT) { // Check whether there is a qualifying rule for using // an OBJECT as source of attributes of a namespace. if ((qualifier = rules.qualify('attr', lowerItem, namespace))) { nodeName = parser(obj[item], qualifier, namespace, flags) .replace(/\/\>/ig, ''); namespace = lowerItem; } // Otherwise, recurse the parser to process the object // as a child JSON object. else { innerXML += parser(obj[item], lowerItem, namespace, flags); } } // Parse "vLine" and other static rules. else { if (flags.applyDSV && (qualifier = rules.qualify('dsv', lowerItem, namespace)) ) { innerXML += obj[item]; }// Check for text qualifier else if ((qualifier = rules.qualify('text', lowerItem, namespace))) { innerXML += '<' + qualifier + '>' + obj[item] + '</' + qualifier + '>'; } else if (lowerItem === 'vline' && Boolean(obj[item])) { namespace = 'vline'; } else { attrString += ' ' + lowerItem + '=\"' + XSSEncode(obj[item]) .toString().replace(/\"/ig, '&quot;') + '\"'; } } } // When parsing completes, we need to check whether we have any // namespace adjustments or not. // Explode rule. if ((qualifier = rules.qualify('explode', namespaceparent, namespace))) { namespace = qualifier; } // Build the final XML node string. outerXML = (nodeName !== '' ? nodeName : '<' + namespace) + attrString + (innerXML !== '' ? '>' + innerXML + '</' + namespace + '>' : ' />'); } return outerXML; }; return function (jsonData) { // Clear error flags of parser. delete parser.errorObject; // In case user sends the JSON data as STRING, we need to parse // it and convert to JSON object. if (jsonData && typeof jsonData === STRING) { // Parse the data within atry block in order to receive all // errors. try { jsonData = JSON.parse(jsonData); } catch (e) { parser.errorObject = e; } } // Call JSON2XML parser to retrieve the parsed data. var rootNS = jsonData && jsonData.graph ? 'graph' : (jsonData && jsonData.map ? 'map' : 'chart'), xmlData = parser(jsonData, rootNS, undefined, {}); // Compile a return object for encoding function. return { data: xmlData, error: parser.errorObject }; }; }()); // Add the data-handler to FusionCharts collection of data-handlers global.addDataHandler('JSON', { encode: json2xml, decode: xml2json }); }()); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, immed: true */ /*global FusionCharts */ /*properties data, decodeLiterals, addDataHandler, addEventListener, categories, category, chart, columnCount, configure, core, data, dataset, decode, delimiter, encode, eolCharacter, error, exportdataqualifier, exportdataseparator, getCSVData, getDataAsCSV, join, label, length, name, options, prototype, qualifier, raiseError, ref, renderer, replace, rowCount, sender, separator, seriesname, set, slice, toString, transcodeData, value, vline, xaxisname, yaxisname */ /** * ----------------------------------------------------------------------------- * CSV Data Handler Stub Module * ----------------------------------------------------------------------------- * This module contains the CSV transcoder. This module adds the 'CSV' data * handler. */ FusionCharts(['private', 'CSVDataHandler', function () { var global = this, BLANK = "", COMMA = ",", QUOTE = "\"", APOS = "\'", TAB = "\t", CRLF = "\r\n", LIT_QUOT = "{quot}", LIT_TAB = "{tab}", LIT_APOS = "{apos}", DSV, // constructor decoder; DSV = function (config) { this.data = []; this.rowCount = 0; this.columnCount = 0; this.configure(config); }; DSV.decodeLiterals = function (str, defaultValue) { if (str === undefined || str === null || !str.toString) { return defaultValue; } return str.replace(LIT_TAB, TAB).replace(LIT_QUOT, QUOTE) .replace(LIT_APOS, APOS); }; DSV.prototype.set = function (row, col, value) { var i; // Initialize a counter // In case data is being set to a row that does not exist, we pad those // many empty spaces with a blank array. So that, there is no error // while setting data anywhere between them. if (this.rowCount <= row) { for (i = this.rowCount; i <= row; i += 1) { this.data[i] = []; } // Increment rowCount this.rowCount = row + 1; } // Increment columnCount if (this.columnCount <= col) { this.columnCount = col + 1; } // Set the value this.data[row][col] = value; }; DSV.prototype.setRow = function (row, value) { var i; // In case data is being set to a row that does not exist, we pad those // many empty spaces with a blank array. So that, there is no error // while setting data anywhere between them. if (this.rowCount <= row) { for (i = this.rowCount; i <= row; i += 1) { this.data[i] = []; } // Increment rowCount this.rowCount = row + 1; } // Increment columnCount if (this.columnCount < value.length) { this.columnCount = value.length; } // Set column. this.data[row] = value; }; DSV.prototype.get = function (row, col) { var data = this.data; return data[row] && data[row][col]; }; DSV.prototype.configure = function (config) { var decodeLiterals = DSV.decodeLiterals; this.delimiter = decodeLiterals(config.delimiter, COMMA); this.qualifier = decodeLiterals(config.qualifier, QUOTE); this.eolCharacter = decodeLiterals(config.eolCharacter, CRLF); }; DSV.prototype.clear = function () { this.data = []; this.rowCount = 0; this.columnCount = 0; }; DSV.prototype.toString = function () { var row, col, str = ''; // Iterate through all rows and generate the string structure for (row = 0; row < this.rowCount; row += 1) { col = this.qualifier + this.data[row].join(this.qualifier + this.delimiter + this.qualifier) + this.qualifier; str += (col === "\"\"" ? this.eolCharacter : col + this.eolCharacter); } // Truncate extra line-break generated while forming the CSV. if (this.rowCount > 0) { str = str.slice(0, str.length - 2); } return str; }; /** * Function to convert a variable into a FusionCharts data-handler API * compatible object. * * @param {variant} data is the dataSource passed on to the decoder. * * @marap {FusionCharts} obj is the FusionCharts object for which the * decoding will take place. * @marap {object} options are the dataOptions passed to this data handler. * * @type object */ decoder = function (data) { var jsondata = global.core.transcodeData(data, 'xml', 'json') || {}, csv, row, column, g, i, j, k, l, chartAttrs = jsondata.chart || jsondata.map || jsondata.graph || {}, forceErrorColumns = Boolean(chartAttrs.exporterrorcolumns || 0), categories = (jsondata.categories && jsondata.categories[0] && jsondata.categories[0].category) || [], isGeoPlot = jsondata.map && !jsondata.chart, isXYPlot = false, isErrorPlot = false, isMapPlot = false, compactDataMode = false, datasets, lineset, axisset, dataCollectionLength, categoryLength, datasetLength, categoryItem, dataCollection, // for ms stacked datasetItem, dataLength, dataItem, dataValue, bumpColumnCount, // for map plots mapRows, mapColumns; // Create a CSV based Delimiter data store csv = new DSV({ separator: chartAttrs.exportdataseparator, qualifier: chartAttrs.exportdataqualifier }); // Try probe maps. For GEO plot, getDataAsCSV exists on chart API. if (isGeoPlot) { csv.setRow(0, ['Id', ' Short Name', 'Long Name', 'Value', 'Formatted Value']); } // Probe widgets. else if ((datasets = (jsondata.dials && jsondata.dials.dial) || (jsondata.pointers && jsondata.pointers.pointer) || jsondata.value) !== undefined) { // Prepare CSV for single-value input. if (typeof datasets === 'string') { csv.set(0, 0, datasets); // Separate single-value for bullet graphs "target" tag if (typeof jsondata.target === 'string') { csv.set(0,1, jsondata.target) } } // For multi-value gauges having dials or pointers. else { // Set column headers. csv.setRow(0, ['Id', 'Value']); for (i = 0, k = 1, j = datasets.length; i < j; i += 1, k += 1) { csv.setRow(k, [k, datasets[i].value]); } } } // Take multi-series decision here. else if ((datasets = jsondata.dataset || (!(jsondata.data instanceof Array) && []))) { column = 1; // Merge lineset with dataset for easy algorithm (will be separated // later.) lineset = jsondata.lineset; if (lineset) { datasets = datasets.concat(lineset); } // Merge axis for multi-axis data axisset = jsondata.axis; if (axisset) { datasets = datasets.concat(axisset); } datasetLength = datasets.length; categoryLength = categories.length; // Add only category rows in case no dataset has been found. if (!(datasetLength = datasets.length)) { for (i = 0; i < categoryLength; i += 1) { categoryItem = categories[i]; csv.set(i+1, 0, categoryItem.label || categoryItem.name); } } for (i = 0; i < datasetLength; i += 1) { dataCollection = datasets; if (dataCollection[i].dataset) { dataCollection = dataCollection[i].dataset; g = 0; dataCollectionLength = dataCollection.length; } else { dataCollection = datasets; g = i; dataCollectionLength = g + 1; } for (; g < dataCollectionLength && !isXYPlot && !isMapPlot; g += 1, column += 1) { // Refer to the dataset item that contains the data and // forms a column. datasetItem = dataCollection[g]; // Set the column header equalling to series name csv.set(0, column, datasetItem.seriesname); if (typeof datasetItem.data === 'string') { compactDataMode = true; datasetItem.data = datasetItem.data.split(chartAttrs.dataseparator || '|'); } // Loop through categories and fill the values of each column // with its values for (j = 0, k = 0, dataLength = datasetItem.data && datasetItem.data.length || 0; j < dataLength || j < categoryLength; j += 1) { categoryItem = categories[j]; row = k + 1; dataItem = datasetItem.data && datasetItem.data[k] || {}; // Keep checking for scatter chart. If present then // raise a flag and exit processing. if (dataItem.x !== undefined && dataItem.y !== undefined) { isXYPlot = true; break; } // Keep checking for HeatMap chart if (dataItem.rowid !== undefined && dataItem.columnid !== undefined) { isMapPlot = true; break } // trap surplus data here if (j < categoryLength && !categoryItem.vline) { csv.set(row, 0, categoryItem.label || categoryItem.name); dataValue = parseFloat(dataItem ? dataItem.value : ''); dataValue = isNaN(dataValue) ? '' : dataValue; csv.set(row, column, dataValue); // Perform check for errorValue on error charts if (isErrorPlot || forceErrorColumns || dataItem.errorvalue) { // Set the next column header and flag that this // dataset has error values. if (!isErrorPlot) { isErrorPlot = true; csv.set(0, column + 1, "Error"); } bumpColumnCount = 1; csv.set(row, column + 1, dataItem.errorvalue) } // Increment the auxilliary counter to ensure sync with // dataset count even after ignoring of vline in category. k += 1; } } // Reset flag for checking error value in set and // bump a column to accomodate error. if (bumpColumnCount) { column += bumpColumnCount; bumpColumnCount = 0; } } } // Split the previously merged lineset and axisset if (lineset) { datasets = datasets.slice(0, -lineset.length); } if (axisset) { datasets = datasets.slice(0, -axisset.length); } } // for non-ms data. else if ((datasets = jsondata.data)){ csv.set(0, 1, chartAttrs.yaxisname || 'Value'); for (i = 0, categoryLength = datasets.length; i < categoryLength; i += 1) { dataItem = datasets[i]; // Ignore vLines if (!dataItem.vline) { // Set the row value. dataValue = parseFloat(dataItem.value ? dataItem.value : ''); dataValue = isNaN(dataValue) ? '' : dataValue; csv.setRow(i + 1, [dataItem.label || dataItem.name, dataValue]); } } } // Special processing for x-y plot data. if (isXYPlot) { // Reset any processing done earlier. csv.clear(); isErrorPlot = false; bumpColumnCount = 0; // Set new column headers. csv.setRow(0, ['Series', 'x', 'y']); // Iterate through all datasets. for (i = 0, row = 1, datasets = jsondata.dataset, dataCollectionLength = datasets.length; i < dataCollectionLength; i += 1) { for (j = 0, datasetItem = datasets[i] && datasets[i].data || [], datasetLength = datasetItem.length; j < datasetLength; j += 1, row += 1) { dataItem = datasetItem[j] || {}; dataValue = [datasets[i].seriesname, dataItem.x, dataItem.y]; // check z index value for bubble charts if (dataItem.z !== undefined) { dataValue.push(dataItem.z); // Set flag for z by using bump column flag. Later // when error values will be set, it would detect whether // z was added from this value. if (!bumpColumnCount) { csv.set(0, 3, 'z'); bumpColumnCount = 1; } } // Set values for error charts after probing presense of // error values. Note that after one errorvalue has been // probed, it will no longer need to compute so many logic // operations since isErrorPlot flag will then be true. if (isErrorPlot || forceErrorColumns || dataItem.errorvalue !== undefined || dataItem.horizontalerrorvalue !== undefined || dataItem.verticalerrorvalue !== undefined) { dataValue.push(dataItem.errorvalue, dataItem.horizontalerrorvalue === undefined ? dataItem.errorvalue : dataItem.horizontalerrorvalue, dataItem.verticalerrorvalue === undefined ? dataItem.errorvalue : dataItem.verticalerrorvalue) // Set column headers. if (!isErrorPlot) { csv.set(0, bumpColumnCount + 3, 'Error'); csv.set(0, bumpColumnCount + 4, 'Horizontal Error'); csv.set(0, bumpColumnCount + 5, 'Vertical Error'); } isErrorPlot = true; } // Now set the entire row of data csv.setRow(row, dataValue); } } } else if (isMapPlot) { // reset parsing; csv.clear(); mapRows = {}; mapColumns = {}; // Iterate through all rows and create a reverse map of id to row // index. for (i = 0, j = 1, categories = jsondata.rows && jsondata.rows.row || [], l = categories.length; i < l; i += 1, j += 1) { categoryItem = categories[i]; if (categoryItem.id) { mapRows[categoryItem.id.toLowerCase()] = j; // desensitize csv.set(j, 0, categoryItem.label || categoryItem.id); } } // Iterate through all columns and reverse map id to column index. for (i = 0, j = 1, categories = jsondata.columns && jsondata.columns.column || [], l = categories.length; i < l; i += 1, j += 1) { categoryItem = categories[i]; if (categoryItem.id) { mapColumns[categoryItem.id.toLowerCase()] = j; // desensitize csv.set(0, j, categoryItem.label || categoryItem.id); } } // Select first dtaset datasetItem = jsondata.dataset && jsondata.dataset[0] && jsondata.dataset[0].data || []; // Iterate through data and based on row and col id of the values, // use the reverseMap to place them on csv. for (i = 0, l = datasetItem.length; i < l; i += 1) { dataItem = datasetItem[i]; row = dataItem.rowid.toLowerCase(); column = dataItem.columnid.toLowerCase(); // If a row is not found on the map, append one. if (!mapRows[row]) { mapRows[row] = csv.rowCount; csv.set(csv.rowCount, 0, dataItem.rowid); // add header } // If a column is not found on the map, append one. if (!mapColumns[column]) { mapColumns[column] = csv.columnCount; csv.set(0, csv.columnCount, dataItem.columnid); // add header } csv.set(mapRows[row], mapColumns[column], dataItem.value); } } // cleanup axisset = null; lineset = null; categories = null; datasets = null; if (csv.rowCount > 0 && csv.get(0, 0) === undefined) { csv.set(0, 0, chartAttrs.xaxisname || 'Label'); } return { data: csv.toString(), error: undefined }; }; // Add Abstract data handler as because when the primary data-type is XML, // it requires a transparent transcoder that has nothing to do. global.addDataHandler('CSV', { encode: function (data, obj) { global.raiseError(obj, '0604111215A', 'run', '::CSVDataHandler.encode()', 'FusionCharts CSV data-handler only supports encoding of data.'); throw "FeatureNotSupportedException()"; }, decode: decoder }); // Add the function reference to getDataAsCSV for JS charts. global.core.addEventListener('Loaded', function (event) { var obj = event.sender; // Execute this event for JS charts only. if (obj.options.renderer !== 'javascript') { return; } // Override the getDataAsCSV if (!obj.getDataAsCSV) { obj.getDataAsCSV = obj.ref.getDataAsCSV = obj.getCSVData; } }); }]); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, immed: true */ /*global Array: false, FusionCharts, RegExp: false, FusionChartsDataFormats: false */ /*members JSON, animation, chart, extend, getChartAttribute, getChartData, graph, length, raiseError, setChartAttribute, setChartData, toLowerCase, toString */ /** * ----------------------------------------------------------------------------- * Dynamic Chart Attributes Module * ----------------------------------------------------------------------------- * This module contains codes required to get and set chart attributes from a * FusionCharts object using simple getter and setter functions. These method * completely bypasses the data transfer from the SWF and computes chart * attributes based on the last set data. */ (function () { // Register the module with FusionCharts. var global = FusionCharts(['private', 'DynamicChartAttributes']); // Check whether the module has been already registered. If true, then // do not bother to re-register. if (global === undefined) { return; } global.extend(global.core, { /** * Updates a FusionCharts object's XML root's attribute with the new * attribute-value pair. In case the attribute does not exist, it adds * it. * * @param attributes {object} The attributes to be updated. * * @type string * @return Updated FusionCharts DataXML with the new attribute added or * updated */ setChartAttribute: function (attributes, value) { // In case attribute is sent as separate arguments, combine them // to one object. if (typeof attributes === 'string') { var temp = arguments[0]; attributes = {}; attributes[temp] = value; } // In case user sends invalid parameters for attributes. else if (attributes === null || typeof attributes !== 'object') { return; } var i = 0, json = this.getChartData(FusionChartsDataFormats.JSON), prop, attList = json.chart || json.graph || json.map || {}; // Iterate through attributes and update them. for (prop in attributes) { i += 1; if (attributes[prop] === null) { delete attList[prop.toLowerCase()]; continue; } attList[prop.toLowerCase()] = attributes[prop]; } // Update chart's XML. if (i > 0) { // In case animation is not specified, then turn it off. if (typeof attList.animation === 'undefined') { attList.animation = '0'; } this.setChartData(json, FusionChartsDataFormats.JSON); } }, /** * Returns the value of a specific chart attribute. * * @param attribute {string} The attributes to be fetched. * * @type string * @return The value of the attribute. */ getChartAttribute: function (attribute) { // Get chart attributes. var attList = (attList = this.getChartData(FusionChartsDataFormats.JSON)).chart || attList.graph || attList.map; // In case no argument is passed, we return the entire set of // chart attributes object. if (arguments.length === 0 || attribute === undefined || attList === undefined) { return attList; } // Create a variable that will store reference to the parameter that // contains attributes. This helps in case user sends one attribute // as string, we covert it to an array witj one element. var value, i; // Convert single attribute to array with one element or directly // send the value as return. if (typeof attribute === 'string') { value = attList[attribute.toString().toLowerCase()]; } // In case user sends an array of attributes, we compile an object // for the same and return. else if (attribute instanceof Array) { value = {}; for (i = 0; i < attribute.length; i += 1) { value[attribute[i]] = attList[attribute[i].toString().toLowerCase()]; } } // If all above conditions fail, there must be some issue with the // parameters. else { global.raiseError(this, '25081429', 'param', '~getChartAttribute()', 'Unexpected value of "attribute"'); } // We return 'value' variable here as because it is equivalent to // sending '{}' in case above conditions fail. return value; } }, true); }()); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, immed: true */ /*global window: false, Array: false, FusionCharts: false, FusionChartsEvents: false FusionChartsDataFormats: false */ /* ----------------------------------------------------------------------------- * Link Manager Module * ----------------------------------------------------------------------------- * This module allows for easy drill-down of charts by handling the link * attrribute of charts. */ (function () { // Register the module with FusionCharts. var global = FusionCharts(['private', 'api.LinkManager']); // Check whether the module has been already registered. If true, then // do not bother to re-register. if (global === undefined) { return; } // Add parameter policy to pass link information during construction of // new FusionCharts object. global.policies.link = ['link', undefined]; // Create Constants for Link InserModes var FusionChartsDOMInsertModes = window.FusionChartsDOMInsertModes = { REPLACE: 'replace', APPEND: 'append', PREPEND: 'prepend' }, // Create a collection to store configuration of every root link. store = {}, // Store root and parent reference of every element. This would allow us // to save the parent and root reference of the "link" object of every // chart. LinkInformation = function (root, parent) { this.items = {}; this.root = root; this.parent = parent; // Do initialization work in case this is the root link. We verify root // link in case parent is undefined if (parent instanceof global.core) { this.level = this.parent.link.level + 1; } else { // Parent is not an instance of FusionCharts, this implies this link is // a root link store[root.id] = [{}]; this.level = 0; } }, checkObjectRenderLocationOverride = function (obj, parent) { return (obj.options.containerElement === parent.options.containerElement || obj.options.containerElementId === parent.options.containerElementId) && obj.options.insertMode === FusionChartsDOMInsertModes.REPLACE; }; // This function would return the current configuration of the link that is // to be used for construction of a new chart. LinkInformation.prototype.configuration = function () { var param = store[this.root.id][this.level] || (store[this.root.id][this.level] = {}); // Return the parameters return param; }; // Add global link configuration API using which users will be able to set // parameters for every level of link. global.extend(global.core, { configureLink: function (param, level) { var i; // In case user provides an array of configuration, we assume that the // user wants to redefine the entire configuration train. if (param instanceof Array) { for (i = 0; i < param.length; i += 1) { // We initialize a blank configuration object for // the link configuration train, in case it is not // pre-defined. if (typeof store[this.link.root.id][i] !== 'object') { store[this.link.root.id][i] = {}; } // The configuration is one-by-one copied two the store. global.extend(store[this.link.root.id][i], param[i]); } // Delete any extra configuration. store[this.link.root.id].splice(param.length); } else if (typeof param === 'object') { // If user has sent one object, we assume he wants to configure // In case level is undefined, we need to assign the current // level of the object. if (typeof level !== 'number') { level = this.link.level; } // Create a blank parameter object in store in case it is not // defined. if (store[this.link.root.id][level] === undefined) { store[this.link.root.id][level] = {}; } // Copy all parameters passed on to the store. global.extend(store[this.link.root.id][level], param); } else { global.raiseError(this, '25081731', 'param', '~configureLink()', 'Unable to update link configuration from set parameters'); } } }, true); // Add construction routines to manage link parameters. global.addEventListener('BeforeInitialize', function (event) { // If LinkInformation is not present in the object, we can assume // that this chart is a root chart and hence we need to create // link related information. if (!(event.sender.link instanceof LinkInformation)) { event.sender.link = new LinkInformation(event.sender); } else { // In case link is predefined, we need to add the new object to the // 'items' collection of parent of the new object. // In case of root link, parent is undefined, we do not need to // add any type of item configuration. if (event.sender.link.parent instanceof global.core) { event.sender.link.parent.link.items[event.sender.id] = event.sender; } } }); // Handle the linked-chart click event. global.addEventListener('LinkedChartInvoked', function (event, args) { var obj = event.sender, param = obj.clone({ dataSource: args.data, dataFormat: args.linkType, // Create a new link between the source chart and the to-be-created // new chart. link: new LinkInformation(obj.link.root, obj) }, true), alias = args.alias; // Pass on the chart alias if passed by event. if (alias) { // In case no swf path is specifed, try to recover the same from // swfUrl. if (!param.swfSrcPath && param.swfUrl) { param.swfSrcPath = param.swfUrl .replace(/(.*?)?[^\/]*\.swf.*?/ig, '$1'); } param.type = alias; } // Delete certain default or post-render state related variables from // params. if (obj.args && parseInt(obj.args.animate, 10) !== 0) { delete param.animate; } // Update parameters by overrides set by user global.extend(param, obj.link.configuration()); // Raise event to denote event that linked chart is going to be // rendererd. global.raiseEvent('BeforeLinkedItemOpen', { level: obj.link.level }, obj.link.root); // Delete the chart with same id, if there is one. if (global.core.items[param.id] instanceof global.core) { global.core.items[param.id].dispose(); } // Create a new FusionCharts object with the construction parameters of // the above link configuration. var childObj = new global.core(param); // Check whether the overlay button text is "close" or "back" depending // upon the place of render of the chart. if (!checkObjectRenderLocationOverride(childObj, obj) && !(obj.options.overlayButton && obj.options.overlayButton.message)) { if (typeof obj.options.overlayButton !== 'object') { obj.options.overlayButton = {}; } obj.options.overlayButton.message = 'Close'; } // Render the linked chart. childObj.render(); // Raise event to denote that linked item was invoked on a chart. global.raiseEvent('LinkedItemOpened', { level: obj.link.level, item: childObj }, obj.link.root); }); /** * This method handles the routines that are performed when a linked chart * is closed. */ global.addEventListener('OverlayButtonClick', function (event, args) { // We need to verify whether this overlay button was initiated by // link-manager or not. if (args.id !== 'LinkManager') { return; } var sender = event.sender, level = sender.link.level - 1, // compute the target link level parent = sender.link.parent, root = sender.link.root; // Raise event to denote event that linked chart is going to be disposed. global.raiseEvent('BeforeLinkedItemClose', { level: level, item: sender }, root); setTimeout(function () { if (global.core.items[sender.id] ) { sender.dispose(); } // Raise event that link has been closed for a root chart. global.raiseEvent('LinkedItemClosed', { level: level }, root); }, 0); // In case link item was closed for an object whose parent is not // active, we re-render it. if (!parent.isActive() && checkObjectRenderLocationOverride(sender, parent)) { parent.render(); } }); global.addEventListener('Loaded', function (event) { var obj = event.sender; // When Chart is rendered using HTML rendering "event.sender.link" is undefined. if (!obj || obj.link === undefined) { return; } // Verify whether the loaded item is a root item or not. In case the // item is a root item, we do not need to process an overlay button. if (obj.link.root === obj || !(obj.link.parent instanceof global.core)) { return; } // Verify whether overlay button API is available if (!(obj.ref && typeof obj.ref.drawOverlayButton === 'function')) { // Warn that it could not draw overlay button. global.raiseWarning(obj, '04091602', 'run', '::LinkManager^Loaded', 'Unable to draw overlay button on object. -' + obj.id); return; } // Get configuration of overlay button var config = global.extend({ show: true, id: 'LinkManager' }, obj.link.parent.options.overlayButton); global.extend(config, obj.link.parent.link.configuration().overlayButton || {}); obj.ref.drawOverlayButton(config); }); // Add method to make sure to delete all fusioncharts objects when // dispose method is invoked. global.addEventListener('BeforeDispose', function (e) { var obj = e.sender; // Validate environment to check sender and its link exists. if (!(obj && obj.link instanceof LinkInformation)) { return; } // In case the object is not a root object, we would need to perform // additional cleanup. if (obj.link.parent instanceof global.core) { // Cleanup the reference to this object to the 'items' collection // of its parent. delete obj.link.parent.link.items[e.sender.id]; } // Remove any configuration set as root configuration delete store[obj.id]; }); FusionChartsEvents.LinkedItemOpened = 'linkeditemopened'; FusionChartsEvents.BeforeLinkedItemOpen = 'beforelinkeditemopen'; FusionChartsEvents.LinkedItemClosed = 'linkeditemclosed'; FusionChartsEvents.BeforeLinkedItemClose = 'beforelinkeditemclose'; }()); /*jslint white: true, browser: true, windows: true, forin: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, immed: true */ /*global window: false, FusionCharts: false, FusionChartsEvents: false, G_vmlCanvasManager: false */ /* ----------------------------------------------------------------------------- * Print Manager Module * ----------------------------------------------------------------------------- */ (function () { // Register the module with FusionCharts. var global = FusionCharts(['private', 'PrintManager']); // Check whether the module has been already registered. If true, then // do not bother to re-register. if (global === undefined) { return; } // Default configuration of print manager. This can be overriden using // parameter of constructor. var config = { enabled: false, invokeCSS: true, processPollInterval: 2000, message: 'Chart is being prepared for print.', useExCanvas: false, bypass: false }; // Contains all independent library functions to be used by various sections // of this code. var lib = { getCanvasElementOf: function (obj, width, height) { // Proceed with creating canvas only if it is not already created. if (obj.__fusioncharts__canvascreated !== true) { // Create <canvas> DOM element. var canvas = document.createElement('canvas'), identifier = global.core.items[obj.id].attributes['class']; // ExCanvas initialization. if (config.useExCanvas && G_vmlCanvasManager) { G_vmlCanvasManager.initElement(canvas); } // Set the class of the canvas to an identifyable value. canvas.setAttribute('class', identifier); canvas.__fusioncharts__reference = obj.id; // Insert the canvas immediately after the embed element. obj.parentNode.insertBefore(canvas, obj.nextSibling); // Mark that canvas has been created. obj.__fusioncharts__canvascreated = true; } // Set dimensions of canvas element obj.nextSibling.setAttribute('width', width || obj.offsetWidth || 2); obj.nextSibling.setAttribute('height', height || obj.offsetHeight || 2); // Return the canvas element for further manipulation. return obj.nextSibling; }, removeCanvasElementOf: function (obj) { var container = obj.ref && obj.ref.parentNode ? obj.ref.parentNode : (obj.options.containerElement || window.getElementById(obj.options.containerElementId)); if (!container) { return; } var canvasItems = container.getElementsByTagName('canvas'), l, i; for (i = 0, l = canvasItems.length; i < l; i += 1) { if (canvasItems[i].__fusioncharts__reference === obj.id) { container.removeChild(canvasItems[i]); if (obj.ref) { obj.ref.__fusioncharts__canvascreated = false; } } } }, rle2rgba: function (rle, rgba, base) { // Check if base colour has been provided. If not then set it to // white. if (typeof base !== 'string') { base = "FFFFFF"; } // Tokenize the incoming RLE stream data. var raw = rle.split(/[;,_]/), run, i, r, g, b, x = 0; // Process every token. for (i = 0; i < raw.length; i += 2) { // Replace missing colour with base colour. if (raw[i] === '') { raw[i] = base; } // Padding maximum left of the colour-data by 0. This allows // easy string manipulation from the right. raw[i] = ('000000' + raw[i]).substr(-6); // Separate the colour components and convert decimal to hex. r = parseInt('0x' + raw[i].substring(0, 2), 16); g = parseInt('0x' + raw[i].substring(2, 4), 16); b = parseInt('0x' + raw[i].substring(4, 6), 16); // Fill the run-length with the extracted rgba data. for (run = 0; run < raw[i + 1]; run += 1) { rgba[x] = r; rgba[x + 1] = g; rgba[x + 2] = b; rgba[x + 3] = 255; x += 4; } } return rgba; }, rle2array: function (rle, base) { // Check if base colour has been provided. If not then set it to // white. if (typeof base !== 'string') { base = "FFFFFF"; } // Tokenize the RLE stream. var raw = rle.split(';'), run, i; for (run in raw) { // Tokenize every run within the stream. raw[run] = raw[run].split(/[_,]/); for (i = 0; i < raw[run].length; i += 2) { // Restore RLE sub-compression losses. // As per processed value, update it with base colour or // Left-pad zero. raw[run][i] = raw[run][i] === '' ? base : ('000000' + raw[run][i]).substr(-6); } } return raw; }, drawText: function (canvas, text, width, height) { var context = canvas.getContext('2d'), w = width || 2, h = height || 2; context.clearRect(0, 0, w, h); context.textBaseline = 'middle'; context.textAlign = 'center'; context.font = '8pt verdana'; context.fillStyle = '#776666'; if (typeof context.fillText === 'function') { context.fillText(text, w / 2, h / 2); } else if (typeof context.mozDrawText === 'function') { context.translate(w / 2, h / 2); context.mozDrawText(text); } else { global.raiseWarning(global.core, '25081803', 'run', '::PrintManager>lib.drawText', 'Canvas text drawing is not supported in browser'); } return true; }, // Appends a given CSS Text to the page <head> element. appendCSS: function (css) { // Create a DOM style element and set its required attributes. var el = document.createElement('style'); el.setAttribute('type', 'text/css'); // Add the CSS passed as argument to the newly created style element. // For IE, use the 'stylesheet.cssText' property and for rest, simply // add the CSS as text to the style element. if (typeof el.styleSheet === 'undefined') { el.appendChild(document.createTextNode(css)); } else { el.styleSheet.cssText = css; } // Append the style element to DOM head and return the same. return document.getElementsByTagName('head')[0].appendChild(el); } }; lib.drawRLE = function (canvas, rle, width, height, baseColor) { // Failsafe height and width parameters width = width || 2; height = height || 2; // Adjust canvas dimension canvas.setAttribute('width', width); canvas.setAttribute('height', height); var context = canvas.getContext('2d'), imageData; // Prepare image data from rle sent from embed parameter. if (typeof context.putImageData === 'function' && typeof context.createImageData === 'function') { imageData = context.createImageData(width, height); lib.rle2rgba(rle, imageData.data, baseColor); context.putImageData(imageData, 0, 0); } else { // Fall-back drawing method imageData = lib.rle2array(rle, baseColor); var x = 0, y = 0, z = 0; for (y in imageData) { x = 0; for (z = 0; z < imageData[y].length; z += 2) { context.fillStyle = "#" + imageData[y][z]; context.fillRect(x, y, imageData[y][z + 1], 1); x += parseInt(imageData[y][z + 1], 10); } } } return true; }; // Manages the dynamically generated CSS of the page var css = { // Available library styles. styles: { print: 'canvas.FusionCharts{display:none;}@media print{object.FusionCharts{display:none;}canvas.FusionCharts{display:block;}}', error: 'canvas.FusionCharts{display:none;}', normal: '' }, // A common variable that stores a reference to the current stylesheet. cssNode: undefined }, activeItems = {}, queuedItems = {}, activeCount = 0, queueTrigger; // Define function that allows switch between stylesheets. css.invoke = function (style) { // Check whether to use one of the available library styles. if (typeof this.styles[style] !== 'undefined') { style = this.styles[style]; } // If style is not set as undefined, set the style. if (typeof style !== 'undefined') { if (this.cssNode !== undefined && this.cssNode.parentNode !== undefined) { this.cssNode.parentNode.removeChild(this.cssNode); } css.cssNode = lib.appendCSS(style); } }; var onDrawComplete = function (event) { // Get reference to the rendered object refetence var obj = event.sender.ref, w, h; // We just verify the external interface for safety sake. Though it is // very unlikely that this event will be fired with crippled EI. if (obj === undefined || typeof obj.prepareImageDataStream !== 'function' || obj.prepareImageDataStream() === false) { // Request obj to prepare image data stream or queue it up in case SWF // is busy. queueTrigger(event.sender); return; } // Add the object to te collection of active objects post successful // imagestream preparation call. if (!activeItems[event.sender.id]) { activeItems[event.sender.id] = obj; activeCount += 1; if (activeCount === 1) { global.raiseEvent('PrintReadyStateChange', { ready: false, bypass: config.bypass }, event.sender); } } // While image is being prepared, render the "waiting" message. try { w = obj.offsetWidth; h = obj.offsetHeight; lib.drawText(lib.getCanvasElementOf(obj, w, h), config.message, w, h); } catch (e) { // In case of error, remove the CSS so that the SWF is still // printable. css.invoke('error'); // invoke the css that hides canvas global.raiseError(event.sender, '25081807', 'run', '::PrintManager>onDrawComplete', 'There was an error while showing message to user via canvas.'); } }, onImageStreamReady = function (event, args) { try { if (lib.drawRLE(lib.getCanvasElementOf(event.sender.ref, args.width, args.height), args.stream, args.width, args.height, args.bgColor) === true) { // On successful canvas rendering, remove the item from active // item collection. if (activeItems[event.sender.id]) { delete activeItems[event.sender.id]; activeCount -= 1; if (activeCount === 0) { global.raiseEvent('PrintReadyStateChange', { ready: true, bypass: config.bypass }, event.sender); } } } } catch (e) { // In case of error, remove the CSS so that the SWF is still // printable. css.invoke('error'); // invoke the css that hides canvas global.raiseError(event.sender, '25081810', 'run', '::PrintManager>onImageStreamReady', 'There was an error while drawing canvas.'); } }, // Method to remove canvas and other print manager stuffs when an object is // disposed. onBeforeDispose = function (event) { lib.removeCanvasElementOf(event.sender); }, subscribeToEvents = function (state) { var eventAction = state ? 'addEventListener' : 'removeEventListener'; // Apply the event listener states to the eventHandlers. global.core[eventAction]('ImageStreamReady', onImageStreamReady); global.core[eventAction]('DrawComplete', onDrawComplete); global.core[eventAction]('BeforeDispose', onBeforeDispose); }, initialize = function () { var item; if (config.invokeCSS === true) { css.invoke('print'); } // Iterate through all FusionCharts object reference and // do a fake call to onDrawComplete event for (item in global.core.items) { queueTrigger(global.core.items[item]); queueTrigger(); } }, destroy = function () { var item; // Hide any of the canvas element in case user disables // print manager. css.invoke('error'); // Iterate through all FusionCharts object reference and remove // their canvases if present. for (item in global.core.items) { lib.removeCanvasElementOf(global.core.items[item]); } if (!config.bypass) { global.raiseEvent('PrintReadyStateChange', { ready: false, bypass: config.bypass }); } // Finally remove all traces of CSS css.invoke('normal'); }; queueTrigger = function (obj) { var item; // In case the first argument is not undefined, it implies that an item // is to be queued up if (obj instanceof global.core) { queuedItems[obj.id] = obj; return; } // Proceed with processing the queue for (item in queuedItems) { onDrawComplete({ sender: queuedItems[item] }, {}); delete queuedItems[item]; } }; global.extend(global.core, { printManager: { // This method allows users to confiure and reconfigure the // configuration of this script. configure: function (configuration) { global.extend(config, configuration || {}); }, isReady: function () { // In case the printManager is bypassed, we always say that it // is ready. This keeps dependent scripts not to fail. if (config.bypass) { return true; } // Check if there is any active job or not and whether printManager // is disabled. In either case, it is not ready. if (activeCount > 0 || !config.enabled) { return false; } var item, ref; // Check each element to see whether it is rendered. In // case they are rendered, and there is no active jobs (as // checked earlier), it implies that all items are successfully // rendered. for (item in global.core.items) { if ((ref = global.core.items[item].ref) !== undefined && ref.hasRendered && ref.hasRendered() === false) { return false; } } return true; }, // Enable or disable canvas print manager. In case browser is not // supported, do not allow to enable enabled: function (state) { // If no parameter is passed, it is assumed that user simply // needs the current status. So we return the current status. if (state === undefined) { return config.enabled; } // Check browser capability to fulfill minimum requirements for // this script. Do not proceed if browser is IE if ('\v' === 'v' || global.renderer.currentRendererName() !== 'flash' || typeof document.createElement('canvas').getContext !== 'function') { config.bypass = true; global.raiseEvent('PrintReadyStateChange', { ready: true, bypass: config.bypass }); global.raiseWarning(global.core, '25081816', 'run', '.printManager.enabled', 'printManager is not compatible with your browser'); return config.enabled; } config.bypass = false; // Apply the event listener states to the eventHandlers. subscribeToEvents(state); // Perform initialization or cleanup depending upon the state. if (state === true) { initialize(); } else { destroy(); } // Return the updated state value. return (config.enabled = state); }, managedPrint: function (eventArg) { // In case printManager is bypassed due to some reason, we directly // invoke the print function of browser. if (config.bypass) { window.print(); return; } // In case managedPrint is called and PrintManager is not enabled, // we enable it and then wait to raise windows print function // as printreadystatechange returns true. if (!global.core.printManager.isReady()) { // Enable Print Manager if (global.core.printManager.enabled(true) !== true) { // If enabling fails, then just invoke a print. window.print(); return; } // Subscribe to the print ready state change event global.addEventListener('PrintReadyStateChange', global.core.printManager.managedPrint); return; } // In case this function is invoked by event-handler, I check // when active is marked as true. if (typeof eventArg === 'object' && eventArg.ready !== true) { return; } // Remove the event that watches completion of canvas image creation global.removeEventListener('PrintReadyStateChange', global.core.printManager.managedPrint); // Execute Printing. window.print(); } } }, false); // Add the event names that this module raises to the events collection. FusionChartsEvents.PrintReadyStateChange = 'printreadystatechange'; }());
/** * @license jqGrid French Translation * Tony Tomov tony@trirand.com with changes by Laurent Rajchenbach. * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ /*jslint white: true */ /*global jQuery */ (function (factory) { "use strict"; if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery"], factory); } else if (typeof exports === "object") { // Node/CommonJS factory(require("jquery")); } else { // Browser globals factory(jQuery); } }(function ($) { "use strict"; var locInfo = { isRTL: false, defaults: { recordtext: "Enregistrements {0} - {1} sur {2}", emptyrecords: "Aucun enregistrement à afficher", loadtext: "Chargement...", pgtext: "Page {0} sur {1}", pgfirst: "Première Page", pglast: "Dernière Page", pgnext: "Page Suivante", pgprev: "Page Précédente", pgrecs: "Enregistrements par page", showhide: "Afficher/Masquer le tableau", savetext: "Enregistrement..." }, search: { caption: "Recherche...", Find: "Chercher", Reset: "Réinitialiser", odata: [ { oper: "eq", text: "égal" }, { oper: "ne", text: "différent" }, { oper: "lt", text: "inférieur" }, { oper: "le", text: "inférieur ou égal" }, { oper: "gt", text: "supérieur" }, { oper: "ge", text: "supérieur ou égal" }, { oper: "bw", text: "commence par" }, { oper: "bn", text: "ne commence pas par" }, { oper: "in", text: "est dans" }, { oper: "ni", text: "n'est pas dans" }, { oper: "ew", text: "finit par" }, { oper: "en", text: "ne finit pas par" }, { oper: "cn", text: "contient" }, { oper: "nc", text: "ne contient pas" }, { oper: "nu", text: "est null" }, { oper: "nn", text: "n'est pas null" } ], groupOps: [ { op: "AND", text: "tous" }, { op: "OR", text: "au moins un" } ], addGroupTitle: "Add subgroup", deleteGroupTitle: "Delete group", addRuleTitle: "Add rule", deleteRuleTitle: "Delete rule", operandTitle: "Cliquer pour sélectionner l'opérateur de recherche.", resetTitle: "Vider la valeur de recherche" }, edit: { addCaption: "Ajouter", editCaption: "Editer", bSubmit: "Valider", bCancel: "Annuler", bClose: "Fermer", saveData: "Les données ont changé ! Enregistrer les modifications ?", bYes: "Oui", bNo: "Non", bExit: "Annuler", msg: { required: "Champ obligatoire", number: "Saisissez un nombre correct", minValue: "La valeur doit être supérieure ou égale à", maxValue: "La valeur doit être inférieure ou égale à", email: "n'est pas un email correct", integer: "Saisissez un entier correct", url: "n'est pas une adresse correcte. Préfixe requis ('http://' or 'https://')", nodefined: " n'est pas défini!", novalue: " la valeur de retour est requise!", customarray: "Une fonction personnalisée devrait retourner un tableau (array)!", customfcheck: "Une fonction personnalisée devrait être présente dans le cas d'une vérification personnalisée!" } }, view: { caption: "Voir les enregistrement", bClose: "Fermer" }, del: { caption: "Supprimer", msg: "Supprimer les enregistrements sélectionnés ?", bSubmit: "Supprimer", bCancel: "Annuler" }, nav: { edittext: "", edittitle: "Editer la ligne sélectionnée", addtext: "", addtitle: "Ajouter une ligne", deltext: "", deltitle: "Supprimer la ligne sélectionnée", searchtext: "", searchtitle: "Chercher un enregistrement", refreshtext: "", refreshtitle: "Recharger le tableau", alertcap: "Avertissement", alerttext: "Veuillez sélectionner une ligne", viewtext: "", viewtitle: "Afficher la ligne sélectionnée", savetext: "", savetitle: "Save row", canceltext: "", canceltitle: "Cancel row editing" }, col: { caption: "Afficher/Masquer les colonnes", bSubmit: "Valider", bCancel: "Annuler" }, errors: { errcap: "Erreur", nourl: "Aucune adresse n'est paramétrée", norecords: "Aucun enregistrement à traiter", model: "Nombre de titres (colNames) <> Nombre de données (colModel)!" }, formatter: { integer: { thousandsSeparator: " ", defaultValue: "0" }, number: { decimalSeparator: ",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: "0,00" }, currency: { decimalSeparator: ",", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix: "", defaultValue: "0,00" }, date: { dayNames: [ "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi" ], monthNames: [ "Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc", "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aout", "Septembre", "Octobre", "Novembre", "Décembre" ], AmPm: ["am", "pm", "AM", "PM"], S: function (j) { return j === 1 ? "er" : "e"; }, srcformat: "Y-m-d", newformat: "d/m/Y", masks: { ShortDate: "j/n/Y", LongDate: "l j n F Y", FullDateTime: "l j n F Y H:i:s", MonthDay: "j F", ShortTime: "H:i", LongTime: "H:i:s", YearMonth: "F Y" } } } }; $.jgrid = $.jgrid || {}; $.extend(true, $.jgrid, { defaults: { locale: "fr-FR" }, locales: { // In general the property name is free, but it's recommended to use the names based on // http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // http://rishida.net/utils/subtags/ and RFC 5646. See Appendix A of RFC 5646 for examples. // One can use the lang attribute to specify language tags in HTML, and the xml:lang attribute for XML // if it exists. See http://www.w3.org/International/articles/language-tags/#extlang fr: $.extend({}, locInfo, { name: "français", nameEnglish: "French" }), "fr-FR": $.extend({}, locInfo, { name: "français (France)", nameEnglish: "French (France)" }) } }); }));
/** * Copyright (c) 2014, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; import type {Path} from 'types/Config'; import type {ModuleMap} from 'jest-haste-map'; const nodeModulesPaths = require('resolve/lib/node-modules-paths'); const path = require('path'); const resolve = require('resolve'); const browserResolve = require('browser-resolve'); type ResolverConfig = {| browser?: boolean, defaultPlatform: ?string, extensions: Array<string>, hasCoreModules: boolean, moduleDirectories: Array<string>, moduleNameMapper: ?{[key: string]: RegExp}, modulePaths: Array<Path>, platforms?: Array<string>, |}; type FindNodeModuleConfig = {| basedir: Path, browser?: boolean, extensions: Array<string>, moduleDirectory: Array<string>, paths?: Array<Path>, |}; export type ResolveModuleConfig = {| skipNodeResolution?: boolean, |}; const NATIVE_PLATFORM = 'native'; const nodePaths = (process.env.NODE_PATH ? process.env.NODE_PATH.split(path.delimiter) : null); class Resolver { _options: ResolverConfig; _moduleMap: ModuleMap; _moduleNameCache: {[name: string]: Path}; _modulePathCache: {[path: Path]: Array<Path>}; constructor(moduleMap: ModuleMap, options: ResolverConfig) { this._options = { browser: options.browser, defaultPlatform: options.defaultPlatform, extensions: options.extensions, hasCoreModules: options.hasCoreModules === undefined ? true : options.hasCoreModules, moduleDirectories: options.moduleDirectories || ['node_modules'], moduleNameMapper: options.moduleNameMapper, modulePaths: options.modulePaths, platforms: options.platforms, }; this._moduleMap = moduleMap; this._moduleNameCache = Object.create(null); this._modulePathCache = Object.create(null); } static findNodeModule(path: Path, options: FindNodeModuleConfig): ?Path { const paths = options.paths; try { const resv = options.browser ? browserResolve : resolve; return resv.sync( path, { basedir: options.basedir, extensions: options.extensions, moduleDirectory: options.moduleDirectory, paths: paths ? (nodePaths || []).concat(paths) : nodePaths, }, ); } catch (e) {} return null; } resolveModule( from: Path, moduleName: string, options?: ResolveModuleConfig, ): Path { const dirname = path.dirname(from); const paths = this._options.modulePaths; const moduleDirectory = this._options.moduleDirectories; const key = dirname + path.delimiter + moduleName; const defaultPlatform = this._options.defaultPlatform; let exts = ['.' + NATIVE_PLATFORM + '.js'].concat( this._options.extensions || [], ); if (defaultPlatform) { exts = ['.' + defaultPlatform + '.js'].concat(exts); } // 0. If we have already resolved this module for this directory name, // return a value from the cache. if (this._moduleNameCache[key]) { return this._moduleNameCache[key]; } // 1. Check if the module is a haste module. let module = this.getModule(moduleName); if (module) { return this._moduleNameCache[key] = module; } // 2. Check if the module is a node module and resolve it based on // the node module resolution algorithm. if (!options || !options.skipNodeResolution) { module = Resolver.findNodeModule(moduleName, { basedir: dirname, browser: this._options.browser, extensions: exts, moduleDirectory, paths, }); if (module) { return this._moduleNameCache[key] = module; } } // 3. Resolve "haste packages" which are `package.json` files outside of // `node_modules` folders anywhere in the file system. const parts = moduleName.split('/'); module = this.getPackage(parts.shift()); if (module) { try { return this._moduleNameCache[key] = require.resolve( path.join.apply(path, [path.dirname(module)].concat(parts)), ); } catch (ignoredError) {} } // 4. Throw an error if the module could not be found. `resolve.sync` // only produces an error based on the dirname but we have the actual // current module name available. const relativePath = path.relative(dirname, from); const err = new Error( `Cannot find module '${moduleName}' from '${relativePath || '.'}'`, ); (err: any).code = 'MODULE_NOT_FOUND'; throw err; } isCoreModule(moduleName: string): boolean { return this._options.hasCoreModules && resolve.isCore(moduleName); } getModule(name: string): ?Path { return this._moduleMap.getModule( name, this._options.defaultPlatform, this._supportsNativePlatform(), ); } getPackage(name: string): ?Path { return this._moduleMap.getPackage( name, this._options.defaultPlatform, this._supportsNativePlatform(), ); } getMockModule(from: Path, name: string): ?Path { const mock = this._moduleMap.getMockModule(name); if (mock) { return mock; } else { const moduleName = this._resolveStubModuleName(from, name); if (moduleName) { return this.getModule(moduleName) || moduleName; } } return null; } getModulePaths(from: Path): Array<Path> { if (!this._modulePathCache[from]) { const moduleDirectory = this._options.moduleDirectories; const paths = nodeModulesPaths(from, {moduleDirectory}); if (paths[paths.length - 1] === undefined) { // circumvent node-resolve bug that adds `undefined` as last item. paths.pop(); } this._modulePathCache[from] = paths; } return this._modulePathCache[from]; } _resolveStubModuleName(from: Path, moduleName: string): ?Path { const dirname = path.dirname(from); const paths = this._options.modulePaths; const extensions = this._options.extensions; const moduleDirectory = this._options.moduleDirectories; const moduleNameMapper = this._options.moduleNameMapper; if (moduleNameMapper) { for (const mappedModuleName in moduleNameMapper) { const regex = moduleNameMapper[mappedModuleName]; if (regex.test(moduleName)) { const matches = moduleName.match(regex); if (!matches) { moduleName = mappedModuleName; } else { moduleName = mappedModuleName.replace( /\$([0-9]+)/g, (_, index) => matches[parseInt(index, 10)], ); } return this.getModule(moduleName) || Resolver.findNodeModule( moduleName, { basedir: dirname, browser: this._options.browser, extensions, moduleDirectory, paths, }, ); } } } return null; } _supportsNativePlatform() { return (this._options.platforms || []).indexOf(NATIVE_PLATFORM) !== -1; } } module.exports = Resolver;
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; function main(autoDelete, deviceName, instance, project, zone) { // [START compute_v1_generated_Instances_SetDiskAutoDelete_async] /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Whether to auto-delete the disk when the instance is deleted. */ // const autoDelete = true /** * The device name of the disk to modify. Make a get() request on the instance to view currently attached disks and device names. */ // const deviceName = 'abc123' /** * The instance name for this request. */ // const instance = 'abc123' /** * Project ID for this request. */ // const project = 'my-project' /** * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). */ // const requestId = 'abc123' /** * The name of the zone for this request. */ // const zone = 'abc123' // Imports the Compute library const {InstancesClient} = require('@google-cloud/compute').v1; // Instantiates a client const computeClient = new InstancesClient(); async function callSetDiskAutoDelete() { // Construct request const request = { autoDelete, deviceName, instance, project, zone, }; // Run request const response = await computeClient.setDiskAutoDelete(request); console.log(response); } callSetDiskAutoDelete(); // [END compute_v1_generated_Instances_SetDiskAutoDelete_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
require('./lib/WebAudioRecorder'); require('./lib/WebAudioRecorderMp3'); require('./lib/WebAudioRecorderOgg'); require('./lib/WebAudioRecorderWav'); require('./lib/Mp3LameEncoder.min'); require('./lib/OggVorbisEncoder.min'); require('./lib/WavAudioEncoder.min'); module.exports = 'WebAudioRecorder';
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _utils = require("./utils"); var _errors = require("@ledgerhq/errors"); var _bignumber = require("bignumber.js"); var _rlp = require("rlp"); /******************************************************************************** * Ledger Node JS API * (c) 2016-2017 Ledger * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ // FIXME drop: const starkQuantizationTypeMap = { eth: 1, erc20: 2, erc721: 3, erc20mintable: 4, erc721mintable: 5 }; function hexBuffer(str) { return Buffer.from(str.startsWith("0x") ? str.slice(2) : str, "hex"); } function maybeHexBuffer(str) { if (!str) return null; return hexBuffer(str); } const remapTransactionRelatedErrors = e => { if (e && e.statusCode === 0x6a80) { return new _errors.EthAppPleaseEnableContractData("Please enable Contract data on the Ethereum app Settings"); } return e; }; /** * Ethereum API * * @example * import Eth from "@ledgerhq/hw-app-eth"; * const eth = new Eth(transport) */ class Eth { constructor(transport, scrambleKey = "w0w") { this.transport = void 0; this.transport = transport; transport.decorateAppAPIMethods(this, ["getAddress", "provideERC20TokenInformation", "signTransaction", "signPersonalMessage", "getAppConfiguration", "signEIP712HashedMessage", "starkGetPublicKey", "starkSignOrder", "starkSignOrder_v2", "starkSignTransfer", "starkSignTransfer_v2", "starkProvideQuantum", "starkProvideQuantum_v2", "starkUnsafeSign", "eth2GetPublicKey", "eth2SetWithdrawalIndex"], scrambleKey); } /** * get Ethereum address for a given BIP 32 path. * @param path a path in BIP 32 format * @option boolDisplay optionally enable or not the display * @option boolChaincode optionally enable or not the chaincode request * @return an object with a publicKey, address and (optionally) chainCode * @example * eth.getAddress("44'/60'/0'/0/0").then(o => o.address) */ getAddress(path, boolDisplay, boolChaincode) { let paths = (0, _utils.splitPath)(path); let buffer = Buffer.alloc(1 + paths.length * 4); buffer[0] = paths.length; paths.forEach((element, index) => { buffer.writeUInt32BE(element, 1 + 4 * index); }); return this.transport.send(0xe0, 0x02, boolDisplay ? 0x01 : 0x00, boolChaincode ? 0x01 : 0x00, buffer).then(response => { let result = {}; let publicKeyLength = response[0]; let addressLength = response[1 + publicKeyLength]; result.publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); result.address = "0x" + response.slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength).toString("ascii"); if (boolChaincode) { result.chainCode = response.slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32).toString("hex"); } return result; }); } /** * This commands provides a trusted description of an ERC 20 token * to associate a contract address with a ticker and number of decimals. * * It shall be run immediately before performing a transaction involving a contract * calling this contract address to display the proper token information to the user if necessary. * * @param {*} info: a blob from "erc20.js" utilities that contains all token information. * * @example * import { byContractAddress } from "@ledgerhq/hw-app-eth/erc20" * const zrxInfo = byContractAddress("0xe41d2489571d322189246dafa5ebde1f4699f498") * if (zrxInfo) await appEth.provideERC20TokenInformation(zrxInfo) * const signed = await appEth.signTransaction(path, rawTxHex) */ provideERC20TokenInformation({ data }) { return this.transport.send(0xe0, 0x0a, 0x00, 0x00, data).then(() => true, e => { if (e && e.statusCode === 0x6d00) { // this case happen for older version of ETH app, since older app version had the ERC20 data hardcoded, it's fine to assume it worked. // we return a flag to know if the call was effective or not return false; } throw e; }); } /** * You can sign a transaction and retrieve v, r, s given the raw transaction and the BIP 32 path of the account to sign * @example eth.signTransaction("44'/60'/0'/0/0", "e8018504e3b292008252089428ee52a8f3d6e5d15f8b131996950d7f296c7952872bd72a2487400080").then(result => ...) */ signTransaction(path, rawTxHex) { let paths = (0, _utils.splitPath)(path); let offset = 0; let rawTx = Buffer.from(rawTxHex, "hex"); let toSend = []; let response; // Check if the TX is encoded following EIP 155 let rlpTx = (0, _rlp.decode)(rawTx); let rlpOffset = 0; let chainIdPrefix = ""; if (rlpTx.length > 6) { let rlpVrs = (0, _rlp.encode)(rlpTx.slice(-3)); rlpOffset = rawTx.length - (rlpVrs.length - 1); const chainIdSrc = rlpTx[6]; const chainIdBuf = Buffer.alloc(4); chainIdSrc.copy(chainIdBuf, 4 - chainIdSrc.length); chainIdPrefix = (chainIdBuf.readUInt32BE(0) * 2 + 35).toString(16).slice(0, -2); // Drop the low byte, that comes from the ledger. if (chainIdPrefix.length % 2 === 1) { chainIdPrefix = "0" + chainIdPrefix; } } while (offset !== rawTx.length) { let maxChunkSize = offset === 0 ? 150 - 1 - paths.length * 4 : 150; let chunkSize = offset + maxChunkSize > rawTx.length ? rawTx.length - offset : maxChunkSize; if (rlpOffset != 0 && offset + chunkSize == rlpOffset) { // Make sure that the chunk doesn't end right on the EIP 155 marker if set chunkSize--; } let buffer = Buffer.alloc(offset === 0 ? 1 + paths.length * 4 + chunkSize : chunkSize); if (offset === 0) { buffer[0] = paths.length; paths.forEach((element, index) => { buffer.writeUInt32BE(element, 1 + 4 * index); }); rawTx.copy(buffer, 1 + 4 * paths.length, offset, offset + chunkSize); } else { rawTx.copy(buffer, 0, offset, offset + chunkSize); } toSend.push(buffer); offset += chunkSize; } return (0, _utils.foreach)(toSend, (data, i) => this.transport.send(0xe0, 0x04, i === 0 ? 0x00 : 0x80, 0x00, data).then(apduResponse => { response = apduResponse; })).then(() => { const v = chainIdPrefix + response.slice(0, 1).toString("hex"); const r = response.slice(1, 1 + 32).toString("hex"); const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex"); return { v, r, s }; }, e => { throw remapTransactionRelatedErrors(e); }); } /** */ getAppConfiguration() { return this.transport.send(0xe0, 0x06, 0x00, 0x00).then(response => { let result = {}; result.arbitraryDataEnabled = response[0] & 0x01; result.erc20ProvisioningNecessary = response[0] & 0x02; result.starkEnabled = response[0] & 0x04; result.starkv2Supported = response[0] & 0x08; result.version = "" + response[1] + "." + response[2] + "." + response[3]; return result; }); } /** * You can sign a message according to eth_sign RPC call and retrieve v, r, s given the message and the BIP 32 path of the account to sign. * @example eth.signPersonalMessage("44'/60'/0'/0/0", Buffer.from("test").toString("hex")).then(result => { var v = result['v'] - 27; v = v.toString(16); if (v.length < 2) { v = "0" + v; } console.log("Signature 0x" + result['r'] + result['s'] + v); }) */ signPersonalMessage(path, messageHex) { let paths = (0, _utils.splitPath)(path); let offset = 0; let message = Buffer.from(messageHex, "hex"); let toSend = []; let response; while (offset !== message.length) { let maxChunkSize = offset === 0 ? 150 - 1 - paths.length * 4 - 4 : 150; let chunkSize = offset + maxChunkSize > message.length ? message.length - offset : maxChunkSize; let buffer = Buffer.alloc(offset === 0 ? 1 + paths.length * 4 + 4 + chunkSize : chunkSize); if (offset === 0) { buffer[0] = paths.length; paths.forEach((element, index) => { buffer.writeUInt32BE(element, 1 + 4 * index); }); buffer.writeUInt32BE(message.length, 1 + 4 * paths.length); message.copy(buffer, 1 + 4 * paths.length + 4, offset, offset + chunkSize); } else { message.copy(buffer, 0, offset, offset + chunkSize); } toSend.push(buffer); offset += chunkSize; } return (0, _utils.foreach)(toSend, (data, i) => this.transport.send(0xe0, 0x08, i === 0 ? 0x00 : 0x80, 0x00, data).then(apduResponse => { response = apduResponse; })).then(() => { const v = response[0]; const r = response.slice(1, 1 + 32).toString("hex"); const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex"); return { v, r, s }; }); } /** * Sign a prepared message following web3.eth.signTypedData specification. The host computes the domain separator and hashStruct(message) * @example eth.signEIP712HashedMessage("44'/60'/0'/0/0", Buffer.from("0101010101010101010101010101010101010101010101010101010101010101").toString("hex"), Buffer.from("0202020202020202020202020202020202020202020202020202020202020202").toString("hex")).then(result => { var v = result['v'] - 27; v = v.toString(16); if (v.length < 2) { v = "0" + v; } console.log("Signature 0x" + result['r'] + result['s'] + v); }) */ signEIP712HashedMessage(path, domainSeparatorHex, hashStructMessageHex) { const domainSeparator = hexBuffer(domainSeparatorHex); const hashStruct = hexBuffer(hashStructMessageHex); let paths = (0, _utils.splitPath)(path); let buffer = Buffer.alloc(1 + paths.length * 4 + 32 + 32, 0); let offset = 0; buffer[0] = paths.length; paths.forEach((element, index) => { buffer.writeUInt32BE(element, 1 + 4 * index); }); offset = 1 + 4 * paths.length; domainSeparator.copy(buffer, offset); offset += 32; hashStruct.copy(buffer, offset); return this.transport.send(0xe0, 0x0c, 0x00, 0x00, buffer).then(response => { const v = response[0]; const r = response.slice(1, 1 + 32).toString("hex"); const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex"); return { v, r, s }; }); } /** * get Stark public key for a given BIP 32 path. * @param path a path in BIP 32 format * @option boolDisplay optionally enable or not the display * @return the Stark public key */ starkGetPublicKey(path, boolDisplay) { let paths = (0, _utils.splitPath)(path); let buffer = Buffer.alloc(1 + paths.length * 4); buffer[0] = paths.length; paths.forEach((element, index) => { buffer.writeUInt32BE(element, 1 + 4 * index); }); return this.transport.send(0xf0, 0x02, boolDisplay ? 0x01 : 0x00, 0x00, buffer).then(response => { return response.slice(0, response.length - 2); }); } /** * sign a Stark order * @param path a path in BIP 32 format * @option sourceTokenAddress contract address of the source token (not present for ETH) * @param sourceQuantization quantization used for the source token * @option destinationTokenAddress contract address of the destination token (not present for ETH) * @param destinationQuantization quantization used for the destination token * @param sourceVault ID of the source vault * @param destinationVault ID of the destination vault * @param amountSell amount to sell * @param amountBuy amount to buy * @param nonce transaction nonce * @param timestamp transaction validity timestamp * @return the signature */ starkSignOrder(path, sourceTokenAddress, sourceQuantization, destinationTokenAddress, destinationQuantization, sourceVault, destinationVault, amountSell, amountBuy, nonce, timestamp) { const sourceTokenAddressHex = maybeHexBuffer(sourceTokenAddress); const destinationTokenAddressHex = maybeHexBuffer(destinationTokenAddress); let paths = (0, _utils.splitPath)(path); let buffer = Buffer.alloc(1 + paths.length * 4 + 20 + 32 + 20 + 32 + 4 + 4 + 8 + 8 + 4 + 4, 0); let offset = 0; buffer[0] = paths.length; paths.forEach((element, index) => { buffer.writeUInt32BE(element, 1 + 4 * index); }); offset = 1 + 4 * paths.length; if (sourceTokenAddressHex) { sourceTokenAddressHex.copy(buffer, offset); } offset += 20; Buffer.from(sourceQuantization.toString(16).padStart(64, "0"), "hex").copy(buffer, offset); offset += 32; if (destinationTokenAddressHex) { destinationTokenAddressHex.copy(buffer, offset); } offset += 20; Buffer.from(destinationQuantization.toString(16).padStart(64, "0"), "hex").copy(buffer, offset); offset += 32; buffer.writeUInt32BE(sourceVault, offset); offset += 4; buffer.writeUInt32BE(destinationVault, offset); offset += 4; Buffer.from(amountSell.toString(16).padStart(16, "0"), "hex").copy(buffer, offset); offset += 8; Buffer.from(amountBuy.toString(16).padStart(16, "0"), "hex").copy(buffer, offset); offset += 8; buffer.writeUInt32BE(nonce, offset); offset += 4; buffer.writeUInt32BE(timestamp, offset); return this.transport.send(0xf0, 0x04, 0x01, 0x00, buffer).then(response => { const r = response.slice(1, 1 + 32).toString("hex"); const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex"); return { r, s }; }); } /** * sign a Stark order using the Starkex V2 protocol * @param path a path in BIP 32 format * @option sourceTokenAddress contract address of the source token (not present for ETH) * @param sourceQuantizationType quantization type used for the source token * @option sourceQuantization quantization used for the source token (not present for erc 721 or mintable erc 721) * @option sourceMintableBlobOrTokenId mintable blob (mintable erc 20 / mintable erc 721) or token id (erc 721) associated to the source token * @option destinationTokenAddress contract address of the destination token (not present for ETH) * @param destinationQuantizationType quantization type used for the destination token * @option destinationQuantization quantization used for the destination token (not present for erc 721 or mintable erc 721) * @option destinationMintableBlobOrTokenId mintable blob (mintable erc 20 / mintable erc 721) or token id (erc 721) associated to the destination token * @param sourceVault ID of the source vault * @param destinationVault ID of the destination vault * @param amountSell amount to sell * @param amountBuy amount to buy * @param nonce transaction nonce * @param timestamp transaction validity timestamp * @return the signature */ starkSignOrder_v2(path, sourceTokenAddress, sourceQuantizationType, sourceQuantization, sourceMintableBlobOrTokenId, destinationTokenAddress, destinationQuantizationType, destinationQuantization, destinationMintableBlobOrTokenId, sourceVault, destinationVault, amountSell, amountBuy, nonce, timestamp) { const sourceTokenAddressHex = maybeHexBuffer(sourceTokenAddress); const destinationTokenAddressHex = maybeHexBuffer(destinationTokenAddress); if (!(sourceQuantizationType in starkQuantizationTypeMap)) { throw new Error("eth.starkSignOrderv2 invalid source quantization type=" + sourceQuantizationType); } if (!(destinationQuantizationType in starkQuantizationTypeMap)) { throw new Error("eth.starkSignOrderv2 invalid destination quantization type=" + destinationQuantizationType); } let paths = (0, _utils.splitPath)(path); let buffer = Buffer.alloc(1 + paths.length * 4 + 1 + 20 + 32 + 32 + 1 + 20 + 32 + 32 + 4 + 4 + 8 + 8 + 4 + 4, 0); let offset = 0; buffer[0] = paths.length; paths.forEach((element, index) => { buffer.writeUInt32BE(element, 1 + 4 * index); }); offset = 1 + 4 * paths.length; buffer[offset] = starkQuantizationTypeMap[sourceQuantizationType]; offset++; if (sourceTokenAddressHex) { sourceTokenAddressHex.copy(buffer, offset); } offset += 20; if (sourceQuantization) { Buffer.from(sourceQuantization.toString(16).padStart(64, "0"), "hex").copy(buffer, offset); } offset += 32; if (sourceMintableBlobOrTokenId) { Buffer.from(sourceMintableBlobOrTokenId.toString(16).padStart(64, "0"), "hex").copy(buffer, offset); } offset += 32; buffer[offset] = starkQuantizationTypeMap[destinationQuantizationType]; offset++; if (destinationTokenAddressHex) { destinationTokenAddressHex.copy(buffer, offset); } offset += 20; if (destinationQuantization) { Buffer.from(destinationQuantization.toString(16).padStart(64, "0"), "hex").copy(buffer, offset); } offset += 32; if (destinationMintableBlobOrTokenId) { Buffer.from(destinationMintableBlobOrTokenId.toString(16).padStart(64, "0"), "hex").copy(buffer, offset); } offset += 32; buffer.writeUInt32BE(sourceVault, offset); offset += 4; buffer.writeUInt32BE(destinationVault, offset); offset += 4; Buffer.from(amountSell.toString(16).padStart(16, "0"), "hex").copy(buffer, offset); offset += 8; Buffer.from(amountBuy.toString(16).padStart(16, "0"), "hex").copy(buffer, offset); offset += 8; buffer.writeUInt32BE(nonce, offset); offset += 4; buffer.writeUInt32BE(timestamp, offset); return this.transport.send(0xf0, 0x04, 0x03, 0x00, buffer).then(response => { const r = response.slice(1, 1 + 32).toString("hex"); const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex"); return { r, s }; }); } /** * sign a Stark transfer * @param path a path in BIP 32 format * @option transferTokenAddress contract address of the token to be transferred (not present for ETH) * @param transferQuantization quantization used for the token to be transferred * @param targetPublicKey target Stark public key * @param sourceVault ID of the source vault * @param destinationVault ID of the destination vault * @param amountTransfer amount to transfer * @param nonce transaction nonce * @param timestamp transaction validity timestamp * @return the signature */ starkSignTransfer(path, transferTokenAddress, transferQuantization, targetPublicKey, sourceVault, destinationVault, amountTransfer, nonce, timestamp) { const transferTokenAddressHex = maybeHexBuffer(transferTokenAddress); const targetPublicKeyHex = hexBuffer(targetPublicKey); let paths = (0, _utils.splitPath)(path); let buffer = Buffer.alloc(1 + paths.length * 4 + 20 + 32 + 32 + 4 + 4 + 8 + 4 + 4, 0); let offset = 0; buffer[0] = paths.length; paths.forEach((element, index) => { buffer.writeUInt32BE(element, 1 + 4 * index); }); offset = 1 + 4 * paths.length; if (transferTokenAddressHex) { transferTokenAddressHex.copy(buffer, offset); } offset += 20; Buffer.from(transferQuantization.toString(16).padStart(64, "0"), "hex").copy(buffer, offset); offset += 32; targetPublicKeyHex.copy(buffer, offset); offset += 32; buffer.writeUInt32BE(sourceVault, offset); offset += 4; buffer.writeUInt32BE(destinationVault, offset); offset += 4; Buffer.from(amountTransfer.toString(16).padStart(16, "0"), "hex").copy(buffer, offset); offset += 8; buffer.writeUInt32BE(nonce, offset); offset += 4; buffer.writeUInt32BE(timestamp, offset); return this.transport.send(0xf0, 0x04, 0x02, 0x00, buffer).then(response => { const r = response.slice(1, 1 + 32).toString("hex"); const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex"); return { r, s }; }); } /** * sign a Stark transfer or conditional transfer using the Starkex V2 protocol * @param path a path in BIP 32 format * @option transferTokenAddress contract address of the token to be transferred (not present for ETH) * @param transferQuantizationType quantization type used for the token to be transferred * @option transferQuantization quantization used for the token to be transferred (not present for erc 721 or mintable erc 721) * @option transferMintableBlobOrTokenId mintable blob (mintable erc 20 / mintable erc 721) or token id (erc 721) associated to the token to be transferred * @param targetPublicKey target Stark public key * @param sourceVault ID of the source vault * @param destinationVault ID of the destination vault * @param amountTransfer amount to transfer * @param nonce transaction nonce * @param timestamp transaction validity timestamp * @option conditionalTransferAddress onchain address of the condition for a conditional transfer * @option conditionalTransferFact fact associated to the condition for a conditional transfer * @return the signature */ starkSignTransfer_v2(path, transferTokenAddress, transferQuantizationType, transferQuantization, transferMintableBlobOrTokenId, targetPublicKey, sourceVault, destinationVault, amountTransfer, nonce, timestamp, conditionalTransferAddress, conditionalTransferFact) { const transferTokenAddressHex = maybeHexBuffer(transferTokenAddress); const targetPublicKeyHex = hexBuffer(targetPublicKey); const conditionalTransferAddressHex = maybeHexBuffer(conditionalTransferAddress); if (!(transferQuantizationType in starkQuantizationTypeMap)) { throw new Error("eth.starkSignTransferv2 invalid quantization type=" + transferQuantizationType); } let paths = (0, _utils.splitPath)(path); let buffer = Buffer.alloc(1 + paths.length * 4 + 1 + 20 + 32 + 32 + 32 + 4 + 4 + 8 + 4 + 4 + (conditionalTransferAddressHex ? 32 + 20 : 0), 0); let offset = 0; buffer[0] = paths.length; paths.forEach((element, index) => { buffer.writeUInt32BE(element, 1 + 4 * index); }); offset = 1 + 4 * paths.length; buffer[offset] = starkQuantizationTypeMap[transferQuantizationType]; offset++; if (transferTokenAddressHex) { transferTokenAddressHex.copy(buffer, offset); } offset += 20; if (transferQuantization) { Buffer.from(transferQuantization.toString(16).padStart(64, "0"), "hex").copy(buffer, offset); } offset += 32; if (transferMintableBlobOrTokenId) { Buffer.from(transferMintableBlobOrTokenId.toString(16).padStart(64, "0"), "hex").copy(buffer, offset); } offset += 32; targetPublicKeyHex.copy(buffer, offset); offset += 32; buffer.writeUInt32BE(sourceVault, offset); offset += 4; buffer.writeUInt32BE(destinationVault, offset); offset += 4; Buffer.from(amountTransfer.toString(16).padStart(16, "0"), "hex").copy(buffer, offset); offset += 8; buffer.writeUInt32BE(nonce, offset); offset += 4; buffer.writeUInt32BE(timestamp, offset); if (conditionalTransferAddressHex && conditionalTransferFact) { offset += 4; Buffer.from(conditionalTransferFact.toString(16).padStart(64, "0"), "hex").copy(buffer, offset); offset += 32; conditionalTransferAddressHex.copy(buffer, offset); } return this.transport.send(0xf0, 0x04, conditionalTransferAddressHex ? 0x05 : 0x04, 0x00, buffer).then(response => { const r = response.slice(1, 1 + 32).toString("hex"); const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex"); return { r, s }; }); } /** * provide quantization information before singing a deposit or withdrawal Stark powered contract call * * It shall be run following a provideERC20TokenInformation call for the given contract * * @param operationContract contract address of the token to be transferred (not present for ETH) * @param operationQuantization quantization used for the token to be transferred */ starkProvideQuantum(operationContract, operationQuantization) { const operationContractHex = maybeHexBuffer(operationContract); let buffer = Buffer.alloc(20 + 32, 0); if (operationContractHex) { operationContractHex.copy(buffer, 0); } Buffer.from(operationQuantization.toString(16).padStart(64, "0"), "hex").copy(buffer, 20); return this.transport.send(0xf0, 0x08, 0x00, 0x00, buffer).then(() => true, e => { if (e && e.statusCode === 0x6d00) { // this case happen for ETH application versions not supporting Stark extensions return false; } throw e; }); } /** * provide quantization information before singing a deposit or withdrawal Stark powered contract call using the Starkex V2 protocol * * It shall be run following a provideERC20TokenInformation call for the given contract * * @param operationContract contract address of the token to be transferred (not present for ETH) * @param operationQuantizationType quantization type of the token to be transferred * @option operationQuantization quantization used for the token to be transferred (not present for erc 721 or mintable erc 721) * @option operationMintableBlobOrTokenId mintable blob (mintable erc 20 / mintable erc 721) or token id (erc 721) of the token to be transferred */ starkProvideQuantum_v2(operationContract, operationQuantizationType, operationQuantization, operationMintableBlobOrTokenId) { const operationContractHex = maybeHexBuffer(operationContract); if (!(operationQuantizationType in starkQuantizationTypeMap)) { throw new Error("eth.starkProvideQuantumV2 invalid quantization type=" + operationQuantizationType); } let buffer = Buffer.alloc(20 + 32 + 32, 0); let offset = 0; if (operationContractHex) { operationContractHex.copy(buffer, offset); } offset += 20; if (operationQuantization) { Buffer.from(operationQuantization.toString(16).padStart(64, "0"), "hex").copy(buffer, offset); } offset += 32; if (operationMintableBlobOrTokenId) { Buffer.from(operationMintableBlobOrTokenId.toString(16).padStart(64, "0"), "hex").copy(buffer, offset); } return this.transport.send(0xf0, 0x08, starkQuantizationTypeMap[operationQuantizationType], 0x00, buffer).then(() => true, e => { if (e && e.statusCode === 0x6d00) { // this case happen for ETH application versions not supporting Stark extensions return false; } throw e; }); } /** * sign the given hash over the Stark curve * It is intended for speed of execution in case an unknown Stark model is pushed and should be avoided as much as possible. * @param path a path in BIP 32 format * @param hash hexadecimal hash to sign * @return the signature */ starkUnsafeSign(path, hash) { const hashHex = hexBuffer(hash); let paths = (0, _utils.splitPath)(path); let buffer = Buffer.alloc(1 + paths.length * 4 + 32); let offset = 0; buffer[0] = paths.length; paths.forEach((element, index) => { buffer.writeUInt32BE(element, 1 + 4 * index); }); offset = 1 + 4 * paths.length; hashHex.copy(buffer, offset); return this.transport.send(0xf0, 0x0a, 0x00, 0x00, buffer).then(response => { const r = response.slice(1, 1 + 32).toString("hex"); const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex"); return { r, s }; }); } /** * get an Ethereum 2 BLS-12 381 public key for a given BIP 32 path. * @param path a path in BIP 32 format * @option boolDisplay optionally enable or not the display * @return an object with a publicKey * @example * eth.eth2GetPublicKey("12381/3600/0/0").then(o => o.publicKey) */ eth2GetPublicKey(path, boolDisplay) { let paths = (0, _utils.splitPath)(path); let buffer = Buffer.alloc(1 + paths.length * 4); buffer[0] = paths.length; paths.forEach((element, index) => { buffer.writeUInt32BE(element, 1 + 4 * index); }); return this.transport.send(0xe0, 0x0e, boolDisplay ? 0x01 : 0x00, 0x00, buffer).then(response => { let result = {}; result.publicKey = response.slice(0, -2).toString("hex"); return result; }); } /** * Set the index of a Withdrawal key used as withdrawal credentials in an ETH 2 deposit contract call signature * * It shall be run before the ETH 2 deposit transaction is signed. If not called, the index is set to 0 * * @param withdrawalIndex index path in the EIP 2334 path m/12381/3600/withdrawalIndex/0 * @return True if the method was executed successfully */ eth2SetWithdrawalIndex(withdrawalIndex) { let buffer = Buffer.alloc(4, 0); buffer.writeUInt32BE(withdrawalIndex, 0); return this.transport.send(0xe0, 0x10, 0x00, 0x00, buffer).then(() => true, e => { if (e && e.statusCode === 0x6d00) { // this case happen for ETH application versions not supporting ETH 2 return false; } throw e; }); } } exports.default = Eth; //# sourceMappingURL=Eth.js.map
'use strict'; var _api = require('./api'); var _api2 = _interopRequireDefault(_api); var _base_model = require('./base_model'); var _base_model2 = _interopRequireDefault(_base_model); var _isString = require('lodash/isString'); var _isString2 = _interopRequireDefault(_isString); var _isFunction = require('lodash/isFunction'); var _isFunction2 = _interopRequireDefault(_isFunction); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } _base_model2.default.addClassAction('create', function (attributes) { var _this = this; if ((0, _isString2.default)(attributes)) { attributes = { name: attributes }; } return _api2.default.request({ method: 'post', data: attributes, endpoint: this.urlRoot, onSuccess: function onSuccess() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var json = options.body; var model = _this.set({ modelJson: json[_this.jsonKey], topLevelJson: json }); if ((0, _isFunction2.default)(model.afterCreate)) { model.afterCreate(options); } } }); }); _base_model2.default.addClassAction('load', function (id, isIncludeDeleted) { var _this2 = this; return _api2.default.request({ endpoint: this.urlRoot + '/' + id, data: { include_deleted: isIncludeDeleted }, onSuccess: function onSuccess() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var json = options.body; _this2.set({ modelJson: json[_this2.jsonKey], topLevelJson: json }); } }); }); _base_model2.default.addAction('update', function () { var _this3 = this; var attributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return _api2.default.request({ method: 'put', data: attributes, endpoint: this.urlRoot + '/' + this.id, onSuccess: function onSuccess() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var json = options.body; _this3.set({ modelJson: json[_this3.jsonKey], topLevelJson: json }); if ((0, _isFunction2.default)(_this3.afterUpdate)) { _this3.afterUpdate(options); } } }); }); _base_model2.default.addAction('destroy', function () { var _this4 = this; return _api2.default.request({ method: 'del', endpoint: this.urlRoot + '/' + this.id, onSuccess: function onSuccess() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _this4.onDestroy(); if ((0, _isFunction2.default)(_this4.afterDestroy)) { _this4.afterDestroy(options); } } }); }); //# sourceMappingURL=restful_actions_mixin.js.map
// Generated on 2014-03-05 using generator-angular 0.7.1 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Define the configuration for all the tasks grunt.initConfig({ // Project settings app: { // configurable paths app: 'src', url: '', default_local_server_url: 'http://0.0.0.0:8001' }, // Watches files for changes and runs tasks based on the changed files watch: { js: { files: ['<%= app.app %>/**/*.js', '!<%= app.app %>/main.js'], tasks: ['browserify'], options: { livereload: 35731 } }, styles: { files: ['<%= app.app %>/css/**/*.css'], tasks: ['newer:copy:styles', 'autoprefixer'] }, gruntfile: { files: ['Gruntfile.js'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '<%= app.app %>/**/*.html', '.tmp/css/**/*.css', '<%= app.app %>/**/*.{png,jpg,jpeg,gif,webp,svg}' ] } }, // The actual grunt server settings connect: { options: { port: 8001, // Change this to '0.0.0.0' to access the server from outside. hostname: '0.0.0.0', livereload: 35731 }, livereload: { options: { // open: { // target: '<%= app.url %>' // }, base: [ '.tmp', '<%= app.app %>' ] } } }, // Empties folders to start fresh clean: { server: '.tmp' }, browserify: { 'src/main.js': ['src/js/app.js'] } }); grunt.registerTask('serve', function (target) { if (target === 'local') { var conn = 'http://' + grunt.config.get('connect.options.hostname') + ':' + grunt.config.get('connect.options.port'); var url = grunt.option('url') || grunt.config.get('app.default_local_server_url'); grunt.config.set('app.url', conn + '/?url=' + url); } else { // open with no url passed to fh-js-sdk grunt.config.set('connect.livereload.options.open', true); } grunt.task.run([ 'browserify', 'clean:server', 'connect:livereload', 'watch' ]); }); grunt.registerTask('default', ['serve']); grunt.loadNpmTasks('grunt-browserify'); };
define("ace/snippets/javascript",["require","exports","module"],function(e,t,n){"use strict";t.snippetText='# Prototype\nsnippet proto\n ${1:class_name}.prototype.${2:method_name} = function(${3:first_argument}) {\n ${4:// body...}\n };\n# Function\nsnippet fun\n function ${1?:function_name}(${2:argument}) {\n ${3:// body...}\n }\n# Anonymous Function\nregex /((=)\\s*|(:)\\s*|(\\()|\\b)/f/(\\))?/\nsnippet f\n function${M1?: ${1:functionName}}($2) {\n ${0:$TM_SELECTED_TEXT}\n }${M2?;}${M3?,}${M4?)}\n# Immediate function\ntrigger \\(?f\\(\nendTrigger \\)?\nsnippet f(\n (function(${1}) {\n ${0:${TM_SELECTED_TEXT:/* code */}}\n }(${1}));\n# if\nsnippet if\n if (${1:true}) {\n ${0}\n }\n# if ... else\nsnippet ife\n if (${1:true}) {\n ${2}\n } else {\n ${0}\n }\n# tertiary conditional\nsnippet ter\n ${1:/* condition */} ? ${2:a} : ${3:b}\n# switch\nsnippet switch\n switch (${1:expression}) {\n case \'${3:case}\':\n ${4:// code}\n break;\n ${5}\n default:\n ${2:// code}\n }\n# case\nsnippet case\n case \'${1:case}\':\n ${2:// code}\n break;\n ${3}\n\n# while (...) {...}\nsnippet wh\n while (${1:/* condition */}) {\n ${0:/* code */}\n }\n# try\nsnippet try\n try {\n ${0:/* code */}\n } catch (e) {}\n# do...while\nsnippet do\n do {\n ${2:/* code */}\n } while (${1:/* condition */});\n# Object Method\nsnippet :f\nregex /([,{[])|^\\s*/:f/\n ${1:method_name}: function(${2:attribute}) {\n ${0}\n }${3:,}\n# setTimeout function\nsnippet setTimeout\nregex /\\b/st|timeout|setTimeo?u?t?/\n setTimeout(function() {${3:$TM_SELECTED_TEXT}}, ${1:10});\n# Get Elements\nsnippet gett\n getElementsBy${1:TagName}(\'${2}\')${3}\n# Get Element\nsnippet get\n getElementBy${1:Id}(\'${2}\')${3}\n# console.log (Firebug)\nsnippet cl\n console.log(${1});\n# return\nsnippet ret\n return ${1:result}\n# for (property in object ) { ... }\nsnippet fori\n for (var ${1:prop} in ${2:Things}) {\n ${0:$2[$1]}\n }\n# hasOwnProperty\nsnippet has\n hasOwnProperty(${1})\n# docstring\nsnippet /**\nsnippet @par\nregex /^\\s*\\*\\s*/@(para?m?)?/\n @param {${1:type}} ${2:name} ${3:description}\nsnippet @ret\n @return {${1:type}} ${2:description}\n# JSON.parse\nsnippet jsonp\n JSON.parse(${1:jstr});\n# JSON.stringify\nsnippet jsons\n JSON.stringify(${1:object});\n# self-defining function\nsnippet sdf\n var ${1:function_name} = function(${2:argument}) {\n ${3:// initial code ...}\n\n $1 = function($2) {\n ${4:// main code}\n };\n }\n# singleton\nsnippet sing\n function ${1:Singleton} (${2:argument}) {\n var instance;\n $1 = function $1($2) {\n return instance;\n };\n $1.prototype = this;\n instance = new $1();\n instance.constructor = $1;\n\n ${3:// code ...}\n\n return instance;\n }\n# class\nsnippet class\nregex /^\\s*/clas{0,2}/\n var ${1:class} = function(${20}) {\n $40$0\n };\n \n (function() {\n ${60:this.prop = ""}\n }).call(${1:class}.prototype);\n \n exports.${1:class} = ${1:class};\n# \nsnippet for-\n for (var ${1:i} = ${2:Things}.length; ${1:i}--; ) {\n ${0:${2:Things}[${1:i}];}\n }\n# for (...) {...}\nsnippet for\n for (var ${1:i} = 0; $1 < ${2:Things}.length; $1++) {\n ${3:$2[$1]}$0\n }\n# for (...) {...} (Improved Native For-Loop)\nsnippet forr\n for (var ${1:i} = ${2:Things}.length - 1; $1 >= 0; $1--) {\n ${3:$2[$1]}$0\n }\n\n\n#modules\nsnippet def\n define(function(require, exports, module) {\n "use strict";\n var ${1/.*\\///} = require("${1}");\n \n $TM_SELECTED_TEXT\n });\nsnippet req\nguard ^\\s*\n var ${1/.*\\///} = require("${1}");\n $0\nsnippet requ\nguard ^\\s*\n var ${1/.*\\/(.)/\\u$1/} = require("${1}").${1/.*\\/(.)/\\u$1/};\n $0\n',t.scope="javascript"});
/// init lua api function Love_Thread_CreateTable (G) { var t = lua_newtable(); var pre = "love.thread."; G.str['love'].str['thread'] = t; t.str['getThread'] = function () { return NotImplemented(pre+'getThread'); } t.str['getThreads'] = function () { return NotImplemented(pre+'getThreads'); } t.str['newThread'] = function (path) { NotImplemented(pre+'newThread'); return [Love_MakeThreadHandle(new cThread(path))]; } } function Love_MakeThreadHandle (o) { var t = lua_newtable(); var pre = "love.thread:"; t._data = o; t.str['demand'] = function (t) { return NotImplemented(pre+'demand' ); } // Receive a message from a thread. Wait for the message to exist before returning. t.str['getName'] = function (t) { return NotImplemented(pre+'getName'); } // Get the name of a thread. t.str['kill'] = function (t) { return NotImplemented(pre+'kill' ); } // Forcefully terminate the thread. t.str['peek'] = function (t) { return NotImplemented(pre+'peek' ); } // Receive a message from a thread, but leave it in the message box. t.str['receive'] = function (t) { return NotImplemented(pre+'receive'); } // Receive a message from a thread. t.str['send'] = function (t) { return NotImplemented(pre+'send' ); } // Send a message. t.str['start'] = function (t) { return NotImplemented(pre+'start' ); } // Starts the thread. t.str['wait'] = function (t) { return NotImplemented(pre+'wait' ); } // Wait for a thread to finish. // 0.8.0 <Boolsheet> send/receive were renamed to set/get. The behaviour is still the same. t.str['get'] = function (t) { return NotImplemented(pre+'get' ); } // new 0.8.0 ? t.str['set'] = function (t) { return NotImplemented(pre+'set' ); } // new 0.8.0 ? t.str['getKeys'] = function (t) { return NotImplemented(pre+'getKeys' ); } // new 0.8.0 ? // getKeys : It returns a table with all the names of the message in the thread message box. t.str['type'] = function (t) { return ["Thread"]; } // Gets the type of the object as a string. t.str['typeOf'] = function (t,x) { return [x == "Object" || x == "Thread"]; } // Checks whether an object is of a certain type. return t; } function cThread(path) { }
function solve() { let $singMeUpButton = $('.courseFoot button'); $singMeUpButton.on('click', function () { let $courses = $('.courseBody ul li'); let $educationForm = $('#educationForm input'); let coursePrices = { fundamentals: 170, advanced: 180, applications: 190, web: 490 }; let checkedCourses = []; for (const $course of $courses) { if (isChecked($course.children[0])) { let courseName = $course.children[1].textContent; addToCourseBody(courseName); checkedCourses.push(courseName.split(' ')[1].toLowerCase()); } } if (checkedCourses.length === 4) { addToCourseBody('HTML and CSS'); } for (const type of $educationForm) { if (type.checked) { calculateCost(checkedCourses, type.value, coursePrices); } } for (const $course of $courses) { $course.children[0].checked = false; } }); function isChecked($courseInput) { return $courseInput.checked; } function addToCourseBody(courseName) { let $courseBody = $('.courseBody ul'); let $li = $('<li></li>'); $li.text(courseName.split(' - ')[0].replace(' ', '-')); $courseBody.append($li); } function calculateCost(courses, formType, coursePrices) { if (courses.includes('advanced') && courses.includes('fundamentals')) { coursePrices['advanced'] = +coursePrices['advanced'] * 0.90; } if (courses.includes('advanced') && courses.includes('fundamentals') && courses.includes('applications')) { coursePrices['fundamentals'] = +coursePrices['fundamentals'] * 0.94; coursePrices['advanced'] = +coursePrices['advanced'] * 0.94; coursePrices['applications'] = +coursePrices['applications'] * 0.94; } if (formType === 'online') { for (const course of courses) { coursePrices[course] = coursePrices[course] - (coursePrices[course] * 0.06); } } let price = 0; for (const course of courses) { price += coursePrices[course]; } $('.courseFoot p').text('Cost: ' + Math.floor(price) + '.00 BGN'); } } solve();
/*! * OpenUI5 * (c) Copyright 2009-2019 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['sap/base/Log','./library','sap/ui/core/Control','sap/ui/core/delegate/ItemNavigation','./RadioButton','./RadioButtonGroupRenderer','sap/ui/core/library'],function(L,l,C,I,R,a,c){"use strict";var V=c.ValueState;var b=C.extend("sap.ui.commons.RadioButtonGroup",{metadata:{interfaces:["sap.ui.core.IFormContent"],library:"sap.ui.commons",properties:{width:{type:"sap.ui.core.CSSSize",group:"Dimension",defaultValue:null},columns:{type:"int",group:"Appearance",defaultValue:1},editable:{type:"boolean",group:"Behavior",defaultValue:true},valueState:{type:"sap.ui.core.ValueState",group:"Data",defaultValue:V.None},selectedIndex:{type:"int",group:"Data",defaultValue:0},enabled:{type:"boolean",group:"Behavior",defaultValue:true}},defaultAggregation:"items",aggregations:{items:{type:"sap.ui.core.Item",multiple:true,singularName:"item",bindable:"bindable"}},associations:{ariaDescribedBy:{type:"sap.ui.core.Control",multiple:true,singularName:"ariaDescribedBy"},ariaLabelledBy:{type:"sap.ui.core.Control",multiple:true,singularName:"ariaLabelledBy"}},events:{select:{parameters:{selectedIndex:{type:"int"}}}}}});b.prototype.exit=function(){this.destroyItems();if(this.oItemNavigation){this.removeDelegate(this.oItemNavigation);this.oItemNavigation.destroy();delete this.oItemNavigation;}};b.prototype.onBeforeRendering=function(){if(this.getSelectedIndex()>this.getItems().length){L.warning("Invalid index, set to 0");this.setSelectedIndex(0);}};b.prototype.onAfterRendering=function(){this.initItemNavigation();for(var i=0;i<this.aRBs.length;i++){this.aRBs[i].getDomRef().setAttribute("aria-posinset",i+1);this.aRBs[i].getDomRef().setAttribute("aria-setsize",this.aRBs.length);}};b.prototype.initItemNavigation=function(){var d=[];this._aActiveItems=[];var A=this._aActiveItems;var e=false;for(var i=0;i<this.aRBs.length;i++){A[d.length]=i;d.push(this.aRBs[i].getDomRef());if(!e&&this.aRBs[i].getEnabled()){e=true;}}if(e){e=this.getEnabled();}if(!e){if(this.oItemNavigation){this.removeDelegate(this.oItemNavigation);this.oItemNavigation.destroy();delete this.oItemNavigation;}return;}if(!this.oItemNavigation){this.oItemNavigation=new I();this.oItemNavigation.attachEvent(I.Events.AfterFocus,this._handleAfterFocus,this);this.addDelegate(this.oItemNavigation);}this.oItemNavigation.setRootDomRef(this.getDomRef());this.oItemNavigation.setItemDomRefs(d);this.oItemNavigation.setCycling(true);this.oItemNavigation.setColumns(this.getColumns());this.oItemNavigation.setSelectedIndex(this.getSelectedIndex());this.oItemNavigation.setFocusedIndex(this.getSelectedIndex());};b.prototype.setSelectedIndex=function(s){var i=this.getSelectedIndex();if(s<0){L.warning("Invalid index, will not be changed");return this;}this.setProperty("selectedIndex",s,true);if(!isNaN(i)&&this.aRBs&&this.aRBs[i]){this.aRBs[i].setSelected(false);}if(this.aRBs&&this.aRBs[s]){this.aRBs[s].setSelected(true);}if(this.oItemNavigation){this.oItemNavigation.setSelectedIndex(s);this.oItemNavigation.setFocusedIndex(s);}return this;};b.prototype.setSelectedItem=function(s){for(var i=0;i<this.getItems().length;i++){if(s.getId()==this.getItems()[i].getId()){this.setSelectedIndex(i);break;}}};b.prototype.getSelectedItem=function(){return this.getItems()[this.getSelectedIndex()];};b.prototype.addItem=function(i){this.myChange=true;this.addAggregation("items",i);i.attachEvent("_change",this._handleItemChanged,this);this.myChange=undefined;if(!this._bUpdateItems){if(this.getSelectedIndex()===undefined){this.setSelectedIndex(0);}}if(!this.aRBs){this.aRBs=[];}var d=this.aRBs.length;this.aRBs[d]=this.createRadioButton(i,d);return this;};b.prototype.insertItem=function(o,d){this.myChange=true;this.insertAggregation("items",o,d);o.attachEvent("_change",this._handleItemChanged,this);this.myChange=undefined;if(!this.aRBs){this.aRBs=[];}var e=this.aRBs.length;if(!this._bUpdateItems){if(this.getSelectedIndex()===undefined||e==0){this.setSelectedIndex(0);}else if(this.getSelectedIndex()>=d){this.setProperty("selectedIndex",this.getSelectedIndex()+1,true);}}if(d>=e){this.aRBs[d]=this.createRadioButton(o,d);}else{for(var i=(e);i>d;i--){this.aRBs[i]=this.aRBs[i-1];if((i-1)==d){this.aRBs[i-1]=this.createRadioButton(o,d);}}}return this;};b.prototype.createRadioButton=function(i,d){if(this.iIDCount==undefined){this.iIDCount=0;}else{this.iIDCount++;}var r=new R(this.getId()+"-"+this.iIDCount);r.setText(i.getText());r.setTooltip(i.getTooltip());if(this.getEnabled()){r.setEnabled(i.getEnabled());}else{r.setEnabled(false);}r.setKey(i.getKey());r.setTextDirection(i.getTextDirection());r.setEditable(this.getEditable());r.setGroupName(this.getId());r.setValueState(this.getValueState());r.setParent(this);if(d==this.getSelectedIndex()){r.setSelected(true);}r.attachEvent('select',this.handleRBSelect,this);return r;};b.prototype.removeItem=function(e){var i=e;if(typeof(e)=="string"){e=sap.ui.getCore().byId(e);}if(typeof(e)=="object"){i=this.indexOfItem(e);}this.myChange=true;var o=this.removeAggregation("items",i);o.detachEvent("_change",this._handleItemChanged,this);this.myChange=undefined;if(!this.aRBs){this.aRBs=[];}if(!this.aRBs[i]){return null;}this.aRBs[i].destroy();this.aRBs.splice(i,1);if(!this._bUpdateItems){if(this.aRBs.length==0){this.setSelectedIndex(undefined);}else if(this.getSelectedIndex()==i){this.setSelectedIndex(0);}else if(this.getSelectedIndex()>i){this.setProperty("selectedIndex",this.getSelectedIndex()-1,true);}}return o;};b.prototype.removeAllItems=function(){this.myChange=true;var d=this.removeAllAggregation("items");for(var i=0;i<d.length;i++){d[i].detachEvent("_change",this._handleItemChanged,this);}this.myChange=undefined;if(!this._bUpdateItems){this.setSelectedIndex(undefined);}if(this.aRBs){while(this.aRBs.length>0){this.aRBs[0].destroy();this.aRBs.splice(0,1);}return d;}else{return null;}};b.prototype.destroyItems=function(){this.myChange=true;var d=this.getItems();for(var i=0;i<d.length;i++){d[i].detachEvent("_change",this._handleItemChanged,this);}this.destroyAggregation("items");this.myChange=undefined;if(!this._bUpdateItems){this.setSelectedIndex(undefined);}if(this.aRBs){while(this.aRBs.length>0){this.aRBs[0].destroy();this.aRBs.splice(0,1);}}return this;};b.prototype.updateItems=function(){var s=this.getSelectedIndex();this._bUpdateItems=true;this.updateAggregation("items");this._bUpdateItems=undefined;var i=this.getItems();if(s===undefined&&i.length>0){this.setSelectedIndex(0);}else if(s>=0&&i.length==0){this.setSelectedIndex(undefined);}else if(s>=i.length){this.setSelectedIndex(i.length-1);}};b.prototype.clone=function(){var d=this.getItems();var i=0;for(i=0;i<d.length;i++){d[i].detachEvent("_change",this._handleItemChanged,this);}var o=C.prototype.clone.apply(this,arguments);for(i=0;i<d.length;i++){d[i].attachEvent("_change",this._handleItemChanged,this);}return o;};b.prototype.handleRBSelect=function(o){for(var i=0;i<this.aRBs.length;i++){if(this.aRBs[i].getId()==o.getParameter("id")){this.setSelectedIndex(i);this.oItemNavigation.setSelectedIndex(i);this.oItemNavigation.setFocusedIndex(i);this.fireSelect({selectedIndex:i});break;}}};b.prototype.setEditable=function(e){this.setProperty("editable",e,false);if(this.aRBs){for(var i=0;i<this.aRBs.length;i++){this.aRBs[i].setEditable(e);}}return this;};b.prototype.setEnabled=function(e){this.setProperty("enabled",e,false);if(this.aRBs){for(var i=0;i<this.aRBs.length;i++){this.aRBs[i].setEnabled(e);}}return this;};b.prototype.setValueState=function(v){this.setProperty("valueState",v,false);if(this.aRBs){for(var i=0;i<this.aRBs.length;i++){this.aRBs[i].setValueState(v);}}return this;};b.prototype._handleAfterFocus=function(o){var i=o.getParameter("index");var e=o.getParameter("event");if(i!=this.getSelectedIndex()&&!(e.ctrlKey||e.metaKey)&&this.aRBs[i].getEditable()&&this.aRBs[i].getEnabled()){this.setSelectedIndex(i);this.oItemNavigation.setSelectedIndex(i);this.fireSelect({selectedIndex:i});}};b.prototype._handleItemChanged=function(e){var o=e.oSource;var p=e.getParameter("name");var s=e.getParameter("newValue");var d=this.getItems();var r;for(var i=0;i<d.length;i++){if(d[i]==o){if(this.aRBs[i]){r=this.aRBs[i];}break;}}switch(p){case"text":r.setText(s);break;case"tooltip":r.setTooltip(s);break;case"enabled":if(this.getEnabled()){r.setEnabled(s);}break;case"key":r.setKey(s);break;case"textDirection":r.setTextDirection(s);break;default:break;}};return b;});
var Model = require('mongoose').Model , ms = require('ms') /** * Exports. */ module.exports = exports = ttl; function ttl (schema, options) { options || (options = {}); var key = '__ttl' , overridden = '__ttlOverride' , ttl = options.ttl || 60000 , interval = options.interval || 60000*5 , reap = false !== options.reap , onReap = 'function' == typeof options.onReap ? options.onReap : undefined var o = {}; o[key] = Date; schema.add(o); schema.index(key, { background: true }); schema.pre('save', function (next) { if (overridden in this) { // nothing to do } else { this[key] = fromNow(); } next(); }); /** * startTTLReaper * * Starts reaping expired docs from the db. */ schema.statics.startTTLReaper = function startTTLReaper () { if (key in this) return; var self = this; self[key] = setInterval((function remove () { self.expireLog(); return remove; })(), interval); } /** * stopTTLReaper * * Stops removing expired docs from the db. */ schema.statics.stopTTLReaper = function stopTTLReapter () { clearInterval(this[key]); delete this[key]; }; /** * Listen to Model.init. */ schema.on('init', init); /** * init * * Hook into all model queries to include the TTL * filter and kick off the expired doc reaper if * enabled. * @private */ function init (model) { if (model.__ttl) return; var distinct_ = model.distinct; model.distinct = function distinct (field, cond, cb) { applyTTL(cond); return distinct_.call(model, field, cond, cb); } 'findOne find count'.split(' ').forEach(function (method) { var fn = model[method]; model[method] = function (cond, fields, opts, cb) { if (!cond) { cond = {}; } else if ('function' == typeof cond) { cb = cond; cond = {}; } applyTTL(cond); return fn.call(model, cond, fields, opts, cb); } }); 'where $where'.split(' ').forEach(function (method) { var fn = model[method]; model[method] = function () { var query = fn.apply(this, arguments) , cond = {}; applyTTL(cond); return query.find(cond); } }); if (reap) { model.startTTLReaper(); } } /** * Getters/setters */ var virt = schema.virtual('ttl'); virt.get(function () { if (this[key]) return this[key]; this.ttl = ttl; return this.ttl; }); virt.set(function (val) { if ('reset' == val) return this.resetTTL(); this[overridden] = arguments.length ? val : ttl; return this[key] = fromNow(this[overridden]); }); /** * resetTTL * * Resets this documents ttl to the default specified * in the plugin options or plugin default. */ schema.methods.resetTTL = function resetTTL () { delete this._doc[key]; delete this[overridden]; } /** * fromNow * @private */ function fromNow (val) { var v = arguments.length ? val : ttl; return new Date(Date.now() + ms(v)); } /** * Applies ttl to query conditions. * @private */ function applyTTL (cond) { if (cond[key]) { cond.$and || (cond.$and = []); var a = {}; a[key] = cond[key]; cond.$and.push(a); var b = {}; b[key] = { $gt: new Date }; cond.$and.push(b); delete cond[key]; } else { cond[key] = { $gt: new Date }; } } }
var THREEx = THREEx || {} THREEx.OutlineHelper = function(object3d, renderer, camera, thickness){ thickness = thickness !== undefined ? thickness : 8 // TODO handle dilatation // compute the object height var boundingBox = new THREE.Box3().setFromObject(object3d) var objectHeight= boundingBox.size().y // build the outline mesh var material = new THREE.MeshBasicMaterial({ color : new THREE.Color(0x0088cc), side : THREE.BackSide, }) THREE.Mesh.call( this, object3d.geometry, material) // update function this.update = function(){ // update worldMatrix object3d.updateMatrixWorld(); // decompose object3d.matrixWorld var position = new THREE.Vector3() var scale = new THREE.Vector3() var quaternion = new THREE.Quaternion() object3d.matrixWorld.decompose(position, quaternion, scale) // from https://developer.valvesoftware.com/wiki/Field_of_View#FOV_calculations var objectDistance = position.distanceTo(camera.position) var verticalFov = camera.fov / 180 * Math.PI var viewPlaneHeight = objectDistance * (2*Math.tan(verticalFov/2)) var screenHeight = renderer.domElement.height var objectScreenHeight = screenHeight/viewPlaneHeight * objectHeight // compute the scale var scaleRatio = 0.0025 * (250/objectScreenHeight) var scaleFactor = 1 + scaleRatio*thickness scale.multiplyScalar(scaleFactor) // now compose the helper matrixWorld this.matrixWorld.compose(position, quaternion, scale) this.matrixAutoUpdate = false; } } THREEx.OutlineHelper.prototype = Object.create( THREE.Mesh.prototype );
import {request} from "./ruquest"; //将home中全部的url在home.js中管理 export function getHomeMultidata() { return request({ url: '/home/multidata' }) } export function getHomeGoods(type, page) { return request({ url: '/home/data', params: { type, page, } }) }
const Database = require("@replit/database") const db = new Database() module.exports = (client, message) => { require("../scripts/dm.js")(message,client) const Discord = require('discord.js'); if (message.author.bot) return; function x(prefix){ if (message.content.indexOf(prefix) !== 0) return; const args = message.content.slice(prefix.length).trim().split(/ +/g); const command = args.shift().toLowerCase(); const cmd = client.commands.get(command); var dm = false if (!cmd) return; if (!message.channel.type === 'text'){ dm = true } cmd.run(client, message, args, Discord); if (message.author.id == 635303930879803412) { return } var Log if (dm == true){ Log = `@${message.author.username} (<@${message.author.id}>) is using ${command} with aguments of (${args.toString()}) in DMs` }else{ Log = `@${message.author.username} (<@${message.author.id}>) is using ${command} with aguments of (${args.toString()}) in ${message.guild.name}, #${message.channel.name}` } const whurl = client.config.secrets.commandWebhook const fetch = require('node-fetch'); const msg = { "content": Log } fetch(whurl + "?wait=true", { "method": "POST", "headers": { "content-type": "application/json" }, "body": JSON.stringify(msg) }) .then(a => a.json()) } if(message.channel.type == "dm"){ x(client.config.prefix); return }else{ db.get(`${message.guild.id}/prefix`).then(value => { if(value == null){ x(client.config.prefix) }else{ x(value) } }); } };
const fs = require('fs'); const xpath = require('xpath-html'); // Assuming you have an html file locally, // Here is the content that I scraped from www.shopback.sg const html = fs.readFileSync(`${__dirname}/shopback.html`, 'utf8'); // Don't worry about the input much, // you are able to use the HTML response of an HTTP request, // as long as the argument is a string type, everything should be fine. const node = xpath.fromPageSource(html).findElement("//*[contains(text(), 'with love')]"); console.log(`The matched tag name is "${node.getTagName()}"`); console.log(`Your full text is "${node.getText()}"`);
/** * Configure your Gatsby site with this file. * * See: https://www.gatsbyjs.org/docs/gatsby-config/ */ module.exports = { /* Your site config here */ plugins: [ `gatsby-plugin-react-helmet`, ] }
import Utils from "./utils.js"; let Model = { api: undefined, view: ko.observable("signin"), signin: { username: ko.observable(""), password: ko.observable(""), error: ko.observable(false) }, signup: { username: ko.observable(""), password: ko.observable(""), error: ko.observable(false), error_msg: ko.observable("") }, // Methods signin_click_signup: function() { this.route("signup"); }, signin_click_auth: async function() { this.signin.error(false); // Get Username and Encrypt Password let username = this.signin.username(); let password = this.signin.password(); // let encrypted = await Utils.hash(password); // Get redirect (if exists) const urlSearchParams = new URLSearchParams(window.location.search); const params = Object.fromEntries(urlSearchParams.entries()); let redirect = params.redirect ? params.redirect : ""; // Post results to authorize let res = await this.api.$post("/authorize", { username: username, password: password, redirect: redirect }); // Handle the response, and redirect if neccessary console.log(res) if (res && res.status === "ok") { // Redirect window.location.assign(res.url); } else { // Raise error this.signin.error(true); } }, signup_click_cancel: function() { this.route("signin"); }, signup_click_register: async function() { this.signin.error(false); let username = this.signup.username(); let password = this.signup.password(); let encrypted = await Utils.hash(password); let res = await this.api.$post("/register", { username: username, password: encrypted }); console.log(res) if (res && res.status === "ok") { this.route("signin"); } else { // Raise error this.signup.error(true); this.signup.error_msg(res.message) } }, route: function(path) { this.view(path); } } export default Model;
export * from 'bpmn-js/test/helper'; import { insertCSS } from 'bpmn-js/test/helper'; insertCSS('diagram-js.css', require('bpmn-js/dist/assets/diagram-js.css')); insertCSS('bpmn-embedded.css', require('bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css')); insertCSS('diagram-js-testing.css', '.test-container .result { height: 500px; }' + '.test-container > div' ); insertCSS('custom-modeler-testing.css', '.icon-custom-triangle {' + 'background: url(\'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20fill%3D%22%233CAA82%22%20width%3D%22270%22%20height%3D%22240%22%3E%3Cpath%20d%3D%22M8%2C40%20l%2015%2C-27%20l%2015%2C27%20z%22%2F%3E%3C%2Fsvg%3E\');' + '}' + '.icon-custom-circle {' + 'background: url(\'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20stroke-width%3D%228%22%20stroke%3D%22%2348a%22%20fill%3D%22none%22%20viewBox%3D%220%200%20120%20120%22%3E%3Ccircle%20cx%3D%2260%22%20cy%3D%2260%22%20r%3D%2240%22%2F%3E%3C%2Fsvg%3E\');' + '}' );
/* MIT License Copyright (c) 2018 monya-wallet zenypota Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module.exports = [ { "constant": true, "inputs": [], "name": "name", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "_spender", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "approve", "outputs": [ { "name": "success", "type": "bool" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [], "name": "totalSupply", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "_from", "type": "address" }, { "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "transferFrom", "outputs": [ { "name": "success", "type": "bool" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [], "name": "decimals", "outputs": [ { "name": "", "type": "uint8" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [], "name": "version", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "_owner", "type": "address" } ], "name": "balanceOf", "outputs": [ { "name": "balance", "type": "uint256" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [], "name": "symbol", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "transfer", "outputs": [ { "name": "success", "type": "bool" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "_spender", "type": "address" }, { "name": "_value", "type": "uint256" }, { "name": "_extraData", "type": "bytes" } ], "name": "approveAndCall", "outputs": [ { "name": "success", "type": "bool" } ], "payable": false, "type": "function" }, { "constant": true, "inputs": [ { "name": "_owner", "type": "address" }, { "name": "_spender", "type": "address" } ], "name": "allowance", "outputs": [ { "name": "remaining", "type": "uint256" } ], "payable": false, "type": "function" }, { "inputs": [ { "name": "_initialAmount", "type": "uint256" }, { "name": "_tokenName", "type": "string" }, { "name": "_decimalUnits", "type": "uint8" }, { "name": "_tokenSymbol", "type": "string" } ], "type": "constructor" }, { "payable": false, "type": "fallback" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "_from", "type": "address" }, { "indexed": true, "name": "_to", "type": "address" }, { "indexed": false, "name": "_value", "type": "uint256" } ], "name": "Transfer", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "_owner", "type": "address" }, { "indexed": true, "name": "_spender", "type": "address" }, { "indexed": false, "name": "_value", "type": "uint256" } ], "name": "Approval", "type": "event" }, ];
module.exports = new Date(1975, 3, 24)
/* * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the * LICENSE file in the root directory of this source tree. * */ /* jshint node: true, devel: true */ 'use strict'; const bodyParser = require('body-parser'), config = require('config'), crypto = require('crypto'), express = require('express'), https = require('https'), request = require('request'); var app = express(); app.set('port', process.env.PORT || 5000); app.set('view engine', 'ejs'); app.use(bodyParser.json({ verify: verifyRequestSignature })); app.use(express.static('public')); /* * Be sure to setup your config values before running this code. You can * set them using environment variables or modifying the config file in /config. * */ // App Secret can be retrieved from the App Dashboard const APP_SECRET = (process.env.MESSENGER_APP_SECRET) ? process.env.MESSENGER_APP_SECRET : config.get('appSecret'); // Arbitrary value used to validate a webhook const VALIDATION_TOKEN = (process.env.MESSENGER_VALIDATION_TOKEN) ? (process.env.MESSENGER_VALIDATION_TOKEN) : config.get('validationToken'); // Generate a page access token for your page from the App Dashboard const PAGE_ACCESS_TOKEN = (process.env.MESSENGER_PAGE_ACCESS_TOKEN) ? (process.env.MESSENGER_PAGE_ACCESS_TOKEN) : config.get('pageAccessToken'); // URL where the app is running (include protocol). Used to point to scripts and // assets located at this address. const SERVER_URL = (process.env.SERVER_URL) ? (process.env.SERVER_URL) : config.get('serverURL'); if (!(APP_SECRET && VALIDATION_TOKEN && PAGE_ACCESS_TOKEN && SERVER_URL)) { console.error("Missing config values"); process.exit(1); } /* * Use your own validation token. Check that the token used in the Webhook * setup is the same token used here. * */ app.get('/webhook', function(req, res) { if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === VALIDATION_TOKEN) { console.log("Validating webhook"); res.status(200).send(req.query['hub.challenge']); } else { console.error("Failed validation. Make sure the validation tokens match."); res.sendStatus(403); } }); /* * All callbacks for Messenger are POST-ed. They will be sent to the same * webhook. Be sure to subscribe your app to your page to receive callbacks * for your page. * https://developers.facebook.com/docs/messenger-platform/product-overview/setup#subscribe_app * */ app.post('/webhook', function (req, res) { var data = req.body; // Make sure this is a page subscription if (data.object == 'page') { // Iterate over each entry // There may be multiple if batched data.entry.forEach(function(pageEntry) { var pageID = pageEntry.id; var timeOfEvent = pageEntry.time; // Iterate over each messaging event pageEntry.messaging.forEach(function(messagingEvent) { if (messagingEvent.optin) { receivedAuthentication(messagingEvent); } else if (messagingEvent.message) { receivedMessage(messagingEvent); } else if (messagingEvent.delivery) { receivedDeliveryConfirmation(messagingEvent); } else if (messagingEvent.postback) { receivedPostback(messagingEvent); } else if (messagingEvent.read) { receivedMessageRead(messagingEvent); } else if (messagingEvent.account_linking) { receivedAccountLink(messagingEvent); } else { console.log("Webhook received unknown messagingEvent: ", messagingEvent); } }); }); // Assume all went well. // // You must send back a 200, within 20 seconds, to let us know you've // successfully received the callback. Otherwise, the request will time out. res.sendStatus(200); } }); /* * This path is used for account linking. The account linking call-to-action * (sendAccountLinking) is pointed to this URL. * */ app.get('/authorize', function(req, res) { var accountLinkingToken = req.query.account_linking_token; var redirectURI = req.query.redirect_uri; // Authorization Code should be generated per user by the developer. This will // be passed to the Account Linking callback. var authCode = "1234567890"; // Redirect users to this URI on successful login var redirectURISuccess = redirectURI + "&authorization_code=" + authCode; res.render('authorize', { accountLinkingToken: accountLinkingToken, redirectURI: redirectURI, redirectURISuccess: redirectURISuccess }); }); /* * Verify that the callback came from Facebook. Using the App Secret from * the App Dashboard, we can verify the signature that is sent with each * callback in the x-hub-signature field, located in the header. * * https://developers.facebook.com/docs/graph-api/webhooks#setup * */ function verifyRequestSignature(req, res, buf) { var signature = req.headers["x-hub-signature"]; if (!signature) { // For testing, let's log an error. In production, you should throw an // error. console.error("Couldn't validate the signature."); } else { var elements = signature.split('='); var method = elements[0]; var signatureHash = elements[1]; var expectedHash = crypto.createHmac('sha1', APP_SECRET) .update(buf) .digest('hex'); if (signatureHash != expectedHash) { throw new Error("Couldn't validate the request signature."); } } } /* * Authorization Event * * The value for 'optin.ref' is defined in the entry point. For the "Send to * Messenger" plugin, it is the 'data-ref' field. Read more at * https://developers.facebook.com/docs/messenger-platform/webhook-reference/authentication * */ function receivedAuthentication(event) { var senderID = event.sender.id; var recipientID = event.recipient.id; var timeOfAuth = event.timestamp; // The 'ref' field is set in the 'Send to Messenger' plugin, in the 'data-ref' // The developer can set this to an arbitrary value to associate the // authentication callback with the 'Send to Messenger' click event. This is // a way to do account linking when the user clicks the 'Send to Messenger' // plugin. var passThroughParam = event.optin.ref; console.log("Received authentication for user %d and page %d with pass " + "through param '%s' at %d", senderID, recipientID, passThroughParam, timeOfAuth); // When an authentication is received, we'll send a message back to the sender // to let them know it was successful. sendTextMessage(senderID, "Authentication successful"); } /* * Message Event * * This event is called when a message is sent to your page. The 'message' * object format can vary depending on the kind of message that was received. * Read more at https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-received * * For this example, we're going to echo any text that we get. If we get some * special keywords ('button', 'generic', 'receipt'), then we'll send back * examples of those bubbles to illustrate the special message bubbles we've * created. If we receive a message with an attachment (image, video, audio), * then we'll simply confirm that we've received the attachment. * */ function receivedMessage(event) { var senderID = event.sender.id; var recipientID = event.recipient.id; var timeOfMessage = event.timestamp; var message = event.message; console.log("Received message for user %d and page %d at %d with message:", senderID, recipientID, timeOfMessage); console.log(JSON.stringify(message)); var isEcho = message.is_echo; var messageId = message.mid; var appId = message.app_id; var metadata = message.metadata; // You may get a text or attachment but not both var messageText = message.text; var messageAttachments = message.attachments; var quickReply = message.quick_reply; if (isEcho) { // Just logging message echoes to console console.log("Received echo for message %s and app %d with metadata %s", messageId, appId, metadata); return; } else if (quickReply) { var quickReplyPayload = quickReply.payload; console.log("Quick reply for message %s with payload %s", messageId, quickReplyPayload); sendTextMessage(senderID, "Quick reply tapped"); return; } if (messageText) { // If we receive a text message, check to see if it matches any special // keywords and send back the corresponding example. Otherwise, just echo // the text we received. switch (messageText.replace(/[^\w\s]/gi, '').trim().toLowerCase()) { case 'hello': case 'hi': sendHiMessage(senderID); break; case 'image': requiresServerURL(sendImageMessage, [senderID]); break; case 'gif': requiresServerURL(sendGifMessage, [senderID]); break; case 'audio': requiresServerURL(sendAudioMessage, [senderID]); break; case 'video': requiresServerURL(sendVideoMessage, [senderID]); break; case 'file': requiresServerURL(sendFileMessage, [senderID]); break; case 'button': sendButtonMessage(senderID); break; case 'generic': requiresServerURL(sendGenericMessage, [senderID]); break; case 'receipt': requiresServerURL(sendReceiptMessage, [senderID]); break; case 'quick reply': sendQuickReply(senderID); break; case 'read receipt': sendReadReceipt(senderID); break; case 'typing on': sendTypingOn(senderID); break; case 'typing off': sendTypingOff(senderID); break; case 'account linking': requiresServerURL(sendAccountLinking, [senderID]); break; default: acknowledgeVehicleCheckRequest(senderID); var request = require('request'); var FormData = require('form-data'); var form = new FormData(); form.append('vrm', messageText); checkVehicleAndRespond(form, senderID); } } else if (messageAttachments) { acknowledgeVehicleCheckRequest(senderID); console.log(messageAttachments[0].payload.url); var request = require('request'); var FormData = require('form-data'); var form = new FormData(); form.append('photo', request(messageAttachments[0].payload.url)); checkVehicleAndRespond(form, senderID); } } function acknowledgeVehicleCheckRequest(senderID) { sendReadReceipt(senderID); sendTypingOn(senderID); } function checkVehicleAndRespond(form, senderID) { form.submit('http://localhost:6000/json', function(error, response) { if (error) throw new Error(error); console.log(response.statusCode); var body = ""; response.on('data', function(chunk) { console.log(chunk); body += chunk; }); response.on('end', function() { console.log(body); var vehicleDetails = JSON.parse(body); sendTypingOff(senderID); sendVehicleDetails(senderID, vehicleDetails); }); }); } function sendVehicleDetails(senderID, vehicleDetails) { sendTextMessage( senderID, "I found these vehicle details for you... \n\n" + "Reg number: " + vehicleDetails.reg + "\n" + "VIN: " + vehicleDetails.vin + "\n" + "Make: " + vehicleDetails.make + "\n" + "Model: " + vehicleDetails.model + "\n" + "Colour: " + vehicleDetails.colour + "\n" + "Engine size: " + vehicleDetails.engineCapacity + "\n" + "Fuel: " + vehicleDetails.fuelType + "\n" + "First registration date: " + vehicleDetails.dateOfFirstRegistration + "\n" + "MOT: " + vehicleDetails.motDetails + "\n" ); } /* * Delivery Confirmation Event * * This event is sent to confirm the delivery of a message. Read more about * these fields at https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-delivered * */ function receivedDeliveryConfirmation(event) { var senderID = event.sender.id; var recipientID = event.recipient.id; var delivery = event.delivery; var messageIDs = delivery.mids; var watermark = delivery.watermark; var sequenceNumber = delivery.seq; if (messageIDs) { messageIDs.forEach(function(messageID) { console.log("Received delivery confirmation for message ID: %s", messageID); }); } console.log("All message before %d were delivered.", watermark); } /* * Postback Event * * This event is called when a postback is tapped on a Structured Message. * https://developers.facebook.com/docs/messenger-platform/webhook-reference/postback-received * */ function receivedPostback(event) { var senderID = event.sender.id; var recipientID = event.recipient.id; var timeOfPostback = event.timestamp; // The 'payload' param is a developer-defined field which is set in a postback // button for Structured Messages. var payload = event.postback.payload; console.log("Received postback for user %d and page %d with payload '%s' " + "at %d", senderID, recipientID, payload, timeOfPostback); // When a postback is called, we'll send a message back to the sender to // let them know it was successful sendTextMessage(senderID, "Postback called"); } /* * Message Read Event * * This event is called when a previously-sent message has been read. * https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-read * */ function receivedMessageRead(event) { var senderID = event.sender.id; var recipientID = event.recipient.id; // All messages before watermark (a timestamp) or sequence have been seen. var watermark = event.read.watermark; var sequenceNumber = event.read.seq; console.log("Received message read event for watermark %d and sequence " + "number %d", watermark, sequenceNumber); } /* * Account Link Event * * This event is called when the Link Account or UnLink Account action has been * tapped. * https://developers.facebook.com/docs/messenger-platform/webhook-reference/account-linking * */ function receivedAccountLink(event) { var senderID = event.sender.id; var recipientID = event.recipient.id; var status = event.account_linking.status; var authCode = event.account_linking.authorization_code; console.log("Received account link event with for user %d with status %s " + "and auth code %s ", senderID, status, authCode); } /* * If users came here through testdrive, they need to configure the server URL * in default.json before they can access local resources likes images/videos. */ function requiresServerURL(next, [recipientId, ...args]) { if (SERVER_URL === "to_be_set_manually") { var messageData = { recipient: { id: recipientId }, message: { text: ` We have static resources like images and videos available to test, but you need to update the code you downloaded earlier to tell us your current server url. 1. Stop your node server by typing ctrl-c 2. Paste the result you got from running "lt —port 5000" into your config/default.json file as the "serverURL". 3. Re-run "node app.js" Once you've finished these steps, try typing “video” or “image”. ` } } callSendAPI(messageData); } else { next.apply(this, [recipientId, ...args]); } } function sendHiMessage(recipientId) { var messageData = { recipient: { id: recipientId }, message: { text: ` Congrats on setting up the DVLA Vehicle Check bot! To get details of a vehicle simply send the vehicle registration number or just upload a picture of a vehicle containing the registration number` } } callSendAPI(messageData); } /* * Send an image using the Send API. * */ function sendImageMessage(recipientId) { var messageData = { recipient: { id: recipientId }, message: { attachment: { type: "image", payload: { url: SERVER_URL + "/assets/rift.png" } } } }; callSendAPI(messageData); } /* * Send a Gif using the Send API. * */ function sendGifMessage(recipientId) { var messageData = { recipient: { id: recipientId }, message: { attachment: { type: "image", payload: { url: SERVER_URL + "/assets/instagram_logo.gif" } } } }; callSendAPI(messageData); } /* * Send audio using the Send API. * */ function sendAudioMessage(recipientId) { var messageData = { recipient: { id: recipientId }, message: { attachment: { type: "audio", payload: { url: SERVER_URL + "/assets/sample.mp3" } } } }; callSendAPI(messageData); } /* * Send a video using the Send API. * */ function sendVideoMessage(recipientId) { var messageData = { recipient: { id: recipientId }, message: { attachment: { type: "video", payload: { url: SERVER_URL + "/assets/allofus480.mov" } } } }; callSendAPI(messageData); } /* * Send a file using the Send API. * */ function sendFileMessage(recipientId) { var messageData = { recipient: { id: recipientId }, message: { attachment: { type: "file", payload: { url: SERVER_URL + "/assets/test.txt" } } } }; callSendAPI(messageData); } /* * Send a text message using the Send API. * */ function sendTextMessage(recipientId, messageText) { var messageData = { recipient: { id: recipientId }, message: { text: messageText, metadata: "DEVELOPER_DEFINED_METADATA" } }; callSendAPI(messageData); } /* * Send a button message using the Send API. * */ function sendButtonMessage(recipientId) { var messageData = { recipient: { id: recipientId }, message: { attachment: { type: "template", payload: { template_type: "button", text: "This is test text", buttons:[{ type: "web_url", url: "https://www.oculus.com/en-us/rift/", title: "Open Web URL" }, { type: "postback", title: "Trigger Postback", payload: "DEVELOPER_DEFINED_PAYLOAD" }, { type: "phone_number", title: "Call Phone Number", payload: "+16505551234" }] } } } }; callSendAPI(messageData); } /* * Send a Structured Message (Generic Message type) using the Send API. * */ function sendGenericMessage(recipientId) { var messageData = { recipient: { id: recipientId }, message: { attachment: { type: "template", payload: { template_type: "generic", elements: [{ title: "rift", subtitle: "Next-generation virtual reality", item_url: "https://www.oculus.com/en-us/rift/", image_url: SERVER_URL + "/assets/rift.png", buttons: [{ type: "web_url", url: "https://www.oculus.com/en-us/rift/", title: "Open Web URL" }, { type: "postback", title: "Call Postback", payload: "Payload for first bubble", }], }, { title: "touch", subtitle: "Your Hands, Now in VR", item_url: "https://www.oculus.com/en-us/touch/", image_url: SERVER_URL + "/assets/touch.png", buttons: [{ type: "web_url", url: "https://www.oculus.com/en-us/touch/", title: "Open Web URL" }, { type: "postback", title: "Call Postback", payload: "Payload for second bubble", }] }] } } } }; callSendAPI(messageData); } /* * Send a receipt message using the Send API. * */ function sendReceiptMessage(recipientId) { // Generate a random receipt ID as the API requires a unique ID var receiptId = "order" + Math.floor(Math.random()*1000); var messageData = { recipient: { id: recipientId }, message:{ attachment: { type: "template", payload: { template_type: "receipt", recipient_name: "Peter Chang", order_number: receiptId, currency: "USD", payment_method: "Visa 1234", timestamp: "1428444852", elements: [{ title: "Oculus Rift", subtitle: "Includes: headset, sensor, remote", quantity: 1, price: 599.00, currency: "USD", image_url: SERVER_URL + "/assets/riftsq.png" }, { title: "Samsung Gear VR", subtitle: "Frost White", quantity: 1, price: 99.99, currency: "USD", image_url: SERVER_URL + "/assets/gearvrsq.png" }], address: { street_1: "1 Hacker Way", street_2: "", city: "Menlo Park", postal_code: "94025", state: "CA", country: "US" }, summary: { subtotal: 698.99, shipping_cost: 20.00, total_tax: 57.67, total_cost: 626.66 }, adjustments: [{ name: "New Customer Discount", amount: -50 }, { name: "$100 Off Coupon", amount: -100 }] } } } }; callSendAPI(messageData); } /* * Send a message with Quick Reply buttons. * */ function sendQuickReply(recipientId) { var messageData = { recipient: { id: recipientId }, message: { text: "What's your favorite movie genre?", quick_replies: [ { "content_type":"text", "title":"Action", "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_ACTION" }, { "content_type":"text", "title":"Comedy", "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_COMEDY" }, { "content_type":"text", "title":"Drama", "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_DRAMA" } ] } }; callSendAPI(messageData); } /* * Send a read receipt to indicate the message has been read * */ function sendReadReceipt(recipientId) { console.log("Sending a read receipt to mark message as seen"); var messageData = { recipient: { id: recipientId }, sender_action: "mark_seen" }; callSendAPI(messageData); } /* * Turn typing indicator on * */ function sendTypingOn(recipientId) { console.log("Turning typing indicator on"); var messageData = { recipient: { id: recipientId }, sender_action: "typing_on" }; callSendAPI(messageData); } /* * Turn typing indicator off * */ function sendTypingOff(recipientId) { console.log("Turning typing indicator off"); var messageData = { recipient: { id: recipientId }, sender_action: "typing_off" }; callSendAPI(messageData); } /* * Send a message with the account linking call-to-action * */ function sendAccountLinking(recipientId) { var messageData = { recipient: { id: recipientId }, message: { attachment: { type: "template", payload: { template_type: "button", text: "Welcome. Link your account.", buttons:[{ type: "account_link", url: SERVER_URL + "/authorize" }] } } } }; callSendAPI(messageData); } /* * Call the Send API. The message data goes in the body. If successful, we'll * get the message id in a response * */ function callSendAPI(messageData) { request({ uri: 'https://graph.facebook.com/v2.6/me/messages', qs: { access_token: PAGE_ACCESS_TOKEN }, method: 'POST', json: messageData }, function (error, response, body) { if (!error && response.statusCode == 200) { var recipientId = body.recipient_id; var messageId = body.message_id; if (messageId) { console.log("Successfully sent message with id %s to recipient %s", messageId, recipientId); } else { console.log("Successfully called Send API for recipient %s", recipientId); } } else { console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error); } }); } // Start server // Webhooks must be available via SSL with a certificate signed by a valid // certificate authority. app.listen(app.get('port'), function() { console.log('Node app is running on port', app.get('port')); }); module.exports = app;
import { useState } from "react"; import { AiOutlineCamera, AiOutlineDelete } from "react-icons/ai"; import { BiCopy } from 'react-icons/bi'; import { connect } from 'react-redux'; import { delScene, changeNameScene, duplicateScene, createThumbnail, changeCurScene, changeCurLayer, } from '../../../redux/actions'; import { getNumScene } from "../../../redux/selectors"; import DeleteModal from "../../DeleteModal"; import RenameModal from "../../RenameModal"; import ImageModal from "./ImageModal"; const SceneView = (props) => { const [show, setShow] = useState(false); const [showDelete, setShowDelete] = useState(false); const [showImage, setShowImage] = useState(false); const onClickDeleteOK = () => { props.delScene(props.id); }; const checkShow = () => { if (!props.inactiveDelete) { setShowDelete(true); } } const changeScene = () => { props.changeCurScene(props.id, props.nameScene); props.changeCurLayer(null); } const createThumbnail = url => { props.createThumbnail(url, props.id); } const rename = newName => { props.changeNameScene(newName, props.id); } const color = (props.id === props.onSelect) ? ' bottom-active' : ''; return ( <div className={`scene-view${color}`} style={{ backgroundImage: `url(${props.img})`, backgroundSize: 'cover' }} > <div className='click-scene-1' onClick={changeScene} /> <div className='buttons-scene-view'> <div className='button-scene-view hover' onClick={() => setShowImage(true)}> <AiOutlineCamera /> </div> <ImageModal setShowImage={setShowImage} showImage={showImage} updateImage={createThumbnail} /> <div className='button-scene-view hover' onClick={() => props.duplicateScene(props.id, props.numScene)}> <BiCopy /> </div> <div className={`button-scene-view hover${props.inactiveDelete ? ' inactive-true' : ''}`} onClick={checkShow}> <AiOutlineDelete /> </div> <DeleteModal setShowDelete={setShowDelete} showDelete={showDelete} onClickDeleteOK={onClickDeleteOK} /> </div> <div className='click-scene-2' onClick={changeScene} /> <span className='name-scene-view' onDoubleClick={() => setShow(true)}> {props.nameScene} </span> <RenameModal show={show} setShow={setShow} name={props.nameScene} rename={rename} /> </div> ); }; const mapStateToProps = state => ({ numScene: getNumScene(state), }); export default connect( mapStateToProps, { delScene, createThumbnail, duplicateScene, changeNameScene, changeCurScene, changeCurLayer } )(SceneView);
export default [ //possible future migrations go here ]
const { test } = require("tap"); const sandbox = require("@log4js-node/sandboxed-module"); const util = require("util"); const recording = require("../../lib/appenders/recording"); test("log4js", batch => { batch.test("shutdown should return appenders and categories back to initial state", t => { const stringifyMap = (map) => JSON.stringify(Array.from(map)); const deepCopyMap = (map) => new Map(JSON.parse(stringifyMap(map))); const log4js = require("../../lib/log4js"); const appenders = require("../../lib/appenders"); const categories = require("../../lib/categories"); const initialAppenders = deepCopyMap(appenders); const initialCategories = deepCopyMap(categories); log4js.configure({ appenders: { recorder: { type: "recording" } }, categories: { default: { appenders: ["recorder"], level: "DEBUG" } } }); const configuredAppenders = deepCopyMap(appenders); const configuredCategories = deepCopyMap(categories); t.not( stringifyMap(configuredAppenders), stringifyMap(initialAppenders), "appenders should be different from initial state" ); t.not( stringifyMap(configuredCategories), stringifyMap(initialCategories), "categories should be different from initial state" ); log4js.shutdown(() => { const finalAppenders = deepCopyMap(appenders); const finalCategories = deepCopyMap(categories); t.equal( stringifyMap(finalAppenders), stringifyMap(initialAppenders), "appenders should revert back to initial state" ); t.equal( stringifyMap(finalCategories), stringifyMap(initialCategories), "categories should revert back to initial state" ); t.end(); }); }); batch.test("getLogger", t => { const log4js = require("../../lib/log4js"); log4js.configure({ appenders: { recorder: { type: "recording" } }, categories: { default: { appenders: ["recorder"], level: "DEBUG" } } }); const logger = log4js.getLogger("tests"); t.test("should take a category and return a logger", assert => { assert.equal(logger.category, "tests"); assert.equal(logger.level.toString(), "DEBUG"); assert.type(logger.debug, "function"); assert.type(logger.info, "function"); assert.type(logger.warn, "function"); assert.type(logger.error, "function"); assert.type(logger.fatal, "function"); assert.end(); }); t.test("log events", assert => { recording.reset(); logger.debug("Debug event"); logger.trace("Trace event 1"); logger.trace("Trace event 2"); logger.warn("Warning event"); logger.error("Aargh!", new Error("Pants are on fire!")); logger.error("Simulated CouchDB problem", { err: 127, cause: "incendiary underwear" }); const events = recording.replay(); assert.equal(events[0].level.toString(), "DEBUG"); assert.equal(events[0].data[0], "Debug event"); assert.type(events[0].startTime, "Date"); assert.equal(events.length, 4, "should not emit events of a lower level"); assert.equal(events[1].level.toString(), "WARN"); assert.type( events[2].data[1], "Error", "should include the error if passed in" ); assert.equal(events[2].data[1].message, "Pants are on fire!"); assert.end(); }); t.end(); }); batch.test("when shutdown is called", t => { const events = { shutdownCalled: [] }; const log4js = sandbox.require("../../lib/log4js", { requires: { "./appenders/file": { name: "file", configure() { function thing(evt) { events.event = evt; return null; } thing.shutdown = function(cb) { events.shutdownCalled.push(true); cb(); }; return thing; } } } }); const config = { appenders: { file: { type: "file", filename: "cheesy-wotsits.log", maxLogSize: 1024, backups: 3 }, alsoFile: { type: "file" } }, categories: { default: { appenders: ["file", "alsoFile"], level: "DEBUG" } } }; log4js.configure(config); const logger = log4js.getLogger(); log4js.shutdown(() => { t.equal( events.shutdownCalled.length, 2, "should invoke appender shutdowns" ); logger.info("this should not go to the appenders"); t.notOk(events.event); t.end(); }); }); batch.test("configuration when passed as filename", t => { let appenderConfig; let configFilename; const log4js = sandbox.require("../../lib/log4js", { ignoreMissing: true, requires: { fs: { statSync() { return { mtime: Date.now() }; }, readFileSync(filename) { configFilename = filename; return JSON.stringify({ appenders: { file: { type: "file", filename: "whatever.log" } }, categories: { default: { appenders: ["file"], level: "DEBUG" } } }); }, readdirSync() { return ["file"]; } }, "./file": { configure(configuration) { appenderConfig = configuration; return function() {}; } } } }); log4js.configure("/path/to/cheese.json"); t.equal( configFilename, "/path/to/cheese.json", "should read the config from a file" ); t.equal( appenderConfig.filename, "whatever.log", "should pass config to appender" ); t.end(); }); batch.test("with configure not called", t => { const fakeStdoutAppender = { configure() { this.required = true; return function(evt) { fakeStdoutAppender.evt = evt; }; } }; const log4js = sandbox.require("../../lib/log4js", { requires: { "./appenders/stdout": fakeStdoutAppender } }); const logger = log4js.getLogger("some-logger"); logger.debug("This is a test"); t.ok(fakeStdoutAppender.required, "stdout should be required"); t.notOk(fakeStdoutAppender.evt, "should not log anything"); t.end(); }); batch.test("with configure called with empty values", t => { [null, undefined, "", " ", []].forEach(config => { const log4js = require("../../lib/log4js"); const expectedError = `Problem reading config from file "${util.inspect( config )}". Error was ENOENT: no such file or directory`; t.throws(() => log4js.configure(config), expectedError); }); t.end(); }); batch.test("configuration persistence", t => { const firstLog4js = require("../../lib/log4js"); firstLog4js.configure({ appenders: { recorder: { type: "recording" } }, categories: { default: { appenders: ["recorder"], level: "DEBUG" } } }); recording.reset(); const secondLog4js = require("../../lib/log4js"); secondLog4js .getLogger() .info("This should go to the appender defined in firstLog4js"); t.equal( recording.replay()[0].data[0], "This should go to the appender defined in firstLog4js" ); t.end(); }); batch.end(); });
//>>built define("dojox/data/QueryReadStore",["dojo","dojox","dojo/data/util/sorter","dojo/string"],function(f,p){return f.declare("dojox.data.QueryReadStore",null,{url:"",requestMethod:"get",_className:"dojox.data.QueryReadStore",_items:[],_lastServerQuery:null,_numRows:-1,lastRequestHash:null,doClientPaging:!1,doClientSorting:!1,_itemsByIdentity:null,_identifier:null,_features:{"dojo.data.api.Read":!0,"dojo.data.api.Identity":!0},_labelAttr:"label",constructor:function(a){f.mixin(this,a)},getValue:function(a, c,e){this._assertIsItem(a);if(!f.isString(c))throw Error(this._className+".getValue(): Invalid attribute, string expected!");return!this.hasAttribute(a,c)&&e?e:a.i[c]},getValues:function(a,c){this._assertIsItem(a);var e=[];this.hasAttribute(a,c)&&e.push(a.i[c]);return e},getAttributes:function(a){this._assertIsItem(a);var c=[],e;for(e in a.i)c.push(e);return c},hasAttribute:function(a,c){return this.isItem(a)&&"undefined"!=typeof a.i[c]},containsValue:function(a,c,e){a=this.getValues(a,c);c=a.length; for(var b=0;b<c;b++)if(a[b]==e)return!0;return!1},isItem:function(a){return a?"undefined"!=typeof a.r&&a.r==this:!1},isItemLoaded:function(a){return this.isItem(a)},loadItem:function(a){this.isItemLoaded(a.item)},fetch:function(a){a=a||{};a.store||(a.store=this);var c=this;this._fetchItems(a,function(a,b,d){var e=b.abort||null,g=!1,k=b.start?b.start:0;0==c.doClientPaging&&(k=0);var m=b.count?k+b.count:a.length;b.abort=function(){g=!0;e&&e.call(b)};var l=b.scope||f.global;b.store||(b.store=c);b.onBegin&& b.onBegin.call(l,d,b);b.sort&&c.doClientSorting&&a.sort(f.data.util.sorter.createSortFunction(b.sort,c));if(b.onItem)for(d=k;d<a.length&&d<m;++d){var n=a[d];g||b.onItem.call(l,n,b)}b.onComplete&&!g&&(d=null,b.onItem||(d=a.slice(k,m)),b.onComplete.call(l,d,b))},function(a,b){b.onError&&b.onError.call(b.scope||f.global,a,b)});return a},getFeatures:function(){return this._features},close:function(a){},getLabel:function(a){if(this._labelAttr&&this.isItem(a))return this.getValue(a,this._labelAttr)},getLabelAttributes:function(a){return this._labelAttr? [this._labelAttr]:null},_xhrFetchHandler:function(a,c,e,b){a=this._filterResponse(a);a.label&&(this._labelAttr=a.label);b=a.numRows||-1;this._items=[];f.forEach(a.items,function(a){this._items.push({i:a,r:this})},this);a=a.identifier;this._itemsByIdentity={};if(a){this._identifier=a;var d;for(d=0;d<this._items.length;++d){var h=this._items[d].i,g=h[a];if(this._itemsByIdentity[g])throw Error(this._className+": The json data as specified by: ["+this.url+"] is malformed. Items within the list have identifier: ["+ a+"]. Value collided: ["+g+"]");this._itemsByIdentity[g]=h}}else for(this._identifier=Number,d=0;d<this._items.length;++d)this._items[d].n=d;b=this._numRows=-1===b?this._items.length:b;e(this._items,c,b);this._numRows=b},_fetchItems:function(a,c,e){var b=a.serverQuery||a.query||{};this.doClientPaging||(b.start=a.start||0,a.count&&(b.count=a.count));if(!this.doClientSorting&&a.sort){var d=[];f.forEach(a.sort,function(a){a&&a.attribute&&d.push((a.descending?"-":"")+a.attribute)});b.sort=d.join(",")}if(this.doClientPaging&& null!==this._lastServerQuery&&f.toJson(b)==f.toJson(this._lastServerQuery))this._numRows=-1===this._numRows?this._items.length:this._numRows,c(this._items,a,this._numRows);else{var h=("post"==this.requestMethod.toLowerCase()?f.xhrPost:f.xhrGet)({url:this.url,handleAs:"json-comment-optional",content:b,failOk:!0});a.abort=function(){h.cancel()};h.addCallback(f.hitch(this,function(b){this._xhrFetchHandler(b,a,c,e)}));h.addErrback(function(b){e(b,a)});this.lastRequestHash=(new Date).getTime()+"-"+String(Math.random()).substring(2); this._lastServerQuery=f.mixin({},b)}},_filterResponse:function(a){return a},_assertIsItem:function(a){if(!this.isItem(a))throw Error(this._className+": Invalid item argument.");},_assertIsAttribute:function(a){if("string"!==typeof a)throw Error(this._className+": Invalid attribute argument ('"+a+"').");},fetchItemByIdentity:function(a){if(this._itemsByIdentity){var c=this._itemsByIdentity[a.identity];if(void 0!==c){a.onItem&&a.onItem.call(a.scope?a.scope:f.global,{i:c,r:this});return}}this._fetchItems({serverQuery:{id:a.identity}}, function(c,b){var d=a.scope?a.scope:f.global;try{var e=null;c&&1==c.length&&(e=c[0]);a.onItem&&a.onItem.call(d,e)}catch(g){a.onError&&a.onError.call(d,g)}},function(c,b){var d=a.scope?a.scope:f.global;a.onError&&a.onError.call(d,c)})},getIdentity:function(a){var c=null;return c=this._identifier===Number?a.n:a.i[this._identifier]},getIdentityAttributes:function(a){return[this._identifier]}})}); //# sourceMappingURL=QueryReadStore.js.map
import { defineMessages } from 'react-intl'; const messages = defineMessages({ emailPlaceholder: { id: 'EmailPasswordSignUpForm.emailPlaceholder', defaultMessage: 'Enter your email', description: 'Placeholder for the email input in the sign up form', }, passwordPlaceholder: { id: 'EmailPasswordSignUpForm.passwordPlaceholder', defaultMessage: 'Enter your password', description: 'Placeholder for the password input in the sign up form', }, }); export default messages;
if ( (typeof module === "object" || typeof module === "function") && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } }
import axios from "axios"; //Revealing Module Pattern const F1API = (function () { console.log("F1API created."); const apiEndpoint = "http://ergast.com/api/f1"; //public methods const getConstructorDrivers = async (season, constructorId) => { try { const response = await axios.get( `http://ergast.com/api/f1/${season}/constructors/${constructorId}/drivers.json` ); const data = response.data.MRData.DriverTable.Drivers; console.log("Drivers ▶️", data); return data; } catch (error) { console.error(error); return null; } }; const getConstructors = async (season) => { try { const response = await axios.get( `http://ergast.com/api/f1/${season}/constructorStandings.json` ); return response.data.MRData.StandingsTable.StandingsLists[0] .ConstructorStandings; // append drivers /* let updatedConstructors = await constructors.reduce( async (initial, current) => { let collection = await initial; const constructorId = current.Constructor.constructorId; const drivers = await getConstructorDrivers(constructorId); current.drivers = drivers; collection.push(current); return collection; }, Promise.resolve([]) ); return updatedConstructors; */ } catch (error) { console.log(error); return null; } }; const getRaces = async () => { try { const response = await axios.get(`${apiEndpoint}/current.json`); let data = response.data.MRData.RaceTable.Races; return data; } catch (error) { console.log(error); return null; } }; const getDrivers = async () => { try { const response = await axios.get( `${apiEndpoint}/current/driverStandings.json` ); return response.data.MRData.StandingsTable.StandingsLists[0] .DriverStandings; } catch (error) { console.log(error); return null; } }; const getRaceResults = async (round) => { try { const response = await axios.get( `${apiEndpoint}/current/${round}/results.json` ); let data = []; if (response.data.MRData.RaceTable.Races[0]) { data = response.data.MRData.RaceTable.Races[0].Results; } return data; } catch (error) { console.log(error); return null; } }; const getQualifyingResults = async (round) => { try { const response = await axios.get( `http://ergast.com/api/f1/current/${round}/qualifying.json` ); let data = []; if (response.data.MRData.RaceTable.Races[0]) { data = response.data.MRData.RaceTable.Races[0].QualifyingResults; } return data; } catch (error) { console.log(error); return null; } }; const getDriverSeasonResults = async (driverId) => { try { const response = await axios.get( `http://ergast.com/api/f1/current/drivers/${driverId}/results.json` ); let data = []; if (response.data.MRData.RaceTable.Races[0]) { data = response.data.MRData.RaceTable.Races; } return data; } catch (error) { console.log(error); return null; } }; const getRaceLapTimesForDriver = async (round, driverId) => { try { const response = await axios.get( `http://ergast.com/api/f1/current/${round}/drivers/${driverId}/laps.json?limit=75` ); let data = {}; if (response.data.MRData.RaceTable.Races[0]) { data = response.data.MRData.RaceTable.Races[0].Laps; } return { driverId: driverId, lap_times: data }; } catch (error) { console.error(error); return null; } }; return { getConstructorDrivers, getConstructors, getRaces, getDrivers, getDriverSeasonResults, getRaceResults, getQualifyingResults, getRaceLapTimesForDriver, }; })(); export default F1API;
!function(e){"use strict";function t(t,a){var n=[];return e.forEach(t,function(t){n.push(e.isFunction(a)?a(t):t[a])}),n}var a=[].indexOf||function(e){for(var t=0,a=this.length;a>t;t++)if(t in this&&this[t]===e)return t;return-1};e.module("pickadate",[]).provider("pickadateI18n",function(){var e={prev:"prev",next:"next"};this.translations={},this.$get=function(){var t=this.translations;return{t:function(a){return t[a]||e[a]}}}}).factory("pickadateModalBindings",["$window","$document",function(e,t){var n=void 0!==e.pageXOffset,i="CSS1Compat"===(t.compatMode||""),r=function(a){var r=n?e.pageXOffset:i?t.documentElement.scrollLeft:t.body.scrollLeft,o=n?e.pageYOffset:i?t.documentElement.scrollTop:t.body.scrollTop,s=e.innerWidth||t.documentElement.clientWidth||t.body.clientWidth,c={top:o+a.getBoundingClientRect().bottom+"px"};return s-a.getBoundingClientRect().left>=300?c.left=r+a.getBoundingClientRect().left+"px":c.right=s-a.getBoundingClientRect().right-r+"px",c},o=function(e,t){for(var a=t.parentNode;null!==a;){if(a===e)return!0;a=a.parentNode}return!1};return function(e,n,i){var s=function(t){e.displayPicker=t,e.$apply()};n.on("focus",function(){e.modalStyles=r(n[0]),s(!0)}),n.on("keydown",function(e){a.call([9,13,27],e.keyCode)>=0&&s(!1)}),t.on("click",function(e){o(i,e.target)||e.target===n[0]||s(!1)})}}]).factory("pickadateDateHelper",["$locale","dateFilter",function(t,n){function i(e){switch(e){case"dd":return"day";case"MM":return"month";case"yyyy":return"year"}}return function(r,o){var s,c,l,d,u,f;return o=o||{},r=r||"yyyy-MM-dd",u=o.weekStartsOn,f=o.noExtraRows,(!e.isNumber(u)||0>u||u>6)&&(u=0),{parseDate:function(t){if(t){if(e.isDate(t))return new Date(t);var a="(dd|MM|yyyy)",n=r.match(/[-|/]/)[0],o=t.split(n),s=new RegExp([a,a,a].join(n)),c=r.match(s),l={};if(c.shift(),e.forEach(c,function(e,t){l[i(e)]=parseInt(o[t],10)}),!(isNaN(l.year)||isNaN(l.month)||isNaN(l.day)))return new Date(l.year,l.month-1,l.day,3)}},setRestrictions:function(e){s=this.parseDate(e.minDate)||new Date(0),c=this.parseDate(e.maxDate)||new Date(99999999999999),d=e.currentDate,l=e.disabledDates||[]},allowPrevMonth:function(){return d>s},allowNextMonth:function(){var t=e.copy(d);return t.setMonth(t.getMonth()+1),c>=t},buildDateObject:function(t){var i=e.copy(t),u=n(i,r),f=a.call(l,u)>=0,p=this.getMonthOffset(i,d),h=s>i,v=i>c,y=-1===p&&!o.previousMonthSelectable||1===p&&!o.nextMonthSelectable;return{date:i,formattedDate:u,today:u===n(new Date,r),disabled:f,outOfMinRange:h,outOfMaxRange:v,monthOffset:p,enabled:!(f||h||v||y)}},buildDates:function(t,a,n){var i=[],r=new Date(t,a,1,3),o=new Date(t,a+1,0,3);for(n=n||{},d=e.copy(r);r.getDay()!==u;)r.setDate(r.getDate()-1);for(var s=0;42>s&&!(f&&r.getDay()===u&&r>o);s++)i.push(this.buildDateObject(r)),r.setDate(r.getDate()+1);return i},buildDayNames:function(){var e=t.DATETIME_FORMATS.SHORTDAY;if(u){e=e.slice(0);for(var a=0;u>a;a++)e.push(e.shift())}return e},getMonthOffset:function(e,t){return e.getMonth()-t.getMonth()+12*(e.getFullYear()-t.getFullYear())}}}}]).directive("pickadate",["$locale","$sce","$compile","$document","$window","pickadateDateHelper","pickadateI18n","pickadateModalBindings","filterFilter",function(n,i,r,o,s,c,l,d,u){var f='<div class="pickadate" ng-show="displayPicker" ng-style="modalStyles"><div class="pickadate-header"><div class="pickadate-controls"><a href="" class="pickadate-prev" ng-click="changeMonth(-1)" ng-show="allowPrevMonth">'+i.trustAsHtml(l.t("prev"))+'</a><a href="" class="pickadate-next" ng-click="changeMonth(1)" ng-show="allowNextMonth">'+i.trustAsHtml(l.t("next"))+'</a></div><h3 class="pickadate-centered-heading">{{currentDate | date:"MMMM yyyy"}}</h3></div><div class="pickadate-body"><div class="pickadate-main"><ul class="pickadate-cell"><li class="pickadate-head" ng-repeat="dayName in dayNames">{{dayName}}</li></ul><ul class="pickadate-cell"><li ng-repeat="dateObj in dates" ng-click="setDate(dateObj)" ng-class="classesFor(dateObj)">{{dateObj.date | date:"d"}}</li></ul></div></div></div>';return{require:"ngModel",scope:{defaultDate:"=",minDate:"=",maxDate:"=",disabledDates:"=",weekStartsOn:"="},link:function(n,i,o,s){function l(){var e=M.buildDates(n.currentDate.getFullYear(),n.currentDate.getMonth());n.allowPrevMonth=M.allowPrevMonth(),n.allowNextMonth=M.allowNextMonth(),n.dayNames=M.buildDayNames(),n.dates=t(e,function(e){return e.classNames=[e.enabled?"pickadate-enabled":"pickadate-disabled"],e.today&&e.classNames.push("pickadate-today"),e.disabled&&e.classNames.push("pickadate-unavailable"),e})}function p(e,a){a=a||{},s.$setViewValue(v?t(e,"formattedDate"):e[0]&&e[0].formattedDate),a.skipRenderInput||i.val(s.$viewValue)}function h(e,t){var n=a.call(t,e);return-1===n?t.push(e):t.splice(n,1),t}var v=o.hasOwnProperty("multiple"),y=[],D=i[0]instanceof HTMLInputElement,g=r(f)(n),m=(o.format||"yyyy-MM-dd").replace(/m/g,"M"),M=c(m,{previousMonthSelectable:/^(previous|both)$/.test(o.selectOtherMonths),nextMonthSelectable:/^(next|both)$/.test(o.selectOtherMonths),weekStartsOn:n.weekStartsOn,noExtraRows:o.hasOwnProperty("noExtraRows")});n.displayPicker=!D,n.setDate=function(e){e.enabled&&(y=v?h(e,y):[e],p(y),n.changeMonth(e.monthOffset),n.displayPicker=!D)};var w=s.$render=function(a){e.isArray(s.$viewValue)?y=s.$viewValue:s.$viewValue&&(y=[s.$viewValue]),n.currentDate=M.parseDate(n.defaultDate||y[0])||new Date,M.setRestrictions(n),y=t(y,function(e){return M.buildDateObject(M.parseDate(e))}),y=u(y,{enabled:!0}),p(y,a),l()};n.classesFor=function(e){var n=t(y,"formattedDate"),i=a.call(n,e.formattedDate)>=0?"pickadate-active":null;return e.classNames.concat(i)},n.changeMonth=function(e){e&&(n.currentDate.setDate(1),n.currentDate.setMonth(n.currentDate.getMonth()+e),l())},n.$watch(function(){return e.toJson([n.minDate,n.maxDate,n.disabledDates])},w),D?(d(n,i,g[0]),n.$watch(function(){return s.$viewValue},function(e){var t=M.parseDate(e);t&&w({skipRenderInput:!0}),s.$setValidity("date",!!t)}),n.$$postDigest(function(){o.value&&(s.$viewValue=o.value,w())}),i.after(g.addClass("pickadate-modal"))):i.append(g)}}}])}(window.angular);
import React from 'react'; import Icon from '../Icon'; /* eslint-disable react/jsx-props-no-spreading */ export default function IconCamera(props) { return ( <Icon {...props}> <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" /> <circle cx="12" cy="13" r="4" /> </Icon> ); }
const net = require("net"); const yargs = require("yargs"); const { hideBin } = require("yargs/helpers"); const { blake2bInit, blake2bUpdate, blake2bFinal } = require("blakejs"); const NO_CONNECTION = 14; function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } function sleep(ms) { return new Promise((resolve) => { setTimeout(resolve, ms); }); } function withTimeout(ms, promise, message = "") { const timeout = new Promise((_resolve, reject) => { setTimeout( () => reject(new Error(message || `Timed out after ${ms}ms`)), ms ); }); return Promise.race([timeout, promise]); } async function waitFor( asyncTestFn, toBe, maxTimeMs, timeOut = 500, skipLog = 50 ) { const now = new Date(); let i = 0; while (new Date() - now < maxTimeMs) { try { const value = await asyncTestFn(); if (value === toBe) { if (i > 1) { console.log("waiting for process...", timeOut, i, value); } break; } if (i % skipLog === 0 && i > 1) { console.log("waiting for process...", timeOut, i, value); } await sleep(timeOut); i++; } catch (e) { if (i > 1) { if (e && e.code && e.code === NO_CONNECTION) { console.log("No connection yet (waitFor)..."); } else { console.error("Error in waitFor: ", e); } } await sleep(timeOut); } } } async function waitForPredicate(predicate, timeOut, sleep_ms = 500) { const now = new Date(); while (new Date() - now < timeOut) { const val = await predicate(); if (val) { return val; } await sleep(sleep_ms); } throw new Error(`Predicate was not true after ${timeOut} ms`); } function dec2hex(n) { return n ? [n % 256].concat(dec2hex(~~(n / 256))) : []; } function toLittleEndianInner(n) { let hexar = dec2hex(n); hexar = hexar.map((h) => (h < 16 ? "0" : "") + h.toString(16)); if (hexar.length < 4) { return hexar.concat(Array(4 - hexar.length).fill("00")); } else { return hexar; } } function toLittleEndian(n, numBits) { const s = toLittleEndianInner(n); for (let i = s.length; i < numBits / 8; i++) { s.push("00"); } const arr = Buffer.from(s.join(""), "hex"); return arr; } function littleEndianHexStringToBigEndianHexString(string) { if (!string) return undefined; var len = string.length; var bigEndianHexString = "0x"; for (var i = 0; i < len / 2; i++) { bigEndianHexString += string.substring(len - (i + 1) * 2, len - i * 2); } return bigEndianHexString; } function hexSwitchEndianness(val) { let res = ""; for (let i = val.length - 2; i > 0; i -= 2) { res += val[i] + val[i + 1]; } return res; } // Thanks to https://stackoverflow.com/questions/29860354/in-nodejs-how-do-i-check-if-a-port-is-listening-or-in-use const portInUse = function (port, callback) { const server = net.createServer(function (socket) { socket.write("Echo server\r\n"); socket.pipe(socket); }); server.listen(port, "127.0.0.1"); server.on("error", function () { callback(true); }); server.on("listening", function () { server.close(); callback(false); }); }; let index = 0; const getFreePort = async function (from, to) { function testPort(port) { return new Promise((r) => { portInUse(port, (v) => { if (v) { r(false); } r(true); }); }); } let port = from + index; if (port > to) { index = from; port = from; } while (port < to) { // let port = getRandomInt(from, to); // await sleep(100); port++; index++; const notInUse = await testPort(port); // console.log("Port not in use:", notInUse); if (notInUse) { return port; } } }; const getTransactionOutputHash = function (output) { const KEY = null; // optional key const OUTPUT_LENGTH = 32; // bytes const context = blake2bInit(OUTPUT_LENGTH, KEY); const flags = Buffer.alloc(1); flags[0] = output.features.flags; const buffer = Buffer.concat([ flags, toLittleEndian(parseInt(output.features.maturity), 64), ]); let nopScriptBytes = Buffer.from([0x73]); blake2bUpdate(context, buffer); blake2bUpdate(context, output.commitment); blake2bUpdate(context, nopScriptBytes); let final = blake2bFinal(context); return Buffer.from(final); }; function consoleLogTransactionDetails(txnDetails, txId) { const found = txnDetails[0]; const status = txnDetails[1]; if (found) { console.log( " Transaction " + pad("'" + status.transactions[0].tx_id + "'", 24) + " has status " + pad("'" + status.transactions[0].status + "'", 40) + " and " + pad("is_cancelled(" + status.transactions[0].is_cancelled + ")", 21) + " and " + pad("is_valid(" + status.transactions[0].valid + ")", 16) ); } else { console.log(" Transaction '" + txId + "' " + status); } } function consoleLogBalance(balance) { console.log( " Available " + pad(balance.available_balance, 16) + " uT, Pending incoming " + pad(balance.pending_incoming_balance, 16) + " uT, Pending outgoing " + pad(balance.pending_outgoing_balance, 16) + " uT" ); } function consoleLogCoinbaseDetails(txnDetails) { console.log( " Transaction " + pad("'" + txnDetails.tx_id + "'", 24) + " has status " + pad("'" + txnDetails.status + "'", 40) + " and " + pad("is_cancelled(" + txnDetails.is_cancelled + ")", 21) + " and " + pad("is_valid(" + txnDetails.valid + ")", 16) ); } function pad(str, length, padLeft = true) { const padding = Array(length).join(" "); if (typeof str === "undefined") return padding; if (padLeft) { return (padding + str).slice(-padding.length); } else { return (str + padding).substring(" ", padding.length); } } function combineTwoTariKeys(key1, key2) { let total_key = BigInt(littleEndianHexStringToBigEndianHexString(key1)) + BigInt(littleEndianHexStringToBigEndianHexString(key2)); if (total_key < 0) { total_key = total_key + BigInt( littleEndianHexStringToBigEndianHexString( "edd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010" ) ); } total_key = total_key.toString(16); while (total_key.length < 64) { total_key = "0" + total_key; } total_key = littleEndianHexStringToBigEndianHexString(total_key); while (total_key.length < 64) { total_key = "0" + total_key; } return total_key; } const byteArrayToHex = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), ""); module.exports = { getRandomInt, sleep, waitFor, toLittleEndian, littleEndianHexStringToBigEndianHexString, // portInUse, getFreePort, getTransactionOutputHash, hexSwitchEndianness, consoleLogTransactionDetails, consoleLogBalance, consoleLogCoinbaseDetails, withTimeout, combineTwoTariKeys, byteArrayToHex, waitForPredicate, yargs: () => yargs(hideBin(process.argv)), NO_CONNECTION, };
const core = require('@actions/core') const versionSeparator = '\n## ' const semverLinkRegex = /^\[v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-?((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?\]/ const unreleasedLinkRegex = /^\[unreleased\]/i const avoidNonVersionData = version => semverLinkRegex.test(version) || unreleasedLinkRegex.test(version) exports.getEntries = rawData => { const content = String(rawData) core.debug(`CHANGELOG content: ${content}`) return content .split(versionSeparator) .filter(avoidNonVersionData) }
'use strict' var log = require('npmlog') var path = require('path') var Promise = require('promise') var fs = require('vigour-fs/lib/server') var _ = require('lodash') var readJSON = Promise.denodeify(fs.readJSON) var editXML = Promise.denodeify(fs.editXML) module.exports = exports = function () { if (this.builds) { var self = this var pluginInfoList = [] log.info('- installing plugins -') for (var pluginName in this.plugins) { log.info(pluginName, this.plugins[pluginName].android) } function buildAllPlugins () { function retrievePluginInfo (pluginPath) { // log.info('pluginPath', pluginPath) return readJSON(path.join(pluginPath, 'package.json')) .then(function (pluginOpts) { // log.info('loaded', pluginOpts) pluginOpts.vigour.plugin.name = pluginOpts.name pluginOpts = pluginOpts.vigour.plugin log.info('pluginOpts', pluginOpts) pluginInfoList.push(pluginOpts) return pluginOpts }) } var pluginsArr = [] var aPlugin for (var key in self.plugins) { aPlugin = self.plugins[key] aPlugin.name = key pluginsArr.push(aPlugin) } return pluginsArr.reduce(function (prev, plugin) { return prev.then(function () { // log.info(' installing plugin: ', plugin) return Promise.resolve(plugin.rootPath) .then(retrievePluginInfo) }) }, Promise.resolve()) } function installIntoTemplate () { var Template = require('./template') var template = new Template() function injectJava (imports, instantiations) { // get the java file and inject instantiations log.info(' inject into java') template.readFile(path.join(self.srcDir, self.mainJavaFile)) template.goto(new RegExp('-- start plugin imports')) imports.forEach(function (s) { var line = 'import ' + s + ';' template.insertLine(line) log.info(line) }) template.goto(new RegExp('private void registerPlugins')) instantiations.forEach(function (s) { var line = ' pluginManager.register(' + s + ');' template.insertLine(line) log.info(line) }) template.save() // template.log() return Promise.resolve() } function injectGradle (pluginInfoList) { log.info(' inject into build.gradle') // insert into gradle template.readFile(path.join(self.buildDir, 'app/build.gradle')) // template.log() template.goto(new RegExp('-- start plugin dependencies')) _.uniqBy(pluginInfoList, plugin => plugin.name) .forEach(function (info) { if (info.android.skipInstall) { return } var pluginName = 'plugin-' + info.name.replace('vigour-', '') var line = '' + " compile ('io.vigour:" + pluginName + ":+') {\n" + ' transitive=true\n' + " exclude module: 'core'\n" + ' }' template.insertLine(line) log.info(line) }) // template.log() template.save() return Promise.resolve() } function injectManifest (permissions, metadata, activities) { log.info('inject manifest') // get the Manifest and inject permissions var manifestPath = path.join(self.buildDir, 'app/src/main/AndroidManifest.xml') return editXML(manifestPath, function (xml) { // log.info('xml before', JSON.stringify(xml.manifest, null, ' ')) xml.manifest['uses-permission'] = _.chain(permissions) .map((permission) => ({ '$': { 'android:name': permission } })) .concat(xml.manifest['uses-permission']) .uniqBy((permission) => permission.$['android:name']) .value() var application = xml.manifest.application[0] activities.forEach(function (activity) { application.activity.push({'$': activity}) }) if (metadata && metadata.constructor === Array && metadata.length > 0 && !application['meta-data']) { application['meta-data'] = [] } metadata.forEach(function (metadataItem) { application['meta-data'].push({'$': metadataItem}) }) // log.info('xml after', JSON.stringify(xml.manifest, null, ' ')) return xml }) } function injectStrings (strings) { log.info('inject strings') // edit or add strings var manifestPath = path.join(self.buildDir, 'app/src/main/res/values/strings.xml') return editXML(manifestPath, function (xml) { // log.info('strings before', JSON.stringify(xml, null, ' ')) var allStrings = {} xml.resources.string.forEach(function (s) { // log.info('existing: ', s) allStrings[s.$.name] = s }) strings.forEach(function (s) { // log.info('s', s) // todo prevent doubles!! for (var key in s) { allStrings[key] = {'_': s[key], '$': {'name': key}} } }) xml.resources.string = Object.keys(allStrings).map(function (key) { return allStrings[key] }) // log.info('strings after', JSON.stringify(xml, null, ' ')) return xml }) } log.info(' installIntoTemplate') var imports = [] var instantiations = [] var permissions = [] var activities = [] var metadata = [] var strings = [] // gather info pluginInfoList.forEach(function (info) { // log.info('plugin info: ', info) if (info.android.skipInstall) { return } if (info.android.instantiation) { instantiations.push(info.android.instantiation) } if (info.android.className) { imports.push(info.android.className) } if (info.android.permissions) { permissions = permissions.concat(info.android.permissions) } if (info.android.metadata) { metadata.push(info.android.metadata) } if (info.android.activity) { activities.push(info.android.activity) } if (info.android.strings) { strings.push(info.android.strings) } }) return Promise.all([ injectJava(imports, instantiations), injectManifest(permissions, metadata, activities), injectGradle(pluginInfoList), injectStrings(strings) ]) } if (self.plugins) { // log.info('plugins: ', this.plugins) return buildAllPlugins() .then(installIntoTemplate) } else { return Promise.resolve() } } else { log.info('- skipping installing plugins -') } }
import React, { useState } from 'react'; import { withRouter } from 'react-router-dom'; var browserError = false; try { var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; var recognition = new SpeechRecognition(); recognition.lang = 'en-US'; } catch (error) { browserError = true; recognition = {}; } function FormSearch (props) { const [state, setState] = useState(''); const onSearch = (e) => { e.preventDefault(); if (state.length > 0) props.history.push('/search?s=' + state); } const onSpeech = () => { if (!browserError) { try { recognition.start(); recognition.onresult = (event) => { const sp = event.results[0][0].transcript; setState(sp); props.history.push('/search?s=' + sp); } } catch (error) { recognition.stop(); } } } return (<> <form onSubmit={onSearch} className="w-100 form-search"> <input className="form-control form-control-dark" type="search" placeholder="# Search" onChange={(e) => { setState((e.target.value).toLowerCase()); }} value={state} /> <button type="submit" className="btn btn-dark"><i className="fas fa-search"></i></button> </form> <span className="nav-link" onClick={onSpeech}><i className="fas fa-microphone"></i></span> </>); } export default withRouter(FormSearch);
(function() { "use strict"; var a = window.anima = window.a = {}; a.world = function() { return new World(); }; a.timeline = function() { return new Timeline(); }; if (typeof module === "object" && typeof module.exports === "object") { module.exports = a; } else if (typeof define === "function" && define.amd) { define(a); } var _requestAnimationFrame = window.requestAnimationFrame, _cancelAnimationFrame = window.cancelAnimationFrame; for (var i = 0, vendors = [ "webkit", "Moz", "O", "ms" ], vendor; i < vendors.length && !_requestAnimationFrame; ++i) { vendor = vendors[i]; _requestAnimationFrame = window[vendor.toLowerCase() + "RequestAnimationFrame"]; _cancelAnimationFrame = window[vendor.toLowerCase() + "CancelAnimationFrame"] || window[vendor.toLowerCase() + "CancelRequestAnimationFrame"]; } if (window.chrome && !vendor) { vendor = vendors[0]; } var _vendor = vendor ? "-" + vendor.toLowerCase() + "-" : "", _transformProperty = getProperty("transform"), _animationProperty = getProperty("animation"); function getProperty(name) { return vendor ? vendor + name[0].toUpperCase() + name.substr(1) : name; } var Vector = { set: function(x, y, z) { if (Array.isArray(x)) { y = x[1]; z = x[2]; x = x[0]; } if (x === undefined) { x = 0; } if (y === undefined) { y = x; z = x; } return [ x, y, z ]; }, length: function(x, y, z) { if (Array.isArray(x)) { y = x[1]; z = x[2]; x = x[0]; } return Math.sqrt(x * x + y * y + z * z); }, add: function(a, b) { return [ a[0] + b[0], a[1] + b[1], a[2] + b[2] ]; }, sub: function(a, b) { return [ a[0] - b[0], a[1] - b[1], a[2] - b[2] ]; }, norm: function(x, y, z) { if (Array.isArray(x)) { y = x[1]; z = x[2]; x = x[0]; } var len = this.length(x, y, z); if (len !== 0) { x /= len; y /= len; z /= len; } else { x = 0; y = 0; z = 0; } return [ x, y, z ]; }, dist: function(a, b) { var dx = a[0] - b[0], dy = a[1] - b[1], dz = a[2] - b[2]; return Math.sqrt(dx * dx + dy * dy + dz + dz); }, cross: function(a, b) { var x = a[1] * b[2] - a[2] * b[1], y = a[2] * b[0] - a[0] * b[2], z = a[1] * b[1] - a[1] * b[0]; return [ x, y, z ]; }, clone: function(v) { return v.slice(); }, scale: function(x, y, z, f) { if (Array.isArray(x)) { f = y; y = x[1]; z = x[2]; x = x[0]; } return [ x * f, y * f, z * f ]; }, zero: function() { return [ 0, 0, 0 ]; } }; var radians = Math.PI / 180; var Matrix = { identity: function() { return [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; }, multiply: function multiply(a, b) { var c = this.identity(); c[0] = a[0] * b[0] + a[1] * b[4] + a[2] * b[8]; c[1] = a[0] * b[1] + a[1] * b[5] + a[2] * b[9]; c[2] = a[0] * b[2] + a[1] * b[6] + a[2] * b[10]; c[4] = a[4] * b[0] + a[5] * b[4] + a[6] * b[8]; c[5] = a[4] * b[1] + a[5] * b[5] + a[6] * b[9]; c[6] = a[4] * b[2] + a[5] * b[6] + a[6] * b[10]; c[8] = a[8] * b[0] + a[9] * b[4] + a[10] * b[8]; c[9] = a[8] * b[1] + a[9] * b[5] + a[10] * b[9]; c[10] = a[8] * b[2] + a[9] * b[6] + a[10] * b[10]; c[12] = a[12] * b[0] + a[13] * b[4] + a[14] * b[8] + b[12]; c[13] = a[12] * b[1] + a[13] * b[5] + a[14] * b[9] + b[13]; c[14] = a[12] * b[2] + a[13] * b[6] + a[14] * b[10] + b[14]; return 2 >= arguments.length ? c : multiply.apply(this, [ c ].concat(Array.prototype.slice.call(arguments, 2))); }, translate: function(tx, ty, tz) { if (!(tx || ty || tz)) return this.identity(); tx || (tx = 0); ty || (ty = 0); tz || (tz = 0); return [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, tx, ty, tz, 1 ]; }, scale: function(sx, sy, sz) { if (!(sx || sy || sz)) return this.identity(); sx || (sx = 1); sy || (sy = 1); sz || (sz = 1); return [ sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, 0, 0, 0, 1 ]; }, rotate: function(ax, ay, az) { if (!(ax || ay || az)) return this.identity(); ax || (ax = 0); ay || (ay = 0); az || (az = 0); ax *= radians; ay *= radians; az *= radians; var sx = Math.sin(ax), cx = Math.cos(ax), sy = Math.sin(ay), cy = Math.cos(ay), sz = Math.sin(az), cz = Math.cos(az); return [ cy * cz, cx * sz + sx * sy * cz, sx * sz - cx * sy * cz, 0, -cy * sz, cx * cz - sx * sy * sz, sx * cz + cx * sy * sz, 0, sy, -sx * cy, cx * cy, 0, 0, 0, 0, 1 ]; }, rotate3d: function(x, y, z, a) { a || (a = 0); a *= radians; var s = Math.sin(a), c = Math.cos(a), norm = Vector.norm(x, y, z); x = norm[0]; y = norm[1]; z = norm[2]; var xx = x * x, yy = y * y, zz = z * z, _c = 1 - c; return [ xx + (1 - xx) * c, x * y * _c + z * s, x * z * _c - y * s, 0, x * y * _c - z * s, yy + (1 - yy) * c, y * z * _c + x * s, 0, x * z * _c + y * s, y * z * _c - x * s, zz + (1 - zz) * c, 0, 0, 0, 0, 1 ]; }, skew: function(ax, ay) { if (!(ax || ay)) return this.identity(); ax || (ax = 0); ay || (ay = 0); ax *= radians; ay *= radians; return [ 1, Math.tan(ay), 0, 0, Math.tan(ax), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; }, perspective: function(p) { p = -1 / p; return [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, p, 0, 0, 0, 1 ]; }, parse: function(s) { var m = s.match(/\((.+)\)/)[1].split(/,\s?/); if (m.length === 6) { m.splice(2, 0, "0", "0"); m.splice(6, 0, "0", "0"); m.splice(8, 0, "0", "0", "1", "0"); m.push("0", "1"); } return m; }, inverse: function(m) { var a = this.identity(), inv0 = m[5] * m[10] - m[6] * m[9], inv1 = m[1] * m[10] - m[2] * m[9], inv2 = m[1] * m[6] - m[2] * m[5], inv4 = m[4] * m[10] - m[6] * m[8], inv5 = m[0] * m[10] - m[2] * m[8], inv6 = m[0] * m[6] - m[2] * m[4], inv8 = m[4] * m[9] - m[5] * m[8], inv9 = m[0] * m[9] - m[1] * m[8], inv10 = m[0] * m[5] - m[1] * m[4], det = 1 / (m[0] * inv0 - m[1] * inv4 + m[2] * inv8); a[0] = det * inv0; a[1] = -det * inv1; a[2] = det * inv2; a[4] = -det * inv4; a[5] = det * inv5; a[6] = -det * inv6; a[8] = det * inv8; a[9] = -det * inv9; a[10] = det * inv10; a[12] = -m[12] * a[0] - m[13] * a[4] - m[14] * a[8]; a[13] = -m[12] * a[1] - m[13] * a[5] - m[14] * a[9]; a[14] = -m[12] * a[2] - m[13] * a[6] - m[14] * a[10]; return a; }, compose: function(translate, rotate, scale) { translate || (translate = []); rotate || (rotate = []); scale || (scale = []); var a = this.rotate(rotate[0], rotate[1], rotate[2]); if (scale.length) { a[0] *= scale[0]; a[1] *= scale[0]; a[2] *= scale[0]; a[4] *= scale[1]; a[5] *= scale[1]; a[6] *= scale[1]; a[8] *= scale[2]; a[9] *= scale[2]; a[10] *= scale[2]; } if (translate.length) { a[12] = translate[0]; a[13] = translate[1]; a[14] = translate[2]; } return a; }, decompose: function(m) { var sX = Vector.length(m[0], m[1], m[2]), sY = Vector.length(m[4], m[5], m[6]), sZ = Vector.length(m[8], m[9], m[10]); var rX = Math.atan2(-m[9] / sZ, m[10] / sZ) / radians, rY = Math.asin(m[8] / sZ) / radians, rZ = Math.atan2(-m[4] / sY, m[0] / sX) / radians; if (m[4] === 1 || m[4] === -1) { rX = 0; rY = m[4] * -Math.PI / 2; rZ = m[4] * Math.atan2(m[6] / sY, m[5] / sY) / radians; } var tX = m[12], tY = m[13], tZ = m[14]; return { translate: [ tX, tY, tZ ], rotate: [ rX, rY, rZ ], scale: [ sX, sY, sZ ] }; }, transpose: function(m) { var t; t = m[1]; m[1] = m[4]; m[4] = t; t = m[2]; m[2] = m[8]; m[8] = t; t = m[6]; m[6] = m[9]; m[9] = t; t = m[3]; m[3] = m[12]; m[12] = t; t = m[7]; m[7] = m[13]; m[13] = t; t = m[11]; m[11] = m[14]; m[14] = t; return m; }, lookAt: function(eye, target, up) { var z = Vector.sub(eye, target); z = Vector.norm(z); if (Vector.length(z) === 0) z[2] = 1; var x = Vector.cross(up, z); if (Vector.length(x) === 0) { z[0] += 1e-4; x = Vector.norm(Vector.cross(up, z)); } var y = Vector.cross(z, x); var a = this.identity(); a[0] = x[0]; a[1] = x[1]; a[2] = x[2]; a[4] = y[0]; a[5] = y[1]; a[6] = y[2]; a[8] = z[0]; a[9] = z[1]; a[10] = z[2]; return a; }, stringify: function(m) { for (var i = 0; i < m.length; ++i) if (Math.abs(m[i]) < 1e-6) m[i] = 0; return "matrix3d(" + m.join() + ")"; } }; function EventEmitter() { this.handlers = {}; } EventEmitter.prototype.on = function(event, handler) { (this.handlers[event] = this.handlers[event] || []).push(handler); return this; }; EventEmitter.prototype.off = function(event, handler) { var handlers = this.handlers[event]; if (handler) { handlers.splice(handlers.indexOf(handler), 1); } else { delete this.handlers[event]; } return this; }; EventEmitter.prototype.emit = function(event) { var args = Array.prototype.slice.call(arguments, 1), handlers = this.handlers[event]; if (handlers) { for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(this, args); } } return this; }; EventEmitter.prototype.listeners = function(event) { return this.handlers[event] || []; }; var easings = function() { var fn = { quad: function(p) { return Math.pow(p, 2); }, cubic: function(p) { return Math.pow(p, 3); }, quart: function(p) { return Math.pow(p, 4); }, quint: function(p) { return Math.pow(p, 5); }, expo: function(p) { return Math.pow(p, 6); }, sine: function(p) { return 1 - Math.cos(p * Math.PI / 2); }, circ: function(p) { return 1 - Math.sqrt(1 - p * p); }, back: function(p) { return p * p * (3 * p - 2); } }; var easings = { linear: function(p) { return p; } }; Object.keys(fn).forEach(function(name) { var ease = fn[name]; easings["ease-in-" + name] = ease; easings["ease-out-" + name] = function(p) { return 1 - ease(1 - p); }; easings["ease-in-out-" + name] = function(p) { return p < .5 ? ease(p * 2) / 2 : 1 - ease(p * -2 + 2) / 2; }; }); easings.css = { linear: "cubic-bezier(0.000, 0.000, 1.000, 1.000)", "ease-in-quad": "cubic-bezier(0.550, 0.085, 0.680, 0.530)", "ease-in-cubic": "cubic-bezier(0.550, 0.055, 0.675, 0.190)", "ease-in-quart": "cubic-bezier(0.895, 0.030, 0.685, 0.220)", "ease-in-quint": "cubic-bezier(0.755, 0.050, 0.855, 0.060)", "ease-in-sine": "cubic-bezier(0.470, 0.000, 0.745, 0.715)", "ease-in-expo": "cubic-bezier(0.950, 0.050, 0.795, 0.035)", "ease-in-circ": "cubic-bezier(0.600, 0.040, 0.980, 0.335)", "ease-in-back": "cubic-bezier(0.600, -0.280, 0.735, 0.045)", "ease-out-quad": "cubic-bezier(0.250, 0.460, 0.450, 0.940)", "ease-out-cubic": "cubic-bezier(0.215, 0.610, 0.355, 1.000)", "ease-out-quart": "cubic-bezier(0.165, 0.840, 0.440, 1.000)", "ease-out-quint": "cubic-bezier(0.230, 1.000, 0.320, 1.000)", "ease-out-sine": "cubic-bezier(0.390, 0.575, 0.565, 1.000)", "ease-out-expo": "cubic-bezier(0.190, 1.000, 0.220, 1.000)", "ease-out-circ": "cubic-bezier(0.075, 0.820, 0.165, 1.000)", "ease-out-back": "cubic-bezier(0.175, 0.885, 0.320, 1.275)", "ease-in-out-quad": "cubic-bezier(0.455, 0.030, 0.515, 0.955)", "ease-in-out-cubic": "cubic-bezier(0.645, 0.045, 0.355, 1.000)", "ease-in-out-quart": "cubic-bezier(0.770, 0.000, 0.175, 1.000)", "ease-in-out-quint": "cubic-bezier(0.860, 0.000, 0.070, 1.000)", "ease-in-out-sine": "cubic-bezier(0.445, 0.050, 0.550, 0.950)", "ease-in-out-expo": "cubic-bezier(1.000, 0.000, 0.000, 1.000)", "ease-in-out-circ": "cubic-bezier(0.785, 0.135, 0.150, 0.860)", "ease-in-out-back": "cubic-bezier(0.680, -0.550, 0.265, 1.550)" }; return easings; }(); function Animation(item, transform, duration, ease, delay) { EventEmitter.call(this); this.item = item; this.translate = transform.translate && transform.translate.map(parseFloat); this.rotate = transform.rotate && transform.rotate.map(parseFloat); this.scale = transform.scale; this.opacity = transform.opacity; this.start = null; this.diff = null; this.duration = (transform.duration || duration) | 0; this.delay = (transform.delay || delay) | 0; this.ease = easings[transform.ease] || easings[ease] || easings.linear; this.easeName = ease || "linear"; } Animation.prototype = Object.create(EventEmitter.prototype); Animation.prototype.constructor = Animation; Animation.prototype.init = function(tick, force) { if (this.start !== null && !force) return; this.start = tick + this.delay; var state = this.item.state; this.initial = { translate: state.translate.slice(), rotate: state.rotate.slice(), scale: state.scale.slice(), opacity: state.opacity }; this.emit("start"); }; Animation.prototype.run = function(tick) { if (tick < this.start) return; var percent = (tick - this.start) / this.duration; percent = this.ease(percent); this.transform(percent); }; Animation.prototype.pause = function() { this.diff = Date.now() - this.start; }; Animation.prototype.resume = function() { this.start = Date.now() - this.diff; }; Animation.prototype.set = function(type, percent) { var state = this.item.state, initial = this.initial; if (Array.isArray(this[type])) { for (var i = 0; i < 3; ++i) if (this[type][i]) { state[type][i] = initial[type][i] + this[type][i] * percent; } } else if (this[type] !== undefined) { state[type] = initial[type] + (this[type] - initial[type]) * percent; } }; Animation.prototype.transform = function(percent) { this.set("translate", percent); this.set("rotate", percent); this.set("scale", percent); this.set("opacity", percent); }; Animation.prototype.end = function(abort) { !abort && this.transform(1); this.start = null; this.emit("end"); }; function CssAnimation(item, animation, duration, ease, delay, generated) { EventEmitter.call(this); this.item = item; this.name = animation.name || animation; this.start = null; this.diff = null; this.duration = (animation.duration || duration) | 0; this.delay = (animation.delay || delay) | 0; this.ease = easings.css[animation.ease] || easings.css[ease] || easings.css.linear; this._infinite = false; this._generated = generated; } CssAnimation.prototype = Object.create(EventEmitter.prototype); CssAnimation.prototype.constructor = CssAnimation; CssAnimation.prototype.init = function(tick, force) { if (this.start !== null && !force) return; this.start = tick + this.delay; this.item.style(_animationProperty, this.name + " " + this.duration + "ms" + " " + this.ease + " " + this.delay + "ms" + (this._infinite ? " infinite" : "") + " " + "forwards"); this.emit("start"); }; CssAnimation.prototype.run = function() {}; CssAnimation.prototype.pause = function() { this.item.style(_animationProperty + "PlayState", "paused"); this.diff = Date.now() - this.start; }; CssAnimation.prototype.resume = function() { this.item.style(_animationProperty + "PlayState", "running"); this.start = Date.now() - this.diff; }; CssAnimation.prototype.end = function() { if (this._generated) { var computed = getComputedStyle(this.item.dom, null), transform = computed[_transformProperty], opacity = computed.opacity; this.item.style(_animationProperty, ""); this.item.state = Matrix.decompose(Matrix.parse(transform)); this.item.state.opacity = opacity; this.item.style(); } this.start = null; this.emit("end"); }; function Collection(item) { EventEmitter.call(this); this.start = null; this.item = item; this.delay = 0; this.duration = 0; this.easeName = "linear"; this.animations = []; } Collection.prototype = Object.create(EventEmitter.prototype); Collection.prototype.constructor = Collection; Collection.prototype.add = function(transform, duration, ease, delay, generated) { if (Array.isArray(transform)) { transform = parallel(this.item, transform); } else if (typeof transform == "string" || transform.name != undefined) { transform = new CssAnimation(this.item, transform, duration, ease, delay, generated); } else if (!(transform instanceof Collection)) { transform = new Animation(this.item, transform, duration, ease, delay); } this.animations.push(transform); duration = this.animations.map(function(a) { return a.duration + a.delay; }); if (this instanceof Parallel) { this.duration = Math.max.apply(null, duration); } else { this.duration = duration.reduce(function(a, b) { return a + b; }, 0); } return this; function sequence(item, transforms) { var sequence = new Sequence(item); transforms.forEach(function(t) { sequence.add(t, duration, ease, delay); }); return sequence; } function parallel(item, transforms) { var parallel = new Parallel(item); transforms.forEach(function(t) { if (Array.isArray(t)) { parallel.add(sequence(item, t)); } else { parallel.add(t, duration, ease, delay); } }); return parallel; } }; Collection.prototype.__defineGetter__("length", function() { return this.animations.length; }); Collection.prototype.get = function(index) { return this.animations[index]; }; Collection.prototype.empty = function() { this.animations = []; }; Collection.prototype.animate = function(transform, duration, ease, delay) { return this.add(transform, duration, ease, delay); }; Collection.prototype.css = function() { return this.item.css(); }; function Parallel(item) { Collection.call(this, item); } Parallel.prototype = Object.create(Collection.prototype); Parallel.prototype.constructor = Parallel; Parallel.prototype.all = function(method) { var args = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < this.animations.length; ++i) { var a = this.animations[i]; a[method].apply(a, args); } }; Parallel.prototype.init = function(tick, force) { if (this.start !== null && !force) return; this.start = tick; this.all("init", tick, force); this.emit("start"); }; Parallel.prototype.run = function(tick) { for (var i = 0; i < this.animations.length; ++i) { var a = this.animations[i]; if (a.start + a.duration <= tick) { this.animations.splice(i--, 1); a.end(); continue; } a.run(tick); } this.item.style(); }; Parallel.prototype.seek = function(tick) { this.run(tick); }; Parallel.prototype.pause = function() { this.all("pause"); }; Parallel.prototype.resume = function() { this.all("resume"); }; Parallel.prototype.end = function(abort) { this.all("end", abort); this.emit("end"); }; function Sequence(item) { Collection.call(this, item); this._infinite = false; } Sequence.prototype = Object.create(Collection.prototype); Sequence.prototype.constructor = Sequence; Sequence.prototype.init = function(tick, force) { if (this.start !== null && !force) return; this.start = tick; this.animations[0].init(tick, force); this.emit("start"); }; Sequence.prototype.run = function(tick) { var a; while (this.animations.length !== 0) { a = this.animations[0]; if (a instanceof CssAnimation) { a._infinite = this._infinite; } a.init(tick); if (a.start + a.duration <= tick) { if (!(this._infinite && a instanceof CssAnimation)) { this.animations.shift(); a.end(); } else { break; } if (this._infinite && !(a instanceof CssAnimation)) { this.animations.push(a); } continue; } a.run(tick); break; } if (!(a instanceof CssAnimation)) { this.item.style(); } }; Sequence.prototype.seek = function(tick) { if (this.animations.length === 0) return; var time = 0; for (var i = 0; i < this.animations.length; ++i) { var a = this.animations[i]; a.init(time, true); if (a.start + a.duration <= tick) { a.end(); time += a.delay + a.duration; continue; } a.run(tick); this.item.style(); break; } }; Sequence.prototype.infinite = function() { this._infinite = true; return this; }; Sequence.prototype.pause = function() { this.animations.length && this.animations[0].pause(); }; Sequence.prototype.resume = function() { this.animations.length && this.animations[0].resume(); }; Sequence.prototype.end = function(abort) { for (var i = 0; i < this.animations.length; ++i) { this.animations[i].end(abort); } this.animations = []; this._infinite = false; this.emit("end"); }; function CSS(item, idle) { !document.styleSheets.length && this.createStyleSheet(); this.stylesheet = document.styleSheets[0]; this.item = item; this.animation = item.animation; !idle && this.style(); } CSS.prototype.createStyleSheet = function() { var style = document.createElement("style"); document.getElementsByTagName("head")[0].appendChild(style); }; CSS.prototype.pause = function() { this.animation.pause(); }; CSS.prototype.resume = function() { this.animation.resume(); }; CSS.prototype.stop = function() { var computed = getComputedStyle(this.item.dom, null), transform = computed[_transformProperty], opacity = computed.opacity; this.item.style(_animationProperty, ""); this.item.state = Matrix.decompose(Matrix.parse(transform)); this.item.state.opacity = opacity; this.item.style(); return this; }; CSS.prototype.style = function() { var animation = "a" + Date.now() + "r" + Math.floor(Math.random() * 1e3); this.stylesheet.insertRule(this.keyframes(animation), 0); this.animation.empty(); this.animation.add(animation, this.animation.duration, "", 0, true); }; CSS.prototype.keyframes = function(name) { var time = 0, rule = [ "@" + _vendor + "keyframes " + name + "{" ]; for (var i = 0; i < this.animation.length; ++i) { var a = this.animation.get(i), aNext = this.animation.get(i + 1); a.init(); if (a instanceof Animation) { i === 0 && rule.push(this.frame(0, easings.css[a.easeName])); a.delay && rule.push(this.frame(time += a.delay)); a.transform(1); rule.push(this.frame(time += a.duration, aNext && easings.css[aNext.easeName])); } else { var frames = []; a.animations.forEach(function(a) { a.delay && frames.indexOf(a.delay) === -1 && frames.push(a.delay); a.duration && frames.indexOf(a.delay + a.duration) === -1 && frames.push(a.delay + a.duration); }); frames = frames.sort(function(a, b) { return a - b; }); for (var k = 0; k < frames.length; ++k) { var frame = frames[k]; for (var j = 0; j < a.animations.length; ++j) { var pa = a.animations[j]; if (pa.delay >= frame || pa.delay + pa.duration < frame) continue; pa.transform(pa.ease((frame - pa.delay) / pa.duration)); } rule.push(this.frame(time += frame)); } } } rule.push("}"); return rule.join(""); }; CSS.prototype.percent = function(time) { return (time * 100 / this.animation.duration).toFixed(3); }; CSS.prototype.frame = function(time, ease) { var percent = this.percent(time); return percent + "% {" + (percent ? _vendor + "transform:" + this.item.transform() + ";" : "") + (percent ? "opacity:" + this.item.opacity() + ";" : "") + (ease ? _vendor + "animation-timing-function:" + ease + ";" : "") + "}"; }; function World() { EventEmitter.call(this); this.items = []; this.frame = null; this.init(); } World.prototype = Object.create(EventEmitter.prototype); World.prototype.constructor = World; World.prototype.init = function() { var self = this; this.frame = _requestAnimationFrame(update); function update(tick) { self.update(tick); self.frame = _requestAnimationFrame(update); } }; World.prototype.update = function(tick) { for (var i = 0; i < this.items.length; ++i) { this.items[i].update(tick); } }; World.prototype.add = function(node, mass, viscosity, edge) { var item; if (mass) { item = new Particle(node, mass, viscosity, edge); } else { item = new Item(node); } this.items.push(item); return item; }; World.prototype.cancel = function() { this.frame && _cancelAnimationFrame(this.frame); this.frame = 0; }; World.prototype.stop = function() { this.cancel(); for (var i = 0; i < this.items.length; ++i) { this.items[i].stop(); } }; World.prototype.pause = function() { this.cancel(); for (var i = 0; i < this.items.length; ++i) { this.items[i].pause(); } }; World.prototype.resume = function() { for (var i = 0; i < this.items.length; ++i) { this.items[i].resume(); } this.init(); }; function Timeline() { World.call(this, true); this.currentTime = 0; this.start = 0; } Timeline.prototype = Object.create(World.prototype); Timeline.prototype.constructor = Timeline; Timeline.prototype.init = function() { this.frame = _requestAnimationFrame(update); var self = this; function update(tick) { if (self.running) { self.currentTime = tick - self.start; } self.update(self.currentTime); self.frame = _requestAnimationFrame(update); } }; Timeline.prototype.update = function(tick) { for (var i = 0; i < this.items.length; ++i) { if (this.changed || this.running) { this.items[i].timeline(tick); this.changed = false; this.emit("update", tick); } else { this.items[i].style(); } } }; Timeline.prototype.play = function() { this.running = true; this.start = Date.now() - this.currentTime; }; Timeline.prototype.pause = function() { this.running = false; }; Timeline.prototype.stop = function() { this.currentTime = 0; this.running = false; }; Timeline.prototype.seek = function(time) { this.changed = true; this.currentTime = time; }; function Item(node) { EventEmitter.call(this); this.dom = node; this.init(); } Item.prototype = Object.create(EventEmitter.prototype); Item.prototype.constructor = Item; Item.prototype.init = function() { this.animation = new Sequence(this); this.running = true; this.state = { translate: Vector.zero(), rotate: Vector.zero(), scale: Vector.set(1), opacity: 1 }; }; Item.prototype.update = function(tick) { this.animation.run(tick); }; Item.prototype.timeline = function(tick) { this.clear(); this.animation.seek(tick); }; Item.prototype.pause = function() { if (!this.running) return; this.animation.pause(); this.running = false; }; Item.prototype.resume = function() { if (this.running) return; this.animation.resume(); this.running = true; }; Item.prototype.style = function(property, value) { if (property && value) { this.dom.style[property] = value; } else { this.dom.style[_transformProperty] = this.transform(); this.dom.style.opacity = this.opacity(); } }; Item.prototype.transform = function() { return Matrix.stringify(this.matrix()); }; Item.prototype.matrix = function() { var state = this.state; return Matrix.compose(state.translate, state.rotate, state.scale); }; Item.prototype.center = function() { return Matrix.decompose(Matrix.inverse(this.matrix())); }; Item.prototype.lookAt = function(vector) { var transform = Matrix.decompose(Matrix.lookAt(vector, this.state.translate, Vector.set(0, 1, 0))); this.state.rotate = transform.rotate; }; Item.prototype.opacity = function() { return this.state.opacity; }; Item.prototype.add = function(type, a) { this.state[type][0] += a[0]; this.state[type][1] += a[1]; this.state[type][2] += a[2]; return this; }; Item.prototype.set = function(type, a) { this.state[type] = a; return this; }; Item.prototype.translate = function(t) { return this.add("translate", t); }; Item.prototype.rotate = function(r) { return this.add("rotate", r); }; Item.prototype.scale = function(s) { return this.add("scale", s); }; Item.prototype.clear = function() { this.state.translate = Vector.zero(); this.state.rotate = Vector.zero(); this.state.scale = Vector.set(1); this.state.opacity = 1; }; Item.prototype.animate = function(transform, duration, ease, delay) { return this.animation.add(transform, duration, ease, delay); }; Item.prototype.finish = function(abort) { this.animation.end(abort); return this; }; Item.prototype.stop = function() { return this.finish(true); }; Item.prototype.css = function(idle) { return new CSS(this, idle); }; function Constant() { var force = Vector.sub(this.state.translate, this.current.position); this.current.acceleration = Vector.add(this.current.acceleration, force); } function Attraction(radius, strength) { radius || (radius = 1e3); strength || (strength = 100); var force = Vector.sub(this.state.translate, this.current.position), distance = Vector.length(force); if (distance < radius) { force = Vector.scale(Vector.norm(force), 1 - distance * distance / (radius * radius)); this.current.acceleration = Vector.add(this.current.acceleration, Vector.scale(force, strength)); } } function Edge(min, max, bounce) { min || (min = Vector.set(0)); max || (max = Vector.set(0)); bounce || (bounce = true); for (var i = 0; i < 3; ++i) { if (this.current.position[i] < min[i] || this.current.position[i] > max[i]) { if (bounce) { this.previous.position[i] = 2 * this.current.position[i] - this.previous.position[i]; } else { this.current.position[i] = Math.max(min[i], Math.min(max[i], this.current.position[i])); } } } } function Verlet(delta, drag) { var current = this.current, previous = this.previous; current.acceleration = Vector.scale(current.acceleration, this.mass); current.velocity = Vector.sub(current.position, previous.position); if (drag) { current.velocity = Vector.scale(current.velocity, drag); } previous.position = current.position; current.position = Vector.add(current.position, Vector.add(current.velocity, Vector.scale(current.acceleration, delta * delta))); current.acceleration = Vector.zero(); } function Particle(node, mass, viscosity, edge) { Item.call(this, node); if (mass === Object(mass)) { viscosity = mass.viscosity; edge = mass.edge; mass = mass.mass; } mass /= 100; mass || (mass = .01); viscosity || (viscosity = .1); edge || (edge = false); this.mass = 1 / mass; this.viscosity = viscosity; this.edge = edge; } Particle.prototype = Object.create(Item.prototype); Particle.prototype.constructor = Particle; Particle.prototype.init = function() { Item.prototype.init.call(this); this.current = { position: Vector.zero(), velocity: Vector.zero(), acceleration: Vector.zero() }; this.previous = { position: Vector.zero(), velocity: Vector.zero(), acceleration: Vector.zero() }; this.clock = null; }; Particle.prototype.update = function(tick) { this.animation.run(tick); this.integrate(tick); this.style(); }; Particle.prototype.timeline = function(tick) { this.clear(); this.animation.seek(tick); this.integrate(tick, true); this.style(); }; Particle.prototype.integrate = function(tick, clamp) { this.clock || (this.clock = tick); var delta = tick - this.clock; if (delta) { clamp && (delta = Math.max(-16, Math.min(16, delta))); this.clock = tick; delta *= .001; Constant.call(this); this.edge && Edge.call(this, Vector.set(this.edge.min), Vector.set(this.edge.max), this.edge.bounce); Verlet.call(this, delta, 1 - this.viscosity); } }; Particle.prototype.css = function() { throw new Error("CSS is nor supported for physics"); }; Particle.prototype.matrix = function() { var state = this.state; return Matrix.compose(this.current.position, state.rotate, state.scale); }; })();
import React from "react"; import cx from "classnames"; import "./_background.scss"; import { SettingsContext } from "../../contexts"; const Background = () => ( <SettingsContext.Consumer> {context => context.bgImg || context.bgColor ? ( <div className={cx("Background", { "Background--tiled": context.bgStyle === "tile", "Background--contain": context.bgStyle === "contain", "Background--stretch": context.bgStyle === "stretch" })} > <div style={{ backgroundImage: `url(${context.bgImg})`, backgroundColor: `${ context.bgColor ? context.bgColor : "#5f9ea0" }` }} /> </div> ) : null } </SettingsContext.Consumer> ); export default Background;
Object.defineProperty(exports,"__esModule",{value:true});var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};var _react=require('react');var React=_interopRequireWildcard(_react);var _reactRouter=require('react-router');var _shallowEqual2=require('fbjs/lib/shallowEqual');var _shallowEqual3=_interopRequireDefault(_shallowEqual2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i];}return arr2;}else{return Array.from(arr);}}function _objectWithoutProperties(obj,keys){var target={};for(var i in obj){if(keys.indexOf(i)>=0)continue;if(!Object.prototype.hasOwnProperty.call(obj,i))continue;target[i]=obj[i];}return target;}exports.default={create:function create(stackChildren,props){var history=props.history,children=props.children,render=props.render,rest=_objectWithoutProperties(props,['history','children','render']);return React.Children.toArray(stackChildren).reduce(function(stack,child){return[].concat(_toConsumableArray(stack),[_extends({},rest,child.props)]);},[]);},shallowEqual:function shallowEqual(oldStack,newStack){if(oldStack.length!==newStack.length)return false;return oldStack.every(function(oldItem,index){return(0,_shallowEqual3.default)(oldItem,newStack[index]);});},getHistoryEntries:function getHistoryEntries(stack,entries,location){var startHistoryIndex=entries.reduce(function(acc,entry,index){if(stack.find(function(item){return(0,_reactRouter.matchPath)(entry.pathname,item);})){if(acc===-1)return index;return acc;}return-1;},-1);var lastHistoryIndex=entries.reduce(function(acc,entry,index){if(index<startHistoryIndex)return-1;if(location.pathname===entry.pathname)return index;return acc;},-1);return entries.slice(startHistoryIndex,lastHistoryIndex+1);}};
function(t,e,o){"use strict";var r=t("./ui.scheduler.work_space.grouped.strategy"),i="dx-group-column-count",n=10,a=1,l=r.inherit({prepareCellIndexes:function(t,e,o){var r=t.rowIndex+e*this._workSpace._getRowCount();return this._workSpace.supportAllDayRow()&&this._workSpace.option("showAllDayPanel")&&(r+=e,o||(r+=1)),{rowIndex:r,cellIndex:t.cellIndex}},calculateCellIndex:function(t,e){return t%=this._workSpace._getRowCount(),this._workSpace._getRowCount()*e+t},getGroupIndex:function(t,e){return Math.floor(t/this._workSpace._getRowCount())},calculateHeaderCellRepeatCount:function(){return 1},insertAllDayRowsIntoDateTable:function(){return this._workSpace.option("showAllDayPanel")},getTotalCellCount:function(t){return this._workSpace._getCellCount()},getTotalRowCount:function(){return this._workSpace._getRowCount()*this._workSpace._getGroupCount()},addAdditionalGroupCellClasses:function(t,e,o,r){return t=this._addLastGroupCellClass(t,o+1),this._addFirstGroupCellClass(t,o+1)},_addLastGroupCellClass:function(t,e){return e%this._workSpace._getRowCount()==0?t+" "+this.getLastGroupCellClass():t},_addFirstGroupCellClass:function(t,e){return(e-1)%this._workSpace._getRowCount()==0?t+" "+this.getFirstGroupCellClass():t},getHorizontalMax:function(t){return this._workSpace.getMaxAllowedPosition()[0]},getVerticalMax:function(t){var e=this._workSpace.getMaxAllowedVerticalPosition()[t];return e+=this._getOffsetByAllDayPanel(t)},_getOffsetByAllDayPanel:function(t){var e=0;return this._workSpace.supportAllDayRow()&&this._workSpace.option("showAllDayPanel")&&(e=this._workSpace.getCellHeight()*(t+1)),e},_getGroupTop:function(t){return this._workSpace.getMaxAllowedVerticalPosition()[t]-this._workSpace.getCellHeight()*this._workSpace._getRowCount()},calculateTimeCellRepeatCount:function(){return this._workSpace._getGroupCount()||1},getWorkSpaceMinWidth:function(){var t=this._workSpace._getWorkSpaceWidth(),e=this._workSpace.$element().get(0).getBoundingClientRect().width-this._workSpace.getTimePanelWidth()-this._workSpace.getGroupTableWidth()-2;return t<e&&(t=e),t},getAllDayOffset:function(){return 0},getAllDayTableHeight:function(){return 0},getGroupCountAttr:function(){return{attr:i,count:this._workSpace.option("groups")&&this._workSpace.option("groups").length}},getLeftOffset:function(){return this._workSpace.getTimePanelWidth()+this._workSpace.getGroupTableWidth()},getGroupBoundsOffset:function(t,e,o,r){var i=r.groupIndex,n=e.eq(0).offset().left,a=e.eq(t-1).offset().left+o,l=this._workSpace._calculateDayDuration()/this._workSpace.option("hoursInterval")*this._workSpace.getCellHeight(),s=this.getScrollableScrollTop(),c=i*l+this._workSpace._$thead.get(0).getBoundingClientRect().height+this._workSpace.invoke("getHeaderHeight")+10-s,p;return this._workSpace.option("showAllDayPanel")&&this._workSpace.supportAllDayRow()&&(c+=this._workSpace.getCellHeight()*(i+1)),{left:n,right:a,top:c,bottom:c+l}},shiftIndicator:function(t,e,o,r){var i=this._workSpace.getIndicatorOffset(0),n=this._workSpace.option("crossScrollingEnabled")?0:this._workSpace.getGroupTableWidth(),a=o?o-i:i,l=this._workSpace._getRowCount()*this._workSpace.getCellHeight()*r;this._workSpace.supportAllDayRow()&&this._workSpace.option("showAllDayPanel")&&(l+=this._workSpace.getAllDayHeight()*(r+1)),t.css("left",a+n),t.css("top",e+l)},getShaderOffset:function(t,e){var o=this._workSpace.option("crossScrollingEnabled")?0:this._workSpace.getGroupTableWidth();return this._workSpace.option("rtlEnabled")?this._$container.get(0).getBoundingClientRect().width-o-this._workSpace.getWorkSpaceLeftOffset()-e:o},getShaderTopOffset:function(t){return 0},getShaderHeight:function(){var t=this._workSpace.getIndicationHeight();return this._workSpace.supportAllDayRow()&&this._workSpace.option("showAllDayPanel")&&(t+=this._workSpace.getCellHeight()),t},getShaderMaxHeight:function(){var t=this._workSpace._getRowCount()*this._workSpace.getCellHeight();return this._workSpace.supportAllDayRow()&&this._workSpace.option("showAllDayPanel")&&(t+=this._workSpace.getCellHeight()),t},getShaderWidth:function(t){return this._workSpace.getIndicationWidth(0)},getScrollableScrollTop:function(t){return this._workSpace.getScrollable().scrollTop()}});o.exports=l}
const path = require('path') const express = require('express') const React = require('react') const Application = require('./components/Application.js').default const server = express() server.get('/', (req, res) => { const ampHtmlRenderer = require('../bundle/AmpHtmlRenderer.js') res.send( ampHtmlRenderer({ entryName: 'home', AppComponent: <Application />, title: 'This is my first AMP page powered by React + CSS modules', canonical: 'https://jimmy.amp.com', headComponents: null }) ) }) if (process.env.NODE_ENV === 'production') { server.listen(3000, () => console.log('Example app listening on port 3000!')) } else { module.exports = server }
import { useEffect } from "react"; // react-router-dom components import { useLocation, NavLink } from "react-router-dom"; // prop-types is a library for typechecking of props. import PropTypes from "prop-types"; // @mui material components import List from "@mui/material/List"; import Divider from "@mui/material/Divider"; import Link from "@mui/material/Link"; import Icon from "@mui/material/Icon"; // Material Dashboard 2 React components import MDBox from "components/MDBox"; import MDTypography from "components/MDTypography"; import MDButton from "components/MDButton"; // Material Dashboard 2 React example components import SidenavCollapse from "examples/Sidenav/SidenavCollapse"; // Custom styles for the Sidenav import SidenavRoot from "examples/Sidenav/SidenavRoot"; import sidenavLogoLabel from "examples/Sidenav/styles/sidenav"; // Material Dashboard 2 PRO React context import { useMaterialUIController, setMiniSidenav, setTransparentSidenav, setWhiteSidenav, } from "context"; function Sidenav({ color, brand, brandName, routes, ...rest }) { const [controller, dispatch] = useMaterialUIController(); const { miniSidenav, transparentSidenav, whiteSidenav, darkMode, sidenavColor } = controller; const location = useLocation(); const collapseName = location.pathname.replace("/", ""); let textColor = "white"; if (transparentSidenav || (whiteSidenav && !darkMode)) { textColor = "dark"; } else if (whiteSidenav && darkMode) { textColor = "inherit"; } const closeSidenav = () => setMiniSidenav(dispatch, true); useEffect(() => { // A function that sets the mini state of the sidenav. function handleMiniSidenav() { setMiniSidenav(dispatch, window.innerWidth < 1200); setTransparentSidenav(dispatch, window.innerWidth < 1200 ? false : transparentSidenav); setWhiteSidenav(dispatch, window.innerWidth < 1200 ? false : whiteSidenav); } /** The event listener that's calling the handleMiniSidenav function when resizing the window. */ window.addEventListener("resize", handleMiniSidenav); // Call the handleMiniSidenav function to set the state with the initial value. handleMiniSidenav(); // Remove event listener on cleanup return () => window.removeEventListener("resize", handleMiniSidenav); }, [dispatch, location]); // Render all the routes from the routes.js (All the visible items on the Sidenav) const renderRoutes = routes.map(({ type, name, icon, title, noCollapse, key, href, route }) => { let returnValue; if (type === "collapse") { returnValue = href ? ( <Link href={href} key={key} target="_blank" rel="noreferrer" sx={{ textDecoration: "none" }} > <SidenavCollapse name={name} icon={icon} active={key === collapseName} noCollapse={noCollapse} /> </Link> ) : ( <NavLink key={key} to={route}> <SidenavCollapse name={name} icon={icon} active={key === collapseName} /> </NavLink> ); } else if (type === "title") { returnValue = ( <MDTypography key={key} color={textColor} display="block" variant="caption" fontWeight="bold" textTransform="uppercase" pl={3} mt={2} mb={1} ml={1} > {title} </MDTypography> ); } else if (type === "divider") { returnValue = ( <Divider key={key} light={ (!darkMode && !whiteSidenav && !transparentSidenav) || (darkMode && !transparentSidenav && whiteSidenav) } /> ); } return returnValue; }); return ( <SidenavRoot {...rest} variant="permanent" ownerState={{ transparentSidenav, whiteSidenav, miniSidenav, darkMode }} > <MDBox pt={3} pb={1} px={4} textAlign="center"> <MDBox display={{ xs: "block", xl: "none" }} position="absolute" top={0} right={0} p={1.625} onClick={closeSidenav} sx={{ cursor: "pointer" }} > <MDTypography variant="h6" color="secondary"> <Icon sx={{ fontWeight: "bold" }}>close</Icon> </MDTypography> </MDBox> <MDBox component={NavLink} to="/" display="flex" alignItems="center"> {brand && <MDBox component="img" src={brand} alt="Brand" width="2rem" />} <MDBox width={!brandName && "100%"} sx={(theme) => sidenavLogoLabel(theme, { miniSidenav })} > <MDTypography component="h6" variant="button" fontWeight="medium" color={textColor}> {brandName} </MDTypography> </MDBox> </MDBox> </MDBox> <Divider light={ (!darkMode && !whiteSidenav && !transparentSidenav) || (darkMode && !transparentSidenav && whiteSidenav) } /> <List>{renderRoutes}</List> </SidenavRoot> ); } // Setting default values for the props of Sidenav Sidenav.defaultProps = { color: "info", brand: "", }; // Typechecking props for the Sidenav Sidenav.propTypes = { color: PropTypes.oneOf(["primary", "secondary", "info", "success", "warning", "error", "dark"]), brand: PropTypes.string, brandName: PropTypes.string.isRequired, routes: PropTypes.arrayOf(PropTypes.object).isRequired, }; export default Sidenav;
import PropTypes from "prop-types"; import { Icon } from "@iconify/react"; import eyeFill from "@iconify/icons-eva/eye-fill"; import { Link as RouterLink } from "react-router-dom"; import shareFill from "@iconify/icons-eva/share-fill"; import messageCircleFill from "@iconify/icons-eva/message-circle-fill"; // material import { alpha, experimentalStyled as styled } from "@material-ui/core/styles"; import { Box, Link, Card, Grid, Avatar, Typography, CardContent, } from "@material-ui/core"; // utils import { fDate } from "../../../utils/formatTime"; import { fShortenNumber } from "../../../utils/formatNumber"; // import SvgIconStyle from "../../SvgIconStyle"; // ---------------------------------------------------------------------- const CardMediaStyle = styled("div")({ position: "relative", paddingTop: "calc(100% * 3 / 4)", }); const TitleStyle = styled(Link)({ height: 44, overflow: "hidden", WebkitLineClamp: 2, display: "-webkit-box", WebkitBoxOrient: "vertical", }); const AvatarStyle = styled(Avatar)(({ theme }) => ({ zIndex: 9, width: 32, height: 32, position: "absolute", left: theme.spacing(3), bottom: theme.spacing(-2), })); const InfoStyle = styled("div")(({ theme }) => ({ display: "flex", flexWrap: "wrap", justifyContent: "flex-end", marginTop: theme.spacing(3), color: theme.palette.text.disabled, })); const CoverImgStyle = styled("img")({ top: 0, width: "100%", height: "100%", objectFit: "cover", position: "absolute", }); // ---------------------------------------------------------------------- BlogPostCard.propTypes = { post: PropTypes.object.isRequired, index: PropTypes.number, }; export default function BlogPostCard({ post, index }) { const { cover, title, view, comment, share, author, createdAt } = post; const latestPostLarge = index === 0; const latestPost = index === 1 || index === 2; const POST_INFO = [ { number: comment, icon: messageCircleFill }, { number: view, icon: eyeFill }, { number: share, icon: shareFill }, ]; return ( <Grid item xs={12} sm={latestPostLarge ? 12 : 6} md={latestPostLarge ? 6 : 3} > <Card sx={{ position: "relative" }}> <CardMediaStyle sx={{ ...((latestPostLarge || latestPost) && { pt: "calc(100% * 4 / 3)", "&:after": { top: 0, content: "''", width: "100%", height: "100%", position: "absolute", bgcolor: (theme) => alpha(theme.palette.grey[900], 0.72), }, }), ...(latestPostLarge && { pt: { xs: "calc(100% * 4 / 3)", sm: "calc(100% * 3 / 4.66)", }, }), }} > <SvgIconStyle color="paper" src="/static/icons/shape-avatar.svg" sx={{ width: 80, height: 36, zIndex: 9, bottom: -15, position: "absolute", ...((latestPostLarge || latestPost) && { display: "none" }), }} /> <AvatarStyle alt={author.name} src={author.avatarUrl} sx={{ ...((latestPostLarge || latestPost) && { zIndex: 9, top: 24, left: 24, width: 40, height: 40, }), }} /> <CoverImgStyle alt={title} src={cover} /> </CardMediaStyle> <CardContent sx={{ pt: 4, ...((latestPostLarge || latestPost) && { bottom: 0, width: "100%", position: "absolute", }), }} > <Typography gutterBottom variant="caption" sx={{ color: "text.disabled", display: "block" }} > {fDate(createdAt)} </Typography> <TitleStyle to="#" color="inherit" variant="subtitle2" underline="hover" component={RouterLink} sx={{ ...(latestPostLarge && { typography: "h5", height: 60 }), ...((latestPostLarge || latestPost) && { color: "common.white", }), }} > {title} </TitleStyle> <InfoStyle> {POST_INFO.map((info, index) => ( <Box key={index} sx={{ display: "flex", alignItems: "center", ml: index === 0 ? 0 : 1.5, ...((latestPostLarge || latestPost) && { color: "grey.500", }), }} > <Box component={Icon} icon={info.icon} sx={{ width: 16, height: 16, mr: 0.5 }} /> <Typography variant="caption"> {fShortenNumber(info.number)} </Typography> </Box> ))} </InfoStyle> </CardContent> </Card> </Grid> ); }
const {EventTarget} = require('./Event'); class FileReader extends EventTarget { constructor() { super(); this.result = null; } get onload() { return _elementGetter(this, 'load'); } set onload(onload) { _elementSetter(this, 'load', onload); } get onerror() { return _elementGetter(this, 'error'); } set onerror(onerror) { _elementSetter(this, 'error', onerror); } readAsArrayBuffer(file) { this.result = file.buffer.buffer.slice(file.buffer.byteOffset, file.buffer.byteOffset + file.buffer.byteLength); process.nextTick(() => { this.dispatchEvent(new Event('load', { target: this, })); }); } readAsDataURL(file) { this.result = 'data:' + file.type + ';base64,' + file.buffer.toString('base64'); process.nextTick(() => { this.dispatchEvent(new Event('load', { target: this, })); }); } readAsText(file) { this.result = file.buffer.toString('utf8'); process.nextTick(() => { this.dispatchEvent(new Event('load', { target: this, })); }); } } module.exports.FileReader = FileReader;
import React from "react"; import { rhythm } from "../utils/typography"; const Footer = () => { return ( <footer style={{ marginTop: rhythm(2.5), paddingTop: rhythm(1), }} > <div style={{ float: "right" }}> <a href="/rss.xml" target="_blank" rel="noopener noreferrer"> rss </a> </div> <a href="https://github.com/cluelesscoders" target="_blank" rel="noopener noreferrer" > github </a> </footer> ); }; export default Footer;
import { TempNode } from '../TempNode.js' var ReflectNode = function ( scope ) { TempNode.call( this, 'v3', { unique: true } ); this.scope = scope || ReflectNode.CUBE; }; ReflectNode.CUBE = 'cube'; ReflectNode.SPHERE = 'sphere'; ReflectNode.VECTOR = 'vector'; ReflectNode.prototype = Object.create( TempNode.prototype ); ReflectNode.prototype.constructor = ReflectNode; ReflectNode.prototype.nodeType = "Reflect"; ReflectNode.prototype.getType = function ( builder ) { switch ( this.scope ) { case ReflectNode.SPHERE: return 'v2'; } return this.type; }; ReflectNode.prototype.generate = function ( builder, output ) { var result; switch ( this.scope ) { case ReflectNode.VECTOR: builder.material.addFragmentNode( 'vec3 reflectVec = inverseTransformDirection( reflect( -normalize( vViewPosition ), normal ), viewMatrix );' ); result = 'reflectVec'; break; case ReflectNode.CUBE: var reflectVec = new ReflectNode( ReflectNode.VECTOR ).build( builder, 'v3' ); builder.material.addFragmentNode( 'vec3 reflectCubeVec = vec3( -1.0 * ' + reflectVec + '.x, ' + reflectVec + '.yz );' ); result = 'reflectCubeVec'; break; case ReflectNode.SPHERE: var reflectVec = new ReflectNode( ReflectNode.VECTOR ).build( builder, 'v3' ); builder.material.addFragmentNode( 'vec2 reflectSphereVec = normalize((viewMatrix * vec4(' + reflectVec + ', 0.0 )).xyz + vec3(0.0,0.0,1.0)).xy * 0.5 + 0.5;' ); result = 'reflectSphereVec'; break; } return builder.format( result, this.getType( this.type ), output ); }; ReflectNode.prototype.toJSON = function ( meta ) { var data = this.getJSONNode( meta ); if ( ! data ) { data = this.createJSONNode( meta ); data.scope = this.scope; } return data; }; export { ReflectNode }
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var proxyquire = require( 'proxyquire' ); var IS_BROWSER = require( '@stdlib/assert/is-browser' ); var dsdot = require( './../lib' ); // VARIABLES // var opts = { 'skip': IS_BROWSER }; // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.strictEqual( typeof dsdot, 'function', 'main export is a function' ); t.end(); }); tape( 'attached to the main export is a method providing an ndarray interface', function test( t ) { t.strictEqual( typeof dsdot.ndarray, 'function', 'method is a function' ); t.end(); }); tape( 'if a native implementation is available, the main export is the native implementation', opts, function test( t ) { var dsdot = proxyquire( './../lib', { '@stdlib/utils/try-require': tryRequire }); t.strictEqual( dsdot, mock, 'returns native implementation' ); t.end(); function tryRequire() { return mock; } function mock() { // Mock... } }); tape( 'if a native implementation is not available, the main export is a JavaScript implementation', opts, function test( t ) { var dsdot; var main; main = require( './../lib/dsdot.js' ); dsdot = proxyquire( './../lib', { '@stdlib/utils/try-require': tryRequire }); t.strictEqual( dsdot, main, 'returns JavaScript implementation' ); t.end(); function tryRequire() { return new Error( 'Cannot find module' ); } });
// @link https://schemas.tmz.com/json-schema/tmz/news/event/article-renamed/1-0-0.json# import DayOfWeek from '@gdbots/schemas/gdbots/common/enums/DayOfWeek'; import Fb from '@gdbots/pbj/FieldBuilder'; import Format from '@gdbots/pbj/enums/Format'; import GdbotsPbjxEventV1Mixin from '@gdbots/schemas/gdbots/pbjx/mixin/event/EventV1Mixin'; import Message from '@gdbots/pbj/Message'; import Month from '@gdbots/schemas/gdbots/common/enums/Month'; import NodeStatus from '@gdbots/schemas/gdbots/ncr/enums/NodeStatus'; import Schema from '@gdbots/pbj/Schema'; import T from '@gdbots/pbj/types'; export default class ArticleRenamedV1 extends Message { /** * @private * * @returns {Schema} */ static defineSchema() { return new Schema(this.SCHEMA_ID, this, [ Fb.create('event_id', T.TimeUuidType.create()) .required() .build(), Fb.create('occurred_at', T.MicrotimeType.create()) .build(), /* * Multi-tenant apps can use this field to track the tenant id. */ Fb.create('ctx_tenant_id', T.StringType.create()) .pattern('^[\\w\\/\\.:-]+$') .build(), Fb.create('ctx_causator_ref', T.MessageRefType.create()) .build(), Fb.create('ctx_correlator_ref', T.MessageRefType.create()) .build(), Fb.create('ctx_user_ref', T.MessageRefType.create()) .build(), /* * The "ctx_app" refers to the application used to send the command which * in turn resulted in this event being published. */ Fb.create('ctx_app', T.MessageType.create()) .anyOfCuries([ 'gdbots:contexts::app', ]) .build(), /* * The "ctx_cloud" is usually copied from the command that resulted in this * event being published. This means the value most likely refers to the cloud * that received the command originally, not the machine processing the event. */ Fb.create('ctx_cloud', T.MessageType.create()) .anyOfCuries([ 'gdbots:contexts::cloud', ]) .build(), Fb.create('ctx_ip', T.StringType.create()) .format(Format.IPV4) .overridable(true) .build(), Fb.create('ctx_ipv6', T.StringType.create()) .format(Format.IPV6) .overridable(true) .build(), Fb.create('ctx_ua', T.TextType.create()) .overridable(true) .build(), /* * An optional message/reason for the event being created. * Consider this like a git commit message. */ Fb.create('ctx_msg', T.TextType.create()) .build(), Fb.create('node_ref', T.NodeRefType.create()) .required() .build(), Fb.create('node_status', T.StringEnumType.create()) .classProto(NodeStatus) .build(), Fb.create('new_slug', T.StringType.create()) .format(Format.SLUG) .build(), Fb.create('old_slug', T.StringType.create()) .format(Format.SLUG) .build(), Fb.create('month_of_year', T.IntEnumType.create()) .withDefault(0) .classProto(Month) .build(), Fb.create('day_of_month', T.TinyIntType.create()) .max(31) .build(), Fb.create('day_of_week', T.IntEnumType.create()) .withDefault(0) .classProto(DayOfWeek) .build(), Fb.create('is_weekend', T.BooleanType.create()) .build(), Fb.create('hour_of_day', T.TinyIntType.create()) .max(23) .build(), Fb.create('ts_ymdh', T.IntType.create()) .build(), Fb.create('ts_ymd', T.IntType.create()) .build(), Fb.create('ts_ym', T.MediumIntType.create()) .build(), ], this.MIXINS, ); } } const M = ArticleRenamedV1; M.prototype.SCHEMA_ID = M.SCHEMA_ID = 'pbj:tmz:news:event:article-renamed:1-0-0'; M.prototype.SCHEMA_CURIE = M.SCHEMA_CURIE = 'tmz:news:event:article-renamed'; M.prototype.SCHEMA_CURIE_MAJOR = M.SCHEMA_CURIE_MAJOR = 'tmz:news:event:article-renamed:v1'; M.prototype.MIXINS = M.MIXINS = [ 'gdbots:pbjx:mixin:event:v1', 'gdbots:pbjx:mixin:event', 'gdbots:ncr:mixin:node-renamed:v1', 'gdbots:ncr:mixin:node-renamed', 'gdbots:analytics:mixin:tracked-message:v1', 'gdbots:analytics:mixin:tracked-message', 'gdbots:enrichments:mixin:time-parting:v1', 'gdbots:enrichments:mixin:time-parting', 'gdbots:enrichments:mixin:time-sampling:v1', 'gdbots:enrichments:mixin:time-sampling', ]; GdbotsPbjxEventV1Mixin(M); Object.freeze(M); Object.freeze(M.prototype);
/*globals require*/ /*eslint-env node, mocha*/ /** * @author lattmann / https://github.com/lattmann * @author pmeijer / https://github.com/pmeijer */ var testFixture = require('../../../_globals.js'); describe('USER REST API', function () { 'use strict'; var gmeConfig = testFixture.getGmeConfig(), WebGME = testFixture.WebGME, expect = testFixture.expect, Q = testFixture.Q, fs = require('fs'), jwt = require('jsonwebtoken'), privateKey, superagent = testFixture.superagent; describe('USER SPECIFIC API', function () { var gmeAuth; before(function (done) { this.timeout(4000); var gmeAuthConfig = JSON.parse(JSON.stringify(gmeConfig)); gmeAuthConfig.authentication.enable = true; testFixture.clearDBAndGetGMEAuth(gmeAuthConfig) .then(function (gmeAuth_) { gmeAuth = gmeAuth_; return Q.allDone([ gmeAuth.addUser('guest', 'guest@example.com', 'guest', true, {overwrite: true, data: {d: 1}}), gmeAuth.addUser('admin', 'admin@example.com', 'admin', true, { overwrite: true, siteAdmin: true }), gmeAuth.addUser('user', 'user@example.com', 'plaintext', true, {overwrite: true}), gmeAuth.addUser('user2', 'user2@example.com', 'plaintext', true, { overwrite: true, data: {d: 1} }), gmeAuth.addUser('user_to_delete', 'user@example.com', 'plaintext', true, {overwrite: true}), gmeAuth.addUser('self_delete_1', 'user@example.com', 'plaintext', true, {overwrite: true}), gmeAuth.addUser('self_delete_2', 'user@example.com', 'plaintext', true, {overwrite: true}), gmeAuth.addUser('user_to_modify', 'user@example.com', 'plaintext', true, {overwrite: true, data: {d: 1}}), gmeAuth.addUser('user_without_create', 'user@example.com', 'plaintext', false, { overwrite: true }), gmeAuth.addUser('user_w_data', 'e@mail.com', 'plaintext', false, {overwrite: true}), gmeAuth.addUser('user_w_data1', 'e@mail.com', 'plaintext', false, { overwrite: true, data: {a: 1} }), gmeAuth.addUser('user_w_data2', 'e@mail.com', 'plaintext', false, { overwrite: true, data: {a: 1} }), gmeAuth.addUser('user_w_data3', 'e@mail.com', 'plaintext', false, { overwrite: true, data: {a: 1} }), gmeAuth.addUser('user_w_data4', 'e@mail.com', 'plaintext', false, { overwrite: true, data: {a: 1} }), gmeAuth.addUser('user_w_data5', 'e@mail.com', 'plaintext', false, { overwrite: true, data: {a: 1} }), gmeAuth.addUser('user_w_data6', 'e@mail.com', 'plaintext', false, { overwrite: true, data: {a: 1} }), gmeAuth.addUser('user_w_data7', 'e@mail.com', 'plaintext', false, { overwrite: true, data: {a: 1} }), gmeAuth.addUser('user_w_data8', 'e@mail.com', 'plaintext', false, { overwrite: true, data: {a: 1} }), gmeAuth.addUser('user_w_settings1', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('user_w_settings2', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('user_w_settings3', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('user_w_settings4', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('user_w_c_settings1', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('user_w_c_settings2', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('user_w_c_settings3', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('user_w_c_settings4', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('user_w_c_settings5', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('users_w_settings1', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('users_w_settings2', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('users_w_settings3', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('users_w_settings4', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('users_w_c_settings1', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('users_w_c_settings2', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('users_w_c_settings3', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('users_w_c_settings4', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('users_w_c_settings5', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}} }), gmeAuth.addUser('user_not_in_db', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1}} }), gmeAuth.addUser('user_not_in_db2', 'e@mail.com', 'plaintext', false, { overwrite: true, settings: {comp1: {a: 1}} }), gmeAuth.addUser('user_disabled_but_has_token', 'e@mail.com', 'plaintext', false, { overwrite: true }), gmeAuth.addUser('disabled_user_at_start', 'e@mail.com', 'plaintext', false, { overwrite: true, disabled: true }) ]); }) .then(function () { return Q.allDone([ gmeAuth.authorizeByUserId('user', 'project', 'create', { read: true, write: true, delete: false }), gmeAuth.authorizeByUserId('user', 'unauthorized_project', 'create', { read: false, write: false, delete: false }) ]); }) .nodeify(done); }); after(function (done) { gmeAuth.unload() .nodeify(done); }); describe('auth off, allowGuests false', function () { var server, agent; before(function (done) { var gmeConfig = testFixture.getGmeConfig(); gmeConfig.authentication.enable = false; gmeConfig.authentication.allowGuests = false; server = WebGME.standaloneServer(gmeConfig); server.start(done); }); after(function (done) { server.stop(done); }); beforeEach(function () { agent = superagent.agent(); }); // NO AUTH methods it('should get api links /api', function (done) { agent.get(server.getUrl() + '/api').end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.hasOwnProperty('api_documentation_url')).true; expect(res.body.hasOwnProperty('source_code_documentation_url')).true; done(); }); }); it('should get api documentation link', function (done) { agent.get(server.getUrl() + '/api').end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.hasOwnProperty('api_documentation_url')).true; agent.get(res.body.api_documentation_url).end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); }); it('should get api v1 links /api/v1', function (done) { agent.get(server.getUrl() + '/api/v1').end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); it('should return with 404 for any non resource that does not exist /api/does_not_exist', function (done) { agent.get(server.getUrl() + '/api/does_not_exist').end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should get all users /api/v1/users', function (done) { agent.get(server.getUrl() + '/api/v1/users').end(function (err, res) { expect(res.status).equal(200, err); //expect(res.body.length).equal(8); // TODO: check all users are there done(); }); }); it('should get all organizations /api/v1/orgs', function (done) { agent.get(server.getUrl() + '/api/v1/orgs').end(function (err, res) { expect(res.status).equal(200, err); //expect(res.body.length).equal(8); // TODO: check all users are there done(); }); }); // AUTH METHODS it('should return with guest account and 200 GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user').end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).equal(gmeConfig.authentication.guestAccount); done(); }); }); it('should support basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); it('should return 404 for GET /api/v1/user/token', function (done) { agent.get(server.getUrl() + '/api/v1/user/token').end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should use guest account with no password and no username basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).to.equal('guest'); done(); }); } ); it('should use guest account with wrong password basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:wrong_password').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).to.equal('guest'); done(); }); }); it('should use guest account wrong username basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('unknown_username:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).to.equal('guest'); done(); }); }); it('should GET /api/v1/users/guest', function (done) { agent.get(server.getUrl() + '/api/v1/users/guest') .end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); it('should return with the same information GET /api/v1/user and /api/v1/users/guest', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); agent.get(server.getUrl() + '/api/v1/users/guest') .end(function (err, res2) { expect(res2.status).equal(200, err); expect(res.body).deep.equal(res2.body); done(); }); }); }); it('should fail to update user without authentication PATCH /api/v1/users/user_to_modify', function (done) { agent.patch(server.getUrl() + '/api/v1/users/user_to_modify') //.set('Authorization', 'Basic ' + new Buffer('unknown_username:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(403, err); done(); }); }); it('should fail to update user without siteAdmin role PATCH /api/v1/users/user_to_modify', function (done) { agent.patch(server.getUrl() + '/api/v1/users/user_to_modify') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(403, err); done(); }); }); it('should fail to update non existent user PATCH /api/v1/users/does_not_exist', function (done) { var updates = { email: 'new_email_address', canCreate: false }; agent.get(server.getUrl() + '/api/v1/users/does_not_exist') .end(function (err, res) { expect(res.status).equal(404, err); agent.patch(server.getUrl() + '/api/v1/users/does_not_exist') //.set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .send(updates) .end(function (err, res2) { expect(res2.status).equal(403, err); done(); }); }); }); it('should fail to grant site admin access with no site admin roles PATCH /api/v1/user', function (done) { var updates = { email: 'new_email_address', siteAdmin: true }; agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.email).not.equal(updates.email); expect(res.body.siteAdmin).not.equal(updates.siteAdmin); agent.patch(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .send(updates) .end(function (err, res2) { expect(res2.status).equal(403, err); done(); }); }); }); it('should fail to set canCreate access with no site admin roles PATCH /api/v1/user', function (done) { var updates = { email: 'new_email_address', canCreate: false }; agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.email).not.equal(updates.email); expect(res.body.canCreate).not.equal(updates.canCreate); agent.patch(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .send(updates) .end(function (err, res2) { expect(res2.status).equal(403, err); done(); }); }); }); it('should fail to grant site admin acc with no site admin roles PATCH /api/v1/users/guest', function (done) { var updates = { email: 'new_email_address', siteAdmin: true }; agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.email).not.equal(updates.email); expect(res.body.siteAdmin).not.equal(true); agent.patch(server.getUrl() + '/api/v1/users/guest') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .send(updates) .end(function (err, res2) { expect(res2.status).equal(403, err); done(); }); }); }); it('should fail to set canCreate access acc with no site admin roles PATCH /api/v1/users/guest', function (done) { var updates = { email: 'new_email_address', canCreate: false }; agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.email).not.equal(updates.email); expect(res.body.canCreate).not.equal(updates.canCreate); agent.patch(server.getUrl() + '/api/v1/users/guest') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .send(updates) .end(function (err, res2) { expect(res2.status).equal(403, err); done(); }); }); }); it('should fail to create a new user if acting user is not a site admin PUT /api/v1/users', function (done) { var newUser = { userId: 'new_user2', email: 'new_email_address2', password: 'new_user_pass2', canCreate: true }; agent.get(server.getUrl() + '/api/v1/users/new_user2') .end(function (err, res) { expect(res.status).equal(404, err); // user should not exist at this point agent.put(server.getUrl() + '/api/v1/users') //.set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .send(newUser) .end(function (err, res2) { expect(res2.status).equal(403, err); done(); }); }); }); it('should fail to create a new user if not authenticated PUT /api/v1/users', function (done) { var newUser = { userId: 'new_user2', email: 'new_email_address2', password: 'new_user_pass2', canCreate: true }; agent.get(server.getUrl() + '/api/v1/users/new_user2') .end(function (err, res) { expect(res.status).equal(404, err); // user should not exist at this point agent.put(server.getUrl() + '/api/v1/users') .send(newUser) .end(function (err, res2) { expect(res2.status).equal(403, err); done(); }); }); }); it('should fail to delete a non existent user as site admin DELETE /api/v1/users/does_not_exist', function (done) { agent.get(server.getUrl() + '/api/v1/users/does_not_exist') .end(function (err, res) { expect(res.status).equal(404, err); agent.del(server.getUrl() + '/api/v1/users/does_not_exist') //.set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res2) { expect(res2.status).equal(403, err); done(); }); }); }); it('should return 404 when posting /api/v1/register', function (done) { var newUser = { userId: 'new_user404', email: 'new_email_address404', password: 'new_user_pass', canCreate: true }; agent.post(server.getUrl() + '/api/v1/register') .send(newUser) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); }); describe('auth on, allowGuests false, allowUserRegistration=true, registerUsersCanCreate=true', function () { var server, agent; before(function (done) { var gmeConfig = testFixture.getGmeConfig(); gmeConfig.authentication.enable = true; gmeConfig.authentication.allowGuests = false; gmeConfig.authentication.allowUserRegistration = true; gmeConfig.authentication.registeredUsersCanCreate = true; server = WebGME.standaloneServer(gmeConfig); privateKey = fs.readFileSync(gmeConfig.authentication.jwt.privateKey, 'utf8'); server.start(done); }); after(function (done) { server.stop(done); }); beforeEach(function () { agent = superagent.agent(); }); // NO AUTH methods it('should get api documentation link', function (done) { agent.get(server.getUrl() + '/api').end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.hasOwnProperty('api_documentation_url')).true; agent.get(res.body.api_documentation_url).end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); }); it('should get api v1 links /api/v1', function (done) { agent.get(server.getUrl() + '/api/v1').end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); it('should return with 404 for any non resource that does not exist /api/does_not_exist', function (done) { agent.get(server.getUrl() + '/api/does_not_exist').end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should 401 all users /api/v1/users', function (done) { agent.get(server.getUrl() + '/api/v1/users') .end(function (err, res) { expect(res.status).equal(401, err); done(); }); }); it('should 401 all orgs /api/v1/orgs', function (done) { agent.get(server.getUrl() + '/api/v1/orgs') .end(function (err, res) { expect(res.status).equal(401, err); done(); }); }); // AUTH METHODS it('should get all users /api/v1/users if authenticated and admin', function (done) { agent.get(server.getUrl() + '/api/v1/users') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); //expect(res.body.length).gt(2); // TODO: check all users are there done(); }); }); it('should return with 401 GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user').end(function (err, res) { expect(res.status).equal(401, err); done(); }); }); it('should support basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); it('should return 401 when no auth used for GET /api/v1/user/token', function (done) { agent.get(server.getUrl() + '/api/v1/user/token').end(function (err, res) { expect(res.status).equal(401, err); done(); }); }); it('should return an access_token when authed used for GET /api/v1/user/token', function (done) { agent.get(server.getUrl() + '/api/v1/user/token') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.webgmeToken.split('.').length).equal(3, 'Returned token not correct format'); done(); }); }); it('should create user when accessed in db and not existing for user', function (done) { var userId = 'user_not_in_db', token; gmeAuth.generateJWTokenForAuthenticatedUser(userId) .then(function (token_) { token = token_; return gmeAuth.deleteUser(userId, true); }) .then(function () { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Bearer ' + token) .end(function (err, res) { try { expect(res.status).equal(200, err); expect(res.body._id).equal(userId); expect(res.body.settings).to.deep.equal({}); } catch (e) { err = e; } done(err); }); }) .catch(done); }); it('should create user when accessed in db and not existing for user when token in query', function (done) { var userId = 'user_not_in_db2', token; gmeAuth.generateJWTokenForAuthenticatedUser(userId) .then(function (token_) { token = token_; return gmeAuth.deleteUser(userId, true); }) .then(function () { agent.get(server.getUrl() + '/api/v1/user') .query({token: token}) .end(function (err, res) { try { expect(res.status).equal(200, err); expect(res.body._id).equal(userId); expect(res.body.canCreate).equal(false); expect(res.body.settings).to.deep.equal({}); } catch (e) { err = e; } done(err); }); }) .catch(done); }); it('should create user when token in query has displayName', function (done) { var userId = 'user_with_displayName', dName = 'My Name'; Q.ninvoke(jwt, 'sign', {userId: userId, displayName: dName}, privateKey, { algorithm: gmeConfig.authentication.jwt.algorithm, expiresIn: gmeConfig.authentication.jwt.expiresIn }) .then(function (token) { agent.get(server.getUrl() + '/api/v1/user') .query({token: token}) .end(function (err, res) { try { expect(res.status).equal(200, err); expect(res.body._id).equal(userId); expect(res.body.displayName).equal(dName); expect(res.body.canCreate).equal(false); expect(res.body.settings).to.deep.equal({}); } catch (e) { err = e; } done(err); }); }); }); it('should create user when token in bearer has displayName', function (done) { var userId = 'user_with_displayName', dName = 'My Name'; Q.ninvoke(jwt, 'sign', {userId: userId, displayName: dName}, privateKey, { algorithm: gmeConfig.authentication.jwt.algorithm, expiresIn: gmeConfig.authentication.jwt.expiresIn }) .then(function (token) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Bearer ' + token) .end(function (err, res) { try { expect(res.status).equal(200, err); expect(res.body._id).equal(userId); expect(res.body.displayName).equal(dName); expect(res.body.canCreate).equal(false); expect(res.body.settings).to.deep.equal({}); } catch (e) { err = e; } done(err); }); }); }); it('should 401 when user identified via token but user is disabled', function (done) { var userId = 'user_disabled_but_has_token', token; gmeAuth.generateJWTokenForAuthenticatedUser(userId) .then(function (token_) { token = token_; return gmeAuth.deleteUser(userId); }) .then(function () { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Bearer ' + token) .end(function (err, res) { try { expect(res.status).to.equal(401); done(); } catch (e) { done(e); } }); }) .catch(done); }); it('should fail with wrong password basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:wrong_password').toString('base64')) .end(function (err, res) { expect(res.status).equal(401, err); done(); }); }); it('should fail with wrong username basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('unknown_username:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(401, err); done(); }); }); it('should update user with valid data PATCH /api/v1/users/user_to_modify', function (done) { var updates = { email: 'new_email_address', password: 'newPlainPassword', canCreate: false }; agent.get(server.getUrl() + '/api/v1/users/user_to_modify') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.email).not.equal(updates.email); expect(res.body.canCreate).not.equal(updates.canCreate); agent.patch(server.getUrl() + '/api/v1/users/user_to_modify') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .send(updates) .end(function (err, res2) { expect(res2.status).equal(200, err); // have not changed anything that we did not requested to change expect(res2.body._id).equal(res.body._id); expect(res2.body.siteAdmin).equal(res.body.siteAdmin); // we have just changed these fields expect(res2.body.email).equal(updates.email); expect(res2.body.canCreate).equal(updates.canCreate); done(); }); }); }); it('should give site admin access to user with valid data PATCH /api/v1/users/user_to_modify', function (done) { var updates = { siteAdmin: true }; agent.get(server.getUrl() + '/api/v1/users/user_to_modify') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.siteAdmin).not.equal(updates.siteAdmin); agent.patch(server.getUrl() + '/api/v1/users/user_to_modify') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .send(updates) .end(function (err, res2) { expect(res2.status).equal(200, err); // have not changed anything that we did not requested to change expect(res2.body._id).equal(res.body._id); expect(res2.body.siteAdmin).equal(true); done(); }); }); }); it('should update user with no data PATCH /api/v1/users/user_to_modify', function (done) { agent.patch(server.getUrl() + '/api/v1/users/user_to_modify') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) // no data .end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); it('should update self user with valid data PATCH /api/v1/user', function (done) { var updates = { email: 'new_email_address' }; agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('user:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.email).not.equal(updates.email); agent.patch(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('user:plaintext').toString('base64')) .send(updates) .end(function (err, res2) { expect(res2.status).equal(200, err); // have not changed anything that we did not requested to change expect(res2.body._id).equal(res.body._id); expect(res2.body.siteAdmin).equal(res.body.siteAdmin); // we have changed just these fields expect(res2.body.email).equal(updates.email); done(); }); }); }); it('should create a new user with valid data PUT /api/v1/users', function (done) { var newUser = { userId: 'new_user', email: 'new_email_address', password: 'new_user_pass', canCreate: true }; agent.get(server.getUrl() + '/api/v1/users/new_user') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); // user should not exist at this point agent.put(server.getUrl() + '/api/v1/users') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .send(newUser) .end(function (err, res2) { expect(res2.status).equal(200, err); expect(res2.body._id).equal(newUser.userId); expect(res2.body.email).equal(newUser.email); expect(res2.body.canCreate).equal(newUser.canCreate); done(); }); }); }); it('should create a new user with valid data PUT /api/v1/users/new_user_param', function (done) { var newUser = { email: 'new_email_address', password: 'pass', canCreate: true }, userId = 'new_user_param'; agent.get(server.getUrl() + '/api/v1/users/new_user_param') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); // user should not exist at this point agent.put(server.getUrl() + '/api/v1/users/' + userId) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .send(newUser) .end(function (err, res2) { expect(res2.status).equal(200, err); expect(res2.body._id).equal(userId); expect(res2.body.email).equal(newUser.email); expect(res2.body.canCreate).equal(newUser.canCreate); done(); }); }); }); it('should fail to create a new user with login name that exists PUT /api/v1/users/guest', function (done) { var newUser = { userId: 'new_user', email: 'new_email_address', password: 'new_user_pass', canCreate: true }; agent.get(server.getUrl() + '/api/v1/users/guest') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); // user should not exist at this point agent.put(server.getUrl() + '/api/v1/users') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .send(newUser) .end(function (err, res2) { expect(res2.status).equal(400, err); done(); }); }); }); it('should delete a specified user as site admin DELETE /api/v1/users/user_to_delete', function (done) { agent.get(server.getUrl() + '/api/v1/users') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); agent.del(server.getUrl() + '/api/v1/users/user_to_delete') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res2) { expect(res2.status).equal(204, err); agent.get(server.getUrl() + '/api/v1/users') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res2) { expect(res2.status).equal(200, err); expect(res.body.length - 1).equal(res2.body.length); done(); }); }); }); }); it('should delete a self user DELETE /api/v1/users/self_delete_2', function (done) { agent.get(server.getUrl() + '/api/v1/users') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); agent.del(server.getUrl() + '/api/v1/users/self_delete_2') .set('Authorization', 'Basic ' + new Buffer('self_delete_2:plaintext').toString('base64')) .end(function (err, res2) { expect(res2.status).equal(204, err); agent.get(server.getUrl() + '/api/v1/users') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res2) { expect(res2.status).equal(200, err); expect(res.body.length - 1).equal(res2.body.length); done(); }); }); }); }); it('should delete a self user DELETE /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/users') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); agent.del(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('self_delete_1:plaintext').toString('base64')) .end(function (err, res2) { expect(res2.status).equal(204, err); agent.get(server.getUrl() + '/api/v1/users') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res2) { expect(res2.status).equal(200, err); expect(res.body.length - 1).equal(res2.body.length); done(); }); }); }); }); it('should add user when posting /api/v1/register', function (done) { var newUser = { userId: 'reg_user', email: 'em@il', password: 'pass' }; agent.post(server.getUrl() + '/api/v1/register') .send(newUser) .end(function (err, res) { expect(res.status).equal(200, err); agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('reg_user:pass').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).to.equal('reg_user'); expect(res.body.canCreate).to.equal(true); done(); }); }); }); it('should fail with 400 to add user twice when posting /api/v1/register', function (done) { var newUser = { userId: 'reg_user_twice', email: 'orgEmail', password: 'pass' }; agent.post(server.getUrl() + '/api/v1/register') .send(newUser) .end(function (err, res) { expect(res.status).equal(200, err); newUser.email = 'updateEmail'; agent.post(server.getUrl() + '/api/v1/register') .send(newUser) .end(function (err, res) { expect(res.status).equal(400, err); agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('reg_user_twice:pass').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).to.equal('reg_user_twice'); expect(res.body.email).to.equal('orgEmail'); done(); }); }); }); }); }); describe('auth on, allowGuests false, allowUserRegistration=true, registerUsersCanCreate=false', function () { var server, agent; before(function (done) { var gmeConfig = testFixture.getGmeConfig(); gmeConfig.authentication.enable = true; gmeConfig.authentication.allowGuests = false; gmeConfig.authentication.allowUserRegistration = true; gmeConfig.authentication.registeredUsersCanCreate = false; server = WebGME.standaloneServer(gmeConfig); server.start(done); }); after(function (done) { server.stop(done); }); beforeEach(function () { agent = superagent.agent(); }); it('should add user when posting /api/v1/register', function (done) { var newUser = { userId: 'reg_user_no_create', email: 'em@il', password: 'pass' }; agent.post(server.getUrl() + '/api/v1/register') .send(newUser) .end(function (err, res) { expect(res.status).equal(200, err); agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('reg_user_no_create:pass').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).to.equal('reg_user_no_create'); expect(res.body.canCreate).to.equal(false); done(); }); }); }); }); describe('auth on, allowGuests true, allowUserRegistration=false, inferredUsersCanCreate=true', function () { var server, agent, guestAccount = 'guest'; before(function (done) { var gmeConfig = testFixture.getGmeConfig(); gmeConfig.authentication.enable = true; gmeConfig.authentication.allowGuests = true; gmeConfig.authentication.guestAccount = guestAccount; gmeConfig.authentication.allowUserRegistration = false; gmeConfig.authentication.inferredUsersCanCreate = true; server = WebGME.standaloneServer(gmeConfig); server.start(done); }); after(function (done) { server.stop(done); }); beforeEach(function () { agent = superagent.agent(); }); // NO AUTH methods it('should get api documentation link', function (done) { agent.get(server.getUrl() + '/api').end(function (err, res) { expect(res.status).equal(200, err); // TODO: redirects to login page done(); }); }); it('should get api v1 links /api/v1', function (done) { agent.get(server.getUrl() + '/api/v1').end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); it('should return with 404 for any non resource that does not exist /api/does_not_exist', function (done) { agent.get(server.getUrl() + '/api/does_not_exist').end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); // AUTH it('should get users and filter depending on user-type /api/v1/users', function (done) { var numberOfUsers; agent.get(server.getUrl() + '/api/v1/users').end(function (err, res) { expect(res.status).equal(200, err); // Guest can only see him/herself. try { expect(res.body.length).to.equal(1); expect(res.body[0]._id).to.equal('guest'); } catch (e) { return done(e); } agent.get(server.getUrl() + '/api/v1/users') .set('Authorization', 'Basic ' + new Buffer('user2:plaintext').toString('base64')) .end(function (err, res) { // Regular user can only see details about him/herself. try { numberOfUsers = res.body.length; expect(numberOfUsers > 1).to.equal(true); res.body.forEach(function (uData) { if (uData._id !== 'user2') { expect(uData.email.length).to.equal(0); expect(Object.keys(uData.data).length).to.equal(0); } else { expect(uData.email.length > 1).to.equal(true); } }); } catch (e) { return done(e); } agent.get(server.getUrl() + '/api/v1/users') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { // Admin can see all details about everyone. var gotData = false; try { expect(res.body.length).to.equal(numberOfUsers); res.body.forEach(function (uData) { expect(uData.email.length > 1).to.equal(true); if (uData._id !== 'admin' && Object.keys(uData.data).length > 0) { gotData = true; } }); expect(gotData).to.equal(true); } catch (e) { return done(e); } done(); }); }); }); }); it('should 404 GET /api/v1/users/user if guest', function (done) { agent.get(server.getUrl() + '/api/v1/users/user') .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should GET /api/v1/users/user if non guest user but filter out email and projects', function (done) { agent.get(server.getUrl() + '/api/v1/users/user') .set('Authorization', 'Basic ' + new Buffer('user2:plaintext').toString('base64')) .end(function (err, res) { try { expect(res.status).equal(200, err); expect(res.body.email.length).to.equal(0); expect(Object.keys(res.body.projects).length).to.equal(0); done(); } catch (e) { done(e); } }); }); it('should GET /api/v1/users/user if admin and contain email', function (done) { agent.get(server.getUrl() + '/api/v1/users/user') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(Object.keys(res.body.projects).length).to.equal(1); expect(res.body.email.length > 1).to.equal(true); done(); }); }); it('should GET /api/v1/users/guest if same user', function (done) { agent.get(server.getUrl() + '/api/v1/users/guest') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); it('should get all users /api/v1/users', function (done) { agent.get(server.getUrl() + '/api/v1/users') .end(function (err, res) { expect(res.status).equal(200, err); //expect(res.body.length).equal(8); // TODO: check all users are there done(); }); }); it('should fail to delete a specified user if not authenticated DELETE /api/v1/users/admin', function (done) { agent.get(server.getUrl() + '/api/v1/users/admin') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); agent.del(server.getUrl() + '/api/v1/users/admin') .end(function (err, res2) { expect(res2.status).equal(403, err); agent.get(server.getUrl() + '/api/v1/users/admin') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res2) { expect(res.status).equal(200, err); // make sure we did not lose any users expect(res.body).deep.equal(res2.body); done(); }); }); }); }); it('should fail to delete a specified user if acting user is not a site admin DELETE /api/v1/users/guest', function (done) { agent.get(server.getUrl() + '/api/v1/users/user') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); agent.del(server.getUrl() + '/api/v1/users/user') //.set('Authorization', 'Basic ' + new Buffer('user:plaintext').toString('base64')) .end(function (err, res2) { expect(res2.status).equal(403, err); agent.get(server.getUrl() + '/api/v1/users/user') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res2) { expect(res.status).equal(200, err); // make sure we did not lose any users expect(res.body).deep.equal(res2.body); done(); }); }); }); }); it('should get disabled user too if /api/v1/users?includeDisabled=true for site-admin', function (done) { var dUsers, users; function report(err) { if (err) { done(err); } else if (dUsers && users) { var hadWhenShouldHave = false, hadWhenShouldNotHave = false; try { expect(dUsers.length > users.length).to.equal(true); dUsers.forEach(function (uData) { if (uData.disabled) { hadWhenShouldHave = true; } }); users.forEach(function (uData) { if (uData.disabled) { hadWhenShouldNotHave = true; } }); expect(hadWhenShouldHave).to.equal(true); expect(hadWhenShouldNotHave).to.equal(false); done(); } catch (e) { done(e); } } } agent.get(server.getUrl() + '/api/v1/users') .query({includeDisabled: true}) .end(function (err, res) { users = res.body; report(err); }); agent.get(server.getUrl() + '/api/v1/users') .query({includeDisabled: true}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { dUsers = res.body; report(err); }); }); it('should return with 204 and delete user from db if site-admin DEL /api/v1/users/:userId?force=true', function (done) { var userId = 'to_be_force_deleted'; gmeAuth.addUser(userId, '@', 'p', true, {overwrite: true}) .then(function () { var deferred = Q.defer(); agent.del(server.getUrl() + '/api/v1/users/' + userId) .query({force: true}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { try { expect(res.status).equal(204, err); deferred.resolve(); } catch (e) { deferred.reject(e); } }); return deferred.promise; }) .then(function () { return gmeAuth.listUsers({disabled: undefined}); }) .then(function (users) { users.forEach(function (userData) { if (userData._id === userId) { throw new Error('User still exists'); } }); }) .nodeify(done); } ); it('should 204 but NOT delete user from db if not site-admin DEL /api/v1/users/:userId?force=true', function (done) { var userId = 'to_be_attempted_force_deletion'; gmeAuth.addUser(userId, '@', 'p', true, {overwrite: true}) .then(function () { var deferred = Q.defer(); agent.del(server.getUrl() + '/api/v1/users/' + userId) .query({force: true}) .set('Authorization', 'Basic ' + new Buffer(userId + ':p').toString('base64')) .end(function (err, res) { try { expect(res.status).equal(204, err); deferred.resolve(); } catch (e) { deferred.reject(e); } }); return deferred.promise; }) .then(function () { return gmeAuth.listUsers({disabled: undefined}); }) .then(function (users) { var userExists = false; users.forEach(function (userData) { if (userData._id === userId) { userExists = true; expect(userData.disabled).to.equal(true); } }); expect(userExists).to.equal(true); }) .nodeify(done); } ); it('should re-enable user if site-admin patch /api/v1/users/:userId with body {disabled: true}', function (done) { var userId = 'to_be_reEnabled_deleted'; gmeAuth.addUser(userId, '@', 'p', true, {overwrite: true, disabled: true}) .then(function () { var deferred = Q.defer(); agent.patch(server.getUrl() + '/api/v1/users/' + userId) .send({disabled: false}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { try { expect(res.status).equal(200, err); expect(res.body.disabled).to.equal(false); deferred.resolve(); } catch (e) { deferred.reject(e); } }); return deferred.promise; }) .then(function () { return gmeAuth.getUser(userId); }) .then(function (user) { expect(user.disabled).to.equal(false); }) .nodeify(done); } ); it('should 403 if not site-admin patch /api/v1/users/:userId with body {disabled: true}', function (done) { var userId = 'attempt_to_be_reEnabled_deleted'; gmeAuth.addUser(userId, '@', 'p', true, {overwrite: true}) .then(function () { var deferred = Q.defer(); agent.patch(server.getUrl() + '/api/v1/users/' + userId) .send({disabled: false}) .set('Authorization', 'Basic ' + new Buffer(userId + ':p').toString('base64')) .end(function (err, res) { try { expect(res.status).equal(403, err); deferred.resolve(); } catch (e) { deferred.reject(e); } }); return deferred.promise; }) .nodeify(done); } ); it('should return with 200 and guest is logged in GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user').end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).equal(guestAccount); done(); }); }); it('should support basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); it('should return an access_token for guest for GET /api/v1/user/token', function (done) { agent.get(server.getUrl() + '/api/v1/user/token') .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.webgmeToken.split('.').length) .equal(3, 'Returned token not correct format'); agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Bearer ' + res.body.webgmeToken) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).equal('guest', err); done(); }); }); }); it('should return an access_token for admin for GET /api/v1/user/token', function (done) { agent.get(server.getUrl() + '/api/v1/user/token') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.webgmeToken.split('.').length).equal(3, 'Returned token not correct format'); agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Bearer ' + res.body.webgmeToken) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).equal('admin', err); done(); }); }); }); it('should return 401 with invalid access_token for guest for GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Bearer ' + '42.mombo.jumbo') .end(function (err, res) { expect(res.status).equal(401, err); done(); }); }); it('should not check password of guest basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:wrong_password').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); it('should fail with wrong password basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('admin:wrong_password').toString('base64')) .end(function (err, res) { expect(res.status).equal(401, err); done(); }); }); it('should fail with wrong username basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('unknown_username:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(401, err); done(); }); }); // User data methods /user/data it('should get empty user data basic authentication GET /api/v1/user/data', function (done) { agent.get(server.getUrl() + '/api/v1/user/data') .set('Authorization', 'Basic ' + new Buffer('user_w_data:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({}); done(); }); }); it('should get user data basic authentication GET /api/v1/user/data', function (done) { agent.get(server.getUrl() + '/api/v1/user/data') .set('Authorization', 'Basic ' + new Buffer('user_w_data1:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({a: 1}); done(); }); }); it('should overwrite user data basic authentication PUT /api/v1/user/data', function (done) { agent.put(server.getUrl() + '/api/v1/user/data') .send({b: 1}) .set('Authorization', 'Basic ' + new Buffer('user_w_data2:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({b: 1}); gmeAuth.getUser('user_w_data2') .then(function (userData) { expect(userData.data).to.deep.equal({b: 1}); }) .nodeify(done); }); }); it('should update user data basic authentication PATCH /api/v1/user/data', function (done) { agent.patch(server.getUrl() + '/api/v1/user/data') .send({b: 1}) .set('Authorization', 'Basic ' + new Buffer('user_w_data3:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({a: 1, b: 1}); gmeAuth.getUser('user_w_data3') .then(function (userData) { expect(userData.data).to.deep.equal({a: 1, b: 1}); }) .nodeify(done); }); }); it('should delete user data basic authentication DELETE /api/v1/user/data', function (done) { agent.del(server.getUrl() + '/api/v1/user/data') .set('Authorization', 'Basic ' + new Buffer('user_w_data4:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(204, err); gmeAuth.getUser('user_w_data4') .then(function (userData) { expect(userData.data).to.deep.equal({}); }) .nodeify(done); }); }); // User data methods /users/:username/data it('should get user data basic authentication "admin" GET /api/v1/users/:username/data', function (done) { agent.get(server.getUrl() + '/api/v1/users/user_w_data5/data') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({a: 1}); done(); }); }); it('should overwrite user data basic authentication "admin" PUT /api/v1/users/:username/data', function (done) { agent.put(server.getUrl() + '/api/v1/users/user_w_data6/data') .send({b: 1}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({b: 1}); gmeAuth.getUser('user_w_data6') .then(function (userData) { expect(userData.data).to.deep.equal({b: 1}); }) .nodeify(done); }); } ); it('should update user data basic authentication "admin" PATCH /api/v1/users/:username/data', function (done) { agent.patch(server.getUrl() + '/api/v1/users/user_w_data7/data') .send({b: 1}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({a: 1, b: 1}); gmeAuth.getUser('user_w_data7') .then(function (userData) { expect(userData.data).to.deep.equal({a: 1, b: 1}); }) .nodeify(done); }); } ); it('should delete user data basic authentication "admin" DELETE /api/v1/users/:username/data', function (done) { agent.del(server.getUrl() + '/api/v1/users/user_w_data8/data') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(204, err); gmeAuth.getUser('user_w_data8') .then(function (userData) { expect(userData.data).to.deep.equal({}); }) .nodeify(done); }); } ); // Component Settings it('should get empty user settings basic authentication GET /api/v1/componentSettings', function (done) { agent.get(server.getUrl() + '/api/v1/componentSettings') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({}); done(); }); }); it('should get empty user settings basic authentication GET /api/v1/componentSettings/componentId', function (done) { agent.get(server.getUrl() + '/api/v1/componentSettings/componentId') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({}); done(); }); } ); // User setting methods /user/settings it('should get empty user settings basic authentication GET /api/v1/user/settings', function (done) { agent.get(server.getUrl() + '/api/v1/user/settings') .set('Authorization', 'Basic ' + new Buffer('user_w_data:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({}); done(); }); }); it('should get user settings basic authentication GET /api/v1/user/settings', function (done) { agent.get(server.getUrl() + '/api/v1/user/settings') .set('Authorization', 'Basic ' + new Buffer('user_w_settings1:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}}); done(); }); }); it('should overwrite user settings basic authentication PUT /api/v1/user/settings', function (done) { agent.put(server.getUrl() + '/api/v1/user/settings') .send({comp3: {a: 1, b: 1}}) .set('Authorization', 'Basic ' + new Buffer('user_w_settings2:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({comp3: {a: 1, b: 1}}); gmeAuth.getUser('user_w_settings2') .then(function (userData) { expect(userData.settings).to.deep.equal({comp3: {a: 1, b: 1}}); }) .nodeify(done); }); }); it('should update user settings basic authentication PATCH /api/v1/user/settings', function (done) { agent.patch(server.getUrl() + '/api/v1/user/settings') .send({comp2: {a: 1, b: 1}}) .set('Authorization', 'Basic ' + new Buffer('user_w_settings3:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({comp1: {a: 1, b: 1}, comp2: {a: 1, b: 1}}); gmeAuth.getUser('user_w_settings3') .then(function (userData) { expect(userData.settings).to.deep.equal({comp1: {a: 1, b: 1}, comp2: {a: 1, b: 1}}); }) .nodeify(done); }); }); it('should delete user settings basic authentication DELETE /api/v1/user/settings', function (done) { agent.del(server.getUrl() + '/api/v1/user/settings') .set('Authorization', 'Basic ' + new Buffer('user_w_settings4:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(204, err); gmeAuth.getUser('user_w_settings4') .then(function (userData) { expect(userData.settings).to.deep.equal({}); }) .nodeify(done); }); }); // User setting methods /user/settings/:componentId it('should get empty user settings basic authentication GET /api/v1/user/settings/comp', function (done) { agent.get(server.getUrl() + '/api/v1/user/settings/comp') .set('Authorization', 'Basic ' + new Buffer('user_w_data:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({}); done(); }); }); it('should get user settings basic authentication GET /api/v1/user/settings/comp1', function (done) { agent.get(server.getUrl() + '/api/v1/user/settings/comp1') .set('Authorization', 'Basic ' + new Buffer('user_w_c_settings1:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({a: 1, b: 1}); done(); }); }); it('should add user settings basic authentication PUT /api/v1/user/settings/comp3', function (done) { agent.put(server.getUrl() + '/api/v1/user/settings/comp3') .send({a: 3, b: 3}) .set('Authorization', 'Basic ' + new Buffer('user_w_c_settings2:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({a: 3, b: 3}); gmeAuth.getUser('user_w_c_settings2') .then(function (userData) { expect(userData.settings).to.deep.equal({ comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}, comp3: {a: 3, b: 3} }); }) .nodeify(done); }); }); it('should overwrite user settings basic authentication PUT /api/v1/user/settings/comp2', function (done) { agent.put(server.getUrl() + '/api/v1/user/settings/comp2') .send({a: 3}) .set('Authorization', 'Basic ' + new Buffer('user_w_c_settings3:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({a: 3}); gmeAuth.getUser('user_w_c_settings3') .then(function (userData) { expect(userData.settings).to.deep.equal({ comp1: {a: 1, b: 1}, comp2: {a: 3} }); }) .nodeify(done); }); }); it('should update user settings basic authentication PATCH /api/v1/user/settings/comp2', function (done) { agent.patch(server.getUrl() + '/api/v1/user/settings/comp2') .send({b: 1}) .set('Authorization', 'Basic ' + new Buffer('user_w_c_settings4:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({a: 2, b: 1}); gmeAuth.getUser('user_w_c_settings4') .then(function (userData) { expect(userData.settings).to.deep.equal({ comp1: {a: 1, b: 1}, comp2: {a: 2, b: 1} }); }) .nodeify(done); }); }); it('should delete user settings basic authentication DELETE /api/v1/user/settings/comp2', function (done) { agent.del(server.getUrl() + '/api/v1/user/settings/comp2') .set('Authorization', 'Basic ' + new Buffer('user_w_c_settings5:plaintext').toString('base64')) .end(function (err, res) { expect(res.status).equal(204, err); gmeAuth.getUser('user_w_c_settings5') .then(function (userData) { expect(userData.settings.comp2).to.deep.equal({}); }) .nodeify(done); }); }); // User settings methods /users/:username/settings it('should get empty user settings basic authentication GET /api/v1/user/:username/settings', function (done) { agent.get(server.getUrl() + '/api/v1/users/user_w_data/settings') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({}); done(); }); } ); it('should get user settings basic authentication GET /api/v1/users/:username/settings', function (done) { agent.get(server.getUrl() + '/api/v1/users/users_w_settings1/settings') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}}); done(); }); }); it('should overwrite user settings basic authentication PUT /api/v1/users/:username/settings', function (done) { agent.put(server.getUrl() + '/api/v1/users/users_w_settings2/settings') .send({comp3: {a: 1, b: 1}}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({comp3: {a: 1, b: 1}}); gmeAuth.getUser('users_w_settings2') .then(function (userData) { expect(userData.settings).to.deep.equal({comp3: {a: 1, b: 1}}); }) .nodeify(done); }); } ); it('should update user settings basic authentication PATCH /api/v1/users/:username/settings', function (done) { agent.patch(server.getUrl() + '/api/v1/users/users_w_settings3/settings') .send({comp2: {a: 1, b: 1}}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({comp1: {a: 1, b: 1}, comp2: {a: 1, b: 1}}); gmeAuth.getUser('users_w_settings3') .then(function (userData) { expect(userData.settings).to.deep.equal({comp1: {a: 1, b: 1}, comp2: {a: 1, b: 1}}); }) .nodeify(done); }); } ); it('should delete user settings basic authentication DELETE /api/v1/users/:username/settings', function (done) { agent.del(server.getUrl() + '/api/v1/users/users_w_settings4/settings') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(204, err); gmeAuth.getUser('users_w_settings4') .then(function (userData) { expect(userData.settings).to.deep.equal({}); }) .nodeify(done); }); } ); // User setting methods /users/:userId/settings/:componentId it('should get empty user settings basic authentication GET /api/v1/users/:username/settings/comp', function (done) { agent.get(server.getUrl() + '/api/v1/users/user_w_data/settings/comp') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({}); done(); }); } ); it('should get user settings basic authentication GET /api/v1/users/:username/settings/comp1', function (done) { agent.get(server.getUrl() + '/api/v1/users/users_w_c_settings1/settings/comp1') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({a: 1, b: 1}); done(); }); } ); it('should add user settings basic authentication PUT /api/v1/users/:username/settings/comp3', function (done) { agent.put(server.getUrl() + '/api/v1/users/users_w_c_settings2/settings/comp3') .send({a: 3, b: 3}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({a: 3, b: 3}); gmeAuth.getUser('users_w_c_settings2') .then(function (userData) { expect(userData.settings).to.deep.equal({ comp1: {a: 1, b: 1}, comp2: {a: 2, b: 2}, comp3: {a: 3, b: 3} }); }) .nodeify(done); }); } ); it('should overwrite user settings basic authentication PUT /api/v1/users/:username/settings/comp2', function (done) { agent.put(server.getUrl() + '/api/v1/users/users_w_c_settings3/settings/comp2') .send({a: 3}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({a: 3}); gmeAuth.getUser('users_w_c_settings3') .then(function (userData) { expect(userData.settings).to.deep.equal({ comp1: {a: 1, b: 1}, comp2: {a: 3} }); }) .nodeify(done); }); } ); it('should update user settings basic authentication PATCH /api/v1/users/:username/settings/comp2', function (done) { agent.patch(server.getUrl() + '/api/v1/users/users_w_c_settings4/settings/comp2') .send({b: 1}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body).to.deep.equal({a: 2, b: 1}); gmeAuth.getUser('users_w_c_settings4') .then(function (userData) { expect(userData.settings).to.deep.equal({ comp1: {a: 1, b: 1}, comp2: {a: 2, b: 1} }); }) .nodeify(done); }); } ); it('should delete user settings basic authentication DELETE /api/v1/users/:username/settings/comp2', function (done) { agent.del(server.getUrl() + '/api/v1/users/users_w_c_settings5/settings/comp2') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(204, err); gmeAuth.getUser('users_w_c_settings5') .then(function (userData) { expect(userData.settings.comp2).to.deep.equal({}); }) .nodeify(done); }); } ); it('should create user when accessed in db and not existing for user when token in query', function (done) { var userId = 'user_not_in_db2', token; gmeAuth.generateJWTokenForAuthenticatedUser(userId) .then(function (token_) { token = token_; return gmeAuth.deleteUser(userId, true); }) .then(function () { agent.get(server.getUrl() + '/api/v1/user') .query({token: token}) .end(function (err, res) { try { expect(res.status).equal(200, err); expect(res.body._id).equal(userId); expect(res.body.canCreate).equal(true); expect(res.body.settings).to.deep.equal({}); } catch (e) { err = e; } done(err); }); }) .catch(done); }); // Fail cases it('should 404 basic authentication "admin" GET /api/v1/users/doesNotExist/data', function (done) { agent.get(server.getUrl() + '/api/v1/users/doesNotExist/data') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should 404 basic authentication "admin" PUT /api/v1/users/doesNotExist/data', function (done) { agent.put(server.getUrl() + '/api/v1/users/doesNotExist/data') .send({b: 1}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should 404 basic authentication "admin" PATCH /api/v1/users/doesNotExist/data', function (done) { agent.patch(server.getUrl() + '/api/v1/users/doesNotExist/data') .send({b: 1}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should 404 basic authentication "admin" DELETE /api/v1/users/doesNotExist/data', function (done) { agent.del(server.getUrl() + '/api/v1/users/doesNotExist/data') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should 403 ensureSameUserOrSiteAdmin "guest" PUT /api/v1/users/doesNotExist/data', function (done) { agent.put(server.getUrl() + '/api/v1/users/user_w_data/data') .send({a: 1}) .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(403, err); done(); }); }); it('should 404 basic authentication "admin" GET /api/v1/users/doesNotExist/settings', function (done) { agent.get(server.getUrl() + '/api/v1/users/doesNotExist/settings') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should 404 basic authentication "admin" PUT /api/v1/users/doesNotExist/settings', function (done) { agent.put(server.getUrl() + '/api/v1/users/doesNotExist/settings') .send({b: 1}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should 404 basic authentication "admin" PATCH /api/v1/users/doesNotExist/settings', function (done) { agent.patch(server.getUrl() + '/api/v1/users/doesNotExist/settings') .send({b: 1}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should 404 basic authentication "admin" DELETE /api/v1/users/doesNotExist/settings', function (done) { agent.del(server.getUrl() + '/api/v1/users/doesNotExist/settings') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should 404 basic authentication "admin" GET /api/v1/users/doesNotExist/settings/comp', function (done) { agent.get(server.getUrl() + '/api/v1/users/doesNotExist/settings/comp') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should 404 basic authentication "admin" PUT /api/v1/users/doesNotExist/settings/comp', function (done) { agent.put(server.getUrl() + '/api/v1/users/doesNotExist/settings/comp') .send({b: 1}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); it('should 404 basic authentication "admin" PATCH /api/v1/users/doesNotExist/settings/comp', function (done) { agent.patch(server.getUrl() + '/api/v1/users/doesNotExist/settings/comp') .send({b: 1}) .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); } ); it('should 404 basic authentication "admin" DELETE /api/v1/users/doesNotExist/settings/comp', function (done) { agent.del(server.getUrl() + '/api/v1/users/doesNotExist/settings/comp') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); } ); it('should 401 basic authentication empty user and password /api/v1/user', function (done) { agent.del(server.getUrl() + '/api/v1/users/doesNotExist/settings/comp') .set('Authorization', 'Basic ' + new Buffer('').toString('base64')) .end(function (err, res) { expect(res.status).equal(401, err); done(); }); }); it('should return 404 when posting /api/v1/register', function (done) { var newUser = { userId: 'new_user404', email: 'new_email_address404', password: 'new_user_pass', canCreate: true }; agent.post(server.getUrl() + '/api/v1/register') .send(newUser) .end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); }); describe('auth on, allowGuests false, allowUserRegistration="./testRegisterEndPoint"', function () { var server, agent; before(function (done) { var gmeConfig = testFixture.getGmeConfig(); gmeConfig.authentication.enable = true; gmeConfig.authentication.allowGuests = false; gmeConfig.authentication.allowUserRegistration = testFixture.path.join(__dirname, 'testRegisterEndPoint'); server = WebGME.standaloneServer(gmeConfig); server.start(done); }); after(function (done) { server.stop(done); }); beforeEach(function () { agent = superagent.agent(); }); it('should add user when posting /api/v1/register and user starts with an "a"', function (done) { var newUser = { userId: 'a_new_user_starts_with_a', email: 'em@il', password: 'pass' }; agent.post(server.getUrl() + '/api/v1/register') .send(newUser) .end(function (err, res) { expect(res.status).equal(200, err); agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('a_new_user_starts_with_a:pass').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).to.equal('a_new_user_starts_with_a'); done(); }); }); }); it('should 400 when posting /api/v1/register if user does NOT starts with an "a"', function (done) { var newUser = { userId: 'not_starting_with_a_new_user', email: 'em@il', password: 'pass' }; agent.post(server.getUrl() + '/api/v1/register') .send(newUser) .end(function (err, res) { if (res.status === 400) { done(); } else { done(new Error('Did not 400, instead ' + res.status)); } }); }); }); describe('auth off, allowGuests true', function () { var server, agent; before(function (done) { var gmeConfig = testFixture.getGmeConfig(); gmeConfig.authentication.enable = false; gmeConfig.authentication.allowGuests = true; server = WebGME.standaloneServer(gmeConfig); server.start(done); }); after(function (done) { server.stop(done); }); beforeEach(function () { agent = superagent.agent(); }); // NO AUTH methods it('should get api documentation link', function (done) { agent.get(server.getUrl() + '/api').end(function (err, res) { expect(res.status).equal(200, err); expect(res.body.hasOwnProperty('api_documentation_url')).true; agent.get(res.body.api_documentation_url).end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); }); it('should get api v1 links /api/v1', function (done) { agent.get(server.getUrl() + '/api/v1').end(function (err, res) { expect(res.status).equal(200, err); done(); }); }); it('should return with 404 for any non resource that does not exist /api/does_not_exist', function (done) { agent.get(server.getUrl() + '/api/does_not_exist').end(function (err, res) { expect(res.status).equal(404, err); done(); }); }); // AUTH METHODS it('should get all users /api/v1/users', function (done) { agent.get(server.getUrl() + '/api/v1/users').end(function (err, res) { expect(res.status).equal(200, err); //expect(res.body.length).equal(8); // TODO: check all users are there done(); }); }); it('should return with guest user account and 200 GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user').end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).equal(gmeConfig.authentication.guestAccount); done(); }); }); it('should use guest account GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).to.deep.equal('guest'); done(); }); }); it('should use guest account with wrong password basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('guest:wrong_password').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).to.deep.equal('guest'); done(); }); }); it('should use guest account with wrong username basic authentication GET /api/v1/user', function (done) { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Basic ' + new Buffer('unknown_username:guest').toString('base64')) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).to.deep.equal('guest'); done(); }); }); }); describe('Token renewal an expiration auth enabled, allowGuests true', function () { var server, agent; before(function (done) { var gmeConfig = testFixture.getGmeConfig(); gmeConfig.authentication.enable = true; gmeConfig.authentication.jwt.expiresIn = 2; gmeConfig.authentication.jwt.renewBeforeExpires = 1; server = WebGME.standaloneServer(gmeConfig); server.start(done); }); after(function (done) { server.stop(done); }); beforeEach(function () { agent = superagent.agent(); }); it('should return an access_token for admin for GET /api/v1/user/token and set a new in the header', function (done) { this.timeout(5000); agent.get(server.getUrl() + '/api/v1/user/token') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { var orginalToken = res.body.webgmeToken; expect(res.status).equal(200, err); expect(orginalToken.split('.').length).equal(3, 'Returned token not correct format'); setTimeout(function () { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Bearer ' + orginalToken) .end(function (err, res) { expect(res.status).equal(200, err); expect(res.body._id).equal('admin', err); expect(res.header.access_token.split('.').length) .to.equal(3, 'no token in header'); expect(res.header.access_token) .to.not.equal(orginalToken, 'no token update'); done(); }); }, 1000); }); } ); it('should return 401 when using expired token', function (done) { this.timeout(5000); agent.get(server.getUrl() + '/api/v1/user/token') .set('Authorization', 'Basic ' + new Buffer('admin:admin').toString('base64')) .end(function (err, res) { var orginaltoken = res.body.webgmeToken; expect(res.status).equal(200, err); expect(orginaltoken.split('.').length).equal(3, 'Returned token not correct format'); setTimeout(function () { agent.get(server.getUrl() + '/api/v1/user') .set('Authorization', 'Bearer ' + orginaltoken) .end(function (err, res) { expect(res.status).equal(401, err); done(); }); }, 2000); }); }); }); }); });
'use strict'; /* * Jaden Smith Case * * Make a `jadenCase` function that takes a string as parameter * and return the string with each words capitilized. * * Example : "How are you ?" -> "How Are You ?" * */ // Your code: function jadenCase(str){ let tmpStr = ''; for(let i = 0; i < str.length; i++){ if (i === 0) { tmpStr += str[i].toUpperCase(); } else { if (str[i] !== ' ') { tmpStr += str[i]; } else { tmpStr += str[i]; i++; tmpStr += str[i].toUpperCase(); } } } return tmpStr; } //* Begin of tests const assert = require('assert'); assert.strictEqual(typeof jadenCase, 'function'); assert.strictEqual(jadenCase.length, 1); assert.strictEqual(jadenCase("Hello World"), "Hello World"); assert.strictEqual(jadenCase("How are you?"), "How Are You?"); assert.strictEqual(jadenCase("123 GGFF eedd CC bbAA"), "123 GGFF Eedd CC BbAA"); // End of tests */
"use strict";(self.webpackChunkdocusaurus_template=self.webpackChunkdocusaurus_template||[]).push([[9874],{3905:function(e,t,n){n.d(t,{Zo:function(){return u},kt:function(){return d}});var r=n(67294);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function c(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?s(Object(n),!0).forEach((function(t){o(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):s(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function a(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},s=Object.keys(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}var i=r.createContext({}),p=function(e){var t=r.useContext(i),n=t;return e&&(n="function"==typeof e?e(t):c(c({},t),e)),n},u=function(e){var t=p(e.components);return r.createElement(i.Provider,{value:t},e.children)},l={inlineCode:"code",wrapper:function(e){var t=e.children;return r.createElement(r.Fragment,{},t)}},f=r.forwardRef((function(e,t){var n=e.components,o=e.mdxType,s=e.originalType,i=e.parentName,u=a(e,["components","mdxType","originalType","parentName"]),f=p(n),d=o,y=f["".concat(i,".").concat(d)]||f[d]||l[d]||s;return n?r.createElement(y,c(c({ref:t},u),{},{components:n})):r.createElement(y,c({ref:t},u))}));function d(e,t){var n=arguments,o=t&&t.mdxType;if("string"==typeof e||o){var s=n.length,c=new Array(s);c[0]=f;var a={};for(var i in t)hasOwnProperty.call(t,i)&&(a[i]=t[i]);a.originalType=e,a.mdxType="string"==typeof e?e:o,c[1]=a;for(var p=2;p<s;p++)c[p]=n[p];return r.createElement.apply(null,c)}return r.createElement.apply(null,n)}f.displayName="MDXCreateElement"},86685:function(e,t,n){n.r(t),n.d(t,{frontMatter:function(){return a},contentTitle:function(){return i},metadata:function(){return p},toc:function(){return u},default:function(){return f}});var r=n(87462),o=n(63366),s=(n(67294),n(3905)),c=["components"],a={title:"Consistency Guarantees provided by Snaptokens"},i=void 0,p={unversionedId:"concepts/snaptokens-evaluation-consistency",id:"version-v0.7/concepts/snaptokens-evaluation-consistency",isDocsHomePage:!1,title:"Consistency Guarantees provided by Snaptokens",description:"This feature is not yet implemented, see",source:"@site/versioned_docs/version-v0.7/concepts/snaptokens-evaluation-consistency.mdx",sourceDirName:"concepts",slug:"/concepts/snaptokens-evaluation-consistency",permalink:"/keto/docs/concepts/snaptokens-evaluation-consistency",editUrl:"https://github.com/ory/keto/edit/master/docs/versioned_docs/version-v0.7/concepts/snaptokens-evaluation-consistency.mdx",tags:[],version:"v0.7",lastUpdatedBy:"zepatrik",lastUpdatedAt:1633089163,formattedLastUpdatedAt:"10/1/2021",frontMatter:{title:"Consistency Guarantees provided by Snaptokens"},sidebar:"version-v0.7/docs",previous:{title:"Internal Algorithms",permalink:"/keto/docs/concepts/internal-algorithms"},next:{title:"Secure",permalink:"/keto/docs/secure"}},u=[],l={toc:u};function f(e){var t=e.components,n=(0,o.Z)(e,c);return(0,s.kt)("wrapper",(0,r.Z)({},l,n,{components:t,mdxType:"MDXLayout"}),(0,s.kt)("p",null,"This feature is not yet implemented, see\n",(0,s.kt)("a",{parentName:"p",href:"https://github.com/ory/keto/issues/517"},"the issue"),"."))}f.isMDXComponent=!0}}]);
const KEY = Object.freeze({ UP: "ArrowUp", DOWN: "ArrowDown", LEFT: "ArrowLeft", RIGHT: "ArrowRight", A: "a", B: "b" }) const KONAMI_PATTERN = Object.freeze([ KEY.UP, KEY.UP, KEY.DOWN, KEY.DOWN, KEY.LEFT, KEY.RIGHT, KEY.LEFT, KEY.RIGHT, KEY.B, KEY.A ]) const DEFAULT_SUCCESS_FUNCTION = () => console.log("Congrats!") module.exports = class KonamiCatcher { currentKey = 0 constructor({ domToListen, pattern = KONAMI_PATTERN, successFunction = DEFAULT_SUCCESS_FUNCTION }) { this.onSuccess = successFunction this.pattern = pattern this.initListener(domToListen) } isSuccessful() { return this.pattern.length === this.currentKey } konamiCatcher(event) { if (event.key !== this.pattern[this.currentKey]) { this.currentKey = 0 return } this.currentKey++ if (this.isSuccessful()) { this.onSuccess() } } initListener(domElement) { domElement.addEventListener("keydown", this.konamiCatcher, false) } }
"function"!=typeof Object.create&&(Object.create=function(t){function o(){}return o.prototype=t,new o}),function(t,o,i,s){"use strict";var n={_positionClasses:["bottom-left","bottom-right","top-right","top-left","bottom-center","top-center","mid-center"],_defaultIcons:["success","error","info","warning"],init:function(o,i){this.prepareOptions(o,t.toast.options),this.process()},prepareOptions:function(o,i){var s={};"string"==typeof o||o instanceof Array?s.text=o:s=o,this.options=t.extend({},i,s)},process:function(){this.setup(),this.addToDom(),this.position(),this.bindToast(),this.animate()},setup:function(){var o="";if(this._toastEl=this._toastEl||t("<div></div>",{class:"jq-toast-single"}),o+='<span class="jq-toast-loader"></span>',this.options.allowToastClose&&(o+='<span class="close-jq-toast-single">&times;</span>'),this.options.text instanceof Array){this.options.heading&&(o+='<h2 class="jq-toast-heading">'+this.options.heading+"</h2>"),o+='<ul class="jq-toast-ul">';for(var i=0;i<this.options.text.length;i++)o+='<li class="jq-toast-li" id="jq-toast-item-'+i+'">'+this.options.text[i]+"</li>";o+="</ul>"}else this.options.heading&&(o+='<h2 class="jq-toast-heading">'+this.options.heading+"</h2>"),o+=this.options.text;this._toastEl.html(o),!1!==this.options.bgColor&&this._toastEl.css("background-color",this.options.bgColor),!1!==this.options.textColor&&this._toastEl.css("color",this.options.textColor),this.options.textAlign&&this._toastEl.css("text-align",this.options.textAlign),!1!==this.options.icon&&(this._toastEl.addClass("jq-has-icon"),-1!==t.inArray(this.options.icon,this._defaultIcons)&&this._toastEl.addClass("jq-icon-"+this.options.icon)),!1!==this.options.class&&this._toastEl.addClass(this.options.class)},position:function(){"string"==typeof this.options.position&&-1!==t.inArray(this.options.position,this._positionClasses)?"bottom-center"===this.options.position?this._container.css({left:t(o).outerWidth()/2-this._container.outerWidth()/2,bottom:20}):"top-center"===this.options.position?this._container.css({left:t(o).outerWidth()/2-this._container.outerWidth()/2,top:20}):"mid-center"===this.options.position?this._container.css({left:t(o).outerWidth()/2-this._container.outerWidth()/2,top:t(o).outerHeight()/2-this._container.outerHeight()/2}):this._container.addClass(this.options.position):"object"==typeof this.options.position?this._container.css({top:this.options.position.top?this.options.position.top:"auto",bottom:this.options.position.bottom?this.options.position.bottom:"auto",left:this.options.position.left?this.options.position.left:"auto",right:this.options.position.right?this.options.position.right:"auto"}):this._container.addClass("bottom-left")},bindToast:function(){var t=this;this._toastEl.on("afterShown",function(){t.processLoader()}),this._toastEl.find(".close-jq-toast-single").on("click",function(o){o.preventDefault(),"fade"===t.options.showHideTransition?(t._toastEl.trigger("beforeHide"),t._toastEl.fadeOut(function(){t._toastEl.trigger("afterHidden")})):"slide"===t.options.showHideTransition?(t._toastEl.trigger("beforeHide"),t._toastEl.slideUp(function(){t._toastEl.trigger("afterHidden")})):(t._toastEl.trigger("beforeHide"),t._toastEl.hide(function(){t._toastEl.trigger("afterHidden")}))}),"function"==typeof this.options.beforeShow&&this._toastEl.on("beforeShow",function(){t.options.beforeShow(t._toastEl)}),"function"==typeof this.options.afterShown&&this._toastEl.on("afterShown",function(){t.options.afterShown(t._toastEl)}),"function"==typeof this.options.beforeHide&&this._toastEl.on("beforeHide",function(){t.options.beforeHide(t._toastEl)}),"function"==typeof this.options.afterHidden&&this._toastEl.on("afterHidden",function(){t.options.afterHidden(t._toastEl)}),"function"==typeof this.options.onClick&&this._toastEl.on("click",function(){t.options.onClick(t._toastEl)})},addToDom:function(){var o=t(".jq-toast-wrap");if(0===o.length?(o=t("<div></div>",{class:"jq-toast-wrap",role:"alert","aria-live":"polite"}),t("body").append(o)):this.options.stack&&!isNaN(parseInt(this.options.stack,10))||o.empty(),o.find(".jq-toast-single:hidden").remove(),o.append(this._toastEl),this.options.stack&&!isNaN(parseInt(this.options.stack),10)){var i=o.find(".jq-toast-single").length-this.options.stack;i>0&&t(".jq-toast-wrap").find(".jq-toast-single").slice(0,i).remove()}this._container=o},canAutoHide:function(){return!1!==this.options.hideAfter&&!isNaN(parseInt(this.options.hideAfter,10))},processLoader:function(){if(!this.canAutoHide()||!1===this.options.loader)return!1;var t=this._toastEl.find(".jq-toast-loader"),o=(this.options.hideAfter-400)/1e3+"s",i=this.options.loaderBg,s=t.attr("style")||"";s=s.substring(0,s.indexOf("-webkit-transition")),s+="-webkit-transition: width "+o+" ease-in; -o-transition: width "+o+" ease-in; transition: width "+o+" ease-in; background-color: "+i+";",t.attr("style",s).addClass("jq-toast-loaded")},animate:function(){t=this;if(this._toastEl.hide(),this._toastEl.trigger("beforeShow"),"fade"===this.options.showHideTransition.toLowerCase()?this._toastEl.fadeIn(function(){t._toastEl.trigger("afterShown")}):"slide"===this.options.showHideTransition.toLowerCase()?this._toastEl.slideDown(function(){t._toastEl.trigger("afterShown")}):this._toastEl.show(function(){t._toastEl.trigger("afterShown")}),this.canAutoHide()){var t=this;o.setTimeout(function(){"fade"===t.options.showHideTransition.toLowerCase()?(t._toastEl.trigger("beforeHide"),t._toastEl.fadeOut(function(){t._toastEl.trigger("afterHidden")})):"slide"===t.options.showHideTransition.toLowerCase()?(t._toastEl.trigger("beforeHide"),t._toastEl.slideUp(function(){t._toastEl.trigger("afterHidden")})):(t._toastEl.trigger("beforeHide"),t._toastEl.hide(function(){t._toastEl.trigger("afterHidden")}))},this.options.hideAfter)}},reset:function(o){"all"===o?t(".jq-toast-wrap").remove():this._toastEl.remove()},update:function(t){this.prepareOptions(t,this.options),this.setup(),this.bindToast()},close:function(){this._toastEl.find(".close-jq-toast-single").click()}};t.toast=function(t){var o=Object.create(n);return o.init(t,this),{reset:function(t){o.reset(t)},update:function(t){o.update(t)},close:function(){o.close()}}},t.toast.options={text:"",heading:"",showHideTransition:"fade",allowToastClose:!0,hideAfter:3e3,loader:!0,loaderBg:"#9EC600",stack:5,position:"bottom-left",bgColor:!1,textColor:!1,textAlign:"left",icon:!1,beforeShow:function(){},afterShown:function(){},beforeHide:function(){},afterHidden:function(){},onClick:function(){}}}(jQuery,window,document);
"main";let OrdersService;_c27‍.w("../services/orders/orders",[["default",["OrdersService"],function(v){OrdersService=v}]]);let SettingsService;_c27‍.w("../services/settings/settings",[["default",["SettingsService"],function(v){SettingsService=v}]]);let PaymentGatewaysService;_c27‍.w("../services/settings/paymentGateways",[["default",["PaymentGatewaysService"],function(v){PaymentGatewaysService=v}]]);let PayPalCheckout;_c27‍.w("./PayPalCheckout",[["default",["PayPalCheckout"],function(v){PayPalCheckout=v}]]);let LiqPay;_c27‍.w("./LiqPay",[["default",["LiqPay"],function(v){LiqPay=v}]]);let StripeElements;_c27‍.w("./StripeElements",[["default",["StripeElements"],function(v){StripeElements=v}]]); const getOptions = orderId => { return Promise.all([ _c27‍.a("OrdersService",OrdersService).getSingleOrder(orderId), _c27‍.a("SettingsService",SettingsService).getSettings() ]).then(([order, settings]) => { if (order && order.payment_method_id) { return _c27‍.a("PaymentGatewaysService",PaymentGatewaysService).getGateway( order.payment_method_gateway ).then(gatewaySettings => { const options = { gateway: order.payment_method_gateway, gatewaySettings: gatewaySettings, order: order, amount: order.grand_total, currency: settings.currency_code }; return options; }); } }); }; const getPaymentFormSettings = orderId => { return getOptions(orderId).then(options => { switch (options.gateway) { case 'paypal-checkout': return _c27‍.a("PayPalCheckout",PayPalCheckout).getPaymentFormSettings(options); case 'liqpay': return _c27‍.a("LiqPay",LiqPay).getPaymentFormSettings(options); case 'stripe-elements': return _c27‍.a("StripeElements",StripeElements).getPaymentFormSettings(options); default: return Promise.reject('Invalid gateway'); } }); }; const paymentNotification = (req, res, gateway) => { return _c27‍.a("PaymentGatewaysService",PaymentGatewaysService).getGateway(gateway).then(gatewaySettings => { const options = { gateway: gateway, gatewaySettings: gatewaySettings, req: req, res: res }; switch (gateway) { case 'paypal-checkout': return _c27‍.a("PayPalCheckout",PayPalCheckout).paymentNotification(options); case 'liqpay': return _c27‍.a("LiqPay",LiqPay).paymentNotification(options); default: return Promise.reject('Invalid gateway'); } }); }; const processOrderPayment = async order => { const orderAlreadyCharged = order.paid === true; if (orderAlreadyCharged) { return true; } const gateway = order.payment_method_gateway; const gatewaySettings = await _c27‍.a("PaymentGatewaysService",PaymentGatewaysService).getGateway(gateway); const settings = await _c27‍.a("SettingsService",SettingsService).getSettings(); switch (gateway) { case 'stripe-elements': return _c27‍.a("StripeElements",StripeElements).processOrderPayment({ order, gatewaySettings, settings }); default: return Promise.reject('Invalid gateway'); } }; _c27‍.d({ getPaymentFormSettings: getPaymentFormSettings, paymentNotification: paymentNotification, processOrderPayment: processOrderPayment });_c27‍.u(["default"]);
import * as BABYLON from 'babylonjs'; import * as Pts from 'pts'; import PtsCanvas from '../../components/PtsCanvas'; import CaseTexture from 'src/images/mix-art/mx011.jpg'; import CDLabelTexture from '../../images/mix-labels/cd_template_MX011.png'; import {scaleLinear} from 'd3'; export const caseTexture = CaseTexture; export const cdLabelTexture = CDLabelTexture; export const build = ({scene}) => { const light = new BABYLON.HemisphericLight('light', new BABYLON.Vector3(0, 1, 0), scene); light.intensity = 10; scene.clearColor = new BABYLON.Color4(0, 0, 0, 0); return scene; }; export class Background extends PtsCanvas { buildScene(space, form) { let lines = []; let rotations = []; const createLines = () => { lines = []; rotations = []; const ps = Pts.Create.distributeRandom(space.innerBound, 100); for (let i = 0, len = ps.length; i < len; i++) { lines.push( new Pts.Group( ps[i], ps[i].clone().toAngle(Math.random() * Pts.Const.pi, (Math.random() * space.size.y) / 2 + 20, true), ), ); rotations.push(Math.random() * 0.0002 + 0.0002); } }; space.add({ start: () => createLines(), resize: () => createLines(), animate: (time) => { const size = Math.min(space.size.y, space.size.x); var freqScale = scaleLinear() .domain([0, 100]) .range([150, size / 2]) .clamp(true); const source = this.props.source; const avgFreq = (source && source.getAverageFrequency()) || 0; const radius = freqScale(avgFreq); let range = Pts.Circle.fromCenter(space.center, radius); form.stroke('#fff').lines(lines); for (let i = 0, len = lines.length; i < len; i++) { lines[i].rotate2D(rotations[i], space.center); // check rays and lines intersection with pointer's range let inPath = Pts.Circle.intersectRay2D(range, lines[i]); let inLine = Pts.Circle.intersectLine2D(range, lines[i]); if (inPath.length > 1) { form.stroke('rgba(255,255,255,.20)').line(lines[i].concat(inPath[0], inPath[1])); form.stroke('#fe6').line(lines[i]); form.fillOnly('#fff').points(inPath, 2, 'circle'); } if (inLine.length > 0) { form.stroke('#fe6').line(lines[i]); form.fillOnly('#ff6').points(inLine, 3, 'circle'); } } }, }); } }
import * as types from '../constants/types'; import { APP } from './actionsTypes'; export function appStart(root, text) { return { type: APP.START, root, text }; } export function appReady() { return { type: APP.READY }; } export function appInit() { return { type: APP.INIT }; } export function appInitLocalSettings() { return { type: APP.INIT_LOCAL_SETTINGS }; } export function setCurrentServer(server) { return { type: types.SET_CURRENT_SERVER, payload: server }; } export function addSettings(settings) { return { type: types.ADD_SETTINGS, payload: settings }; } export function login() { return { type: 'LOGIN' }; }
const express = require('express') const Twitter = require('twit') /* usually this would live inside the configurations of the server as ENV variables but for the sake of this exercise I will put the access tokens here... To prevent basic misusage, I have set the access token to be read only instead of read/write */ const app = express() const client = new Twitter({ consumer_key: process.env.CONSUMER_KEY, consumer_secret: process.env.CONSUMER_SECRET, app_only_auth: true }) app.use(require('cors')()) app.use(require('body-parser').json()) app.get('/api/get_tweets', (req, res) => { const params = { count: 200 } if (req.query.screen_name) { params.screen_name = req.query.screen_name } client .get(`statuses/user_timeline`, params) .then(timeline => { res.send(timeline) }) .catch(error => res.send(error)) }) app.listen(5000, () => console.log('Server running'))
const _ = require('lodash') const path = require('path') const { fmImagesToRelative } = require('gatsby-remark-relative-images') exports.onCreateNode = ({ node }) => { fmImagesToRelative(node) } exports.createPages = ({ actions, graphql }) => { const { createPage } = actions return graphql(` { allMarkdownRemark( limit: 1000 filter: { frontmatter: { templateKey: { eq: "showcase" } } } ) { edges { node { id frontmatter { templateKey title } } } } } `).then(result => { if (result.errors) { result.errors.forEach(e => console.error(e.toString())) return Promise.reject(result.errors) } const showcase = result.data.allMarkdownRemark.edges showcase.forEach(edge => { const id = edge.node.id if (edge.node.frontmatter.templateKey === 'showcase') { createPage({ path: '/showcase/' + _.kebabCase(edge.node.frontmatter.title), component: path.resolve(`src/templates/showcase.jsx`), // additional data can be passed via context context: { id, }, }) } }) }) }
export { default } from './WalletContent.connect';
const MainContainerReducer = (state = {'currentTab':0}, action) => { switch (action.type) { case 'switchTab': return Object.assign({}, state, { currentTab: action.tabId }) case 'loadAboutPatter': return Object.assign({}, state, { aboutPattern: action.data }) default: return state } } export default MainContainerReducer
function plugin(UIkit) { if (plugin.installed) { return; } var {util, mixin} = UIkit; var {append, attr, doc, flipPosition, includes, isTouch, isVisible, matches, on, pointerDown, pointerEnter, pointerLeave, remove, within} = util; var actives = []; UIkit.component('tooltip', { attrs: true, mixins: [mixin.togglable, mixin.position], props: { delay: Number, title: String }, defaults: { pos: 'top', title: '', delay: 0, animation: ['uk-animation-scale-up'], duration: 100, cls: 'uk-active', clsPos: 'uk-tooltip' }, connected() { attr(this.$el, {title: null, 'aria-expanded': false}); }, disconnected() { this.hide(); }, methods: { show() { if (includes(actives, this)) { return; } actives.forEach(active => active.hide()); actives.push(this); this._unbind = on(doc, 'click', e => !within(e.target, this.$el) && this.hide()); clearTimeout(this.showTimer); this.tooltip = append(UIkit.container, `<div class="${this.clsPos}" aria-hidden><div class="${this.clsPos}-inner">${this.title}</div></div>`); attr(this.$el, 'aria-expanded', true); this.positionAt(this.tooltip, this.$el); this.origin = this.getAxis() === 'y' ? `${flipPosition(this.dir)}-${this.align}` : `${this.align}-${flipPosition(this.dir)}`; this.showTimer = setTimeout(() => { this.toggleElement(this.tooltip, true); this.hideTimer = setInterval(() => { if (!isVisible(this.$el)) { this.hide(); } }, 150); }, this.delay); }, hide() { var index = actives.indexOf(this); if (!~index || matches(this.$el, 'input') && this.$el === doc.activeElement) { return; } actives.splice(index, 1); clearTimeout(this.showTimer); clearInterval(this.hideTimer); attr(this.$el, 'aria-expanded', false); this.toggleElement(this.tooltip, false); this.tooltip && remove(this.tooltip); this.tooltip = false; this._unbind(); } }, events: { [`focus ${pointerEnter} ${pointerDown}`](e) { if (e.type !== pointerDown || !isTouch(e)) { this.show(); } }, blur: 'hide', [pointerLeave](e) { if (!isTouch(e)) { this.hide(); } } } }); } if (!BUNDLED && typeof window !== 'undefined' && window.UIkit) { window.UIkit.use(plugin); } export default plugin;
import request from '@/utils/request' const estimateApi = { detail: '/boss/project/assess/getTumourAssessDetail', // 评估详情 add: '/boss/project/assess/addTumourAssess', update: '/boss/project/assess/updateTumourAssess', delete: '/boss/project/assess/deleteTumourAssessById', unInputStageList: '/boss/project/assess/listPtsNotStage', // 未录入试验阶段列表 inputStageList: '/boss/project/assess/listPtsHaveStage' // 已录入试验阶段列表 } export function getTumourEstimateDetail (parameter) { return request({ url: estimateApi.detail, method: 'post', data: parameter }) } export function addTumourEstimate (parameter) { return request({ url: estimateApi.add, method: 'post', data: parameter }) } export function updateTumourEstimate (parameter) { return request({ url: estimateApi.update, method: 'post', data: parameter }) } export function deleteTumourEstimate (parameter) { return request({ url: estimateApi.delete, method: 'post', data: parameter }) } export function getUnInputStageList (parameter) { return request({ url: estimateApi.unInputStageList, method: 'post', data: parameter }) } export function getInputStageList (parameter) { return request({ url: estimateApi.inputStageList, method: 'post', data: parameter }) }
/* global suite, test */ var error = require('../lib/error'); var database = require('../lib/database'); require('should'); suite('Database', function() { test('FINDFIELD', function() { database.FINDFIELD([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,8],['Age',20,12,14,15,8,9],['Yield',14,10,9,10,8,6]],'Yield').should.equal(3); database.FINDFIELD([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,8],['Age',20,12,14,15,8,9],['Yield',14,10,9,10,8,6]],'invalid').should.equal(error.value); }); test('DAVERAGE', function() { database.DAVERAGE([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,8],['Age',20,12,14,15,8,9],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10'],['Age','>14']]).should.equal(12); database.DAVERAGE([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,8],['Age',20,12,14,15,8,9],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10','>9'],['Age','>14']]).should.equal(10.75); database.DAVERAGE([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,8],['Age',20,12,14,15,8,9],['Yield',14,10,9,10,8,6]], undefined, [['Height','>10','>9'],['Age','>14']]).should.equal(error.value); database.DAVERAGE([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,8],['Age',20,12,14,15,8,9],['Yield',14,10,9,10,8,6]], 3, [['Height','>10','>9'],['Age','>14']]).should.equal(10.75); }); test('DCOUNT', function() { database.DCOUNT([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10'],['Age','>14']]).should.equal(2); database.DCOUNT([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], undefined, [['Height','>10'],['Age','>14']]).should.equal(error.value); database.DCOUNT([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], 3, [['Height','>10'],['Age','>14']]).should.equal(2); }); test('DCOUNTA', function() { database.DCOUNTA([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',null,10,9,10,8,6]],'Yield', [['Height','>10'],['Age','>14']]).should.equal(1); database.DCOUNTA([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',null,10,9,10,8,6]], undefined, [['Height','>10'],['Age','>14']]).should.equal(error.value); database.DCOUNTA([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',null,10,9,10,8,6]], 3, [['Height','>10'],['Age','>14']]).should.equal(1); }); test('DGET', function() { database.DGET([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10'],['Age','>16']]).should.equal(14); database.DGET([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10'],['Age','>14']]).should.equal(error.num); database.DGET([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10'],['Age','>20']]).should.equal(error.value); database.DGET([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], undefined, [['Height','>10'],['Age','>16']]).should.equal(error.value); database.DGET([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], 3, [['Height','>10'],['Age','>16']]).should.equal(14); }); test('DMAX', function() { database.DMAX([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10'],['Age','>14']]).should.equal(14); database.DMAX([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',10,10,9,14,8,6]],'Yield', [['Height','>10'],['Age','>14']]).should.equal(14); database.DMAX([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height'],['Age','>14']]).should.equal(14); database.DMAX([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], undefined, [['Height','>10'],['Age','>14']]).should.equal(error.value); database.DMAX([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], 3, [['Height','>10'],['Age','>14']]).should.equal(14); }); test('DMIN', function() { database.DMIN([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10'],['Age','>14']]).should.equal(10); database.DMIN([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], undefined, [['Height','>10'],['Age','>14']]).should.equal(error.value); database.DMIN([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], 3, [['Height','>10'],['Age','>14']]).should.equal(10); }); test('DPRODUCT', function() { database.DPRODUCT([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10'],['Age','>14']]).should.equal(140); database.DPRODUCT([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], undefined, [['Height','>10'],['Age','>14']]).should.equal(error.value); database.DPRODUCT([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], 3, [['Height','>10'],['Age','>14']]).should.equal(140); }); test('DSTDEV', function() { database.DSTDEV([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10']]).should.equal(2.8635642126552705); database.DSTDEV([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], undefined, [['Height','>10']]).should.equal(error.value); database.DSTDEV([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], 3, [['Height','>10']]).should.equal(2.8635642126552705); }); test('DSTDEVP', function() { database.DSTDEVP([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10']]).should.equal(2.5612496949731396); database.DSTDEVP([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], undefined, [['Height','>10']]).should.equal(error.value); database.DSTDEVP([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], 3, [['Height','>10']]).should.equal(2.5612496949731396); }); test('DSUM', function() { database.DSUM([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10'],['Age','>14']]).should.equal(24); database.DSUM([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], undefined, [['Height','>10'],['Age','>14']]).should.equal(error.value); database.DSUM([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], 3, [['Height','>10'],['Age','>14']]).should.equal(24); }); test('DVAR', function() { database.DVAR([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10'],['Age','>14']]).should.equal(8); database.DVAR([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], undefined, [['Height','>10'],['Age','>14']]).should.equal(error.value); database.DVAR([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], 3, [['Height','>10'],['Age','>14']]).should.equal(8); }); test('DVARP', function() { database.DVARP([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]],'Yield', [['Height','>10'],['Age','>14']]).should.equal(4); database.DVARP([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], undefined, [['Height','>10'],['Age','>14']]).should.equal(error.value); database.DVARP([['Tree','Apple','Pear','Cherry','Apple','Pear','Apple'],['Height',18,12,13,14,9,12],['Age',20,12,14,16,8,11],['Yield',14,10,9,10,8,6]], 3, [['Height','>10'],['Age','>14']]).should.equal(4); }); test('VLOOKUP', function() { database.VLOOKUP("B", [["A","B","C"],[5,7,3]], 2); }); });
"use strict"; var sc_lobby = new Phaser.Scene("Lobby"); sc_lobby.preload = function() { } sc_lobby.create = function() { cont.playing = false; mus_game.pause(); mus_game.currentTime = 0; mus_victory.pause(); mus_victory.currentTime = 0; mus_defeat.pause(); mus_defeat.currentTime = 0; mus_menu.play(); sc_lobby.openEnemyName = "none"; sc_lobby.userBoxOpen = false; sc_lobby.userChallenging = false; cont.lastChatMessage = -1; cont.prevScene = sc_lobby; cont.prevSceneName = "Lobby"; //Importante cambiarlo en cada escena en la que se pueda ir la conexión cont.connection = undefined; this.bg = sc_lobby.add.image(400, 300, "fondo online-lobby"); var disconnectButton = sc_lobby.add.sprite(80, 556, "botonDesconectar"); sc_lobby.chatInput = sc_lobby.add.dom(355,557).createFromCache('chatInput'); sc_lobby.chatBox = sc_lobby.add.dom(355,481).createFromCache('chatBox'); sc_lobby.usersBox = sc_lobby.add.dom(355,241).createFromCache('usersBox'); var sendButton = sc_lobby.add.sprite(590, 557, "botonEnviar"); var chatBoxBG = sc_lobby.add.sprite(355, 489, "chatBoxBG"); sc_lobby.pingText = sc_lobby.add.text(790, 10, "Ping: 0", {fontSize: '12px', fontFamily: 'Bookman', color: '#ffffff', stroke: '#000000', strokeThickness: 2, align: 'center'}); sc_lobby.pingText.setOrigin(1, 0); sc_lobby.chatBox.getChildByName('chatBox').value = ""; disconnectButton.setInteractive({cursor: "pointer"}); disconnectButton.on('pointerdown', function (event) { $.ajax({ method: "DELETE", url: cont.server_ip + "players/"+cont.id }).done(function (item) { cont.connected = false; cont.id = -1; cont.name = null; cont.lastChatMessage = -1; sc_lobby.scene.start("MenuPrincipal"); }).error(function(item){ console.log("Something went wrong when disconnecting, but I think you already noticed that."); }); if (cont.connection != undefined) { cont.connection.close(); console.log("CLOSING WEBSOCKET..."); cont.connection = undefined; } }); sendButton.setInteractive({cursor: "pointer"}); sendButton.on('pointerdown', function (event) { sendChatMessage(); }); //Lo de darle al enter this.input.keyboard.on('keyup', function (event) { if (event.keyCode == 13 && document.activeElement == sc_lobby.chatInput.getChildByName('chatField')) { sendChatMessage(); } }); //Perfil del usuario sc_lobby.profileBG = sc_lobby.add.sprite(5, 5, "recuadroPje"); sc_lobby.profileBG.setOrigin(0,0); sc_lobby.profileText = sc_lobby.add.text(20, 20, "", {fontSize: '20px', fontFamily: 'Bookman', color: '#ff6600', stroke: '#000000', strokeThickness: 2, align: 'left'}); sc_lobby.profileText.setOrigin(0, 0); sc_lobby.changeCharacterButton = sc_lobby.add.sprite(20, 115, "botonChange"); sc_lobby.changeCharacterButton.setOrigin(0, 0); sc_lobby.changeCharacterButton.setInteractive({cursor: "pointer"}); sc_lobby.changeCharacterButton.on('pointerdown', function (event) { //Cambio de personaje sc_lobby.scene.start('SeleccionPersonajeOnline'); }); //Perfil de otro jugador sc_lobby.enemyProfileBG = sc_lobby.add.sprite(449, 100, "recuadroPje"); sc_lobby.enemyProfileBG.setOrigin(0,0); sc_lobby.enemyProfileText = sc_lobby.add.text(464, 115, "", {fontSize: '20px', fontFamily: 'Bookman', color: '#ff6600', stroke: '#000000', strokeThickness: 2, align: 'left'}); sc_lobby.enemyProfileText.setOrigin(0, 0); sc_lobby.challengeButton = sc_lobby.add.sprite(464, 210, "botonChallenge"); sc_lobby.challengeButton.setOrigin(0, 0); sc_lobby.challengeButton.setInteractive({cursor: "pointer"}); sc_lobby.challengeButton.on('pointerdown', function (event) { //Decirle al servidor que quieres desafiar a tal persona //AJAX (PUT) CON: // cont.id en la url // sc_lobby.openEnemyName como data //Si te dice que todo bien, pues te toca esperar a que te acepte o no. //En el servidor debería actualizar los datos de un jugador en los del otro y viceversa (si es que se puede, claro) console.log(sc_lobby.openEnemyName); $.ajax({ method: "PUT", url: cont.server_ip + "challenge/"+cont.id, timeout: 3000, data: sc_lobby.openEnemyName, processData: false, headers: { "Content-type": "application/json" }, }).success(function (item) { console.log("Challenge sent."); }).error(function(e) { console.log("Couldn't challenge that player."); console.log(e); }); }); sc_lobby.enemyCross = sc_lobby.add.sprite(597, 115, "cruz3"); sc_lobby.enemyCross.setOrigin(0, 0); sc_lobby.enemyCross.setInteractive({cursor: "pointer"}); sc_lobby.enemyProfileBG.setVisible(false); sc_lobby.enemyProfileText.setVisible(false); sc_lobby.challengeButton.setVisible(false); sc_lobby.enemyCross.setVisible(false); sc_lobby.enemyCross.on('pointerdown', function (event) { sc_lobby.enemyProfileBG.setVisible(false); sc_lobby.enemyProfileText.setVisible(false); sc_lobby.challengeButton.setVisible(false); sc_lobby.challengeButton.removeInteractive(); sc_lobby.enemyCross.setVisible(false); sc_lobby.enemyCross.removeInteractive(); sc_lobby.userBoxOpen = false; }); //Cuadro de que te están desafiando sc_lobby.challengeBG = sc_lobby.add.sprite(560, 230, "recuadroDesafio"); sc_lobby.challengeText = sc_lobby.add.text(560, 160, "\nWants to fight!", {fontSize: '24px', fontFamily: 'Bookman', color: '#ff6600', stroke: '#000000', strokeThickness: 2, align: 'center'}); sc_lobby.challengeText.setOrigin(0.5,0.5); sc_lobby.acceptButton = sc_lobby.add.sprite(560, 230, "botonAccept"); sc_lobby.declineButton = sc_lobby.add.sprite(560, 300, "botonDecline"); //Hacer que no se vean sc_lobby.challengeBG.setVisible(false); sc_lobby.challengeText.setVisible(false); sc_lobby.acceptButton.setVisible(false); sc_lobby.declineButton.setVisible(false); } sc_lobby.update = function() { sc_lobby.pingText.setText("Ping: " + cont.ping); while (unreadChatMessages.length != 0) { var msg = unreadChatMessages.pop(); if (sc_lobby.chatBox.getChildByName('chatBox').value != "") { sc_lobby.chatBox.getChildByName('chatBox').value += "\n"; } sc_lobby.chatBox.getChildByName('chatBox').value += "["+msg.time+"] "+msg.sender+": "+msg.message; sc_lobby.chatBox.getChildByName('chatBox').scrollTop = sc_lobby.chatBox.getChildByName('chatBox').scrollHeight; } var usersList = "" for(var i = 0; i < onlineUsers.length; i++) { if (onlineUsers[i].id == cont.id) { /*if (!onlineUsers[i].inGame && onlineUsers[i].opponentName == "" && cont.connection != undefined) { cont.connection.close(); cont.connection = undefined; }*/ if (onlineUsers[i].inGame/* && cont.connection == undefined*/) { var prosiga = !cont.playing; if (prosiga) { if (cont.connection != undefined) { if (cont.connection.readyState === WebSocket.OPEN) { cont.connection.close(); console.log("CLOSING WEBSOCKET..."); } } //Si tenemos que estar en partida, abrimos websocket sc_lobby.opponentName = onlineUsers[i].opponentName; var wsUrl; if (cont.server_ip.slice(0,4) == "http") { wsUrl = cont.server_ip.slice(4); } else if (cont.server_ip.slice(0,5) == "https") { wsUrl = cont.server_ip.slice(5); } cont.connection = new WebSocket("ws"+wsUrl+"echo"); cont.playing = true; cont.connection.onopen = function() { console.log("Websocket opened"); cont.connection.send(JSON.stringify({ message_type: "OPEN2", opponent_name: sc_lobby.opponentName, player_name: cont.name, player_character: cont.ch })); } cont.connection.onerror = function(e) { console.log("WS error: " + e); } cont.connection.onmessage = function(msg) { websocketOnMessage(msg); } cont.connection.onclose = function(e) { cont.connection = undefined; console.log("Websocket closed."); if (cont.playing) { cont.playing = false; //Igual sí que va a hacer falta al final } } } else { console.log("You are in game, your websocket should already be opened. I hope."); } } //Este es nuestro perfil, así que vamos a mostrar la información necesaria var text = onlineUsers[i].name + "\nWins: " + onlineUsers[i].wins + "\nLosses: " + onlineUsers[i].losses + "\nCharacter: "; cont.ch = onlineUsers[i].character; switch (onlineUsers[i].character.slice(2,3)) { case "H": text += "Ice"; break; case "E": text += "Elf"; break; case "F": text += "Necro"; break; } sc_lobby.profileText.setText(text); //Si nos están desafiando, que salga la caja if (onlineUsers[i].opponentName != "" && !onlineUsers[i].sendingChallenge) { if (!sc_lobby.challengeBG.visible) { sc_lobby.challengeBG.setVisible(true); sc_lobby.challengeText.setVisible(true); sc_lobby.challengeText.setText(onlineUsers[i].opponentName+"\nWants to fight!"); sc_lobby.acceptButton.setVisible(true); sc_lobby.acceptButton.setInteractive({cursor: "pointer"}); sc_lobby.acceptButton.on('pointerdown', function (event) { //Primero mandar una petición ajax diciendo que entramos en partida para que el otro jugador se pueda enterar $.ajax({ method: "PUT", url: cont.server_ip + "beginGame/"+cont.id, timeout: 3000, data: cont.name, processData: false, headers: { "Content-type": "application/json" }, }).success(function (item) { console.log("Challenge accepted."); if (cont.connection != undefined) { if (cont.connection.readyState === WebSocket.OPEN) { cont.connection.close(); console.log("CLOSING WEBSOCKET..."); } } var wsUrl; if (cont.server_ip.slice(0,4) == "http") { wsUrl = cont.server_ip.slice(4); } else if (cont.server_ip.slice(0,5) == "https") { wsUrl = cont.server_ip.slice(5); } cont.connection = new WebSocket("ws"+wsUrl+"echo"); cont.connection.onopen = function() { console.log("Websocket opened"); cont.connection.send(JSON.stringify({ message_type: "OPEN", opponent_name: sc_lobby.declineButton.opponentName, player_name: cont.name, player_character: cont.ch,//cambiarlo en el otro sitio tambien })); //Espero no arrepentirme de poner esto aquí cont.victoryState = -1; sc_lobby.playercontrolling = 1; cont.p1.ch = "SSHielo1"; cont.p2.ch = "SSHielo1"; sc_lobby.scene.stop("Lobby"); sc_lobby.scene.stop("SeleccionPersonajeOnline"); game.scene.stop("JuegoOnline"); game.scene.start("JuegoOnline"); } cont.connection.onerror = function(e) { console.log("WS error: " + e); } cont.connection.onmessage = function(msg) { websocketOnMessage(msg); } cont.connection.onclose = function() { cont.connection = undefined; console.log("Websocket closed."); if (cont.playing) { cont.playing = false; //Igual sí que va a hacer falta al final } } }).error(function(e) { console.log("Couldn't accept that challenge."); }); }); sc_lobby.declineButton.setVisible(true); sc_lobby.declineButton.setInteractive({cursor: "pointer"}); sc_lobby.declineButton.opponentName = onlineUsers[i].opponentName; sc_lobby.declineButton.on('pointerdown', function (event) { cont.playing = false; if (cont.connection != undefined) { cont.connection.close(); console.log("CLOSING WEBSOCKET..."); } $.ajax({ method: "DELETE", url: cont.server_ip + "challenge/"+cont.id, timeout: 3000, data: sc_lobby.declineButton.opponentName, processData: false, headers: { "Content-type": "application/json" } }).done(function (item) { console.log("Challenge declined"); }).error(function(item){ console.log("Challenge couldn't be declined"); }); }); if (sc_lobby.userBoxOpen) { sc_lobby.enemyCross.removeInteractive(); if (sc_lobby.challengeButton.visible) { sc_lobby.challengeButton.removeInteractive(); } } } } else { if (sc_lobby.challengeBG.visible) { sc_lobby.challengeBG.setVisible(false); sc_lobby.challengeText.setVisible(false); sc_lobby.acceptButton.setVisible(false); sc_lobby.acceptButton.removeInteractive(); sc_lobby.declineButton.setVisible(false); sc_lobby.declineButton.removeInteractive(); if (sc_lobby.userBoxOpen) { sc_lobby.enemyCross.setInteractive({cursor: "pointer"}); if (sc_lobby.challengeButton.visible) { sc_lobby.challengeButton.setInteractive({cursor: "pointer"}); } } } } //Si estamos desafiando a alguien, que no podamos intentar desafiar a otro if (onlineUsers[i].opponentName != "") { sc_lobby.userChallenging = true; } else { sc_lobby.userChallenging = false; } } if (onlineUsers[i].timeout > -10) { usersList +="<tr onmousedown='showUserProfile(onlineUsers["+i+"])'><td id='row' style='cursor:pointer;width:200px;height:18px;border:0; background-image:url(../assets/online/userBG"; if (onlineUsers[i].timeout < 0) { usersList+="Away"; } else if (onlineUsers[i].inGame) { usersList+="InGame"; } usersList+=".png);color:white;padding-left:10px;padding-right:20px;'>" + onlineUsers[i].name; if (onlineUsers[i].inGame) { usersList += " (vs. " + onlineUsers[i].opponentName + ")"; } else if (onlineUsers[i].opponentName != "") { if (onlineUsers[i].sendingChallenge) { usersList += " (Challenging " + onlineUsers[i].opponentName + "...)"; } else { usersList += " (Challenged by " + onlineUsers[i].opponentName + "...)"; } } if (onlineUsers[i].timeout < 0) { usersList += " (Away)"; } usersList += "</td></tr>"; } } sc_lobby.usersBox.getChildByID('tabla').innerHTML = usersList; updateEnemyProfile(); } function websocketOnMessage(msg) { var message = JSON.parse(msg.data); if (message.message_type == "begin_game") { console.log("let's begin that game now"); cont.victoryState = -1; if (message.player_1 == cont.name) { sc_lobby.playercontrolling = 1; } else { sc_lobby.playercontrolling = 2; } cont.p1.ch = message.p2_character; cont.p2.ch = message.p1_character; sc_lobby.scene.stop("Lobby"); sc_lobby.scene.stop("SeleccionPersonajeOnline"); game.scene.stop("JuegoOnline"); game.scene.start("JuegoOnline"); } else { if (sc_juegoOnline.scene.isActive()) { //No debería hacer falta, espero. Bueno venga vale, igual sí. switch(message.message_type) { case "game_time": sc_juegoOnline.gameTime = message.game_time; break; case "trap_change": if (message.altarTrap == "none") { sc_juegoOnline.altarTrampas.setTexture("altar1"); } else { sc_juegoOnline.altarTrampas.setTexture("altar2"); } //cambiar la trampa del altar sc_juegoOnline.altarTrampas.trampa = message.altarTrap //cambiar la trampa que lleva el jugador 2 (viene del servidor como el 1) sc_juegoOnline.player2.trampa = message.p1Trap; //cambiar la trampa que lleva el jugador 1 (viene del servidor como el 2) sc_juegoOnline.player.trampa = message.p2Trap; break; case "player_move": sc_juegoOnline.player.x = message.player2_x; sc_juegoOnline.player.y = message.player2_y; sc_juegoOnline.player2.x = message.player1_x; sc_juegoOnline.player2.y = message.player1_y; break; case "player_move_single": if (message.player == 1) { //console.log("SE MUEVE EL DE LA DERECHA"); sc_juegoOnline.player2.x = message.player_x; sc_juegoOnline.player2.y = message.player_y; sc_juegoOnline.player2.spdX = message.player_spdx; sc_juegoOnline.player2.spdY = message.player_spdy; sc_juegoOnline.player2.dir = message.player_direction; } else { //console.log("SE MUEVE EL DE LA IZQUIERDA"); sc_juegoOnline.player.x = message.player_x; sc_juegoOnline.player.y = message.player_y; sc_juegoOnline.player.spdX = message.player_spdx; sc_juegoOnline.player.spdY = message.player_spdy; sc_juegoOnline.player.dir = message.player_direction; } break; case "recetas": sc_juegoOnline.recetas1 = [message.receta_p1_0,message.receta_p1_1,message.receta_p1_2,message.receta_p1_3]; sc_juegoOnline.recetas2 = [message.receta_p2_0,message.receta_p2_1,message.receta_p2_2,message.receta_p2_3]; for (var i = 3; i >= 0; i--) { //esto debería funcionar if (sc_juegoOnline.recetas1[i] == "none") { sc_juegoOnline.recetas1.splice(i,i+1); } if (sc_juegoOnline.recetas2[i] == "none") { sc_juegoOnline.recetas2.splice(i,i+1); } } break; case "estaciones": sc_juegoOnline.player.heldObject = message.p2_ho; sc_juegoOnline.player2.heldObject = message.p1_ho; sc_juegoOnline.hornos.children.iterate(function (child) { if (child.player == 1) { child.timer = message.horno1time; child.heldObject = message.horno1ho; } else { child.timer = message.horno2time; child.heldObject = message.horno2ho; } }); sc_juegoOnline.hornosd.children.iterate(function (child) { if (child.player == 1) { child.timer = message.hornod1time; child.heldObject1 = message.hornod1ho; child.heldObject2 = message.hornod1ho2; } else { child.timer = message.hornod2time; child.heldObject1 = message.hornod2ho; child.heldObject2 = message.hornod2ho2; } }); sc_juegoOnline.yunques.children.iterate(function (child) { if (child.player == 1) { if (child.timer != message.yunque1time) { snd_yunque.pause(); snd_yunque.currentTime = 0; snd_yunque.play(); } child.timer = message.yunque1time; child.heldObject = message.yunque1ho; } else { if (child.timer != message.yunque2time) { snd_yunque.pause(); snd_yunque.currentTime = 0; snd_yunque.play(); } child.timer = message.yunque2time; child.heldObject = message.yunque2ho; } }); sc_juegoOnline.yunquesd.children.iterate(function (child) { if (child.player == 1) { if (child.timer != message.yunqued1time) { snd_yunque.pause(); snd_yunque.currentTime = 0; snd_yunque.play(); } child.timer = message.yunqued1time; child.heldObject1 = message.yunqued1ho; child.heldObject2 = message.yunqued1ho2; } else { if (child.timer != message.yunqued2time) { snd_yunque.pause(); snd_yunque.currentTime = 0; snd_yunque.play(); } child.timer = message.yunqued2time; child.heldObject1 = message.yunqued2ho; child.heldObject2 = message.yunqued2ho2; } }); sc_juegoOnline.barriles.children.iterate(function (child) { if (child.player == 1) { child.timer = message.barril1time; child.heldObject = message.barril1ho; } else { child.timer = message.barril2time; child.heldObject = message.barril2ho; } }); sc_juegoOnline.moldes.children.iterate(function (child) { if (child.player == 1) { child.timer = message.molde1time; child.heldObject = message.molde1ho; } else { child.timer = message.molde2time; child.heldObject = message.molde2ho; } }); sc_juegoOnline.mesas.children.entries[0].heldObject = message.mesa11ho; sc_juegoOnline.mesas.children.entries[1].heldObject = message.mesa21ho; sc_juegoOnline.mesas.children.entries[2].heldObject = message.mesa31ho; sc_juegoOnline.mesas.children.entries[3].heldObject = message.mesa12ho; sc_juegoOnline.mesas.children.entries[4].heldObject = message.mesa22ho; sc_juegoOnline.mesas.children.entries[5].heldObject = message.mesa32ho; //gestionar las trampas de muro y de reloj sc_juegoOnline.player.tiempoInmovil = message.trampareloj2time; sc_juegoOnline.player2.tiempoInmovil = message.trampareloj1time; var muro1 = false, muro2 = false; sc_juegoOnline.muros.children.iterate(function(child) { if (child.player == 1) { muro1 = true; child.timer = message.trampamuro2time; } else if (child.player == 2) { muro2 = true; child.timer = message.trampamuro1time; } }); if (!muro1 && message.trampamuro2time > 0) { var muro = sc_juegoOnline.muros.create(260, 300, 'tripleMuro'); muro.timer = message.trampamuro2time; muro.player = 1; muro.status = sc_juegoOnline.add.image(muro.x-6, muro.y-25, 'empty'); onlineDisconnectNeighbours(getCell(260,300).y,getCell(260,300).x, true, true, true, true); onlineDisconnectNeighbours(getCell(260,300).y,getCell(260,300).x+1, true, true, true, true); onlineDisconnectNeighbours(getCell(260,300).y,getCell(260,300).x-1, true, true, true, true); } if (!muro2 && message.trampamuro1time > 0) { var muro = sc_juegoOnline.muros.create(540, 300, 'tripleMuro'); muro.timer = message.trampamuro1time; muro.player = 2; muro.status = sc_juegoOnline.add.image(muro.x-6, muro.y-25, 'empty'); onlineDisconnectNeighbours(getCell(540,300).y,getCell(540,300).x, true, true, true, true); onlineDisconnectNeighbours(getCell(540,300).y,getCell(540,300).x+1, true, true, true, true); onlineDisconnectNeighbours(getCell(540,300).y,getCell(540,300).x-1, true, true, true, true); } //sc_juegoOnline.player.tiempoInmovil = message.trampamuro2time; //sc_juegoOnline.player2.tiempoInmovil = message.trampamuro1time; //gestionar los objetos de los monstruos (visual) if (message.p1m_ho1 != "none") {onlineArmarMonstruo(sc_juegoOnline.monstruo1, message.p1m_ho1);} if (message.p1m_ho2 != "none") {onlineArmarMonstruo(sc_juegoOnline.monstruo1, message.p1m_ho2);} if (message.p1m_ho3 != "none") {onlineArmarMonstruo(sc_juegoOnline.monstruo1, message.p1m_ho3);} if (message.p1m_ho4 != "none") {onlineArmarMonstruo(sc_juegoOnline.monstruo1, message.p1m_ho4);} if (message.p2m_ho1 != "none") {onlineArmarMonstruo(sc_juegoOnline.monstruo2, message.p2m_ho1);} if (message.p2m_ho2 != "none") {onlineArmarMonstruo(sc_juegoOnline.monstruo2, message.p2m_ho2);} if (message.p2m_ho3 != "none") {onlineArmarMonstruo(sc_juegoOnline.monstruo2, message.p2m_ho3);} if (message.p2m_ho4 != "none") {onlineArmarMonstruo(sc_juegoOnline.monstruo2, message.p2m_ho4);} break; } } else { switch(message.message_type) { case "game_time": sc_juegoOnline.gameTime = message.game_time; break; case "trap_change": //Cambiar la trampa del altar cont.trampa = message.altarTrap; //cambiar la trampa que lleva el jugador 2 (viene del servidor como el 1) cont.p2.trampa = message.p1Trap; //cambiar la trampa que lleva el jugador 1 (viene del servidor como el 2) cont.p1.trampa = message.p2Trap; break; case "player_move": console.log(message.player2_x + ", " + message.player2_y + ", " + message.player1_x + ", " + message.player1_y); cont.p1.x = message.player2_x; cont.p1.y = message.player2_y; cont.p2.x = message.player1_x; cont.p2.y = message.player1_y; break; case "player_move_single": if (message.player == 1) { cont.p2.x = message.player_x; cont.p2.y = message.player_y; } else { cont.p1.x = message.player_x; cont.p1.y = message.player_y; } break; } } if (message.message_type == "timeout") { cont.opTimeOut = message.op_timeout; if (cont.opTimeout == -1) { cont.opTimedOut = false; } else { cont.opTimedOut = true; } } if (message.message_type == "winner") { cont.connection.close(); console.log("CLOSING WEBSOCKET..."); cont.connection = undefined; if (message.winner == "none") { cont.victoryState = 0; //Enviarle un mensaje a API REST diciendo que no ha ganado nadie y que ya no estáis en partida y eso $.ajax({ method: "PUT", url: cont.server_ip + "gameEnd/"+cont.id, timeout: 3000, data: "none", processData: false, headers: { "Content-type": "application/json" }, }); } else { if (message.winner == cont.name) { cont.victoryState = 1; //Enviar el mensaje de API REST diciendo que has ganado $.ajax({ method: "PUT", url: cont.server_ip + "gameEnd/"+cont.id, timeout: 3000, data: cont.name, processData: false, headers: { "Content-type": "application/json" }, }); } else { cont.victoryState = 2; } } } } } function sendChatMessage() { if (sc_lobby.chatInput.getChildByName('chatField').value !== '') { $.ajax({ method: "POST", url: cont.server_ip + "chat/", data: JSON.stringify({ sender: cont.name, message: sc_lobby.chatInput.getChildByName('chatField').value }), processData: false, headers: { "Content-type": "application/json" }, success: function (item, textStatus, jqXHR) { sc_lobby.chatInput.getChildByName('chatField').value = ""; } }); } } function hideLobbyDom() { sc_lobby.chatBox.getChildByName('chatBox').style.visibility = "hidden"; sc_lobby.usersBox.getChildByID('usersBox').style.visibility = "hidden"; sc_lobby.chatInput.getChildByName('chatField').style.visibility = "hidden"; } function showLobbyDom() { sc_lobby.chatBox.getChildByName('chatBox').style.visibility = "visible"; sc_lobby.usersBox.getChildByID('usersBox').style.visibility = "visible"; sc_lobby.chatInput.getChildByName('chatField').style.visibility = "visible"; } function showUserProfile(player) { sc_lobby.openEnemyName = player.name; sc_lobby.enemyProfileBG.setVisible(true); sc_lobby.enemyProfileText.setVisible(true); sc_lobby.enemyCross.setVisible(true); sc_lobby.enemyCross.setInteractive({cursor: "pointer"}); sc_lobby.userBoxOpen = true; if (player.name != cont.name) { sc_lobby.challengeButton.setVisible(true); sc_lobby.challengeButton.setInteractive({cursor: "pointer"}); sc_lobby.challengeButton.setAlpha(1); } else { sc_lobby.challengeButton.setVisible(false); sc_lobby.challengeButton.removeInteractive(); } var text = player.name + "\nWins: " + player.wins + "\nLosses: " + player.losses + "\nCharacter: "; cont.ch = player.character; switch (player.character.slice(2,3)) { case "H": text += "Ice"; break; case "E": text += "Elf"; break; case "F": text += "Necro"; break; } sc_lobby.enemyProfileText.setText(text); } function updateEnemyProfile() { if (sc_lobby.openEnemyName == "none") { return; } else { var player = undefined; for (var i = 0; i < onlineUsers.length; i++) { if (onlineUsers[i].name == sc_lobby.openEnemyName) { player = onlineUsers[i]; } } if (player != undefined) { if (player.timeout < 0 || player.inGame || player.opponentName != "" || sc_lobby.userChallenging) { sc_lobby.challengeButton.setAlpha(0.5); sc_lobby.challengeButton.removeInteractive(); } else { if (sc_lobby.challengeButton.visible) { sc_lobby.challengeButton.setAlpha(1); sc_lobby.challengeButton.setInteractive({cursor: "pointer"}); } } if (player.timeout < -10) { player = undefined; } } if (player == undefined) { sc_lobby.enemyProfileBG.setVisible(false); sc_lobby.enemyProfileText.setVisible(false); sc_lobby.challengeButton.setVisible(false); sc_lobby.challengeButton.removeInteractive(); sc_lobby.enemyCross.setVisible(false); sc_lobby.enemyCross.removeInteractive(); sc_lobby.userBoxOpen = false; return; } var text = player.name; /*if (player.inGame) { text += " (vs. " + player.opponentName + ")"; } else if (player.opponentName != "") { if (player.sendingChallenge) { text += " (Challenging " + player.opponentName + "...)"; } else { text += " (Waiting for " + player.opponentName + "...)"; } } if (player.timeout < 0) { text += " (Away)"; }*/ text += "\nWins: " + player.wins + "\nLosses: " + player.losses + "\nCharacter: "; //cont.ch = player.character; switch (player.character.slice(2,3)) { case "H": text += "Ice"; break; case "E": text += "Elf"; break; case "F": text += "Necro"; break; } sc_lobby.enemyProfileText.setText(text); } }
const Discord = require('discord.js'); const data = require('quick.db'); const ms = require('ms'); exports.run = async (client, message, args) => { let açıkmı = await data.fetch(`premium.${message.guild.id}`) if(açıkmı) { // premium açıksa yapılack işlemler buraya } else { return message.channel.send(`${message.author}, bu komut premium bir komuttur. Bu sunucu da premium bulunmamakta.`) } const datas = await data.fetch(`${message.author.id}.zaman.public`); if(Date.now() < datas) return message.channel.send(new Discord.MessageEmbed().setColor('#00001').setDescription(`${message.author} **__6__ saat de bir kullanabilirsiniz!**`)).then(m => m.delete({timeout: 6000})); data.set(`${message.author.id}.zaman.public`, Date.now()+ms('6h')); message.channel.send(new Discord.MessageEmbed() .setDescription(`${message.author} **Özelden gönderdim __public sunucunu__ gönderdim bakar mısın.**`)); message.author.send(`> **1 adet __Public__ sunucu kurmak için tema geldi.** > Güle güle kullan 😇 https://discord.new/cBD2sY5n7YCA`).catch(error => message.channel.send(new Discord.MessageEmbed().setDescription("Mesajı gönderemedim. Muhtemelen DM'n kapalı."))); }; exports.conf = { enabled: true, guildOnly: true, aliases: [], permLevel: 0 } exports.help = { name: 'public-tema' };
import React from "react"; import { ScrollView, Text } from "react-native"; import { VictoryChart, VictoryScatter, createContainer } from "victory-native"; import viewStyles from "../styles/view-styles"; import { generateRandomData } from "../data"; const VictoryZoomVoronoiContainer = createContainer("zoom", "voronoi"); export default function CreateContainersView() { const [scrollEnabled, setScrollEnabled] = React.useState(true); const randomData = React.useRef(generateRandomData()); return ( <ScrollView style={viewStyles.container} contentContainerStyle={viewStyles.contentContainer} scrollEnabled={scrollEnabled} > <Text style={[viewStyles.header, viewStyles.monospace]}> {'createContainer("zoom", "voronoi")'} </Text> <VictoryChart containerComponent={ <VictoryZoomVoronoiContainer onTouchStart={() => setScrollEnabled(false)} onTouchEnd={() => setScrollEnabled(true)} labels={({ datum }) => `( ${datum.x} , ${datum.y} )`} dimension={"x"} /> } > <VictoryScatter data={randomData.current} /> </VictoryChart> </ScrollView> ); } CreateContainersView.navigationOptions = { headerTitle: "Custom Containers" };
export const ERROR_STATUS = [ 'FRAUD_DOCS_REQUESTED', 'FRAUD_MANUAL_REVIEW', 'FRAUD_REFUSED', 'notPaid', ]; export const WAITING_PAYMENT_LABEL = 'custom_payment_waiting'; export default { ERROR_STATUS, WAITING_PAYMENT_LABEL, };
import React, { useState, Fragment, useEffect } from "react"; import { makeStyles } from "@material-ui/core/styles"; import TitleContext, { withSetTitle } from "./TitleContext"; import { Typography, Grid, TextField, CircularProgress, Button, Link } from "@material-ui/core"; import querystring from "query-string"; const useStyles = makeStyles(theme => ({ root: { width: "90%" }, button: { marginRight: theme.spacing(1) }, instructions: { marginTop: theme.spacing(1), marginBottom: theme.spacing(1) } })); export const mainPageTitle = "Gmail to Telegram forwarder"; function MainPage({ setTitle }) { const classes = useStyles(); const [botApiToken, setBotApiToken] = useState({}); const [shouldRetry, setShouldRetry] = useState(0); const [group, setGroup] = useState({}); const [fetching, setFetching] = useState(false); const [authorizedSender, setAuthorizedSender] = useState(""); useEffect(() => { setTitle(mainPageTitle); }, [setTitle]); useEffect(() => { if (botApiToken.id) { const tgAPI = `https://api.telegram.org/bot${botApiToken.id}:${ botApiToken.token }`; async function getUpdates() { setFetching(true); const updates = await fetch(`${tgAPI}/getUpdates`).then(d => d.json()); updates.result ? updates.result .filter( upd => !!( upd.message["new_chat_member"] && upd.message["new_chat_member"].id.toString() === botApiToken.id ) ) .forEach(upd => setGroup(upd.message.chat)) : setGroup({}); setFetching(false); } getUpdates(); } }, [botApiToken, shouldRetry]); return ( <Fragment> <div className={classes.root}> <Grid container direction="column"> <Typography className={classes.instructions} style={{ marginTop: "5em" }} > You will need a Telegram bot that you own. You can use{" "} <a href="https://telegram.me/BotFather">BotFather</a> to set one up, you just need to add @BotFather to your contacts, then tell him "/newbot". Once you have your bot, enter its HTTP API token below. BotFather displays the token when it creates your bot. </Typography> <TextField fullWidth onChange={event => { const m = event.target.value.match(/^(\d{9}):(.{35})$/); if (m) { setBotApiToken({ id: m[1], token: m[2] }); } }} placeholder="Bot HTTP API token" /> {botApiToken.id && ( <Grid container justify="center"> <Typography noWrap style={{ paddingRight: "1em" }}> Detected group:{" "} </Typography> {fetching ? ( <CircularProgress /> ) : group.title ? ( <Typography noWrap color="primary"> {group.title} </Typography> ) : ( <Typography color="error" noWrap> Unknown </Typography> )} {!fetching && !group.title && ( <> <Typography color="error" className={classes.instructions}> The tool needs to know the group where you want your messages sent. In order to have this info, you will need to add your bot to that group, or if it's already added, remove and add it again. Click Retry to try again. </Typography> <Button onClick={() => setShouldRetry(v => v + 1)}> Retry </Button> </> )} </Grid> )} <Typography className={classes.instructions}> You can restrict the forwarding to a single sender by typing the email address below. If left empty, all mail will get forwarded. </Typography> <TextField fullWidth placeholder="Filter by sender" value={authorizedSender} onChange={ev => setAuthorizedSender(ev.target.value)} /> </Grid> <Grid container justify="center"> <Button size="large" variant="contained" disabled={!group.id} color="primary" href={`https://us-central1-gmail-to-telegram-forwarder.cloudfunctions.net/oauth2init?${querystring.stringify( { tgGroup: group.id, tgAPIKey: `${botApiToken.id}:${botApiToken.token}`, authorizedSender } )}`} style={{ marginTop: "5em" }} > Authorize Gmail account </Button> </Grid> </div> </Fragment> ); } export default withSetTitle(MainPage);
const { ApolloServer, gql } = require("apollo-server"); const ResultAPI = require("./datasources/results"); const typeDefs = require("./schema.js"); const resolvers = require("./resolvers.js"); const dataSources = () => ({ resultAPI: new ResultAPI() }); const server = new ApolloServer({ typeDefs, resolvers, dataSources }); server.listen(8080, "127.0.0.1").then(({ url }) => { console.log(`graphQL running at ${url}`); });
const CustomError = require("../extensions/custom-error"); module.exports = function calculateHanoi(disk, speed) { let turnsPerSec = speed / 3600; let turns = (2 ** disk) - 1; let seconds = Math.floor(turns / turnsPerSec); return { turns, seconds }; };
!function(v){var c,h='<svg><symbol id="icon-zhuanji" viewBox="0 0 1024 1024"><path d="M511.654123 959.701578c-247.249197 0-447.683159-200.433962-447.683159-447.682136S264.404925 64.336284 511.654123 64.336284s447.683159 200.433962 447.683159 447.682136S758.902296 959.701578 511.654123 959.701578zM511.654123 120.143311c-216.427214 0-391.875109 175.447894-391.875109 391.875109s175.446871 391.875109 391.875109 391.875109 391.874085-175.448918 391.874085-391.875109S728.081337 120.143311 511.654123 120.143311zM511.654123 651.92075c-77.266781 0-139.901307-62.635549-139.901307-139.901307 0-77.264735 62.635549-139.900284 139.901307-139.900284 77.265758 0 139.901307 62.635549 139.901307 139.900284C651.555429 589.285201 588.91988 651.92075 511.654123 651.92075zM511.654123 428.079682c-46.357817 0-83.941807 37.581943-83.941807 83.939761 0 46.358841 37.58399 83.940784 83.941807 83.940784s83.941807-37.581943 83.941807-83.940784C595.594907 465.660602 558.01194 428.079682 511.654123 428.079682zM252.759701 451.877691l-59.259662 11.851932c20.418029-135.654586 125.540228-243.481384 259.772418-268.099061l-7.348362 58.784848C350.090447 278.794657 275.119965 355.255073 252.759701 451.877691z" ></path></symbol><symbol id="icon-suijibofang" viewBox="0 0 1024 1024"><path d="M503.212 399.62c48.02-47.603 109.809-68.831 200.348-68.831l4.625 0 0 51.633c0 16.49 11.334 22.663 25.186 13.716l124.264-80.254c13.852-8.946 13.717-23.371-0.301-32.055l-123.662-76.61c-14.017-8.685-25.486-2.298-25.486 14.192l0 51.378-4.625 0c-105.604 0-182.241 27.212-241.181 85.639-59.046 58.532-60.589 112.848-61.83 156.492-0.532 18.725-0.991 34.896-5.667 49.654-10.522 33.214-38.07 63.935-77.57 86.504-49.704 28.4-116.796 42.932-193.967 42.096-0.11-0.001-0.22-0.002-0.33-0.002-15.865 0-28.814 12.771-28.992 28.677-0.179 16.015 12.659 29.143 28.675 29.321 2.402 0.027 4.795 0.04 7.182 0.04 42.758 0 82.892-4.298 119.396-12.793 35.926-8.36 68.498-20.803 96.811-36.979 52.187-29.818 89.152-72.203 104.087-119.347 7.129-22.505 7.751-44.374 8.352-65.523C459.667 476.453 460.651 441.81 503.212 399.62z" ></path><path d="M123.347 330.826c97.024-1.086 178.164 22.495 228.401 66.391 5.499 4.805 12.299 7.163 19.07 7.163 8.079 0 16.116-3.357 21.85-9.919 10.539-12.061 9.304-30.381-2.756-40.919-29.181-25.497-65.695-45.388-108.529-59.12-46.728-14.979-100.112-22.25-158.682-21.591-16.015 0.179-28.853 13.306-28.674 29.322C94.203 318.167 107.314 331.044 123.347 330.826z" ></path><path d="M857.334 704.25l-123.662-76.61c-14.017-8.685-25.486-2.298-25.486 14.192l0 51.379-4.625 0c-80.96 0-143.128-24.247-195.645-76.307-11.375-11.274-29.737-11.196-41.012 0.18-11.275 11.374-11.195 29.736 0.18 41.012 63.207 62.657 140.56 93.115 236.477 93.115l4.625 0 0 51.632c0 16.49 11.334 22.663 25.186 13.716l124.264-80.254C871.486 727.359 871.352 712.934 857.334 704.25z" ></path></symbol><symbol id="icon-danquxunhuan" viewBox="0 0 1024 1024"><path d="M659.437037 834.446222 380.776296 834.446222l101.963852 102.172444c11.320889 11.320889 11.320889 29.696 0 41.035852-11.320889 11.339852-29.639111 11.339852-40.96 0l-150.20563-150.509037c-11.301926-11.320889-11.301926-29.696 0-41.035852 11.264-11.282963 30.568296-9.159111 49.891556-9.159111l0 0c6.618074 0.493037 13.217185 1.005037 19.949037 1.005037l298.875259 0c147.683556 0 267.396741-119.011556 267.396741-265.822815 0-87.058963-42.287407-164.086519-107.349333-212.574815l0 0c-5.404444-5.176889-8.836741-12.382815-8.836741-20.442074 0-15.720296 12.743111-28.444444 28.444444-28.444444 8.969481 0 16.630519 4.399407 21.845333 10.884741 74.884741 59.050667 124.150519 148.612741 124.150519 250.576593C985.92237 690.157037 839.755852 834.446222 659.437037 834.446222zM710.580148 237.530074c-8.00237 7.983407-22.300444 12.951704-32.331852 9.690074l0 0c-5.973333-0.398222-11.908741-0.910222-17.976889-0.910222L361.396148 246.309926c-147.683556 0-267.415704 119.011556-267.415704 265.822815 0 82.697481 38.437926 156.046222 98.038519 204.781037 11.036444 3.90637 17.825185 14.715259 17.825185 27.079111 0 15.701333-12.743111 28.444444-28.444444 28.444444-7.300741 0-13.805037-2.958222-18.830222-7.471407l0.360296 0.341333c-75.927704-59.012741-124.852148-150.376296-124.852148-253.174519 0-177.98637 146.166519-322.294519 326.485333-322.294519l257.403259 0-102.665481-102.798222c-11.320889-11.339852-11.320889-29.733926 0-41.054815 11.320889-11.320889 29.696-11.320889 40.997926 0l147.702519 147.930074c6.257778 5.594074 9.291852 14.032593 9.291852 14.032593C720.611556 218.036148 718.582519 229.508741 710.580148 237.530074z" ></path><path d="M532.043852 663.514074c-15.701333 0-28.444444-12.743111-28.444444-28.444444l0-218.074074-9.481481 0c-15.701333 0-28.444444-12.743111-28.444444-28.444444s12.743111-28.444444 28.444444-28.444444l37.925926 0c15.701333 0 28.444444 12.743111 28.444444 28.444444l0 246.518519C560.488296 650.789926 547.745185 663.514074 532.043852 663.514074z" ></path></symbol><symbol id="icon-heart" viewBox="0 0 1024 1024"><path d="M511.622912 903.957996c-3.717671 0-7.473205-0.815575-10.956539-2.520403-1.421372-0.679475-2.780323-1.481747-4.064572-2.446725C473.625506 882.735649 73.968154 596.98558 64.196603 389.67193c-4.01443-85.334527 16.281825-152.016229 60.332087-198.198038 55.662741-58.343803 133.684722-67.052139 175.240163-67.052139 102.270245 0 177.536462 65.792449 211.878618 102.944604 34.341133-37.152155 109.608374-102.944604 211.879642-102.944604 41.554418 0 119.575376 8.709359 175.238117 67.052139 44.051285 46.181809 64.34754 112.862487 60.33311 198.198038C949.326788 596.893482 550.015314 882.489032 526.719748 898.967332c-1.373277 1.01205-2.831488 1.890047-4.349051 2.593058-3.38612 1.582031-7.005554 2.372024-10.611685 2.397606C511.721149 903.957996 511.67203 903.957996 511.622912 903.957996zM299.768853 175.020152c-33.465183 0-95.970772 6.677073-138.625244 51.382251-34.131355 35.780925-49.744961 89.911776-46.397726 160.885224 6.91755 146.833183 276.090059 372.337123 396.901589 460.229916 120.81153-87.940888 389.996318-313.500087 396.901589-460.229916 3.347235-70.973448-12.267395-125.104299-46.39875-160.885224-42.655496-44.705178-105.160061-51.382251-138.624221-51.382251-110.708428 0-186.40648 99.806123-191.08913 106.131179-0.851391 1.235131-1.828648 2.396583-2.90312 3.477194-2.12336 2.131547-4.570085 3.816932-7.201006 5.039783-3.41068 1.587148-7.04137 2.359744-10.661827 2.359744 0 0-0.023536 0-0.049119 0-3.594875 0-7.201006-0.760317-10.587126-2.328022-2.666736-1.228991-5.1503-2.933819-7.300266-5.095042-1.063215-1.062192-2.013867-2.205225-2.852978-3.409656C486.459812 275.251971 410.081261 175.020152 299.768853 175.020152z" ></path></symbol><symbol id="icon-sousuo" viewBox="0 0 1024 1024"><path d="M452.605917 831.323555c-211.505599 0-383.573537-172.066939-383.573537-383.572938 0-211.495006 172.067938-383.562944 383.573537-383.562944 211.506599 0 383.58433 172.067938 383.58433 383.562944S664.112516 831.323555 452.605917 831.323555M452.605917 158.594465c-159.446096 0-289.161149 129.720649-289.161149 289.156152 0 159.445496 129.715253 289.156152 289.161149 289.156152s289.166745-129.710656 289.166745-289.156152C741.772662 288.315114 612.052013 158.594465 452.605917 158.594465M900.611569 953.828296c-14.873716 0-29.741835-5.665159-41.087942-17.00647L659.124897 736.429093c-22.686618-22.681622-22.686618-59.472478 0-82.165092 22.69861-22.681622 59.48347-22.681622 82.176085 0L941.693516 854.645542c22.692614 22.693614 22.692614 59.48367 0 82.176085C930.347209 948.162938 915.484486 953.828296 900.611569 953.828296" ></path></symbol><symbol id="icon-goumai" viewBox="0 0 1024 1024"><path d="M365.920994 811.381531c-39.030945 0-70.78516 31.754215-70.78516 70.78516s31.754215 70.784136 70.78516 70.784136c39.030945 0 70.784136-31.753191 70.784136-70.784136S404.951939 811.381531 365.920994 811.381531zM365.920994 901.784494c-10.818393 0-19.61985-8.801457-19.61985-19.618826 0-10.818393 8.801457-19.61985 19.61985-19.61985s19.618826 8.801457 19.618826 19.61985C385.540843 892.984061 376.739387 901.784494 365.920994 901.784494zM808.821219 811.381531c-39.030945 0-70.784136 31.754215-70.784136 70.78516s31.753191 70.784136 70.784136 70.784136 70.78516-31.753191 70.78516-70.784136S847.852164 811.381531 808.821219 811.381531zM808.821219 901.784494c-10.81737 0-19.618826-8.801457-19.618826-19.618826 0-10.818393 8.801457-19.61985 19.618826-19.61985 10.818393 0 19.61985 8.801457 19.61985 19.61985C828.441069 892.984061 819.640636 901.784494 808.821219 901.784494zM443.99107 590.059843c-14.057157 1.416256-24.305569 13.959943-22.890336 28.0171 1.328251 13.187347 12.446473 23.02132 25.423019 23.02132 0.856507 0 1.723248-0.042979 2.594081-0.130983l439.314561-44.245713c0.088004-0.007163 0.174985-0.01842 0.261966-0.026606l0.180102-0.01842c0.50449-0.051165 1.001817-0.119727 1.496074-0.198521 0.222057-0.035816 0.443092-0.076748 0.663102-0.11768 0.552585-0.103354 1.100054-0.217964 1.638313-0.355087 0.085958-0.022513 0.169869-0.047072 0.254803-0.069585 0.586354-0.156566 1.161453-0.334621 1.728364-0.530073 0.077771-0.026606 0.155543-0.051165 0.233314-0.078795 0.626263-0.222057 1.239224-0.469698 1.840928-0.737804 0.039909-0.017396 0.078795-0.035816 0.118704-0.054235 1.277086-0.577145 2.496867-1.252527 3.647063-2.020006 0.001023-0.001023 0.002047-0.001023 0.00307-0.002047 0.553609-0.369414 1.088798-0.76134 1.609661-1.170662 0.069585-0.054235 0.137123-0.10847 0.205685-0.163729 0.48607-0.38988 0.958838-0.795109 1.413186-1.218758 0.092098-0.084934 0.180102-0.173962 0.270153-0.25992 0.394996-0.378623 0.778736-0.76748 1.14815-1.169639 0.11154-0.121773 0.222057-0.243547 0.331551-0.367367 0.333598-0.3776 0.653893-0.766456 0.964978-1.163499 0.12382-0.158612 0.249687-0.314155 0.370437-0.475837 0.322341-0.432859 0.629333-0.876973 0.925069-1.329275 0.113587-0.173962 0.224104-0.348947 0.333598-0.525979 0.296759-0.479931 0.580215-0.968048 0.845251-1.467421 0.069585-0.130983 0.134053-0.265036 0.201591-0.397043 0.289596-0.568958 0.563842-1.147126 0.811482-1.738597 0.00307-0.007163 0.005117-0.014326 0.008186-0.021489 0.569982-1.369184 1.019213-2.796696 1.345648-4.26514 0-0.001023 0-0.002047 0.001023-0.00307l0.00307-0.013303c0.035816-0.162706 0.075725-0.323365 0.10847-0.487094l56.17951-252.734118c0.895393-4.030803 0.780783-8.04728-0.165776-11.794627 0.50449-2.003634 0.774643-4.101411 0.774643-6.261611 0-14.128789-11.452843-25.582655-25.582655-25.582655L195.47502 279.901875l-52.358485-159.553902c-3.631714-11.067057-14.093996-17.972327-25.177426-17.590634-0.207731-0.005117-0.413416-0.01535-0.62217-0.01535L54.663994 102.741989c-14.128789 0-25.582655 11.453866-25.582655 25.582655s11.453866 25.582655 25.582655 25.582655l45.614897 0 197.955514 603.235934c3.536546 10.776438 13.546527 17.613146 24.303522 17.613146 2.067079 0 4.16281-0.26299 6.245238-0.788969l567.583946 0c14.129812 0 25.582655-11.453866 25.582655-25.582655s-11.452843-25.582655-25.582655-25.582655L340.816223 722.8021 212.265428 331.066161l701.224666 0-48.137347 216.557174L443.99107 590.059843z" ></path></symbol><symbol id="icon-gengduo" viewBox="0 0 1024 1024"><path d="M512 863.361024m-109.441024 0a53.438 53.438 0 1 0 218.882048 0 53.438 53.438 0 1 0-218.882048 0Z" ></path><path d="M512 517.761024m-109.441024 0a53.438 53.438 0 1 0 218.882048 0 53.438 53.438 0 1 0-218.882048 0Z" ></path><path d="M512 160.641024m-109.441024 0a53.438 53.438 0 1 0 218.882048 0 53.438 53.438 0 1 0-218.882048 0Z" ></path></symbol><symbol id="icon-xunhuanbofang" viewBox="0 0 1167 1024"><path d="M193.225 621.115c17.818-4.943 28.242-23.401 23.298-41.198-5.543-19.981-8.363-40.725-8.363-61.695 0-126.768 103.141-229.909 229.909-229.909h311.524v59.306c0 19.034 13.245 26.408 29.416 16.376l142.733-88.414c16.17-10.031 16.334-26.677 0.351-36.997l-143.433-92.635c-15.984-10.32-29.065-3.193-29.065 15.82v59.594h-311.545c-79.287 0-153.836 30.878-209.907 86.95-56.050 56.072-86.93 130.62-86.93 209.907 0 27.026 3.646 53.806 10.815 79.616 4.12 14.812 17.572 24.514 32.239 24.514 2.947 0 5.974-0.39 8.961-1.236z" ></path><path d="M964.362 412.918c-4.12-14.812-17.572-24.514-32.239-24.514-2.966 0-5.974 0.39-8.981 1.236-17.818 4.943-28.242 23.401-23.298 41.198 5.542 19.981 8.363 40.725 8.363 61.695 0 126.768-103.142 229.909-229.909 229.909h-311.504v-59.306c0-19.034-13.245-26.408-29.416-16.376l-142.733 88.414c-16.17 10.031-16.334 26.677-0.351 36.997l143.413 92.635c15.985 10.32 29.065 3.193 29.065-15.82v-59.594h311.524c79.287 0 153.836-30.878 209.907-86.95s86.95-130.62 86.95-209.907c0-27.007-3.625-53.806-10.793-79.616z" ></path></symbol><symbol id="icon-duoxuan" viewBox="0 0 1024 1024"><path d="M528.87552 621.3632L401.20832 493.69088 339.57888 550.9632l189.29664 189.31712L947.2 322.00192l-57.2416-57.27232z" ></path><path d="M883.90144 883.90656H257.55136V257.60256h438.64064V194.304H277.92896c-44.032 0-83.65056 39.61344-83.65056 83.6608v585.58976c0 44.02688 39.61344 83.64032 83.64544 83.64032H863.5392c44.02688 0 83.6352-39.61344 83.6352-83.64032v-334.6432h-63.26784v354.99008z" ></path><path d="M517.07904 76.8H160.44032C116.41344 76.8 76.8 116.43904 76.8 160.46592v356.62848h58.17344V140.09344h382.1056V76.8z" ></path></symbol><symbol id="icon-fenxiang" viewBox="0 0 1024 1024"><path d="M746.13248 653.696c-48.31232 0-94.05952 22.85568-123.35104 61.37344l-261.57056-160.9728a154.48576 154.48576 0 0 0 6.53312-44.33408c0-10.6496-1.21856-21.63712-3.62496-32.7168l252.5952-156.928c28.83072 43.91936 76.8256 69.98528 129.39264 69.98528 85.43744 0 154.94656-69.49888 154.94656-154.91584 0.01536-41.39008-16.09728-80.3072-45.35808-109.57824-29.2608-29.27104-68.1728-45.39392-109.56288-45.39392-85.43744 0-154.94144 69.50912-154.94144 154.94656 0 4.29568 0.18944 8.69376 0.56832 13.11744L331.3152 410.06592c-29.5936-35.2-72.5248-55.296-118.49728-55.296-85.43744 0-154.94656 69.51936-154.94656 154.96704 0 85.43744 69.50912 154.94144 154.94656 154.94144 41.4464 0 81.536-16.9728 110.64832-46.70976l269.7984 166.05184a151.00416 151.00416 0 0 0-2.05824 24.6016c0 85.4272 69.50912 154.92096 154.94656 154.92096s154.94656-69.49376 154.94656-154.92096c-0.02048-85.4272-69.53984-154.92608-154.96704-154.92608z m-0.512 73.91744c44.04224 0 79.872 35.82464 79.872 79.86176 0.01024 21.33504-8.2944 41.3952-23.38304 56.48384s-35.1488 23.3984-56.48384 23.3984c-44.04224 0-79.872-35.84-79.872-79.89248-0.00512-44.02688 35.82464-79.85152 79.86688-79.85152z m0-573.50144c44.04224 0 79.872 35.81952 79.872 79.85152 0 44.05248-35.82976 79.89248-79.872 79.89248s-79.872-35.84-79.872-79.89248c0-44.032 35.82976-79.85152 79.872-79.85152zM212.28544 428.71296c44.04224 0 79.872 35.82976 79.872 79.87712a79.29856 79.29856 0 0 1-23.37792 56.47872 79.37024 79.37024 0 0 1-56.49408 23.38816c-44.04224 0-79.872-35.82976-79.872-79.872s35.82976-79.872 79.872-79.872z" ></path></symbol><symbol id="icon-xiazai" viewBox="0 0 1024 1024"><path d="M950.104 241.938c-6.162-13.261-21.91-18.99-35.146-12.84-13.261 6.162-19.003 21.897-12.829 35.146 26.45 56.888 39.854 117.811 39.854 181.065 0 237.088-192.896 429.984-429.984 429.984-237.099 0-429.984-192.896-429.984-429.984 0-63.241 13.405-124.153 39.843-181.041 6.162-13.261 0.409-28.996-12.84-35.146-13.273-6.162-28.996-0.409-35.146 12.84-29.717 63.927-44.779 132.333-44.779 203.347 0 266.276 216.632 482.908 482.908 482.908s482.908-216.632 482.908-482.908c0-71.026-15.075-139.445-44.804-203.37z" ></path><path d="M499.989 683.477L637.09 546.376c9.381-9.381 9.381-24.588 0-33.97s-24.588-9.381-33.97 0l-79.109 79.109V120.991c0-13.261-10.762-24.024-24.024-24.024s-24.024 10.762-24.024 24.024v470.524l-79.097-79.109c-9.369-9.381-24.6-9.381-33.97 0-9.381 9.381-9.381 24.588 0 33.97l137.09 137.101z" ></path></symbol><symbol id="icon-paihangbang-" viewBox="0 0 1024 1024"><path d="M218.4704 814.30528a81.54112 81.54112 0 0 1-163.072 0V490.67008a81.53088 81.53088 0 1 1 163.072 0v323.6352zM966.0928 814.30528a81.54112 81.54112 0 0 1-163.08224 0V490.67008a81.54112 81.54112 0 0 1 163.08224 0v323.6352zM627.4048 752.41472c0 79.21664-49.41824 143.43168-110.3872 143.43168s-110.3872-64.21504-110.3872-143.43168V183.11168c0-79.21664 49.41824-143.43168 110.3872-143.43168 60.95872 0 110.3872 64.21504 110.3872 143.43168v569.30304z" fill="#FFFFFF" ></path><path d="M271.3088 813.50656c-3.69664 62.96576-55.40864 112.98816-119.27552 112.98816h-21.80096C63.95904 926.49472 10.24 872.77568 10.24 806.5024v-69.35552a746.8544 746.8544 0 0 0 261.0688 76.35968z m393.41056-65.80224v36.98688c0 78.32576-63.49824 141.78304-141.81376 141.78304h-21.80096c-67.15392 0-123.07456-46.77632-137.75872-109.43488 107.49952-2.10944 209.44896-26.68544 301.37344-69.33504zM1004.544 433.3056c5.888 14.1824 9.20576 29.68576 9.20576 45.95712V806.5024c0 66.27328-53.71904 119.99232-119.99232 119.99232h-21.80096c-66.27328 0-119.99232-53.71904-119.99232-119.99232V699.91424A755.47648 755.47648 0 0 0 1004.544 433.3056z" fill="#D2D2D2" ></path><path d="M893.76768 926.49472h-21.80096c-66.27328 0-119.99232-53.71904-119.99232-119.99232V479.26272c0-66.24256 53.71904-119.95136 119.99232-119.95136h21.80096C960.04096 359.31136 1013.76 413.0304 1013.76 479.26272V806.5024c0 66.27328-53.71904 119.99232-119.99232 119.99232z m54.55872-447.232a54.55872 54.55872 0 0 0-54.55872-54.528h-21.80096a54.55872 54.55872 0 0 0-54.55872 54.528V806.5024a54.56896 54.56896 0 0 0 54.55872 54.55872h21.80096a54.56896 54.56896 0 0 0 54.55872-54.55872V479.26272zM522.89536 926.49472h-21.80096c-78.32576 0-141.81376-63.46752-141.81376-141.78304V152.02304C359.28064 73.73824 422.77888 10.24 501.10464 10.24h21.80096c78.32576 0 141.81376 63.49824 141.81376 141.78304v632.6784c0 78.32576-63.49824 141.79328-141.824 141.79328z m76.35968-774.44096a76.35968 76.35968 0 0 0-76.35968-76.35968h-21.80096a76.35968 76.35968 0 0 0-76.35968 76.35968v632.64768a76.35968 76.35968 0 0 0 76.35968 76.35968h21.80096a76.35968 76.35968 0 0 0 76.35968-76.35968V152.05376zM152.02304 926.49472h-21.80096C63.95904 926.49472 10.24 872.77568 10.24 806.5024V479.26272c0-66.24256 53.71904-119.95136 119.99232-119.95136h21.80096c66.27328 0 119.99232 53.71904 119.99232 119.95136V806.5024c-0.01024 66.27328-53.72928 119.99232-120.00256 119.99232z m54.56896-447.232a54.55872 54.55872 0 0 0-54.55872-54.528h-21.80096a54.55872 54.55872 0 0 0-54.55872 54.528V806.5024a54.56896 54.56896 0 0 0 54.55872 54.55872h21.80096a54.56896 54.56896 0 0 0 54.55872-54.55872V479.26272zM10.24 948.3264h1003.52V1013.76H10.24z" fill="#464646" ></path></symbol><symbol id="icon-geshou" viewBox="0 0 1024 1024"><path d="M679.444 148.275a204.8 204.8 0 1 0 34.08 81.224 20.48 20.48 0 0 0-40.305 7.373 163.84 163.84 0 1 1-27.239-64.922 20.48 20.48 0 0 0 33.464-23.634zM880.64 880.64a368.64 368.64 0 0 0-617.759-271.729 20.48 20.48 0 1 0 27.69 30.188A326.042 326.042 0 0 1 512 552.96a327.68 327.68 0 0 1 327.68 327.68 20.48 20.48 0 1 0 40.96 0zM229.376 643.891A367.165 367.165 0 0 0 143.36 880.64a20.48 20.48 0 1 0 40.96 0c0-78.07 27.361-151.839 76.472-210.412a20.48 20.48 0 0 0-31.375-26.337z" ></path><path d="M491.52 675.84v81.92c0 11.264 9.216 20.48 20.48 20.48 11.469 0 20.48-9.052 20.48-20.48v-81.92c0-11.264-9.216-20.48-20.48-20.48-11.469 0-20.48 9.052-20.48 20.48z m-40.96 0c0-33.915 27.28-61.44 61.44-61.44 33.915 0 61.44 27.607 61.44 61.44v81.92c0 33.915-27.28 61.44-61.44 61.44-33.915 0-61.44-27.607-61.44-61.44v-81.92z" ></path><path d="M491.52 798.72v81.92a20.48 20.48 0 1 0 40.96 0v-81.92a20.48 20.48 0 1 0-40.96 0z" ></path></symbol><symbol id="icon-bofang" viewBox="0 0 1024 1024"><path d="M479.4 615.1c1 0 2 0.1 3 0.1 1-0.1 2-0.1 3-0.1h-6zM485.3 831.8c-1 0-2-0.1-3-0.1-1 0.1-2 0.1-3 0.1h6z" ></path><path d="M512 0.2C229.7 0.2 0 229.5 0 511.8s229.7 512 512 512 512-229.7 512-512C1023.6 229.5 793.9 0.2 512 0.2z m0 982.5c-259.7 0-470.9-211.2-470.9-470.9S252.3 40.9 512 40.9s470.5 211.6 470.5 470.9c0 259.7-211.2 470.9-470.5 470.9z" ></path><path d="M665.7 469.5L468.4 355.6c-9.9-5.8-19.7-8.6-29.2-8.6-26.3 0-44.4 21-44.4 51v226.8c0 14 3.7 26.3 11.1 35.3 8.2 10.3 19.7 15.6 33.3 15.6 9.5 0 19.3-2.9 29.2-8.6l197.2-113.4c17.7-10.3 27.9-25.5 27.9-42.3 0.1-16-10.1-31.7-27.8-41.9z m-20.6 49.3L447.9 632.2c-4.9 2.9-7.8 2.9-8.6 2.9h-0.8c-0.4-0.4-2.5-2.9-2.5-9.9V398.4c0-7 1.6-9.5 2.5-9.9h0.8c1.2 0 4.1 0.4 8.6 2.9l197.2 113.8c5.8 3.3 7.4 6.2 7.4 6.6 0 0.8-1.6 3.7-7.4 7z" ></path></symbol><symbol id="icon-jia1" viewBox="0 0 1024 1024"><path d="M469.333333 469.333333H213.333333v85.333334h256v256h85.333334v-256h256v-85.333334h-256V213.333333h-85.333334v256z" ></path></symbol><symbol id="icon-jiarushoucang" viewBox="0 0 1170 1024"><path d="M469.577143 73.142857l83.382857 243.565714a73.142857 73.142857 0 0 0 69.485714 49.737143H1097.142857v512a73.142857 73.142857 0 0 1-73.142857 73.142857H146.285714a73.142857 73.142857 0 0 1-73.142857-73.142857V111.908571A39.497143 39.497143 0 0 1 111.908571 73.142857h357.668572m0-73.142857H111.908571A112.64 112.64 0 0 0 0 111.908571V877.714286a146.285714 146.285714 0 0 0 146.285714 146.285714h877.714286a146.285714 146.285714 0 0 0 146.285714-146.285714V347.428571a54.857143 54.857143 0 0 0-54.857143-54.857142H622.445714L539.062857 49.737143A73.142857 73.142857 0 0 0 469.577143 0z" ></path><path d="M919.405714 73.142857H512v73.142857h405.211429a33.645714 33.645714 0 0 1 33.645714 33.645715V365.714286h73.142857V177.737143A104.594286 104.594286 0 0 0 919.405714 73.142857zM365.714286 585.142857h365.714285v73.142857H365.714286z" ></path><path d="M512 438.857143h73.142857v365.714286H512z" ></path></symbol><symbol id="icon-bofang02" viewBox="0 0 1024 1024"><path d="M384 752.288V289.184l299.68 231.552L384 752.288z m371.552-256.896l-384-296.704a31.936 31.936 0 0 0-51.552 25.28v593.504a32 32 0 0 0 51.552 25.28l384-296.704a32 32 0 0 0 0-50.656z" ></path></symbol><symbol id="icon-xiaoxi" viewBox="0 0 1024 1024"><path d="M506.480838 894.286289l-83.59683 0L193.004352 1019.685579 193.004352 789.809968c-114.594533-80.443168-188.097418-195.893102-188.097418-334.417655 0-242.374995 224.571311-438.876787 501.573905-438.876787 277.00765 0 501.577949 196.501793 501.577949 438.876787C1008.077998 697.809774 783.511743 894.286289 506.480838 894.286289L506.480838 894.286289 506.480838 894.286289zM506.480838 79.193432c-242.374995 0-438.914199 168.431264-438.914199 376.19787 0 127.489261 74.966978 245.444735 188.139885 313.476486l0 139.338499 167.154227-76.617115 83.600875 0c242.374995 0 438.919254-168.431264 438.919254-376.19787C945.401103 247.605484 748.860888 79.193432 506.480838 79.193432L506.480838 79.193432 506.480838 79.193432zM757.303685 518.088419c-34.651866 0-62.721384-28.064462-62.721384-62.716328 0-34.651866 28.069518-62.721384 62.721384-62.721384 34.609399 0 62.678917 28.069518 62.678917 62.721384C819.982602 490.023957 791.912073 518.088419 757.303685 518.088419L757.303685 518.088419 757.303685 518.088419zM506.480838 518.088419c-34.651866 0-62.716328-28.064462-62.716328-62.716328 0-34.651866 28.064462-62.721384 62.716328-62.721384 34.651866 0 62.721384 28.069518 62.721384 62.721384C569.202222 490.023957 541.132704 518.088419 506.480838 518.088419L506.480838 518.088419 506.480838 518.088419zM255.687313 518.088419c-34.613444 0-62.681951-28.064462-62.681951-62.697117 0-34.633666 28.068507-62.721384 62.681951-62.721384 34.651866 0 62.716328 28.069518 62.716328 62.721384C318.403642 490.042157 290.314912 518.088419 255.687313 518.088419L255.687313 518.088419 255.687313 518.088419zM255.687313 518.088419" fill="#515151" ></path></symbol><symbol id="icon-gaofenqiang-pinglunicon" viewBox="0 0 1024 1024"><path d="M340.945455 842.472727l107.752727-107.52a32.116364 32.116364 0 0 1 23.272727-9.774545h367.243636a48.872727 48.872727 0 0 0 48.872728-48.872727V410.530909a32.814545 32.814545 0 0 1 65.396363 0v265.774546A114.269091 114.269091 0 0 1 839.214545 791.272727H485.236364l-153.832728 153.832728a32.581818 32.581818 0 0 1-55.621818-23.272728V791.272727H186.181818a114.269091 114.269091 0 0 1-114.269091-114.269091V227.141818A114.269091 114.269091 0 0 1 186.181818 112.872727h427.054546a32.814545 32.814545 0 0 1 0 65.396364H186.181818a48.872727 48.872727 0 0 0-49.105454 48.872727v449.163637A48.872727 48.872727 0 0 0 186.181818 725.178182h122.414546a32.581818 32.581818 0 0 1 32.581818 32.814545z m-106.123637-460.101818v-65.396364h432.872727v65.396364z m0 204.101818v-65.396363h269.498182v65.396363z" ></path></symbol><symbol id="icon-paihangbang" viewBox="0 0 1024 1024"><path d="M160 608c-19.2 0-32 12.8-32 32v128c0 19.2 12.8 32 32 32h64c19.2 0 32-12.8 32-32V640c0-19.2-12.8-32-32-32h-64z m0-64h64c54.4 0 96 41.6 96 96v128c0 54.4-41.6 96-96 96h-64c-54.4 0-96-41.6-96-96V640c0-54.4 41.6-96 96-96z m320-320c-19.2 0-32 12.8-32 32v512c0 19.2 12.8 32 32 32h64c19.2 0 32-12.8 32-32V256c0-19.2-12.8-32-32-32h-64z m0-64h64c54.4 0 96 41.6 96 96v512c0 54.4-41.6 96-96 96h-64c-54.4 0-96-41.6-96-96V256c0-54.4 41.6-96 96-96z m320 320c-19.2 0-32 12.8-32 32v256c0 19.2 12.8 32 32 32h64c19.2 0 32-12.8 32-32V512c0-19.2-12.8-32-32-32h-64z m0-64h64c54.4 0 96 41.6 96 96v256c0 54.4-41.6 96-96 96h-64c-54.4 0-96-41.6-96-96V512c0-54.4 41.6-96 96-96z" ></path></symbol><symbol id="icon-live" viewBox="0 0 1024 1024"><path d="M797.767442 357.209302c65.488372 0 119.069767 53.581395 119.069767 119.069768v333.395349c0 65.488372-53.581395 119.069767-119.069767 119.069767H226.232558c-65.488372 0-119.069767-53.581395-119.069767-119.069767V476.27907c0-65.488372 53.581395-119.069767 119.069767-119.069768h571.534884m0-71.44186H226.232558C121.451163 285.767442 35.72093 371.497674 35.72093 476.27907v333.395349c0 104.781395 85.730233 190.511628 190.511628 190.511628h571.534884c104.781395 0 190.511628-85.730233 190.511628-190.511628V476.27907c0-104.781395-85.730233-190.511628-190.511628-190.511628z" ></path><path d="M256 109.544186c-9.525581 0-17.860465 3.572093-25.004651 10.716279-14.288372 14.288372-14.288372 36.911628 0 50.009302l176.223256 176.223256c7.144186 7.144186 16.669767 10.716279 25.004651 10.716279 9.525581 0 17.860465-3.572093 25.004651-10.716279 14.288372-14.288372 14.288372-36.911628 0-50.009302L281.004651 119.069767c-7.144186-5.953488-15.47907-9.525581-25.004651-9.525581zM827.534884 9.525581c-9.525581 0-17.860465 3.572093-25.004651 10.716279L526.288372 296.483721c-14.288372 14.288372-14.288372 36.911628 0 50.009302 7.144186 7.144186 16.669767 10.716279 25.004651 10.716279s17.860465-3.572093 25.004651-10.716279L852.539535 71.44186c14.288372-14.288372 14.288372-36.911628 0-50.009302-7.144186-8.334884-15.47907-11.906977-25.004651-11.906977zM628.688372 679.888372L441.748837 832.297674c-14.288372 11.906977-36.911628 1.190698-36.911628-17.860465V495.330233c0-19.051163 22.623256-29.767442 36.911628-17.860466l186.939535 152.409303c16.669767 13.097674 16.669767 36.911628 0 50.009302z" ></path></symbol><symbol id="icon-caidan1" viewBox="0 0 1024 1024"><path d="M256 21.333333a234.666667 234.666667 0 0 0 0 469.333334h234.666667V256A234.666667 234.666667 0 0 0 256 21.333333z m170.666667 405.333334h-170.666667a170.666667 170.666667 0 1 1 170.666667-170.666667zM1002.666667 256a234.666667 234.666667 0 0 0-469.333334 0v234.666667h234.666667a234.666667 234.666667 0 0 0 234.666667-234.666667z m-405.333334 0a170.666667 170.666667 0 1 1 170.666667 170.666667h-170.666667zM768 533.333333H533.333333v234.666667a234.666667 234.666667 0 1 0 234.666667-234.666667z m0 405.333334a170.666667 170.666667 0 0 1-170.666667-170.666667v-170.666667h170.666667a170.666667 170.666667 0 0 1 0 341.333334zM21.333333 768a234.666667 234.666667 0 0 0 469.333334 0V533.333333H256A234.666667 234.666667 0 0 0 21.333333 768z m405.333334 0a170.666667 170.666667 0 1 1-170.666667-170.666667h170.666667z" ></path></symbol><symbol id="icon-yinle" viewBox="0 0 1024 1024"><path d="M904.943 731.367c42.062-67.907 66.99-150.264 66.99-238.445l-0.001-0.683C971.919 238.269 766.005 32.356 512 32.356c-254.005 0-459.919 205.913-459.919 459.919l-0.001 0.674c0 83.742 22.479 162.234 61.733 229.77 4.214 7.1 14.11 13.246 25.443 13.246 16.938 0 30.668-13.731 30.668-30.668 0-5.605-1.504-10.86-4.131-15.382-32.916-56.46-52.393-124.454-52.393-196.997l0.001-0.678c0-220.107 178.455-398.562 398.597-398.562s398.597 178.455 398.597 398.597c0 74.17-20.252 145.263-57.995 207.176-2.508 4.348-3.988 9.563-3.988 15.123 0 16.937 13.731 30.668 30.668 30.668 10.688 0 20.1-5.468 25.589-13.76zM747.765 622.229c25.234-40.748 40.189-90.164 40.189-143.075v-0.422c0-152.368-123.55-275.919-275.954-275.919s-275.954 123.55-275.954 275.954c0 48.683 12.651 95.605 36.349 136.964 5.288 9.667 15.389 16.115 26.994 16.115 16.937 0 30.668-13.731 30.668-30.668a30.525 30.525 0 0 0-4.53-16.05c-17.678-30.334-28.159-66.927-28.159-105.969v-0.413c0-118.519 96.092-214.597 214.632-214.597s214.619 96.079 214.619 214.619c0 39.938-10.889 78.207-31.207 111.544-2.567 4.387-4.083 9.662-4.083 15.289 0 16.937 13.731 30.668 30.667 30.668 10.759 0 20.223-5.54 25.697-13.922zM450.678 952.18c50.801 0 91.989-34.31 91.989-76.643 0-42.345-41.188-76.656-91.989-76.656s-91.989 34.324-91.989 76.656 41.188 76.656 91.989 76.656z" fill="#515151" ></path><path d="M444.195 749.751c-79.233 0-146.038 52.313-146.038 121.013s66.805 121.013 146.038 121.013S590.22 939.464 590.22 870.764s-66.792-121.012-146.025-121.012z m0 61.322c48.197 0 84.703 28.59 84.703 59.691 0 31.088-36.506 59.691-84.703 59.691s-84.716-28.603-84.716-59.704c0-31.088 36.519-59.678 84.716-59.678z" fill="#515151" ></path><path d="M590.273 851.656l10.087-341.655 0.001-0.286c0-16.937-13.731-30.668-30.668-30.668-16.4 0-29.793 12.873-30.626 29.064L528.964 849.84l-0.001 0.27c0 16.937 13.731 30.668 30.668 30.668 16.399 0 29.791-12.871 30.626-29.062z m56.864-396.165c-30.42 4.452-57.813 12.134-83.638 22.835 31.246-11.275 7.509-3.266 4.222-2.477-13.417 3.468-23.167 15.463-23.167 29.736 0 16.937 13.731 30.668 30.667 30.668 2.475 0 4.882-0.293 7.187-0.847 6.275-1.536 31.235-9.952 38.73-12.017 10.521-2.893 21.751-5.287 34.942-7.233 14.581-2.549 25.522-15.113 25.522-30.232 0-16.937-13.731-30.668-30.667-30.668a30.85 30.85 0 0 0-3.951 0.252z" fill="#515151" ></path></symbol><symbol id="icon-fanhui" viewBox="0 0 1365 1024"><path d="M217.4343 597.312041l318.216298 319.922552a62.70482 62.70482 0 0 1-0.170625 88.511906 62.363569 62.363569 0 0 1-88.298625-0.127969L37.893763 594.112815a67.14108 67.14108 0 0 1-16.55066-10.749398 60.913254 60.913254 0 0 1-20.38973-42.357745 62.619508 62.619508 0 0 1 37.324298-68.548739L438.906018 22.432543A67.055767 67.055767 0 0 1 533.389812 16.75925c25.167241 22.437235 27.428027 61.041223 4.990792 86.25112l-326.065065 366.289994H1301.033312a63.98451 63.98451 0 0 1 63.98451 63.98451v0.042656a63.98451 63.98451 0 0 1-63.98451 63.984511H217.4343z" ></path></symbol><symbol id="icon-guanbi" viewBox="0 0 1024 1024"><path d="M512 1016C233.6 1016 8 790.4 8 512S233.6 8 512 8 1016 233.6 1016 512 790.4 1016 512 1016z m0-960C260.8 56 56 260.8 56 512S260.8 968 512 968 968 763.2 968 512 763.2 56 512 56z" ></path><path d="M548.8 512l195.2-195.2c9.6-9.6 9.6-25.6 0-36.8l-1.6-1.6c-9.6-9.6-25.6-9.6-35.2 0L512 475.2 316.8 280c-9.6-9.6-25.6-9.6-35.2 0l-1.6 1.6c-9.6 9.6-9.6 25.6 0 36.8L475.2 512 280 707.2c-9.6 9.6-9.6 25.6 0 36.8l1.6 1.6c9.6 9.6 25.6 9.6 35.2 0L512 548.8l195.2 195.2c9.6 9.6 25.6 9.6 35.2 0l1.6-1.6c9.6-9.6 9.6-25.6 0-36.8L548.8 512z" ></path></symbol><symbol id="icon-xiayige" viewBox="0 0 1024 1024"><path d="M648.564364 524.986182c5.492364-13.312 3.723636-29.556364-6.004364-40.261818l-219.787636-242.501819c-12.008727-13.172364-30.906182-12.567273-42.263273 1.396364a39.098182 39.098182 0 0 0 1.210182 49.245091l197.213091 217.646545-196.421819 220.858182A39.098182 39.098182 0 0 0 381.672727 780.567273a27.834182 27.834182 0 0 0 21.504 10.658909c7.447273 0 14.894545-3.258182 20.712728-9.774546l217.832727-244.829091c0.418909-0.465455 0.558545-1.163636 0.930909-1.675636l1.024-0.977454c1.675636-2.094545 2.606545-4.608 3.723636-6.981819 0.325818-0.698182 0.837818-1.303273 1.117091-2.048z" fill="#E6E6E6" ></path></symbol><symbol id="icon-bofang2" viewBox="0 0 1024 1024"><path d="M512 993.792c-265.728 0-481.792-216.064-481.792-481.792S246.272 30.208 512 30.208c265.728 0 481.792 216.064 481.792 481.792s-216.064 481.792-481.792 481.792M512 0C229.888 0 0 229.888 0 512s229.888 512 512 512 512-229.888 512-512S794.112 0 512 0" ></path><path d="M434.176 338.944v346.112l285.184-173.056-285.184-173.056" ></path></symbol><symbol id="icon-quanping" viewBox="0 0 1024 1024"><path d="M333.493 428.648l94.83-94.816-165.75-165.787 104.135-103.6H64.097l-0.244 302.126 103.431-104.11zM854.845 760.133L688.61 593.96l-94.805 94.806 165.75 165.796-104.109 103.6h302.61l0.218-302.126zM688.536 428.55L854.31 262.801l103.625 104.12V64.349L655.81 64.08l104.11 103.455-166.211 166.196zM333.59 594.033L167.818 759.805 64.22 655.672v302.599l302.124 0.231-104.109-103.43 166.187-166.21z" ></path></symbol><symbol id="icon-meirituijian_huaban" viewBox="0 0 1024 1024"><path d="M800 144h-90.4a48 48 0 0 0-96 0h-208a48 48 0 0 0-96 0H208a64 64 0 0 0-64 64v624a64 64 0 0 0 64 64h592a64 64 0 0 0 64-64V208a64 64 0 0 0-64-64z" fill="#1C1514" ></path><path d="M240 320m32 0l464 0q32 0 32 32l0 416q0 32-32 32l-464 0q-32 0-32-32l0-416q0-32 32-32Z" fill="#D7B57F" ></path></symbol><symbol id="icon-zan" viewBox="0 0 1024 1024"><path d="M757.76 956.928c-2.56 0-5.12 0-7.68-0.512h-154.112c-55.808-0.512-111.616-7.168-166.4-18.944-56.32-13.824-93.696-23.04-113.664-28.16H312.832l-6.144-1.536h-1.024c-2.048 0-3.584 1.024-4.608 3.072-12.8 27.136-40.448 45.056-70.656 45.568H146.432c-43.52 0-79.36-35.328-79.36-79.36V427.52c0-43.52 35.84-79.36 79.36-79.36h84.48c18.944 0.512 37.888 7.68 52.224 20.48 1.024 1.024 2.048 1.024 3.584 1.024 1.024 0 1.536 0 2.048-0.512l28.672-14.336c103.936-54.784 115.2-164.352 115.2-208.896C432.64 102.4 467.968 66.56 512 66.56c24.064 0 50.176 12.8 73.216 36.352C622.08 140.288 645.12 196.608 645.12 250.88c1.024 30.72-1.024 61.44-7.168 91.648-0.512 1.536 0 3.072 1.024 4.096 1.024 1.024 2.56 2.048 4.096 2.048 25.088 0.512 48.128 1.024 69.632 1.536 81.408 2.048 140.288 3.072 167.936 10.24 43.008 10.24 74.24 48.128 76.288 92.16v19.968c-1.024 20.992-9.728 41.472-24.064 57.344-1.536 1.536-1.536 4.096-0.512 5.632 10.24 19.456 13.824 41.984 10.24 63.488a132.096 132.096 0 0 1-36.352 75.264c-1.536 1.536-2.048 3.584-1.024 5.632 8.704 23.552 8.704 49.664 0 73.216v0.512c-6.144 27.648-22.016 52.224-44.032 69.632-1.536 1.024-2.56 3.584-2.048 5.632 4.096 15.36 4.096 31.232 0 46.592-3.072 9.728-7.168 19.456-12.288 29.184-18.432 32.256-52.224 52.224-89.088 52.224z m-8.192-46.592c2.56 0.512 5.12 0.512 7.68 0.512 19.456 0 37.888-10.752 48.128-27.648 3.584-7.168 6.144-14.336 8.192-21.504 1.024-3.584 2.048-7.168 2.048-11.264 0-9.216-3.584-17.92-10.24-24.576-6.656-6.656-15.36-10.24-24.576-10.24h-44.032c-5.12 0-8.704-4.096-8.704-8.704 0-5.12 4.096-8.704 8.704-8.704h46.592c60.928 0 69.632-27.648 77.824-54.272l1.024-4.096c4.608-14.336 7.68-34.816-2.56-49.152-7.68-10.24-20.48-15.36-38.912-15.36h-56.32c-5.12 0-8.704-4.096-8.704-8.704s4.096-8.704 8.704-8.704h67.072c35.84-0.512 65.024-29.696 66.048-65.024 1.024-4.608 1.024-8.704 1.024-13.312-2.048-24.576-23.04-44.032-47.616-44.032H793.088c-5.12 0-8.704-4.096-8.704-8.704 0-5.12 4.096-8.704 8.704-8.704h56.32c10.24 0 61.44-2.048 61.44-46.08v-17.92c0.512-22.528-15.36-43.008-37.376-48.128l-3.584-1.024c-22.016-6.144-34.304-9.728-293.888-9.728 17.92-45.056 26.112-94.208 23.552-142.848 0-74.752-53.76-138.24-87.552-138.24-18.432 0-33.28 14.848-33.28 33.28 0 57.856-16.384 199.168-165.376 261.12l-6.144 3.072c-14.848 4.096-25.088 17.408-25.6 32.768v388.096c0 19.456 17.92 27.648 27.648 29.696 4.096 1.536 7.68 2.56 24.576 6.144s47.616 10.752 105.984 25.088c51.712 11.264 104.448 17.408 156.672 17.92h153.088zM146.432 394.24c-18.432 0-33.28 14.848-33.28 33.28v450.048c0 18.432 14.848 33.28 33.28 33.28h84.48c18.432 0 33.28-14.848 33.28-33.28V427.52c0-18.432-14.848-33.28-33.28-33.28H146.432z" ></path><path d="M188.416 793.088c-23.04 0-41.984 18.944-41.984 41.984 0 23.04 18.944 41.984 41.984 41.984s41.984-18.944 41.984-41.984c0.512-23.04-18.432-41.984-41.984-41.984z m0 56.32c-7.68 0-13.824-6.144-13.824-13.824s6.144-13.824 13.824-13.824 13.824 6.144 13.824 13.824-6.144 13.824-13.824 13.824z" ></path></symbol><symbol id="icon-caidan" viewBox="0 0 1024 1024"><path d="M800 320 224 320c-17.664 0-32-14.336-32-32s14.336-32 32-32l576 0c17.696 0 32 14.336 32 32S817.696 320 800 320z" ></path><path d="M800 544 224 544c-17.664 0-32-14.336-32-32s14.336-32 32-32l576 0c17.696 0 32 14.336 32 32S817.696 544 800 544z" ></path><path d="M800 768 224 768c-17.664 0-32-14.336-32-32s14.336-32 32-32l576 0c17.696 0 32 14.336 32 32S817.696 768 800 768z" ></path></symbol><symbol id="icon-xiayishou" viewBox="0 0 1024 1024"><path d="M863.979361 506.637904V32.026659a31.99914 31.99914 0 1 1 63.99828 0v954.854339a31.99914 31.99914 0 1 1-63.99828 0V536.141111a43.90282 43.90282 0 0 1-17.023543 21.759415L164.158168 1011.584334A43.90282 43.90282 0 0 1 96 974.977317V43.930339A43.90282 43.90282 0 0 1 165.054144 7.963306l36.09503 25.279321 646.638622 452.147848c7.551797 5.311857 13.183646 12.799656 16.191565 21.247429zM166.398108 924.802666l607.98366-403.957144-607.98366-425.204572v829.161716z" ></path></symbol><symbol id="icon-shanchu" viewBox="0 0 1024 1024"><path d="M764.42168889 830.5152c0 30.23530667-24.61013333 54.84430222-54.84316444 54.84430222H314.42147555c-30.23416889 0-54.84316445-24.61013333-54.84316444-54.84430222V248.32796445h504.84337778v582.18723555zM369.26577778 149.89084445c0-6.32832 4.92202667-11.25034667 11.25034667-11.25034667H644.18702222c6.32832 0 11.25034667 4.92202667 11.25034667 11.25034667v33.04675555H369.26577778V149.89084445z m559.68768 33.04675555H720.82773333V149.89084445c0-42.1888-34.45191111-76.64071111-76.64071111-76.64071112H380.51612445c-42.1888 0-76.64071111 34.45191111-76.64071112 76.64071112v33.04675555h-208.82773333c-18.28181333 0-33.04789333 14.76608-33.04789333 33.04675555s14.76608 33.04675555 33.04675555 33.04675556h98.43825778v581.48408889c0 66.79779555 54.14001778 120.93781333 120.93667555 120.93781333h395.1570489c66.79665778 0 120.93667555-54.14001778 120.93667555-120.93781333V248.32796445h98.43825778c18.28067555 0 33.04675555-14.76494222 33.04675555-33.04675556s-14.76608-32.34360889-33.04675555-32.34360889zM512 786.21923555c18.28181333 0 33.04675555-14.76608 33.04675555-33.04789333v-351.56195555c0-18.28181333-14.76494222-33.04675555-33.04675555-33.04675556s-33.04675555 14.76494222-33.04675555 33.04675556v351.56195555c0 18.28181333 14.76494222 33.04789333 33.04675555 33.04789333m-153.98456889 0c18.28181333 0 33.04675555-14.76608 33.04675556-33.04789333v-351.56195555c0-18.28181333-14.76494222-33.04675555-33.04675556-33.04675556s-33.04675555 14.76494222-33.04675556 33.04675556v351.56195555c0.70314667 18.28181333 15.46922667 33.04789333 33.04675556 33.04789333m307.96913778 0c18.28067555 0 33.04675555-14.76608 33.04675556-33.04789333v-351.56195555c0-18.28181333-14.76608-33.04675555-33.04675556-33.04675556s-33.04675555 14.76494222-33.04675556 33.04675556v351.56195555c0 18.28181333 14.76494222 33.04789333 33.04675556 33.04789333" ></path></symbol><symbol id="icon-lingsheng" viewBox="0 0 1024 1024"><path d="M779.9 651.3h-13.4V411.9c0-110.2-70.5-204.3-168.8-239.5v-23c0-47.2-38.4-85.5-85.5-85.5s-85.5 38.4-85.5 85.5v23C328.4 207.6 258 301.7 258 411.9v239.4h-13.4c-52.5 0-95.2 42.7-95.2 95.2s42.7 95.1 95.2 95.1H397v3.7c0 63.6 51.7 115.3 115.3 115.3s115.3-51.7 115.3-115.3v-3.7H780c52.5 0 95.2-42.7 95.2-95.1-0.1-52.5-42.9-95.2-95.3-95.2zM477.3 149.4c0-19.2 15.7-34.9 34.9-34.9 19.3 0 34.9 15.7 34.9 34.9V160c-11.4-1.6-23.1-2.4-34.9-2.4-11.9 0-23.5 0.8-34.9 2.4v-10.6z m99.6 695.9c0 35.7-29 64.7-64.7 64.7s-64.7-29-64.7-64.7v-3.7h129.4v3.7z m203-54.3H244.6c-24.6 0-44.6-20-44.6-44.6s20-44.6 44.6-44.6h64v-290c0-81.8 48.4-152.5 118.2-184.9 15.8-7.4 32.8-12.8 50.6-15.9 11.3-2 23-3 34.9-3 11.9 0 23.6 1 34.9 3 17.8 3.1 34.7 8.5 50.6 15.9 69.7 32.4 118.2 103 118.2 184.9v290h64c24.6 0 44.6 20 44.6 44.6-0.1 24.7-20.2 44.6-44.7 44.6zM390.1 533.5c-13.8 0-25-11-25.3-24.8 0-1.3-0.6-31.9-0.6-119.8 0-96.7 77-127.7 117.7-130.6 13.9-1 26 9.5 27 23.4 1 13.9-9.4 26-23.3 27-7.4 0.6-70.9 8.2-70.9 80.2 0 87.3 0.5 118.6 0.6 118.9 0.3 14-10.9 25.5-24.8 25.7h-0.4z" ></path></symbol><symbol id="icon-xiayishou1" viewBox="0 0 1024 1024"><path d="M160.020639 517.362096L160.020639 991.973341a31.99914 31.99914 0 1 1-63.99828 0l0-954.854339a31.99914 31.99914 0 1 1 63.99828 0L160.020639 487.858889a43.90282 43.90282 0 0 1 17.023543-21.759415L859.841832 12.415666A43.90282 43.90282 0 0 1 928 49.022683L927.99999999 980.069661A43.90282 43.90282 0 0 1 858.945856 1016.036694l-36.09503-25.279321-646.638622-452.147848c-7.55179699-5.311857-13.183646-12.799656-16.191565-21.247429zM857.60189199 99.197334l-607.98365999 403.957144 607.98366 425.204572-1e-8-829.161716z" ></path></symbol><symbol id="icon-icon_common_tip_normal" viewBox="0 0 1024 1024"><path d="M514.7 908.5c-53 0-104.5-10.4-152.9-30.9-46.8-19.8-88.8-48.1-124.9-84.2-36.1-36.1-64.4-78.1-84.2-124.9-20.5-48.5-30.9-99.9-30.9-152.9s10.4-104.5 30.9-152.9c19.8-46.8 48.1-88.8 84.2-124.9 36.1-36.1 78.1-64.4 124.9-84.2 48.5-20.5 99.9-30.9 152.9-30.9s104.5 10.4 152.9 30.9c46.8 19.8 88.8 48.1 124.9 84.2s64.4 78.1 84.2 124.9c20.5 48.5 30.9 99.9 30.9 152.9s-10.4 104.5-30.9 152.9c-19.8 46.8-48.1 88.8-84.2 124.9-36.1 36.1-78.1 64.4-124.9 84.2-48.5 20.5-99.9 30.9-152.9 30.9z m0-735.7c-189.1 0-342.9 153.8-342.9 342.9 0 189.1 153.8 342.9 342.9 342.9 189.1 0 342.9-153.8 342.9-342.9-0.1-189.1-153.9-342.9-342.9-342.9z" ></path><path d="M283.8 515.6a39.9 39.9 0 1 0 79.8 0 39.9 39.9 0 1 0-79.8 0zM476 515.6a39.9 39.9 0 1 0 79.8 0 39.9 39.9 0 1 0-79.8 0zM665.8 515.6a39.9 39.9 0 1 0 79.8 0 39.9 39.9 0 1 0-79.8 0z" ></path></symbol><symbol id="icon-laba" viewBox="0 0 1024 1024"><path d="M548.864 225.28c-6.144-2.048-14.336-4.096-20.48-4.096-12.288 0-24.576 4.096-32.768 12.288l-178.176 151.552h-143.36c-10.24 0-20.48 4.096-30.72 10.24h-2.048l-8.192 8.192c-6.144 6.144-10.24 18.432-10.24 28.672v260.096c0 14.336 6.144 28.672 14.336 36.864 8.192 8.192 24.576 14.336 36.864 14.336h141.312l178.176 147.456c8.192 6.144 20.48 14.336 30.72 14.336 4.096 0 14.336 0 24.576-6.144 8.192-4.096 16.384-10.24 20.48-16.384 4.096-8.192 8.192-16.384 8.192-28.672V270.336c0-12.288-2.048-20.48-8.192-28.672-2.048-8.192-10.24-14.336-20.48-16.384z m-22.528 51.2v573.44l-184.32-151.552-8.192-6.144H176.128V438.272h159.744l190.464-161.792z m342.016 98.304c-18.432-28.672-40.96-55.296-67.584-75.776-2.048 0-2.048-2.048-2.048-2.048-4.096-2.048-8.192-4.096-14.336-4.096-8.192 0-18.432 4.096-28.672 12.288-8.192 12.288-4.096 32.768 8.192 40.96 6.144 2.048 12.288 8.192 18.432 14.336 8.192 8.192 20.48 20.48 34.816 40.96 22.528 32.768 47.104 88.064 47.104 169.984 0 81.92-24.576 137.216-45.056 169.984-12.288 20.48-24.576 32.768-32.768 40.96-8.192 8.192-14.336 12.288-18.432 14.336-12.288 8.192-14.336 24.576-8.192 40.96 4.096 6.144 14.336 12.288 24.576 12.288 4.096 0 12.288 0 16.384-4.096l2.048-2.048c24.576-20.48 47.104-45.056 65.536-73.728 34.816-57.344 51.2-122.88 51.2-196.608 2.048-77.824-16.384-143.36-51.2-198.656z m0 0" ></path><path d="M737.28 442.368c-20.48-24.576-43.008-36.864-47.104-36.864h-2.048l-2.048-2.048c-2.048-2.048-6.144-2.048-10.24-2.048-10.24 0-22.528 6.144-24.576 14.336-4.096 6.144-4.096 12.288-2.048 20.48s8.192 14.336 12.288 14.336c0 0 14.336 8.192 30.72 26.624 14.336 16.384 28.672 45.056 28.672 86.016 0 86.016-49.152 114.688-53.248 116.736-12.288 8.192-20.48 24.576-12.288 36.864 4.096 8.192 16.384 16.384 24.576 16.384 4.096 0 8.192 0 10.24-4.096l2.048-2.048h2.048c6.144-2.048 24.576-14.336 45.056-38.912 18.432-24.576 40.96-65.536 40.96-131.072 0-53.248-24.576-92.16-43.008-114.688z m0 0" ></path></symbol><symbol id="icon-jia" viewBox="0 0 1024 1024"><path d="M828.96896 453.85728H572.19072V196.608a59.392 59.392 0 0 0-118.784 0v257.24928H196.608a59.392 59.392 0 0 0 0 118.784h256.77824V829.44a59.392 59.392 0 0 0 118.784 0V572.64128H829.44a59.26912 59.26912 0 0 0 59.392-59.392 60.25216 60.25216 0 0 0-59.86304-59.392z m0 0" ></path></symbol><symbol id="icon-shipin" viewBox="0 0 1024 1024"><path d="M417.831 700.337a18.64 18.64 0 0 1-8.437-1.996 18.865 18.865 0 0 1-10.396-16.838V342.497c0-7.12 4.03-13.674 10.396-16.838s14.012-2.486 19.738 1.77l226.004 169.504c4.746 3.54 7.534 9.153 7.534 15.067s-2.788 11.526-7.534 15.067L429.132 696.57a18.863 18.863 0 0 1-11.3 3.767z m18.834-320.173v263.672L612.46 512 436.665 380.164zM869.84 210.66H154.16c-10.397 0-18.834 8.438-18.834 18.834v565.012c0 10.396 8.437 18.833 18.834 18.833h715.68c10.397 0 18.834-8.437 18.834-18.833V229.494c0-10.396-8.437-18.833-18.834-18.833zM248.328 549.668h-75.335v-75.334h75.335v75.334z m0-113.002h-75.335V361.33h75.335v75.335z m-75.335 150.67h75.335v75.335h-75.335v-75.335z m113.003-339.007h452.008v527.344H285.996V248.328z m489.676 226.005h75.335v75.334h-75.335v-75.334z m0-37.668V361.33h75.335v75.335h-75.335z m0 150.67h75.335v75.335h-75.335v-75.335z m75.335-263.672h-75.335v-75.335h75.335v75.335z m-602.679-75.335v75.335h-75.335v-75.335h75.335z m-75.335 452.01h75.335v75.334h-75.335v-75.335z m602.679 75.334v-75.335h75.335v75.335h-75.335z" ></path></symbol><symbol id="icon-jingyunyinxiaopt" viewBox="0 0 1024 1024"><path d="M634.07 98.45c-50.47 0-95 25.15-121.97 63.53-26.97-38.38-71.5-63.53-121.97-63.53H64.87V196.72c0 125.37 101.63 227.01 227.01 227.01 29.89 0 54.21 24.32 54.21 54.21v121.95c0 14.97 12.14 27.11 27.11 27.11 14.97 0 27.11-12.14 27.11-27.11V477.94c0-59.88-48.54-108.42-108.42-108.42-95.28 0-172.79-77.52-172.79-172.79v-44.06h271.05c52.21 0 94.68 42.39 94.85 94.56v68.45c0 14.97 12.14 27.11 27.11 27.11 14.97 0 27.11-12.14 27.11-27.11v-68.14h0.02c0-52.31 42.56-94.87 94.87-94.87h271.05v44.06c0 95.28-77.52 172.79-172.79 172.79-59.88 0-108.42 48.54-108.42 108.42V627c-0.01 143.46-124.5 258.4-271.13 242.45-111.11-12.08-201.3-101.19-214.9-212.12-6.19-50.52 3.35-98.36 24.2-139.57 9.18-18.14-3.85-39.53-24.18-39.53-10.44 0-19.87 6.01-24.55 15.34C92 536.19 80.48 584.6 81.98 635.88 86.4 788.58 208.99 915.4 361.5 924.59c173.04 10.43 316.62-126.82 316.62-297.6V477.94c0-29.89 24.32-54.21 54.21-54.21 125.37 0 227.01-101.63 227.01-227.01V98.45H634.07z" ></path></symbol><symbol id="icon-gedan" viewBox="0 0 1024 1024"><path d="M606.7 179.8H80.5c-10.1 0-18.5 8.3-18.5 18.5v117c0 10.1 8.3 18.5 18.5 18.5h526.3c10.1 0 18.5-8.3 18.5-18.5v-117c-0.3-10.1-8.4-18.5-18.6-18.5z m-23.1 112.3h-480v-70.9h479.9v70.9zM435.3 573.1H82.9c-11.5 0-20.9-9.2-20.9-20.9 0-11.5 9.5-20.9 20.9-20.9h331.4v-75.2H82.9c-11.5 0-20.9-9.5-20.9-20.9 0-11.5 9.5-20.9 20.9-20.9h352.4c11.5 0 20.9 9.2 20.9 20.9v117c0 11.7-9.4 20.9-20.9 20.9zM258.2 654.1H80.5c-10.1 0-18.5 8.3-18.5 18.5v117c0 10.1 8.3 18.5 18.5 18.5h177.8c10.1 0 18.5-8.3 18.5-18.5v-117c-0.1-10.1-8.5-18.5-18.6-18.5z m-22.9 112.3H103.6v-70.9h131.6v70.9zM960 117.5c-5-10.4-17.3-14.9-27.7-10.1L742 224.8c-7.2 3.4-11.9 10.8-11.9 18.9v378.9l-33.8-23.4C667 578.8 632.6 568 596.8 568h-0.2c-96.8 0-175.3 78.5-175.3 175.3s78.5 175.3 175.3 175.3c96.5 0 175.3-78.5 175.3-175.3V257l178.6-112c9.9-4.8 14.4-17.4 9.5-27.5zM596.8 876.4c-73.6 0-133.2-59.8-133.2-133.2 0-73.6 59.8-133.2 133.2-133.2S730 669.9 730 743.2c0 73.6-59.8 133.2-133.2 133.2z" fill="#595757" ></path><path d="M103.6 695.8h131.6v70.9H103.6zM103.6 221.5h479.9v70.9H103.6z" fill="#DBDCDC" ></path></symbol><symbol id="icon-icon-test" viewBox="0 0 1024 1024"><path d="M832 768v64H192v-64H128v128h768v-128zM822.624 438.624l-45.248-45.248L544 626.752V128h-64v498.752l-233.376-233.376-45.248 45.248L512 749.248z" fill="#181818" ></path></symbol><symbol id="icon-del" viewBox="0 0 1024 1024"><path d="M512 472.66826911L367.84855732 328.484375a27.81129776 27.81129776 0 1 0-39.33173008 39.33173089L472.63581768 512l-144.18389492 144.15144268a27.81129776 27.81129776 0 1 0 39.3317309 39.33173008L512 551.36418232l144.15144268 144.18389492a27.81129776 27.81129776 0 1 0 39.33173008-39.3317309L551.36418232 512l144.18389492-144.15144268a27.81129776 27.81129776 0 1 0-39.3317309-39.33173008L512 472.63581768z" ></path></symbol><symbol id="icon-bofang1" viewBox="0 0 1024 1024"><path d="M512 1024C229.216 1024 0 794.784 0 512S229.216 0 512 0s512 229.216 512 512-229.216 512-512 512z m0-31.04c265.632 0 480.96-215.328 480.96-480.96C992.96 246.368 777.632 31.04 512 31.04 246.368 31.04 31.04 246.368 31.04 512c0 265.632 215.328 480.96 480.96 480.96z m-93.12-667.136a31.04 31.04 0 0 1 31.04 31.04v310.272a31.04 31.04 0 0 1-62.048 0v-310.272a31.04 31.04 0 0 1 31.04-31.04z m186.24 0a31.04 31.04 0 0 1 31.008 31.04v310.272a31.04 31.04 0 1 1-62.08 0v-310.272a31.04 31.04 0 0 1 31.04-31.04z" ></path></symbol><symbol id="icon-juxing" viewBox="0 0 1024 1024"><path d="M151.703704 168.618667v212.688592a18.962963 18.962963 0 0 0 29.639111 15.663408l155.97037-106.344297a18.962963 18.962963 0 0 0 0-31.326814L181.342815 152.955259A18.962963 18.962963 0 0 0 151.703704 168.618667z" fill="#000000" ></path><path d="M474.074074 246.518519m28.444445 0l341.333333 0q28.444444 0 28.444444 28.444444l0 0q0 28.444444-28.444444 28.444444l-341.333333 0q-28.444444 0-28.444445-28.444444l0 0q0-28.444444 28.444445-28.444444Z" fill="#000000" ></path><path d="M151.703704 530.962963m28.444444 0l663.703704 0q28.444444 0 28.444444 28.444444l0 0q0 28.444444-28.444444 28.444445l-663.703704 0q-28.444444 0-28.444444-28.444445l0 0q0-28.444444 28.444444-28.444444Z" fill="#000000" ></path><path d="M151.703704 815.407407m28.444444 0l663.703704 0q28.444444 0 28.444444 28.444445l0 0q0 28.444444-28.444444 28.444444l-663.703704 0q-28.444444 0-28.444444-28.444444l0 0q0-28.444444 28.444444-28.444445Z" fill="#000000" ></path></symbol><symbol id="icon-customer-service-line" viewBox="0 0 1024 1024"><path d="M938.666667 725.418667a256.085333 256.085333 0 0 1-201.088 250.026666l-27.221334-81.664A170.794667 170.794667 0 0 0 830.506667 810.666667H725.333333a85.333333 85.333333 0 0 1-85.333333-85.333334v-170.666666a85.333333 85.333333 0 0 1 85.333333-85.333334h125.354667a341.376 341.376 0 0 0-677.376 0H298.666667a85.333333 85.333333 0 0 1 85.333333 85.333334v170.666666a85.333333 85.333333 0 0 1-85.333333 85.333334H170.666667a85.333333 85.333333 0 0 1-85.333334-85.333334v-213.333333C85.333333 276.352 276.352 85.333333 512 85.333333s426.666667 191.018667 426.666667 426.666667v213.418667zM853.333333 725.333333v-170.666666h-128v170.666666h128zM170.666667 554.666667v170.666666h128v-170.666666H170.666667z" ></path></symbol><symbol id="icon-shoucangjia" viewBox="0 0 1201 1024"><path d="M1060.352 158.208H565.248L494.592 16.896h-353.28c-78.336 0-141.312 63.488-141.312 141.312V865.28c0 78.336 63.488 141.312 141.312 141.312H1060.352c78.336 0 141.312-63.488 141.312-141.312V300.032c0.512-78.336-62.976-141.824-141.312-141.824z m71.168 707.584c0 38.912-31.744 70.656-70.656 70.656H141.312c-38.912 0-70.656-31.744-70.656-70.656V158.208c0-38.912 31.744-70.656 70.656-70.656H451.072l70.656 141.312H1060.352c38.912 0 70.656 31.744 70.656 70.656v566.272z" ></path><path d="M762.88 539.136h-123.904V415.744c0-24.576-19.968-44.032-44.032-44.032-24.576 0-44.032 19.968-44.032 44.032v123.904H427.008c-24.576 0-44.032 19.968-44.032 44.032 0 24.576 19.968 44.032 44.032 44.032h123.904v123.904c0 24.576 19.968 44.032 44.032 44.032 24.576 0 44.032-19.968 44.032-44.032v-123.904h123.904c24.576 0 44.032-19.968 44.032-44.032 0.512-24.576-19.456-44.544-44.032-44.544z" ></path></symbol></svg>',a=(c=document.getElementsByTagName("script"))[c.length-1].getAttribute("data-injectcss");if(a&&!v.__iconfont__svg__cssinject__){v.__iconfont__svg__cssinject__=!0;try{document.write("<style>.svgfont {display: inline-block;width: 1em;height: 1em;fill: currentColor;vertical-align: -0.1em;font-size:16px;}</style>")}catch(c){console&&console.log(c)}}!function(c){if(document.addEventListener)if(~["complete","loaded","interactive"].indexOf(document.readyState))setTimeout(c,0);else{var a=function(){document.removeEventListener("DOMContentLoaded",a,!1),c()};document.addEventListener("DOMContentLoaded",a,!1)}else document.attachEvent&&(l=c,o=v.document,t=!1,(i=function(){try{o.documentElement.doScroll("left")}catch(c){return void setTimeout(i,50)}h()})(),o.onreadystatechange=function(){"complete"==o.readyState&&(o.onreadystatechange=null,h())});function h(){t||(t=!0,l())}var l,o,t,i}(function(){var c,a;(c=document.createElement("div")).innerHTML=h,h=null,(a=c.getElementsByTagName("svg")[0])&&(a.setAttribute("aria-hidden","true"),a.style.position="absolute",a.style.width=0,a.style.height=0,a.style.overflow="hidden",function(c,a){a.firstChild?function(c,a){a.parentNode.insertBefore(c,a)}(c,a.firstChild):a.appendChild(c)}(a,document.body))})}(window);
(function(){ window.app('const', { APP_PREFIX: 'f1' }); })();
"use strict";function u(u){return u&&"object"==typeof u&&"default"in u?u.default:u}var D=u(require("util")),e=require("path"),t=require("fs"),r=u(require("os")),n=u(require("tty"));"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function s(u,D){return u(D={exports:{}},D.exports),D.exports}var o,i=(o=Object.freeze({__proto__:null,default:[{name:"AppVeyor",constant:"APPVEYOR",env:"APPVEYOR",pr:"APPVEYOR_PULL_REQUEST_NUMBER"},{name:"Bamboo",constant:"BAMBOO",env:"bamboo_planKey"},{name:"Bitbucket Pipelines",constant:"BITBUCKET",env:"BITBUCKET_COMMIT"},{name:"Bitrise",constant:"BITRISE",env:"BITRISE_IO",pr:"BITRISE_PULL_REQUEST"},{name:"Buddy",constant:"BUDDY",env:"BUDDY_WORKSPACE_ID",pr:"BUDDY_EXECUTION_PULL_REQUEST_ID"},{name:"Buildkite",constant:"BUILDKITE",env:"BUILDKITE",pr:{env:"BUILDKITE_PULL_REQUEST",ne:"false"}},{name:"CircleCI",constant:"CIRCLE",env:"CIRCLECI",pr:"CIRCLE_PULL_REQUEST"},{name:"Cirrus CI",constant:"CIRRUS",env:"CIRRUS_CI",pr:"CIRRUS_PR"},{name:"AWS CodeBuild",constant:"CODEBUILD",env:"CODEBUILD_BUILD_ARN"},{name:"Codeship",constant:"CODESHIP",env:{CI_NAME:"codeship"}},{name:"Drone",constant:"DRONE",env:"DRONE",pr:{DRONE_BUILD_EVENT:"pull_request"}},{name:"dsari",constant:"DSARI",env:"DSARI"},{name:"GitLab CI",constant:"GITLAB",env:"GITLAB_CI"},{name:"GoCD",constant:"GOCD",env:"GO_PIPELINE_LABEL"},{name:"Hudson",constant:"HUDSON",env:"HUDSON_URL"},{name:"Jenkins",constant:"JENKINS",env:["JENKINS_URL","BUILD_ID"],pr:{any:["ghprbPullId","CHANGE_ID"]}},{name:"Magnum CI",constant:"MAGNUM",env:"MAGNUM"},{name:"Sail CI",constant:"SAIL",env:"SAILCI",pr:"SAIL_PULL_REQUEST_NUMBER"},{name:"Semaphore",constant:"SEMAPHORE",env:"SEMAPHORE",pr:"PULL_REQUEST_NUMBER"},{name:"Shippable",constant:"SHIPPABLE",env:"SHIPPABLE",pr:{IS_PULL_REQUEST:"true"}},{name:"Solano CI",constant:"SOLANO",env:"TDDIUM",pr:"TDDIUM_PR_ID"},{name:"Strider CD",constant:"STRIDER",env:"STRIDER"},{name:"TaskCluster",constant:"TASKCLUSTER",env:["TASK_ID","RUN_ID"]},{name:"Solano CI",constant:"TDDIUM",env:"TDDIUM",pr:"TDDIUM_PR_ID",deprecated:!0},{name:"TeamCity",constant:"TEAMCITY",env:"TEAMCITY_VERSION"},{name:"Team Foundation Server",constant:"TFS",env:"TF_BUILD"},{name:"Travis CI",constant:"TRAVIS",env:"TRAVIS",pr:{env:"TRAVIS_PULL_REQUEST",ne:"false"}}]}))&&o.default||o,a=s((function(u,D){var e=process.env;function t(u){return"string"==typeof u?!!e[u]:Object.keys(u).every((function(D){return e[D]===u[D]}))}Object.defineProperty(D,"_vendors",{value:i.map((function(u){return u.constant}))}),D.name=null,D.isPR=null,i.forEach((function(u){var r=(Array.isArray(u.env)?u.env:[u.env]).every((function(u){return t(u)}));if(D[u.constant]=r,r)switch(D.name=u.name,typeof u.pr){case"string":D.isPR=!!e[u.pr];break;case"object":"env"in u.pr?D.isPR=u.pr.env in e&&e[u.pr.env]!==u.pr.ne:"any"in u.pr?D.isPR=u.pr.any.some((function(u){return!!e[u]})):D.isPR=t(u.pr);break;default:D.isPR=null}})),D.isCI=!!(e.CI||e.CONTINUOUS_INTEGRATION||e.BUILD_NUMBER||e.RUN_ID||D.name)})),l=(a.name,a.isPR,a.isCI,!1),c=!1,h=!1,F="development",C="undefined"!=typeof window,f="",E=!1;function g(u){return!(!u||"false"===u)}"undefined"!=typeof process&&(process.platform&&(f=String(process.platform)),process.stdout&&(h=g(process.stdout.isTTY)),l=Boolean(a.isCI),process.env&&(process.env.NODE_ENV&&(F=process.env.NODE_ENV),c=g(process.env.DEBUG),E=g(process.env.MINIMAL)));var d={browser:C,test:"test"===F,dev:"development"===F||"dev"===F,production:"production"===F,debug:c,ci:l,tty:h,minimal:void 0,minimalCLI:void 0,windows:/^win/i.test(f),darwin:/^darwin/i.test(f),linux:/^linux/i.test(f)};d.minimal=E||d.ci||d.test||!d.tty,d.minimalCLI=d.minimal;var p=Object.freeze(d);const m={};m[m.Fatal=0]="Fatal",m[m.Error=0]="Error",m[m.Warn=1]="Warn",m[m.Log=2]="Log",m[m.Info=3]="Info",m[m.Success=3]="Success",m[m.Debug=4]="Debug",m[m.Trace=5]="Trace",m[m.Silent=-1/0]="Silent",m[m.Verbose=1/0]="Verbose";var b={silent:{level:-1},fatal:{level:m.Fatal},error:{level:m.Error},warn:{level:m.Warn},log:{level:m.Log},info:{level:m.Info},success:{level:m.Success},debug:{level:m.Debug},trace:{level:m.Trace},verbose:{level:m.Trace},ready:{level:m.Info},start:{level:m.Info}};function y(u){return D=u,"[object Object]"===Object.prototype.toString.call(D)&&(!(!u.message&&!u.args)&&!u.stack);var D}let B=!1;const v=[];class _{constructor(u={}){this._reporters=u.reporters||[],this._types=u.types||b,this.level=void 0!==u.level?u.level:3,this._defaults=u.defaults||{},this._async=void 0!==u.async?u.async:void 0,this._stdout=u.stdout,this._stderr=u.stderr,this._mockFn=u.mockFn,this._throttle=u.throttle||1e3,this._throttleMin=u.throttleMin||5;for(const u in this._types)this[u]=this._wrapLogFn(Object.assign({type:u},this._types[u],this._defaults));this._mockFn&&this.mockTypes(),this._lastLogSerialized=void 0,this._lastLog=void 0,this._lastLogTime=void 0,this._lastLogCount=0,this._throttleTimeout=void 0}get stdout(){return this._stdout||console._stdout}get stderr(){return this._stderr||console._stderr}create(u){return new _(Object.assign({reporters:this._reporters,level:this.level,types:this._types,defaults:this._defaults,stdout:this._stdout,stderr:this._stderr,mockFn:this._mockFn},u))}withDefaults(u){return this.create({defaults:Object.assign({},this._defaults,u)})}withTag(u){return this.withDefaults({tag:this._defaults.tag?this._defaults.tag+":"+u:u})}addReporter(u){return this._reporters.push(u),this}removeReporter(u){if(u){const D=this._reporters.indexOf(u);if(D>=0)return this._reporters.splice(D,1)}else this._reporters.splice(0);return this}setReporters(u){return this._reporters=Array.isArray(u)?u:[u],this}wrapAll(){this.wrapConsole(),this.wrapStd()}restoreAll(){this.restoreConsole(),this.restoreStd()}wrapConsole(){for(const u in this._types)console["__"+u]||(console["__"+u]=console[u]),console[u]=this[u]}restoreConsole(){for(const u in this._types)console["__"+u]&&(console[u]=console["__"+u],delete console["__"+u])}wrapStd(){this._wrapStream(this.stdout,"log"),this._wrapStream(this.stderr,"log")}_wrapStream(u,D){u&&(u.__write||(u.__write=u.write),u.write=u=>{this[D](String(u).trim())})}restoreStd(){this._restoreStream(this.stdout),this._restoreStream(this.stderr)}_restoreStream(u){u&&u.__write&&(u.write=u.__write,delete u.__write)}pauseLogs(){B=!0}resumeLogs(){B=!1;const u=v.splice(0);for(const D of u)D[0]._logFn(D[1],D[2])}mockTypes(u){if(this._mockFn=u||this._mockFn,"function"==typeof this._mockFn)for(const u in this._types)this[u]=this._mockFn(u,this._types[u])||this[u]}_wrapLogFn(u){return function(){if(!B)return this._logFn(u,arguments);v.push([this,u,arguments])}.bind(this)}_logFn(u,D){if(u.level>this.level)return!!this._async&&Promise.resolve(!1);const e=Object.assign({date:new Date,args:[]},u);1===D.length&&y(D[0])?Object.assign(e,D[0]):e.args=Array.from(D),e.message&&(e.args.unshift(e.message),delete e.message),e.additional&&(Array.isArray(e.additional)||(e.additional=e.additional.split("\n")),e.args.push("\n"+e.additional.join("\n")),delete e.additional),e.type="string"==typeof e.type?e.type.toLowerCase():"",e.tag="string"==typeof e.tag?e.tag.toLowerCase():"";const t=(u=!1)=>{const D=this._lastLogCount-this._throttleMin;if(this._lastLog&&D>0){const u=[...this._lastLog.args];D>1&&u.push(`(repeated ${D} times)`),this._log({...this._lastLog,args:u}),this._lastLogCount=1}if(u){if(this._lastLog=e,this._async)return this._logAsync(e);this._log(e)}};clearTimeout(this._throttleTimeout);const r=this._lastLogTime?e.date-this._lastLogTime:0;if(this._lastLogTime=e.date,r<this._throttle)try{const u=JSON.stringify([e.type,e.tag,e.args]),D=this._lastLogSerialized===u;if(this._lastLogSerialized=u,D&&(this._lastLogCount++,this._lastLogCount>this._throttleMin))return void(this._throttleTimeout=setTimeout(t,this._throttle))}catch(u){}t(!0)}_log(u){for(const D of this._reporters)D.log(u,{async:!1,stdout:this.stdout,stderr:this.stderr})}_logAsync(u){return Promise.all(this._reporters.map(D=>D.log(u,{async:!0,stdout:this.stdout,stderr:this.stderr})))}}function A(u){const D=process.cwd()+e.sep;return u.split("\n").splice(1).map(u=>u.trim().replace("file://","").replace(D,""))}_.prototype.add=_.prototype.addReporter,_.prototype.remove=_.prototype.removeReporter,_.prototype.clear=_.prototype.removeReporter,_.prototype.withScope=_.prototype.withTag,_.prototype.mock=_.prototype.mockTypes,_.prototype.pause=_.prototype.pauseLogs,_.prototype.resume=_.prototype.resumeLogs;var w=s((function(u,D){u.exports=function(){var u="millisecond",D="second",e="minute",t="hour",r="day",n="week",s="month",o="quarter",i="year",a=/^(\d{4})-?(\d{1,2})-?(\d{0,2})[^0-9]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?.?(\d{1,3})?$/,l=/\[([^\]]+)]|Y{2,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,c=function(u,D,e){var t=String(u);return!t||t.length>=D?u:""+Array(D+1-t.length).join(e)+u},h={s:c,z:function(u){var D=-u.utcOffset(),e=Math.abs(D),t=Math.floor(e/60),r=e%60;return(D<=0?"+":"-")+c(t,2,"0")+":"+c(r,2,"0")},m:function(u,D){var e=12*(D.year()-u.year())+(D.month()-u.month()),t=u.clone().add(e,s),r=D-t<0,n=u.clone().add(e+(r?-1:1),s);return Number(-(e+(D-t)/(r?t-n:n-t))||0)},a:function(u){return u<0?Math.ceil(u)||0:Math.floor(u)},p:function(a){return{M:s,y:i,w:n,d:r,D:"date",h:t,m:e,s:D,ms:u,Q:o}[a]||String(a||"").toLowerCase().replace(/s$/,"")},u:function(u){return void 0===u}},F={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_")},C="en",f={};f[C]=F;var E=function(u){return u instanceof m},g=function(u,D,e){var t;if(!u)return C;if("string"==typeof u)f[u]&&(t=u),D&&(f[u]=D,t=u);else{var r=u.name;f[r]=u,t=r}return!e&&t&&(C=t),t||!e&&C},d=function(u,D){if(E(u))return u.clone();var e="object"==typeof D?D:{};return e.date=u,e.args=arguments,new m(e)},p=h;p.l=g,p.i=E,p.w=function(u,D){return d(u,{locale:D.$L,utc:D.$u,$offset:D.$offset})};var m=function(){function c(u){this.$L=this.$L||g(u.locale,null,!0),this.parse(u)}var h=c.prototype;return h.parse=function(u){this.$d=function(u){var D=u.date,e=u.utc;if(null===D)return new Date(NaN);if(p.u(D))return new Date;if(D instanceof Date)return new Date(D);if("string"==typeof D&&!/Z$/i.test(D)){var t=D.match(a);if(t)return e?new Date(Date.UTC(t[1],t[2]-1,t[3]||1,t[4]||0,t[5]||0,t[6]||0,t[7]||0)):new Date(t[1],t[2]-1,t[3]||1,t[4]||0,t[5]||0,t[6]||0,t[7]||0)}return new Date(D)}(u),this.init()},h.init=function(){var u=this.$d;this.$y=u.getFullYear(),this.$M=u.getMonth(),this.$D=u.getDate(),this.$W=u.getDay(),this.$H=u.getHours(),this.$m=u.getMinutes(),this.$s=u.getSeconds(),this.$ms=u.getMilliseconds()},h.$utils=function(){return p},h.isValid=function(){return!("Invalid Date"===this.$d.toString())},h.isSame=function(u,D){var e=d(u);return this.startOf(D)<=e&&e<=this.endOf(D)},h.isAfter=function(u,D){return d(u)<this.startOf(D)},h.isBefore=function(u,D){return this.endOf(D)<d(u)},h.$g=function(u,D,e){return p.u(u)?this[D]:this.set(e,u)},h.year=function(u){return this.$g(u,"$y",i)},h.month=function(u){return this.$g(u,"$M",s)},h.day=function(u){return this.$g(u,"$W",r)},h.date=function(u){return this.$g(u,"$D","date")},h.hour=function(u){return this.$g(u,"$H",t)},h.minute=function(u){return this.$g(u,"$m",e)},h.second=function(u){return this.$g(u,"$s",D)},h.millisecond=function(D){return this.$g(D,"$ms",u)},h.unix=function(){return Math.floor(this.valueOf()/1e3)},h.valueOf=function(){return this.$d.getTime()},h.startOf=function(u,o){var a=this,l=!!p.u(o)||o,c=p.p(u),h=function(u,D){var e=p.w(a.$u?Date.UTC(a.$y,D,u):new Date(a.$y,D,u),a);return l?e:e.endOf(r)},F=function(u,D){return p.w(a.toDate()[u].apply(a.toDate("s"),(l?[0,0,0,0]:[23,59,59,999]).slice(D)),a)},C=this.$W,f=this.$M,E=this.$D,g="set"+(this.$u?"UTC":"");switch(c){case i:return l?h(1,0):h(31,11);case s:return l?h(1,f):h(0,f+1);case n:var d=this.$locale().weekStart||0,m=(C<d?C+7:C)-d;return h(l?E-m:E+(6-m),f);case r:case"date":return F(g+"Hours",0);case t:return F(g+"Minutes",1);case e:return F(g+"Seconds",2);case D:return F(g+"Milliseconds",3);default:return this.clone()}},h.endOf=function(u){return this.startOf(u,!1)},h.$set=function(n,o){var a,l=p.p(n),c="set"+(this.$u?"UTC":""),h=(a={},a.day=c+"Date",a.date=c+"Date",a[s]=c+"Month",a[i]=c+"FullYear",a[t]=c+"Hours",a[e]=c+"Minutes",a[D]=c+"Seconds",a[u]=c+"Milliseconds",a)[l],F=l===r?this.$D+(o-this.$W):o;if(l===s||l===i){var C=this.clone().set("date",1);C.$d[h](F),C.init(),this.$d=C.set("date",Math.min(this.$D,C.daysInMonth())).toDate()}else h&&this.$d[h](F);return this.init(),this},h.set=function(u,D){return this.clone().$set(u,D)},h.get=function(u){return this[p.p(u)]()},h.add=function(u,o){var a,l=this;u=Number(u);var c=p.p(o),h=function(D){var e=d(l);return p.w(e.date(e.date()+Math.round(D*u)),l)};if(c===s)return this.set(s,this.$M+u);if(c===i)return this.set(i,this.$y+u);if(c===r)return h(1);if(c===n)return h(7);var F=(a={},a[e]=6e4,a[t]=36e5,a[D]=1e3,a)[c]||1,C=this.$d.getTime()+u*F;return p.w(C,this)},h.subtract=function(u,D){return this.add(-1*u,D)},h.format=function(u){var D=this;if(!this.isValid())return"Invalid Date";var e=u||"YYYY-MM-DDTHH:mm:ssZ",t=p.z(this),r=this.$locale(),n=this.$H,s=this.$m,o=this.$M,i=r.weekdays,a=r.months,c=function(u,t,r,n){return u&&(u[t]||u(D,e))||r[t].substr(0,n)},h=function(u){return p.s(n%12||12,u,"0")},F=r.meridiem||function(u,D,e){var t=u<12?"AM":"PM";return e?t.toLowerCase():t},C={YY:String(this.$y).slice(-2),YYYY:this.$y,M:o+1,MM:p.s(o+1,2,"0"),MMM:c(r.monthsShort,o,a,3),MMMM:c(a,o),D:this.$D,DD:p.s(this.$D,2,"0"),d:String(this.$W),dd:c(r.weekdaysMin,this.$W,i,2),ddd:c(r.weekdaysShort,this.$W,i,3),dddd:i[this.$W],H:String(n),HH:p.s(n,2,"0"),h:h(1),hh:h(2),a:F(n,s,!0),A:F(n,s,!1),m:String(s),mm:p.s(s,2,"0"),s:String(this.$s),ss:p.s(this.$s,2,"0"),SSS:p.s(this.$ms,3,"0"),Z:t};return e.replace(l,(function(u,D){return D||C[u]||t.replace(":","")}))},h.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},h.diff=function(u,r,a){var l,c=p.p(r),h=d(u),F=6e4*(h.utcOffset()-this.utcOffset()),C=this-h,f=p.m(this,h);return f=(l={},l[i]=f/12,l[s]=f,l[o]=f/3,l[n]=(C-F)/6048e5,l.day=(C-F)/864e5,l[t]=C/36e5,l[e]=C/6e4,l[D]=C/1e3,l)[c]||C,a?f:p.a(f)},h.daysInMonth=function(){return this.endOf(s).$D},h.$locale=function(){return f[this.$L]},h.locale=function(u,D){if(!u)return this.$L;var e=this.clone(),t=g(u,D,!0);return t&&(e.$L=t),e},h.clone=function(){return p.w(this.$d,this)},h.toDate=function(){return new Date(this.valueOf())},h.toJSON=function(){return this.isValid()?this.toISOString():null},h.toISOString=function(){return this.$d.toISOString()},h.toString=function(){return this.$d.toUTCString()},c}();return d.prototype=m.prototype,d.extend=function(u,D){return u(D,m,d),d},d.locale=g,d.isDayjs=E,d.unix=function(u){return d(1e3*u)},d.en=f[C],d.Ls=f,d}()}));const O={dateFormat:"HH:mm:ss",formatOptions:{colors:!1,compact:!0}},M=u=>u?`[${u}]`:"";class S{constructor(u){this.options=Object.assign({},O,u)}formatStack(u){return" "+A(u).join("\n ")}formatArgs(u){const e=u.map(u=>u&&"string"==typeof u.stack?u.message+"\n"+this.formatStack(u.stack):u);return"function"==typeof D.formatWithOptions?D.formatWithOptions(this.options.formatOptions,...e):D.format(...e)}formatDate(u){return function(u,D){return w(D).format(u)}(this.options.dateFormat,u)}filterAndJoin(u){return u.filter(u=>u).join(" ")}formatLogObj(u){const D=this.formatArgs(u.args);return this.filterAndJoin([M(u.type),M(u.tag),D])}log(u,{async:D,stdout:e,stderr:r}={}){return function(u,D,e="default"){const r=D.__write||D.write;switch(e){case"async":return new Promise(e=>{!0===r.call(D,u)?e():D.once("drain",()=>{e()})});case"sync":return t.writeSync(D.fd,u);default:return r.call(D,u)}}(this.formatLogObj(u,{width:e.columns||0})+"\n",u.level<2?r:e,D?"async":"default")}}var I=u=>"string"==typeof u?u.replace((({onlyFirst:u=!1}={})=>{const D=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(D,u?void 0:"g")})(),""):u;const k=u=>!Number.isNaN(u)&&(u>=4352&&(u<=4447||9001===u||9002===u||11904<=u&&u<=12871&&12351!==u||12880<=u&&u<=19903||19968<=u&&u<=42182||43360<=u&&u<=43388||44032<=u&&u<=55203||63744<=u&&u<=64255||65040<=u&&u<=65049||65072<=u&&u<=65131||65281<=u&&u<=65376||65504<=u&&u<=65510||110592<=u&&u<=110593||127488<=u&&u<=127569||131072<=u&&u<=262141));var R=k,T=k;R.default=T;const L=u=>{if("string"!=typeof(u=u.replace(/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g," "))||0===u.length)return 0;u=I(u);let D=0;for(let e=0;e<u.length;e++){const t=u.codePointAt(e);t<=31||t>=127&&t<=159||(t>=768&&t<=879||(t>65535&&e++,D+=R(t)?2:1))}return D};var $=L,x=L;$.default=x;var j=/[|\\{}()[\]^$+*?.]/g,U=function(u){if("string"!=typeof u)throw new TypeError("Expected a string");return u.replace(j,"\\$&")};const{platform:P}=process,N={tick:"✔",cross:"✖",star:"★",square:"▇",squareSmall:"◻",squareSmallFilled:"◼",play:"▶",circle:"◯",circleFilled:"◉",circleDotted:"◌",circleDouble:"◎",circleCircle:"ⓞ",circleCross:"ⓧ",circlePipe:"Ⓘ",circleQuestionMark:"?⃝",bullet:"●",dot:"․",line:"─",ellipsis:"…",pointer:"❯",pointerSmall:"›",info:"ℹ",warning:"⚠",hamburger:"☰",smiley:"㋡",mustache:"෴",heart:"♥",nodejs:"⬢",arrowUp:"↑",arrowDown:"↓",arrowLeft:"←",arrowRight:"→",radioOn:"◉",radioOff:"◯",checkboxOn:"☒",checkboxOff:"☐",checkboxCircleOn:"ⓧ",checkboxCircleOff:"Ⓘ",questionMarkPrefix:"?⃝",oneHalf:"½",oneThird:"⅓",oneQuarter:"¼",oneFifth:"⅕",oneSixth:"⅙",oneSeventh:"⅐",oneEighth:"⅛",oneNinth:"⅑",oneTenth:"⅒",twoThirds:"⅔",twoFifths:"⅖",threeQuarters:"¾",threeFifths:"⅗",threeEighths:"⅜",fourFifths:"⅘",fiveSixths:"⅚",fiveEighths:"⅝",sevenEighths:"⅞"},q={tick:"√",cross:"×",star:"*",square:"█",squareSmall:"[ ]",squareSmallFilled:"[█]",play:"►",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(○)",circleCross:"(×)",circlePipe:"(│)",circleQuestionMark:"(?)",bullet:"*",dot:".",line:"─",ellipsis:"...",pointer:">",pointerSmall:"»",info:"i",warning:"‼",hamburger:"≡",smiley:"☺",mustache:"┌─┐",heart:N.heart,nodejs:"♦",arrowUp:N.arrowUp,arrowDown:N.arrowDown,arrowLeft:N.arrowLeft,arrowRight:N.arrowRight,radioOn:"(*)",radioOff:"( )",checkboxOn:"[×]",checkboxOff:"[ ]",checkboxCircleOn:"(×)",checkboxCircleOff:"( )",questionMarkPrefix:"?",oneHalf:"1/2",oneThird:"1/3",oneQuarter:"1/4",oneFifth:"1/5",oneSixth:"1/6",oneSeventh:"1/7",oneEighth:"1/8",oneNinth:"1/9",oneTenth:"1/10",twoThirds:"2/3",twoFifths:"2/5",threeQuarters:"3/4",threeFifths:"3/5",threeEighths:"3/8",fourFifths:"4/5",fiveSixths:"5/6",fiveEighths:"5/8",sevenEighths:"7/8"};"linux"===P&&(N.questionMarkPrefix="?");const Y="win32"===P?q:N;var H=Object.assign(u=>{if(Y===N)return u;for(const[D,e]of Object.entries(N))e!==Y[D]&&(u=u.replace(new RegExp(U(e),"g"),Y[D]));return u},Y),V=N,W=q;H.main=V,H.windows=W;var G={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};const z={};for(const u of Object.keys(G))z[G[u]]=u;const Q={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};var J=Q;for(const u of Object.keys(Q)){if(!("channels"in Q[u]))throw new Error("missing channels property: "+u);if(!("labels"in Q[u]))throw new Error("missing channel labels property: "+u);if(Q[u].labels.length!==Q[u].channels)throw new Error("channel and label counts mismatch: "+u);const{channels:D,labels:e}=Q[u];delete Q[u].channels,delete Q[u].labels,Object.defineProperty(Q[u],"channels",{value:D}),Object.defineProperty(Q[u],"labels",{value:e})}function K(u){const D=function(){const u={},D=Object.keys(J);for(let e=D.length,t=0;t<e;t++)u[D[t]]={distance:-1,parent:null};return u}(),e=[u];for(D[u].distance=0;e.length;){const u=e.pop(),t=Object.keys(J[u]);for(let r=t.length,n=0;n<r;n++){const r=t[n],s=D[r];-1===s.distance&&(s.distance=D[u].distance+1,s.parent=u,e.unshift(r))}}return D}function Z(u,D){return function(e){return D(u(e))}}function X(u,D){const e=[D[u].parent,u];let t=J[D[u].parent][u],r=D[u].parent;for(;D[r].parent;)e.unshift(D[r].parent),t=Z(J[D[r].parent][r],t),r=D[r].parent;return t.conversion=e,t}Q.rgb.hsl=function(u){const D=u[0]/255,e=u[1]/255,t=u[2]/255,r=Math.min(D,e,t),n=Math.max(D,e,t),s=n-r;let o,i;n===r?o=0:D===n?o=(e-t)/s:e===n?o=2+(t-D)/s:t===n&&(o=4+(D-e)/s),o=Math.min(60*o,360),o<0&&(o+=360);const a=(r+n)/2;return i=n===r?0:a<=.5?s/(n+r):s/(2-n-r),[o,100*i,100*a]},Q.rgb.hsv=function(u){let D,e,t,r,n;const s=u[0]/255,o=u[1]/255,i=u[2]/255,a=Math.max(s,o,i),l=a-Math.min(s,o,i),c=function(u){return(a-u)/6/l+.5};return 0===l?(r=0,n=0):(n=l/a,D=c(s),e=c(o),t=c(i),s===a?r=t-e:o===a?r=1/3+D-t:i===a&&(r=2/3+e-D),r<0?r+=1:r>1&&(r-=1)),[360*r,100*n,100*a]},Q.rgb.hwb=function(u){const D=u[0],e=u[1];let t=u[2];const r=Q.rgb.hsl(u)[0],n=1/255*Math.min(D,Math.min(e,t));return t=1-1/255*Math.max(D,Math.max(e,t)),[r,100*n,100*t]},Q.rgb.cmyk=function(u){const D=u[0]/255,e=u[1]/255,t=u[2]/255,r=Math.min(1-D,1-e,1-t);return[100*((1-D-r)/(1-r)||0),100*((1-e-r)/(1-r)||0),100*((1-t-r)/(1-r)||0),100*r]},Q.rgb.keyword=function(u){const D=z[u];if(D)return D;let e,t=1/0;for(const D of Object.keys(G)){const s=(n=G[D],((r=u)[0]-n[0])**2+(r[1]-n[1])**2+(r[2]-n[2])**2);s<t&&(t=s,e=D)}var r,n;return e},Q.keyword.rgb=function(u){return G[u]},Q.rgb.xyz=function(u){let D=u[0]/255,e=u[1]/255,t=u[2]/255;D=D>.04045?((D+.055)/1.055)**2.4:D/12.92,e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,t=t>.04045?((t+.055)/1.055)**2.4:t/12.92;return[100*(.4124*D+.3576*e+.1805*t),100*(.2126*D+.7152*e+.0722*t),100*(.0193*D+.1192*e+.9505*t)]},Q.rgb.lab=function(u){const D=Q.rgb.xyz(u);let e=D[0],t=D[1],r=D[2];e/=95.047,t/=100,r/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,t=t>.008856?t**(1/3):7.787*t+16/116,r=r>.008856?r**(1/3):7.787*r+16/116;return[116*t-16,500*(e-t),200*(t-r)]},Q.hsl.rgb=function(u){const D=u[0]/360,e=u[1]/100,t=u[2]/100;let r,n,s;if(0===e)return s=255*t,[s,s,s];r=t<.5?t*(1+e):t+e-t*e;const o=2*t-r,i=[0,0,0];for(let u=0;u<3;u++)n=D+1/3*-(u-1),n<0&&n++,n>1&&n--,s=6*n<1?o+6*(r-o)*n:2*n<1?r:3*n<2?o+(r-o)*(2/3-n)*6:o,i[u]=255*s;return i},Q.hsl.hsv=function(u){const D=u[0];let e=u[1]/100,t=u[2]/100,r=e;const n=Math.max(t,.01);t*=2,e*=t<=1?t:2-t,r*=n<=1?n:2-n;return[D,100*(0===t?2*r/(n+r):2*e/(t+e)),100*((t+e)/2)]},Q.hsv.rgb=function(u){const D=u[0]/60,e=u[1]/100;let t=u[2]/100;const r=Math.floor(D)%6,n=D-Math.floor(D),s=255*t*(1-e),o=255*t*(1-e*n),i=255*t*(1-e*(1-n));switch(t*=255,r){case 0:return[t,i,s];case 1:return[o,t,s];case 2:return[s,t,i];case 3:return[s,o,t];case 4:return[i,s,t];case 5:return[t,s,o]}},Q.hsv.hsl=function(u){const D=u[0],e=u[1]/100,t=u[2]/100,r=Math.max(t,.01);let n,s;s=(2-e)*t;const o=(2-e)*r;return n=e*r,n/=o<=1?o:2-o,n=n||0,s/=2,[D,100*n,100*s]},Q.hwb.rgb=function(u){const D=u[0]/360;let e=u[1]/100,t=u[2]/100;const r=e+t;let n;r>1&&(e/=r,t/=r);const s=Math.floor(6*D),o=1-t;n=6*D-s,0!=(1&s)&&(n=1-n);const i=e+n*(o-e);let a,l,c;switch(s){default:case 6:case 0:a=o,l=i,c=e;break;case 1:a=i,l=o,c=e;break;case 2:a=e,l=o,c=i;break;case 3:a=e,l=i,c=o;break;case 4:a=i,l=e,c=o;break;case 5:a=o,l=e,c=i}return[255*a,255*l,255*c]},Q.cmyk.rgb=function(u){const D=u[0]/100,e=u[1]/100,t=u[2]/100,r=u[3]/100;return[255*(1-Math.min(1,D*(1-r)+r)),255*(1-Math.min(1,e*(1-r)+r)),255*(1-Math.min(1,t*(1-r)+r))]},Q.xyz.rgb=function(u){const D=u[0]/100,e=u[1]/100,t=u[2]/100;let r,n,s;return r=3.2406*D+-1.5372*e+-.4986*t,n=-.9689*D+1.8758*e+.0415*t,s=.0557*D+-.204*e+1.057*t,r=r>.0031308?1.055*r**(1/2.4)-.055:12.92*r,n=n>.0031308?1.055*n**(1/2.4)-.055:12.92*n,s=s>.0031308?1.055*s**(1/2.4)-.055:12.92*s,r=Math.min(Math.max(0,r),1),n=Math.min(Math.max(0,n),1),s=Math.min(Math.max(0,s),1),[255*r,255*n,255*s]},Q.xyz.lab=function(u){let D=u[0],e=u[1],t=u[2];D/=95.047,e/=100,t/=108.883,D=D>.008856?D**(1/3):7.787*D+16/116,e=e>.008856?e**(1/3):7.787*e+16/116,t=t>.008856?t**(1/3):7.787*t+16/116;return[116*e-16,500*(D-e),200*(e-t)]},Q.lab.xyz=function(u){let D,e,t;e=(u[0]+16)/116,D=u[1]/500+e,t=e-u[2]/200;const r=e**3,n=D**3,s=t**3;return e=r>.008856?r:(e-16/116)/7.787,D=n>.008856?n:(D-16/116)/7.787,t=s>.008856?s:(t-16/116)/7.787,D*=95.047,e*=100,t*=108.883,[D,e,t]},Q.lab.lch=function(u){const D=u[0],e=u[1],t=u[2];let r;r=360*Math.atan2(t,e)/2/Math.PI,r<0&&(r+=360);return[D,Math.sqrt(e*e+t*t),r]},Q.lch.lab=function(u){const D=u[0],e=u[1],t=u[2]/360*2*Math.PI;return[D,e*Math.cos(t),e*Math.sin(t)]},Q.rgb.ansi16=function(u,D=null){const[e,t,r]=u;let n=null===D?Q.rgb.hsv(u)[2]:D;if(n=Math.round(n/50),0===n)return 30;let s=30+(Math.round(r/255)<<2|Math.round(t/255)<<1|Math.round(e/255));return 2===n&&(s+=60),s},Q.hsv.ansi16=function(u){return Q.rgb.ansi16(Q.hsv.rgb(u),u[2])},Q.rgb.ansi256=function(u){const D=u[0],e=u[1],t=u[2];if(D===e&&e===t)return D<8?16:D>248?231:Math.round((D-8)/247*24)+232;return 16+36*Math.round(D/255*5)+6*Math.round(e/255*5)+Math.round(t/255*5)},Q.ansi16.rgb=function(u){let D=u%10;if(0===D||7===D)return u>50&&(D+=3.5),D=D/10.5*255,[D,D,D];const e=.5*(1+~~(u>50));return[(1&D)*e*255,(D>>1&1)*e*255,(D>>2&1)*e*255]},Q.ansi256.rgb=function(u){if(u>=232){const D=10*(u-232)+8;return[D,D,D]}let D;u-=16;return[Math.floor(u/36)/5*255,Math.floor((D=u%36)/6)/5*255,D%6/5*255]},Q.rgb.hex=function(u){const D=(((255&Math.round(u[0]))<<16)+((255&Math.round(u[1]))<<8)+(255&Math.round(u[2]))).toString(16).toUpperCase();return"000000".substring(D.length)+D},Q.hex.rgb=function(u){const D=u.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!D)return[0,0,0];let e=D[0];3===D[0].length&&(e=e.split("").map(u=>u+u).join(""));const t=parseInt(e,16);return[t>>16&255,t>>8&255,255&t]},Q.rgb.hcg=function(u){const D=u[0]/255,e=u[1]/255,t=u[2]/255,r=Math.max(Math.max(D,e),t),n=Math.min(Math.min(D,e),t),s=r-n;let o,i;return o=s<1?n/(1-s):0,i=s<=0?0:r===D?(e-t)/s%6:r===e?2+(t-D)/s:4+(D-e)/s,i/=6,i%=1,[360*i,100*s,100*o]},Q.hsl.hcg=function(u){const D=u[1]/100,e=u[2]/100,t=e<.5?2*D*e:2*D*(1-e);let r=0;return t<1&&(r=(e-.5*t)/(1-t)),[u[0],100*t,100*r]},Q.hsv.hcg=function(u){const D=u[1]/100,e=u[2]/100,t=D*e;let r=0;return t<1&&(r=(e-t)/(1-t)),[u[0],100*t,100*r]},Q.hcg.rgb=function(u){const D=u[0]/360,e=u[1]/100,t=u[2]/100;if(0===e)return[255*t,255*t,255*t];const r=[0,0,0],n=D%1*6,s=n%1,o=1-s;let i=0;switch(Math.floor(n)){case 0:r[0]=1,r[1]=s,r[2]=0;break;case 1:r[0]=o,r[1]=1,r[2]=0;break;case 2:r[0]=0,r[1]=1,r[2]=s;break;case 3:r[0]=0,r[1]=o,r[2]=1;break;case 4:r[0]=s,r[1]=0,r[2]=1;break;default:r[0]=1,r[1]=0,r[2]=o}return i=(1-e)*t,[255*(e*r[0]+i),255*(e*r[1]+i),255*(e*r[2]+i)]},Q.hcg.hsv=function(u){const D=u[1]/100,e=D+u[2]/100*(1-D);let t=0;return e>0&&(t=D/e),[u[0],100*t,100*e]},Q.hcg.hsl=function(u){const D=u[1]/100,e=u[2]/100*(1-D)+.5*D;let t=0;return e>0&&e<.5?t=D/(2*e):e>=.5&&e<1&&(t=D/(2*(1-e))),[u[0],100*t,100*e]},Q.hcg.hwb=function(u){const D=u[1]/100,e=D+u[2]/100*(1-D);return[u[0],100*(e-D),100*(1-e)]},Q.hwb.hcg=function(u){const D=u[1]/100,e=1-u[2]/100,t=e-D;let r=0;return t<1&&(r=(e-t)/(1-t)),[u[0],100*t,100*r]},Q.apple.rgb=function(u){return[u[0]/65535*255,u[1]/65535*255,u[2]/65535*255]},Q.rgb.apple=function(u){return[u[0]/255*65535,u[1]/255*65535,u[2]/255*65535]},Q.gray.rgb=function(u){return[u[0]/100*255,u[0]/100*255,u[0]/100*255]},Q.gray.hsl=function(u){return[0,0,u[0]]},Q.gray.hsv=Q.gray.hsl,Q.gray.hwb=function(u){return[0,100,u[0]]},Q.gray.cmyk=function(u){return[0,0,0,u[0]]},Q.gray.lab=function(u){return[u[0],0,0]},Q.gray.hex=function(u){const D=255&Math.round(u[0]/100*255),e=((D<<16)+(D<<8)+D).toString(16).toUpperCase();return"000000".substring(e.length)+e},Q.rgb.gray=function(u){return[(u[0]+u[1]+u[2])/3/255*100]};const uu={};Object.keys(J).forEach(u=>{uu[u]={},Object.defineProperty(uu[u],"channels",{value:J[u].channels}),Object.defineProperty(uu[u],"labels",{value:J[u].labels});const D=function(u){const D=K(u),e={},t=Object.keys(D);for(let u=t.length,r=0;r<u;r++){const u=t[r];null!==D[u].parent&&(e[u]=X(u,D))}return e}(u);Object.keys(D).forEach(e=>{const t=D[e];uu[u][e]=function(u){const D=function(...D){const e=D[0];if(null==e)return e;e.length>1&&(D=e);const t=u(D);if("object"==typeof t)for(let u=t.length,D=0;D<u;D++)t[D]=Math.round(t[D]);return t};return"conversion"in u&&(D.conversion=u.conversion),D}(t),uu[u][e].raw=function(u){const D=function(...D){const e=D[0];return null==e?e:(e.length>1&&(D=e),u(D))};return"conversion"in u&&(D.conversion=u.conversion),D}(t)})});var Du=uu,eu=s((function(u){const D=(u,D)=>(...e)=>`[${u(...e)+D}m`,e=(u,D)=>(...e)=>{const t=u(...e);return`[${38+D};5;${t}m`},t=(u,D)=>(...e)=>{const t=u(...e);return`[${38+D};2;${t[0]};${t[1]};${t[2]}m`},r=u=>u,n=(u,D,e)=>[u,D,e],s=(u,D,e)=>{Object.defineProperty(u,D,{get:()=>{const t=e();return Object.defineProperty(u,D,{value:t,enumerable:!0,configurable:!0}),t},enumerable:!0,configurable:!0})};let o;const i=(u,D,e,t)=>{void 0===o&&(o=Du);const r=t?10:0,n={};for(const[t,s]of Object.entries(o)){const o="ansi16"===t?"ansi":t;t===D?n[o]=u(e,r):"object"==typeof s&&(n[o]=u(s[D],r))}return n};Object.defineProperty(u,"exports",{enumerable:!0,get:function(){const u=new Map,o={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};o.color.gray=o.color.blackBright,o.bgColor.bgGray=o.bgColor.bgBlackBright,o.color.grey=o.color.blackBright,o.bgColor.bgGrey=o.bgColor.bgBlackBright;for(const[D,e]of Object.entries(o)){for(const[D,t]of Object.entries(e))o[D]={open:`[${t[0]}m`,close:`[${t[1]}m`},e[D]=o[D],u.set(t[0],t[1]);Object.defineProperty(o,D,{value:e,enumerable:!1})}return Object.defineProperty(o,"codes",{value:u,enumerable:!1}),o.color.close="",o.bgColor.close="",s(o.color,"ansi",()=>i(D,"ansi16",r,!1)),s(o.color,"ansi256",()=>i(e,"ansi256",r,!1)),s(o.color,"ansi16m",()=>i(t,"rgb",n,!1)),s(o.bgColor,"ansi",()=>i(D,"ansi16",r,!0)),s(o.bgColor,"ansi256",()=>i(e,"ansi256",r,!0)),s(o.bgColor,"ansi16m",()=>i(t,"rgb",n,!0)),o}})})),tu=(u,D=process.argv)=>{const e=u.startsWith("-")?"":1===u.length?"-":"--",t=D.indexOf(e+u),r=D.indexOf("--");return-1!==t&&(-1===r||t<r)};const{env:ru}=process;let nu;function su(u){return 0!==u&&{level:u,hasBasic:!0,has256:u>=2,has16m:u>=3}}function ou(u,D){if(0===nu)return 0;if(tu("color=16m")||tu("color=full")||tu("color=truecolor"))return 3;if(tu("color=256"))return 2;if(u&&!D&&void 0===nu)return 0;const e=nu||0;if("dumb"===ru.TERM)return e;if("win32"===process.platform){const u=r.release().split(".");return Number(u[0])>=10&&Number(u[2])>=10586?Number(u[2])>=14931?3:2:1}if("CI"in ru)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(u=>u in ru)||"codeship"===ru.CI_NAME?1:e;if("TEAMCITY_VERSION"in ru)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ru.TEAMCITY_VERSION)?1:0;if("GITHUB_ACTIONS"in ru)return 1;if("truecolor"===ru.COLORTERM)return 3;if("TERM_PROGRAM"in ru){const u=parseInt((ru.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ru.TERM_PROGRAM){case"iTerm.app":return u>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ru.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ru.TERM)||"COLORTERM"in ru?1:e}tu("no-color")||tu("no-colors")||tu("color=false")||tu("color=never")?nu=0:(tu("color")||tu("colors")||tu("color=true")||tu("color=always"))&&(nu=1),"FORCE_COLOR"in ru&&(nu="true"===ru.FORCE_COLOR?1:"false"===ru.FORCE_COLOR?0:0===ru.FORCE_COLOR.length?1:Math.min(parseInt(ru.FORCE_COLOR,10),3));var iu={supportsColor:function(u){return su(ou(u,u&&u.isTTY))},stdout:su(ou(!0,n.isatty(1))),stderr:su(ou(!0,n.isatty(2)))};var au={stringReplaceAll:(u,D,e)=>{let t=u.indexOf(D);if(-1===t)return u;const r=D.length;let n=0,s="";do{s+=u.substr(n,t-n)+D+e,n=t+r,t=u.indexOf(D,n)}while(-1!==t);return s+=u.substr(n),s},stringEncaseCRLFWithFirstIndex:(u,D,e,t)=>{let r=0,n="";do{const s="\r"===u[t-1];n+=u.substr(r,(s?t-1:t)-r)+D+(s?"\r\n":"\n")+e,r=t+1,t=u.indexOf("\n",r)}while(-1!==t);return n+=u.substr(r),n}};const lu=/(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,cu=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,hu=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,Fu=/\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi,Cu=new Map([["n","\n"],["r","\r"],["t","\t"],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e",""],["a",""]]);function fu(u){const D="u"===u[0],e="{"===u[1];return D&&!e&&5===u.length||"x"===u[0]&&3===u.length?String.fromCharCode(parseInt(u.slice(1),16)):D&&e?String.fromCodePoint(parseInt(u.slice(2,-1),16)):Cu.get(u)||u}function Eu(u,D){const e=[],t=D.trim().split(/\s*,\s*/g);let r;for(const D of t){const t=Number(D);if(Number.isNaN(t)){if(!(r=D.match(hu)))throw new Error(`Invalid Chalk template style argument: ${D} (in style '${u}')`);e.push(r[2].replace(Fu,(u,D,e)=>D?fu(D):e))}else e.push(t)}return e}function gu(u){cu.lastIndex=0;const D=[];let e;for(;null!==(e=cu.exec(u));){const u=e[1];if(e[2]){const t=Eu(u,e[2]);D.push([u].concat(t))}else D.push([u])}return D}function du(u,D){const e={};for(const u of D)for(const D of u.styles)e[D[0]]=u.inverse?null:D.slice(1);let t=u;for(const[u,D]of Object.entries(e))if(Array.isArray(D)){if(!(u in t))throw new Error("Unknown Chalk style: "+u);t=D.length>0?t[u](...D):t[u]}return t}var pu=(u,D)=>{const e=[],t=[];let r=[];if(D.replace(lu,(D,n,s,o,i,a)=>{if(n)r.push(fu(n));else if(o){const D=r.join("");r=[],t.push(0===e.length?D:du(u,e)(D)),e.push({inverse:s,styles:gu(o)})}else if(i){if(0===e.length)throw new Error("Found extraneous } in Chalk template literal");t.push(du(u,e)(r.join(""))),r=[],e.pop()}else r.push(a)}),t.push(r.join("")),e.length>0){const u=`Chalk template literal is missing ${e.length} closing bracket${1===e.length?"":"s"} (\`}\`)`;throw new Error(u)}return t.join("")};const{stdout:mu,stderr:bu}=iu,{stringReplaceAll:yu,stringEncaseCRLFWithFirstIndex:Bu}=au,vu=["ansi","ansi","ansi256","ansi16m"],_u=Object.create(null);class Au{constructor(u){return wu(u)}}const wu=u=>{const D={};return((u,D={})=>{if(D.level&&!(Number.isInteger(D.level)&&D.level>=0&&D.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const e=mu?mu.level:0;u.level=void 0===D.level?e:D.level})(D,u),D.template=(...u)=>Lu(D.template,...u),Object.setPrototypeOf(D,Ou.prototype),Object.setPrototypeOf(D.template,D),D.template.constructor=()=>{throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.")},D.template.Instance=Au,D.template};function Ou(u){return wu(u)}for(const[u,D]of Object.entries(eu))_u[u]={get(){const e=ku(this,Iu(D.open,D.close,this._styler),this._isEmpty);return Object.defineProperty(this,u,{value:e}),e}};_u.visible={get(){const u=ku(this,this._styler,!0);return Object.defineProperty(this,"visible",{value:u}),u}};const Mu=["rgb","hex","keyword","hsl","hsv","hwb","ansi","ansi256"];for(const u of Mu)_u[u]={get(){const{level:D}=this;return function(...e){const t=Iu(eu.color[vu[D]][u](...e),eu.color.close,this._styler);return ku(this,t,this._isEmpty)}}};for(const u of Mu){_u["bg"+u[0].toUpperCase()+u.slice(1)]={get(){const{level:D}=this;return function(...e){const t=Iu(eu.bgColor[vu[D]][u](...e),eu.bgColor.close,this._styler);return ku(this,t,this._isEmpty)}}}}const Su=Object.defineProperties(()=>{},{..._u,level:{enumerable:!0,get(){return this._generator.level},set(u){this._generator.level=u}}}),Iu=(u,D,e)=>{let t,r;return void 0===e?(t=u,r=D):(t=e.openAll+u,r=D+e.closeAll),{open:u,close:D,openAll:t,closeAll:r,parent:e}},ku=(u,D,e)=>{const t=(...u)=>Ru(t,1===u.length?""+u[0]:u.join(" "));return Object.setPrototypeOf(t,Su),t._generator=u,t._styler=D,t._isEmpty=e,t},Ru=(u,D)=>{if(u.level<=0||!D)return u._isEmpty?"":D;let e=u._styler;if(void 0===e)return D;const{openAll:t,closeAll:r}=e;if(-1!==D.indexOf(""))for(;void 0!==e;)D=yu(D,e.close,e.open),e=e.parent;const n=D.indexOf("\n");return-1!==n&&(D=Bu(D,r,t,n)),t+D+r};let Tu;const Lu=(u,...D)=>{const[e]=D;if(!Array.isArray(e))return D.join(" ");const t=D.slice(1),r=[e.raw[0]];for(let u=1;u<e.length;u++)r.push(String(t[u-1]).replace(/[{}\\]/g,"\\$&"),String(e.raw[u]));return void 0===Tu&&(Tu=pu),Tu(u,r.join(""))};Object.defineProperties(Ou.prototype,_u);const $u=Ou();$u.supportsColor=mu,$u.stderr=Ou({level:bu?bu.level:0}),$u.stderr.supportsColor=bu;var xu=$u;const ju={};function Uu(u){let D=ju[u];return D||(D="#"===u[0]?xu.hex(u):xu[u]||xu.keyword(u),ju[u]=D,D)}const Pu={};const Nu={info:"cyan"},qu={0:"red",1:"yellow",2:"white",3:"green"},Yu={secondaryColor:"grey",formatOptions:{colors:!0,compact:!1}},Hu={info:H("ℹ"),success:H("✔"),debug:H("›"),trace:H("›"),log:""};class Vu extends S{constructor(u){super(Object.assign({},Yu,u))}formatStack(u){const D=Uu("grey"),e=Uu("cyan");return"\n"+A(u).map(u=>" "+u.replace(/^at +/,u=>D(u)).replace(/\((.+)\)/,(u,D)=>`(${e(D)})`)).join("\n")}formatType(u,D){const e=Nu[u.type]||qu[u.level]||this.options.secondaryColor;if(D)return function(u){let D=Pu[u];return D||(D="#"===u[0]?xu.bgHex(u):xu["bg"+u[0].toUpperCase()+u.slice(1)]||xu.bgKeyword(u),Pu[u]=D,D)}(e).black(` ${u.type.toUpperCase()} `);const t="string"==typeof Hu[u.type]?Hu[u.type]:u.icon||u.type;return t?Uu(e)(t):""}formatLogObj(u,{width:D}){const[e,...t]=this.formatArgs(u.args).split("\n"),r=void 0!==u.badge?Boolean(u.badge):u.level<2,n=Uu(this.options.secondaryColor),s=n(this.formatDate(u.date)),o=this.formatType(u,r),i=u.tag?n(u.tag):"",a=e.replace(/`([^`]+)`/g,(u,D)=>xu.cyan(D));let l;const c=this.filterAndJoin([o,a]),h=this.filterAndJoin([i,s]),F=D-$(c)-$(h)-2;return l=F>0&&D>=80?c+" ".repeat(F)+h:c,l+=t.length?"\n"+t.join("\n"):"",r?"\n"+l+"\n":l}}class Wu{constructor({stream:u}={}){this.stream=u||process.stdout}log(u){this.stream.write(JSON.stringify(u)+"\n")}}const Gu="undefined"!=typeof __non_webpack_require__?__non_webpack_require__:require;class zu{constructor(u){if(u&&u.log)this.logger=u;else{const D=Gu("winston");this.logger=D.createLogger(Object.assign({level:"info",format:D.format.simple(),transports:[new D.transports.Console]},u))}}log(u){const D=[].concat(u.args),e=D.shift();this.logger.log({level:Qu[u.level]||"info",label:u.tag,message:e,args:D,timestamp:u.date.getTime()/1e3})}}const Qu={0:"error",1:"warn",2:"info",3:"verbose",4:"debug",5:"silly"};global.consola||(global.consola=function(){let u=p.debug?4:3;process.env.CONSOLA_LEVEL&&(u=parseInt(process.env.CONSOLA_LEVEL)||u);const D=new _({level:u,reporters:[p.ci||p.test?new S:new Vu]});return D.Consola=_,D.BasicReporter=S,D.FancyReporter=Vu,D.JSONReporter=Wu,D.WinstonReporter=zu,D.LogLevel=m,D}());var Ju=global.consola;module.exports=Ju;
import React from "react"; import css from "./CardText.css"; const CardText = ({ item, limitTitle, limitVenue, setEventPrice, ticketMasterCategories }) => { return ( <div className={`searchResultCardTextWrapper ${css.searchResultCardTextWrapper}`} > <ul className={`itemText ${css.itemText}`}> <li className={`itemTitle ${css.itemTitle}`}> <a href={item.url} target="_blank"> {limitTitle(item.name)} </a> </li> {ticketMasterCategories(item)} {parseTicketMasterTime(item)} <li className={`itemDetails ${css.itemDetails}`}> {limitVenue(item._embedded.venues[0].name)} </li> {setEventPrice(item)} </ul> </div> ); }; export default CardText;
export default { cartLength(state){ return state.shops.length }, cartList(state){ return state.shops } }
import { handleBugs } from './bug.js' // Add `error.config` and `error.errors` to every error // Also mark exceptions that are probably bugs as such export const topLevelHandler = function(error, config) { // eslint-disable-next-line fp/no-mutation, no-param-reassign error.config = config const errorA = handleBugs({ error }) throw errorA }
var postcss = require('postcss'); module.exports = postcss.plugin('pseudoelements', function(options) { options = options || {}; var selectors = options.selectors || [ 'before', 'after', 'first-letter', 'first-line' ] var replacements = new RegExp('::(' + selectors.join('|') + ')', 'gi'); return function(css) { css.walkRules(function(rule) { rule.selector = rule.selector.replace(replacements, ':$1'); }); } });