code
stringlengths
2
1.05M
module.exports = require('./register')().Promise
/*! * # Semantic UI 2.2.4 - Visibility * http://github.com/semantic-org/semantic-ui/ * * * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { "use strict"; window = (typeof window != 'undefined' && window.Math == Math) ? window : (typeof self != 'undefined' && self.Math == Math) ? self : Function('return this')() ; $.fn.visibility = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue, moduleCount = $allModules.length, loadedCount = 0 ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.visibility.settings, parameters) : $.extend({}, $.fn.visibility.settings), className = settings.className, namespace = settings.namespace, error = settings.error, metadata = settings.metadata, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $window = $(window), $module = $(this), $context = $(settings.context), $placeholder, selector = $module.selector || '', instance = $module.data(moduleNamespace), requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); }, element = this, disabled = false, contextObserver, observer, module ; module = { initialize: function() { module.debug('Initializing', settings); module.setup.cache(); if( module.should.trackChanges() ) { if(settings.type == 'image') { module.setup.image(); } if(settings.type == 'fixed') { module.setup.fixed(); } if(settings.observeChanges) { module.observeChanges(); } module.bind.events(); } module.save.position(); if( !module.is.visible() ) { module.error(error.visible, $module); } if(settings.initialCheck) { module.checkVisibility(); } module.instantiate(); }, instantiate: function() { module.debug('Storing instance', module); $module .data(moduleNamespace, module) ; instance = module; }, destroy: function() { module.verbose('Destroying previous module'); if(observer) { observer.disconnect(); } if(contextObserver) { contextObserver.disconnect(); } $window .off('load' + eventNamespace, module.event.load) .off('resize' + eventNamespace, module.event.resize) ; $context .off('scroll' + eventNamespace, module.event.scroll) .off('scrollchange' + eventNamespace, module.event.scrollchange) ; if(settings.type == 'fixed') { module.resetFixed(); module.remove.placeholder(); } $module .off(eventNamespace) .removeData(moduleNamespace) ; }, observeChanges: function() { if('MutationObserver' in window) { contextObserver = new MutationObserver(module.event.contextChanged); observer = new MutationObserver(module.event.changed); contextObserver.observe(document, { childList : true, subtree : true }); observer.observe(element, { childList : true, subtree : true }); module.debug('Setting up mutation observer', observer); } }, bind: { events: function() { module.verbose('Binding visibility events to scroll and resize'); if(settings.refreshOnLoad) { $window .on('load' + eventNamespace, module.event.load) ; } $window .on('resize' + eventNamespace, module.event.resize) ; // pub/sub pattern $context .off('scroll' + eventNamespace) .on('scroll' + eventNamespace, module.event.scroll) .on('scrollchange' + eventNamespace, module.event.scrollchange) ; } }, event: { changed: function(mutations) { module.verbose('DOM tree modified, updating visibility calculations'); module.timer = setTimeout(function() { module.verbose('DOM tree modified, updating sticky menu'); module.refresh(); }, 100); }, contextChanged: function(mutations) { [].forEach.call(mutations, function(mutation) { if(mutation.removedNodes) { [].forEach.call(mutation.removedNodes, function(node) { if(node == element || $(node).find(element).length > 0) { module.debug('Element removed from DOM, tearing down events'); module.destroy(); } }); } }); }, resize: function() { module.debug('Window resized'); if(settings.refreshOnResize) { requestAnimationFrame(module.refresh); } }, load: function() { module.debug('Page finished loading'); requestAnimationFrame(module.refresh); }, // publishes scrollchange event on one scroll scroll: function() { if(settings.throttle) { clearTimeout(module.timer); module.timer = setTimeout(function() { $context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]); }, settings.throttle); } else { requestAnimationFrame(function() { $context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]); }); } }, // subscribes to scrollchange scrollchange: function(event, scrollPosition) { module.checkVisibility(scrollPosition); }, }, precache: function(images, callback) { if (!(images instanceof Array)) { images = [images]; } var imagesLength = images.length, loadedCounter = 0, cache = [], cacheImage = document.createElement('img'), handleLoad = function() { loadedCounter++; if (loadedCounter >= images.length) { if ($.isFunction(callback)) { callback(); } } } ; while (imagesLength--) { cacheImage = document.createElement('img'); cacheImage.onload = handleLoad; cacheImage.onerror = handleLoad; cacheImage.src = images[imagesLength]; cache.push(cacheImage); } }, enableCallbacks: function() { module.debug('Allowing callbacks to occur'); disabled = false; }, disableCallbacks: function() { module.debug('Disabling all callbacks temporarily'); disabled = true; }, should: { trackChanges: function() { if(methodInvoked) { module.debug('One time query, no need to bind events'); return false; } module.debug('Callbacks being attached'); return true; } }, setup: { cache: function() { module.cache = { occurred : {}, screen : {}, element : {}, }; }, image: function() { var src = $module.data(metadata.src) ; if(src) { module.verbose('Lazy loading image', src); settings.once = true; settings.observeChanges = false; // show when top visible settings.onOnScreen = function() { module.debug('Image on screen', element); module.precache(src, function() { module.set.image(src, function() { loadedCount++; if(loadedCount == moduleCount) { settings.onAllLoaded.call(this); } settings.onLoad.call(this); }); }); }; } }, fixed: function() { module.debug('Setting up fixed'); settings.once = false; settings.observeChanges = false; settings.initialCheck = true; settings.refreshOnLoad = true; if(!parameters.transition) { settings.transition = false; } module.create.placeholder(); module.debug('Added placeholder', $placeholder); settings.onTopPassed = function() { module.debug('Element passed, adding fixed position', $module); module.show.placeholder(); module.set.fixed(); if(settings.transition) { if($.fn.transition !== undefined) { $module.transition(settings.transition, settings.duration); } } }; settings.onTopPassedReverse = function() { module.debug('Element returned to position, removing fixed', $module); module.hide.placeholder(); module.remove.fixed(); }; } }, create: { placeholder: function() { module.verbose('Creating fixed position placeholder'); $placeholder = $module .clone(false) .css('display', 'none') .addClass(className.placeholder) .insertAfter($module) ; } }, show: { placeholder: function() { module.verbose('Showing placeholder'); $placeholder .css('display', 'block') .css('visibility', 'hidden') ; } }, hide: { placeholder: function() { module.verbose('Hiding placeholder'); $placeholder .css('display', 'none') .css('visibility', '') ; } }, set: { fixed: function() { module.verbose('Setting element to fixed position'); $module .addClass(className.fixed) .css({ position : 'fixed', top : settings.offset + 'px', left : 'auto', zIndex : settings.zIndex }) ; settings.onFixed.call(element); }, image: function(src, callback) { $module .attr('src', src) ; if(settings.transition) { if( $.fn.transition !== undefined ) { $module.transition(settings.transition, settings.duration, callback); } else { $module.fadeIn(settings.duration, callback); } } else { $module.show(); } } }, is: { onScreen: function() { var calculations = module.get.elementCalculations() ; return calculations.onScreen; }, offScreen: function() { var calculations = module.get.elementCalculations() ; return calculations.offScreen; }, visible: function() { if(module.cache && module.cache.element) { return !(module.cache.element.width === 0 && module.cache.element.offset.top === 0); } return false; } }, refresh: function() { module.debug('Refreshing constants (width/height)'); if(settings.type == 'fixed') { module.resetFixed(); } module.reset(); module.save.position(); if(settings.checkOnRefresh) { module.checkVisibility(); } settings.onRefresh.call(element); }, resetFixed: function () { module.remove.fixed(); module.remove.occurred(); }, reset: function() { module.verbose('Resetting all cached values'); if( $.isPlainObject(module.cache) ) { module.cache.screen = {}; module.cache.element = {}; } }, checkVisibility: function(scroll) { module.verbose('Checking visibility of element', module.cache.element); if( !disabled && module.is.visible() ) { // save scroll position module.save.scroll(scroll); // update calculations derived from scroll module.save.calculations(); // percentage module.passed(); // reverse (must be first) module.passingReverse(); module.topVisibleReverse(); module.bottomVisibleReverse(); module.topPassedReverse(); module.bottomPassedReverse(); // one time module.onScreen(); module.offScreen(); module.passing(); module.topVisible(); module.bottomVisible(); module.topPassed(); module.bottomPassed(); // on update callback if(settings.onUpdate) { settings.onUpdate.call(element, module.get.elementCalculations()); } } }, passed: function(amount, newCallback) { var calculations = module.get.elementCalculations(), amountInPixels ; // assign callback if(amount && newCallback) { settings.onPassed[amount] = newCallback; } else if(amount !== undefined) { return (module.get.pixelsPassed(amount) > calculations.pixelsPassed); } else if(calculations.passing) { $.each(settings.onPassed, function(amount, callback) { if(calculations.bottomVisible || calculations.pixelsPassed > module.get.pixelsPassed(amount)) { module.execute(callback, amount); } else if(!settings.once) { module.remove.occurred(callback); } }); } }, onScreen: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onOnScreen, callbackName = 'onScreen' ; if(newCallback) { module.debug('Adding callback for onScreen', newCallback); settings.onOnScreen = newCallback; } if(calculations.onScreen) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback !== undefined) { return calculations.onOnScreen; } }, offScreen: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onOffScreen, callbackName = 'offScreen' ; if(newCallback) { module.debug('Adding callback for offScreen', newCallback); settings.onOffScreen = newCallback; } if(calculations.offScreen) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback !== undefined) { return calculations.onOffScreen; } }, passing: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onPassing, callbackName = 'passing' ; if(newCallback) { module.debug('Adding callback for passing', newCallback); settings.onPassing = newCallback; } if(calculations.passing) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback !== undefined) { return calculations.passing; } }, topVisible: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onTopVisible, callbackName = 'topVisible' ; if(newCallback) { module.debug('Adding callback for top visible', newCallback); settings.onTopVisible = newCallback; } if(calculations.topVisible) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return calculations.topVisible; } }, bottomVisible: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onBottomVisible, callbackName = 'bottomVisible' ; if(newCallback) { module.debug('Adding callback for bottom visible', newCallback); settings.onBottomVisible = newCallback; } if(calculations.bottomVisible) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return calculations.bottomVisible; } }, topPassed: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onTopPassed, callbackName = 'topPassed' ; if(newCallback) { module.debug('Adding callback for top passed', newCallback); settings.onTopPassed = newCallback; } if(calculations.topPassed) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return calculations.topPassed; } }, bottomPassed: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onBottomPassed, callbackName = 'bottomPassed' ; if(newCallback) { module.debug('Adding callback for bottom passed', newCallback); settings.onBottomPassed = newCallback; } if(calculations.bottomPassed) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return calculations.bottomPassed; } }, passingReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onPassingReverse, callbackName = 'passingReverse' ; if(newCallback) { module.debug('Adding callback for passing reverse', newCallback); settings.onPassingReverse = newCallback; } if(!calculations.passing) { if(module.get.occurred('passing')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback !== undefined) { return !calculations.passing; } }, topVisibleReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onTopVisibleReverse, callbackName = 'topVisibleReverse' ; if(newCallback) { module.debug('Adding callback for top visible reverse', newCallback); settings.onTopVisibleReverse = newCallback; } if(!calculations.topVisible) { if(module.get.occurred('topVisible')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return !calculations.topVisible; } }, bottomVisibleReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onBottomVisibleReverse, callbackName = 'bottomVisibleReverse' ; if(newCallback) { module.debug('Adding callback for bottom visible reverse', newCallback); settings.onBottomVisibleReverse = newCallback; } if(!calculations.bottomVisible) { if(module.get.occurred('bottomVisible')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return !calculations.bottomVisible; } }, topPassedReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onTopPassedReverse, callbackName = 'topPassedReverse' ; if(newCallback) { module.debug('Adding callback for top passed reverse', newCallback); settings.onTopPassedReverse = newCallback; } if(!calculations.topPassed) { if(module.get.occurred('topPassed')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return !calculations.onTopPassed; } }, bottomPassedReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onBottomPassedReverse, callbackName = 'bottomPassedReverse' ; if(newCallback) { module.debug('Adding callback for bottom passed reverse', newCallback); settings.onBottomPassedReverse = newCallback; } if(!calculations.bottomPassed) { if(module.get.occurred('bottomPassed')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return !calculations.bottomPassed; } }, execute: function(callback, callbackName) { var calculations = module.get.elementCalculations(), screen = module.get.screenCalculations() ; callback = callback || false; if(callback) { if(settings.continuous) { module.debug('Callback being called continuously', callbackName, calculations); callback.call(element, calculations, screen); } else if(!module.get.occurred(callbackName)) { module.debug('Conditions met', callbackName, calculations); callback.call(element, calculations, screen); } } module.save.occurred(callbackName); }, remove: { fixed: function() { module.debug('Removing fixed position'); $module .removeClass(className.fixed) .css({ position : '', top : '', left : '', zIndex : '' }) ; settings.onUnfixed.call(element); }, placeholder: function() { module.debug('Removing placeholder content'); if($placeholder) { $placeholder.remove(); } }, occurred: function(callback) { if(callback) { var occurred = module.cache.occurred ; if(occurred[callback] !== undefined && occurred[callback] === true) { module.debug('Callback can now be called again', callback); module.cache.occurred[callback] = false; } } else { module.cache.occurred = {}; } } }, save: { calculations: function() { module.verbose('Saving all calculations necessary to determine positioning'); module.save.direction(); module.save.screenCalculations(); module.save.elementCalculations(); }, occurred: function(callback) { if(callback) { if(module.cache.occurred[callback] === undefined || (module.cache.occurred[callback] !== true)) { module.verbose('Saving callback occurred', callback); module.cache.occurred[callback] = true; } } }, scroll: function(scrollPosition) { scrollPosition = scrollPosition + settings.offset || $context.scrollTop() + settings.offset; module.cache.scroll = scrollPosition; }, direction: function() { var scroll = module.get.scroll(), lastScroll = module.get.lastScroll(), direction ; if(scroll > lastScroll && lastScroll) { direction = 'down'; } else if(scroll < lastScroll && lastScroll) { direction = 'up'; } else { direction = 'static'; } module.cache.direction = direction; return module.cache.direction; }, elementPosition: function() { var element = module.cache.element, screen = module.get.screenSize() ; module.verbose('Saving element position'); // (quicker than $.extend) element.fits = (element.height < screen.height); element.offset = $module.offset(); element.width = $module.outerWidth(); element.height = $module.outerHeight(); // store module.cache.element = element; return element; }, elementCalculations: function() { var screen = module.get.screenCalculations(), element = module.get.elementPosition() ; // offset if(settings.includeMargin) { element.margin = {}; element.margin.top = parseInt($module.css('margin-top'), 10); element.margin.bottom = parseInt($module.css('margin-bottom'), 10); element.top = element.offset.top - element.margin.top; element.bottom = element.offset.top + element.height + element.margin.bottom; } else { element.top = element.offset.top; element.bottom = element.offset.top + element.height; } // visibility element.topVisible = (screen.bottom >= element.top); element.topPassed = (screen.top >= element.top); element.bottomVisible = (screen.bottom >= element.bottom); element.bottomPassed = (screen.top >= element.bottom); element.pixelsPassed = 0; element.percentagePassed = 0; // meta calculations element.onScreen = (element.topVisible && !element.bottomPassed); element.passing = (element.topPassed && !element.bottomPassed); element.offScreen = (!element.onScreen); // passing calculations if(element.passing) { element.pixelsPassed = (screen.top - element.top); element.percentagePassed = (screen.top - element.top) / element.height; } module.cache.element = element; module.verbose('Updated element calculations', element); return element; }, screenCalculations: function() { var scroll = module.get.scroll() ; module.save.direction(); module.cache.screen.top = scroll; module.cache.screen.bottom = scroll + module.cache.screen.height; return module.cache.screen; }, screenSize: function() { module.verbose('Saving window position'); module.cache.screen = { height: $context.height() }; }, position: function() { module.save.screenSize(); module.save.elementPosition(); } }, get: { pixelsPassed: function(amount) { var element = module.get.elementCalculations() ; if(amount.search('%') > -1) { return ( element.height * (parseInt(amount, 10) / 100) ); } return parseInt(amount, 10); }, occurred: function(callback) { return (module.cache.occurred !== undefined) ? module.cache.occurred[callback] || false : false ; }, direction: function() { if(module.cache.direction === undefined) { module.save.direction(); } return module.cache.direction; }, elementPosition: function() { if(module.cache.element === undefined) { module.save.elementPosition(); } return module.cache.element; }, elementCalculations: function() { if(module.cache.element === undefined) { module.save.elementCalculations(); } return module.cache.element; }, screenCalculations: function() { if(module.cache.screen === undefined) { module.save.screenCalculations(); } return module.cache.screen; }, screenSize: function() { if(module.cache.screen === undefined) { module.save.screenSize(); } return module.cache.screen; }, scroll: function() { if(module.cache.scroll === undefined) { module.save.scroll(); } return module.cache.scroll; }, lastScroll: function() { if(module.cache.screen === undefined) { module.debug('First scroll event, no last scroll could be found'); return false; } return module.cache.screen.top; } }, setting: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(!settings.silent && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(!settings.silent && settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { if(!settings.silent) { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); } }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } instance.save.scroll(); instance.save.calculations(); module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.visibility.settings = { name : 'Visibility', namespace : 'visibility', debug : false, verbose : false, performance : true, // whether to use mutation observers to follow changes observeChanges : true, // check position immediately on init initialCheck : true, // whether to refresh calculations after all page images load refreshOnLoad : true, // whether to refresh calculations after page resize event refreshOnResize : true, // should call callbacks on refresh event (resize, etc) checkOnRefresh : true, // callback should only occur one time once : true, // callback should fire continuously whe evaluates to true continuous : false, // offset to use with scroll top offset : 0, // whether to include margin in elements position includeMargin : false, // scroll context for visibility checks context : window, // visibility check delay in ms (defaults to animationFrame) throttle : false, // special visibility type (image, fixed) type : false, // z-index to use with visibility 'fixed' zIndex : '10', // image only animation settings transition : 'fade in', duration : 1000, // array of callbacks for percentage onPassed : {}, // standard callbacks onOnScreen : false, onOffScreen : false, onPassing : false, onTopVisible : false, onBottomVisible : false, onTopPassed : false, onBottomPassed : false, // reverse callbacks onPassingReverse : false, onTopVisibleReverse : false, onBottomVisibleReverse : false, onTopPassedReverse : false, onBottomPassedReverse : false, // special callbacks for image onLoad : function() {}, onAllLoaded : function() {}, // special callbacks for fixed position onFixed : function() {}, onUnfixed : function() {}, // utility callbacks onUpdate : false, // disabled by default for performance onRefresh : function(){}, metadata : { src: 'src' }, className: { fixed : 'fixed', placeholder : 'placeholder' }, error : { method : 'The method you called is not defined.', visible : 'Element is hidden, you must call refresh after element becomes visible' } }; })( jQuery, window, document );
/*globals describe, beforeEach, afterEach, it*/ var rewire = require('rewire'), ampController = rewire('../lib/router'), path = require('path'), sinon = require('sinon'), Promise = require('bluebird'), errors = require('../../../errors'), should = require('should'), configUtils = require('../../../../test/utils/configUtils'), sandbox = sinon.sandbox.create(); // Helper function to prevent unit tests // from failing via timeout when they // should just immediately fail function failTest(done) { return function (err) { done(err); }; } describe('AMP Controller', function () { var res, req, defaultPath, setResponseContextStub; beforeEach(function () { res = { render: sandbox.spy(), locals: { context: ['amp', 'post'] } }; req = { app: {get: function () { return 'casper'; }}, route: {path: '/'}, query: {r: ''}, params: {}, body: {} }; defaultPath = path.join(configUtils.config.paths.appRoot, '/core/server/apps/amp/lib/views/amp.hbs'); configUtils.set({ theme: { permalinks: '/:slug/' } }); }); afterEach(function () { sandbox.restore(); configUtils.restore(); }); it('should render default amp page when theme has no amp template', function (done) { configUtils.set({paths: {availableThemes: {casper: {}}}}); setResponseContextStub = sandbox.stub(); ampController.__set__('setResponseContext', setResponseContextStub); res.render = function (view) { view.should.eql(defaultPath); done(); }; ampController.controller(req, res, failTest(done)); }); it('should render theme amp page when theme has amp template', function (done) { configUtils.set({paths: {availableThemes: {casper: { 'amp.hbs': '/content/themes/casper/amp.hbs' }}}}); setResponseContextStub = sandbox.stub(); ampController.__set__('setResponseContext', setResponseContextStub); res.render = function (view) { view.should.eql('amp'); done(); }; ampController.controller(req, res, failTest(done)); }); it('should render with error when error is passed in', function (done) { configUtils.set({paths: {availableThemes: {casper: {}}}}); res.error = 'Test Error'; setResponseContextStub = sandbox.stub(); ampController.__set__('setResponseContext', setResponseContextStub); res.render = function (view, context) { view.should.eql(defaultPath); context.should.eql({error: 'Test Error'}); done(); }; ampController.controller(req, res, failTest(done)); }); it('does not render amp page when amp context is missing', function (done) { var renderSpy; configUtils.set({paths: {availableThemes: {casper: {}}}}); setResponseContextStub = sandbox.stub(); ampController.__set__('setResponseContext', setResponseContextStub); res.locals.context = ['post']; res.render = sandbox.spy(function () { done(); }); renderSpy = res.render; ampController.controller(req, res, failTest(done)); renderSpy.called.should.be.false(); }); it('does not render amp page when context is other than amp and post', function (done) { var renderSpy; configUtils.set({paths: {availableThemes: {casper: {}}}}); setResponseContextStub = sandbox.stub(); ampController.__set__('setResponseContext', setResponseContextStub); res.locals.context = ['amp', 'page']; res.render = sandbox.spy(function () { done(); }); renderSpy = res.render; ampController.controller(req, res, failTest(done)); renderSpy.called.should.be.false(); }); }); describe('AMP getPostData', function () { var res, req, postLookupStub, next; beforeEach(function () { res = { locals: { relativeUrl: '/welcome-to-ghost/amp/' } }; req = { body: { post: {} } }; next = function () {}; }); afterEach(function () { sandbox.restore(); }); it('should successfully get the post data from slug', function (done) { postLookupStub = sandbox.stub(); postLookupStub.returns(new Promise.resolve({ post: { id: '1', slug: 'welcome-to-ghost', isAmpURL: true } })); ampController.__set__('postLookup', postLookupStub); ampController.getPostData(req, res, function () { req.body.post.should.be.eql({ id: '1', slug: 'welcome-to-ghost', isAmpURL: true } ); done(); }); }); it('should return error if postlookup returns NotFoundError', function (done) { postLookupStub = sandbox.stub(); postLookupStub.returns(new Promise.reject(new errors.NotFoundError('not found'))); ampController.__set__('postLookup', postLookupStub); ampController.getPostData(req, res, function (err) { should.exist(err); should.exist(err.message); should.exist(err.statusCode); should.exist(err.errorType); err.message.should.be.eql('not found'); err.statusCode.should.be.eql(404); err.errorType.should.be.eql('NotFoundError'); req.body.post.should.be.eql({}); done(); }); }); it('should return error and if postlookup returns error', function (done) { postLookupStub = sandbox.stub(); postLookupStub.returns(new Promise.reject('not found')); ampController.__set__('postLookup', postLookupStub); ampController.getPostData(req, res, function (err) { should.exist(err); err.should.be.eql('not found'); req.body.post.should.be.eql({}); done(); }); }); });
YUI.add('dd-drag', function(Y) { /** * Provides the ability to drag a Node. * @module dd * @submodule dd-drag */ /** * Provides the ability to drag a Node. * @class Drag * @extends Base * @constructor * @namespace DD */ var DDM = Y.DD.DDM, NODE = 'node', DRAGGING = 'dragging', DRAG_NODE = 'dragNode', OFFSET_HEIGHT = 'offsetHeight', OFFSET_WIDTH = 'offsetWidth', /** * @event drag:mouseup * @description Handles the mouseup DOM event, does nothing internally just fires. * @bubbles DDM * @type {CustomEvent} */ /** * @event drag:mouseDown * @description Handles the mousedown DOM event, checks to see if you have a valid handle then starts the drag timers. * @preventable _defMouseDownFn * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl><dt>ev</dt><dd>The original mousedown event.</dd></dl> * @bubbles DDM * @type {CustomEvent} */ EV_MOUSE_DOWN = 'drag:mouseDown', /** * @event drag:afterMouseDown * @description Fires after the mousedown event has been cleared. * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl><dt>ev</dt><dd>The original mousedown event.</dd></dl> * @bubbles DDM * @type {CustomEvent} */ EV_AFTER_MOUSE_DOWN = 'drag:afterMouseDown', /** * @event drag:removeHandle * @description Fires after a handle is removed. * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl><dt>handle</dt><dd>The handle that was removed.</dd></dl> * @bubbles DDM * @type {CustomEvent} */ EV_REMOVE_HANDLE = 'drag:removeHandle', /** * @event drag:addHandle * @description Fires after a handle is added. * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl><dt>handle</dt><dd>The handle that was added.</dd></dl> * @bubbles DDM * @type {CustomEvent} */ EV_ADD_HANDLE = 'drag:addHandle', /** * @event drag:removeInvalid * @description Fires after an invalid selector is removed. * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl><dt>handle</dt><dd>The handle that was removed.</dd></dl> * @bubbles DDM * @type {CustomEvent} */ EV_REMOVE_INVALID = 'drag:removeInvalid', /** * @event drag:addInvalid * @description Fires after an invalid selector is added. * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl><dt>handle</dt><dd>The handle that was added.</dd></dl> * @bubbles DDM * @type {CustomEvent} */ EV_ADD_INVALID = 'drag:addInvalid', /** * @event drag:start * @description Fires at the start of a drag operation. * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl> * <dt>pageX</dt><dd>The original node position X.</dd> * <dt>pageY</dt><dd>The original node position Y.</dd> * <dt>startTime</dt><dd>The startTime of the event. getTime on the current Date object.</dd> * </dl> * @bubbles DDM * @type {CustomEvent} */ EV_START = 'drag:start', /** * @event drag:end * @description Fires at the end of a drag operation. * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl> * <dt>pageX</dt><dd>The current node position X.</dd> * <dt>pageY</dt><dd>The current node position Y.</dd> * <dt>startTime</dt><dd>The startTime of the event, from the start event.</dd> * <dt>endTime</dt><dd>The endTime of the event. getTime on the current Date object.</dd> * </dl> * @bubbles DDM * @type {CustomEvent} */ EV_END = 'drag:end', /** * @event drag:drag * @description Fires every mousemove during a drag operation. * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl> * <dt>pageX</dt><dd>The current node position X.</dd> * <dt>pageY</dt><dd>The current node position Y.</dd> * <dt>scroll</dt><dd>Should a scroll action occur.</dd> * <dt>info</dt><dd>Object hash containing calculated XY arrays: start, xy, delta, offset</dd> * </dl> * @bubbles DDM * @type {CustomEvent} */ EV_DRAG = 'drag:drag', /** * @event drag:align * @preventable _defAlignFn * @description Fires when this node is aligned. * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl> * <dt>pageX</dt><dd>The current node position X.</dd> * <dt>pageY</dt><dd>The current node position Y.</dd> * </dl> * @bubbles DDM * @type {CustomEvent} */ EV_ALIGN = 'drag:align', /** * @event drag:over * @description Fires when this node is over a Drop Target. (Fired from dd-drop) * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl> * <dt>drop</dt><dd>The drop object at the time of the event.</dd> * <dt>drag</dt><dd>The drag object at the time of the event.</dd> * </dl> * @bubbles DDM * @type {CustomEvent} */ /** * @event drag:enter * @description Fires when this node enters a Drop Target. (Fired from dd-drop) * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl> * <dt>drop</dt><dd>The drop object at the time of the event.</dd> * <dt>drag</dt><dd>The drag object at the time of the event.</dd> * </dl> * @bubbles DDM * @type {CustomEvent} */ /** * @event drag:exit * @description Fires when this node exits a Drop Target. (Fired from dd-drop) * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl> * <dt>drop</dt><dd>The drop object at the time of the event.</dd> * </dl> * @bubbles DDM * @type {CustomEvent} */ /** * @event drag:drophit * @description Fires when this node is dropped on a valid Drop Target. (Fired from dd-ddm-drop) * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl> * <dt>drop</dt><dd>The best guess on what was dropped on.</dd> * <dt>drag</dt><dd>The drag object at the time of the event.</dd> * <dt>others</dt><dd>An array of all the other drop targets that was dropped on.</dd> * </dl> * @bubbles DDM * @type {CustomEvent} */ /** * @event drag:dropmiss * @description Fires when this node is dropped on an invalid Drop Target. (Fired from dd-ddm-drop) * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl> * <dt>pageX</dt><dd>The current node position X.</dd> * <dt>pageY</dt><dd>The current node position Y.</dd> * </dl> * @bubbles DDM * @type {CustomEvent} */ Drag = function(o) { this._lazyAddAttrs = false; Drag.superclass.constructor.apply(this, arguments); var valid = DDM._regDrag(this); if (!valid) { Y.error('Failed to register node, already in use: ' + o.node); } }; Drag.NAME = 'drag'; /** * This property defaults to "mousedown", but when drag-gestures is loaded, it is changed to "gesturemovestart" * @static * @property START_EVENT */ Drag.START_EVENT = 'mousedown'; Drag.ATTRS = { /** * @attribute node * @description Y.Node instance to use as the element to initiate a drag operation * @type Node */ node: { setter: function(node) { if (this._canDrag(node)) { return node; } var n = Y.one(node); if (!n) { Y.error('DD.Drag: Invalid Node Given: ' + node); } return n; } }, /** * @attribute dragNode * @description Y.Node instance to use as the draggable element, defaults to node * @type Node */ dragNode: { setter: function(node) { if (this._canDrag(node)) { return node; } var n = Y.one(node); if (!n) { Y.error('DD.Drag: Invalid dragNode Given: ' + node); } return n; } }, /** * @attribute offsetNode * @description Offset the drag element by the difference in cursor position: default true * @type Boolean */ offsetNode: { value: true }, /** * @attribute startCentered * @description Center the dragNode to the mouse position on drag:start: default false * @type Boolean */ startCentered: { value: false }, /** * @attribute clickPixelThresh * @description The number of pixels to move to start a drag operation, default is 3. * @type Number */ clickPixelThresh: { value: DDM.get('clickPixelThresh') }, /** * @attribute clickTimeThresh * @description The number of milliseconds a mousedown has to pass to start a drag operation, default is 1000. * @type Number */ clickTimeThresh: { value: DDM.get('clickTimeThresh') }, /** * @attribute lock * @description Set to lock this drag element so that it can't be dragged: default false. * @type Boolean */ lock: { value: false, setter: function(lock) { if (lock) { this.get(NODE).addClass(DDM.CSS_PREFIX + '-locked'); } else { this.get(NODE).removeClass(DDM.CSS_PREFIX + '-locked'); } return lock; } }, /** * @attribute data * @description A payload holder to store arbitrary data about this drag object, can be used to store any value. * @type Mixed */ data: { value: false }, /** * @attribute move * @description If this is false, the drag element will not move with the cursor: default true. Can be used to "resize" the element. * @type Boolean */ move: { value: true }, /** * @attribute useShim * @description Use the protective shim on all drag operations: default true. Only works with dd-ddm, not dd-ddm-base. * @type Boolean */ useShim: { value: true }, /** * @attribute activeHandle * @description This config option is set by Drag to inform you of which handle fired the drag event (in the case that there are several handles): default false. * @type Node */ activeHandle: { value: false }, /** * @attribute primaryButtonOnly * @description By default a drag operation will only begin if the mousedown occurred with the primary mouse button. Setting this to false will allow for all mousedown events to trigger a drag. * @type Boolean */ primaryButtonOnly: { value: true }, /** * @attribute dragging * @description This attribute is not meant to be used by the implementor, it is meant to be used as an Event tracker so you can listen for it to change. * @type Boolean */ dragging: { value: false }, parent: { value: false }, /** * @attribute target * @description This attribute only works if the dd-drop module has been loaded. It will make this node a drop target as well as draggable. * @type Boolean */ target: { value: false, setter: function(config) { this._handleTarget(config); return config; } }, /** * @attribute dragMode * @description This attribute only works if the dd-drop module is active. It will set the dragMode (point, intersect, strict) of this Drag instance. * @type String */ dragMode: { value: null, setter: function(mode) { return DDM._setDragMode(mode); } }, /** * @attribute groups * @description Array of groups to add this drag into. * @type Array */ groups: { value: ['default'], getter: function() { if (!this._groups) { this._groups = {}; } var ret = []; Y.each(this._groups, function(v, k) { ret[ret.length] = k; }); return ret; }, setter: function(g) { this._groups = {}; Y.each(g, function(v, k) { this._groups[v] = true; }, this); return g; } }, /** * @attribute handles * @description Array of valid handles to add. Adding something here will set all handles, even if previously added with addHandle * @type Array */ handles: { value: null, setter: function(g) { if (g) { this._handles = {}; Y.each(g, function(v, k) { var key = v; if (v instanceof Y.Node || v instanceof Y.NodeList) { key = v._yuid; } this._handles[key] = v; }, this); } else { this._handles = null; } return g; } }, /** * @deprecated * @attribute bubbles * @description Controls the default bubble parent for this Drag instance. Default: Y.DD.DDM. Set to false to disable bubbling. Use bubbleTargets in config * @type Object */ bubbles: { setter: function(t) { Y.log('bubbles is deprecated use bubbleTargets: HOST', 'warn', 'dd'); this.addTarget(t); return t; } }, /** * @attribute haltDown * @description Should the mousedown event be halted. Default: true * @type Boolean */ haltDown: { value: true } }; Y.extend(Drag, Y.Base, { /** * Checks the object for the methods needed to drag the object around. * Normally this would be a node instance, but in the case of Graphics, it * may be an SVG node or something similar. * @method _canDrag * @private * @param {Object} n The object to check * @return {Boolean} True or false if the Object contains the methods needed to Drag */ _canDrag: function(n) { if (n && n.setXY && n.getXY && n.test && n.contains) { return true; } return false; }, /** * @private * @property _bubbleTargets * @description The default bubbleTarget for this object. Default: Y.DD.DDM */ _bubbleTargets: Y.DD.DDM, /** * @method addToGroup * @description Add this Drag instance to a group, this should be used for on-the-fly group additions. * @param {String} g The group to add this Drag Instance to. * @return {Self} * @chainable */ addToGroup: function(g) { this._groups[g] = true; DDM._activateTargets(); return this; }, /** * @method removeFromGroup * @description Remove this Drag instance from a group, this should be used for on-the-fly group removals. * @param {String} g The group to remove this Drag Instance from. * @return {Self} * @chainable */ removeFromGroup: function(g) { delete this._groups[g]; DDM._activateTargets(); return this; }, /** * @property target * @description This will be a reference to the Drop instance associated with this drag if the target: true config attribute is set.. * @type {Object} */ target: null, /** * @private * @method _handleTarget * @description Attribute handler for the target config attribute. * @param {Boolean/Object} config The Config */ _handleTarget: function(config) { if (Y.DD.Drop) { if (config === false) { if (this.target) { DDM._unregTarget(this.target); this.target = null; } return false; } else { if (!Y.Lang.isObject(config)) { config = {}; } config.bubbleTargets = ('bubbleTargets' in config) ? config.bubbleTargets : Y.Object.values(this._yuievt.targets); config.node = this.get(NODE); config.groups = config.groups || this.get('groups'); this.target = new Y.DD.Drop(config); } } else { return false; } }, /** * @private * @property _groups * @description Storage Array for the groups this drag belongs to. * @type {Array} */ _groups: null, /** * @private * @method _createEvents * @description This method creates all the events for this Event Target and publishes them so we get Event Bubbling. */ _createEvents: function() { this.publish(EV_MOUSE_DOWN, { defaultFn: this._defMouseDownFn, queuable: false, emitFacade: true, bubbles: true, prefix: 'drag' }); this.publish(EV_ALIGN, { defaultFn: this._defAlignFn, queuable: false, emitFacade: true, bubbles: true, prefix: 'drag' }); this.publish(EV_DRAG, { defaultFn: this._defDragFn, queuable: false, emitFacade: true, bubbles: true, prefix: 'drag' }); this.publish(EV_END, { defaultFn: this._defEndFn, preventedFn: this._prevEndFn, queuable: false, emitFacade: true, bubbles: true, prefix: 'drag' }); var ev = [ EV_AFTER_MOUSE_DOWN, EV_REMOVE_HANDLE, EV_ADD_HANDLE, EV_REMOVE_INVALID, EV_ADD_INVALID, EV_START, 'drag:drophit', 'drag:dropmiss', 'drag:over', 'drag:enter', 'drag:exit' ]; Y.each(ev, function(v, k) { this.publish(v, { type: v, emitFacade: true, bubbles: true, preventable: false, queuable: false, prefix: 'drag' }); }, this); }, /** * @private * @property _ev_md * @description A private reference to the mousedown DOM event * @type {EventFacade} */ _ev_md: null, /** * @private * @property _startTime * @description The getTime of the mousedown event. Not used, just here in case someone wants/needs to use it. * @type Date */ _startTime: null, /** * @private * @property _endTime * @description The getTime of the mouseup event. Not used, just here in case someone wants/needs to use it. * @type Date */ _endTime: null, /** * @private * @property _handles * @description A private hash of the valid drag handles * @type {Object} */ _handles: null, /** * @private * @property _invalids * @description A private hash of the invalid selector strings * @type {Object} */ _invalids: null, /** * @private * @property _invalidsDefault * @description A private hash of the default invalid selector strings: {'textarea': true, 'input': true, 'a': true, 'button': true, 'select': true} * @type {Object} */ _invalidsDefault: {'textarea': true, 'input': true, 'a': true, 'button': true, 'select': true }, /** * @private * @property _dragThreshMet * @description Private flag to see if the drag threshhold was met * @type {Boolean} */ _dragThreshMet: null, /** * @private * @property _fromTimeout * @description Flag to determine if the drag operation came from a timeout * @type {Boolean} */ _fromTimeout: null, /** * @private * @property _clickTimeout * @description Holder for the setTimeout call * @type {Boolean} */ _clickTimeout: null, /** * @property deltaXY * @description The offset of the mouse position to the element's position * @type {Array} */ deltaXY: null, /** * @property startXY * @description The initial mouse position * @type {Array} */ startXY: null, /** * @property nodeXY * @description The initial element position * @type {Array} */ nodeXY: null, /** * @property lastXY * @description The position of the element as it's moving (for offset calculations) * @type {Array} */ lastXY: null, /** * @property actXY * @description The xy that the node will be set to. Changing this will alter the position as it's dragged. * @type {Array} */ actXY: null, /** * @property realXY * @description The real xy position of the node. * @type {Array} */ realXY: null, /** * @property mouseXY * @description The XY coords of the mousemove * @type {Array} */ mouseXY: null, /** * @property region * @description A region object associated with this drag, used for checking regions while dragging. * @type Object */ region: null, /** * @private * @method _handleMouseUp * @description Handler for the mouseup DOM event * @param {EventFacade} ev The Event */ _handleMouseUp: function(ev) { this.fire('drag:mouseup'); this._fixIEMouseUp(); if (DDM.activeDrag) { DDM._end(); } }, /** * @private * @method _fixDragStart * @description The function we use as the ondragstart handler when we start a drag in Internet Explorer. This keeps IE from blowing up on images as drag handles. * @param {Event} e The Event */ _fixDragStart: function(e) { e.preventDefault(); }, /** * @private * @method _ieSelectFix * @description The function we use as the onselectstart handler when we start a drag in Internet Explorer */ _ieSelectFix: function() { return false; }, /** * @private * @property _ieSelectBack * @description We will hold a copy of the current "onselectstart" method on this property, and reset it after we are done using it. */ _ieSelectBack: null, /** * @private * @method _fixIEMouseDown * @description This method copies the onselectstart listner on the document to the _ieSelectFix property */ _fixIEMouseDown: function(e) { if (Y.UA.ie) { this._ieSelectBack = Y.config.doc.body.onselectstart; Y.config.doc.body.onselectstart = this._ieSelectFix; } }, /** * @private * @method _fixIEMouseUp * @description This method copies the _ieSelectFix property back to the onselectstart listner on the document. */ _fixIEMouseUp: function() { if (Y.UA.ie) { Y.config.doc.body.onselectstart = this._ieSelectBack; } }, /** * @private * @method _handleMouseDownEvent * @description Handler for the mousedown DOM event * @param {EventFacade} ev The Event */ _handleMouseDownEvent: function(ev) { this.fire(EV_MOUSE_DOWN, { ev: ev }); }, /** * @private * @method _defMouseDownFn * @description Handler for the mousedown DOM event * @param {EventFacade} e The Event */ _defMouseDownFn: function(e) { var ev = e.ev; this._dragThreshMet = false; this._ev_md = ev; if (this.get('primaryButtonOnly') && ev.button > 1) { return false; } if (this.validClick(ev)) { this._fixIEMouseDown(ev); if (this.get('haltDown')) { Y.log('Halting MouseDown', 'info', 'drag'); ev.halt(); } else { Y.log('Preventing Default on MouseDown', 'info', 'drag'); ev.preventDefault(); } this._setStartPosition([ev.pageX, ev.pageY]); DDM.activeDrag = this; this._clickTimeout = Y.later(this.get('clickTimeThresh'), this, this._timeoutCheck); } this.fire(EV_AFTER_MOUSE_DOWN, { ev: ev }); }, /** * @method validClick * @description Method first checks to see if we have handles, if so it validates the click against the handle. Then if it finds a valid handle, it checks it against the invalid handles list. Returns true if a good handle was used, false otherwise. * @param {EventFacade} ev The Event * @return {Boolean} */ validClick: function(ev) { var r = false, n = false, tar = ev.target, hTest = null, els = null, nlist = null, set = false; if (this._handles) { Y.each(this._handles, function(i, n) { if (i instanceof Y.Node || i instanceof Y.NodeList) { if (!r) { nlist = i; if (nlist instanceof Y.Node) { nlist = new Y.NodeList(i._node); } nlist.each(function(nl) { if (nl.contains(tar)) { r = true; } }); } } else if (Y.Lang.isString(n)) { //Am I this or am I inside this if (tar.test(n + ', ' + n + ' *') && !hTest) { hTest = n; r = true; } } }); } else { n = this.get(NODE); if (n.contains(tar) || n.compareTo(tar)) { r = true; } } if (r) { if (this._invalids) { Y.each(this._invalids, function(i, n) { if (Y.Lang.isString(n)) { //Am I this or am I inside this if (tar.test(n + ', ' + n + ' *')) { r = false; } } }); } } if (r) { if (hTest) { els = ev.currentTarget.all(hTest); set = false; els.each(function(n, i) { if ((n.contains(tar) || n.compareTo(tar)) && !set) { set = true; this.set('activeHandle', n); } }, this); } else { this.set('activeHandle', this.get(NODE)); } } return r; }, /** * @private * @method _setStartPosition * @description Sets the current position of the Element and calculates the offset * @param {Array} xy The XY coords to set the position to. */ _setStartPosition: function(xy) { this.startXY = xy; this.nodeXY = this.lastXY = this.realXY = this.get(NODE).getXY(); if (this.get('offsetNode')) { this.deltaXY = [(this.startXY[0] - this.nodeXY[0]), (this.startXY[1] - this.nodeXY[1])]; } else { this.deltaXY = [0, 0]; } }, /** * @private * @method _timeoutCheck * @description The method passed to setTimeout to determine if the clickTimeThreshold was met. */ _timeoutCheck: function() { if (!this.get('lock') && !this._dragThreshMet && this._ev_md) { this._fromTimeout = this._dragThreshMet = true; this.start(); this._alignNode([this._ev_md.pageX, this._ev_md.pageY], true); } }, /** * @method removeHandle * @description Remove a Selector added by addHandle * @param {String} str The selector for the handle to be removed. * @return {Self} * @chainable */ removeHandle: function(str) { var key = str; if (str instanceof Y.Node || str instanceof Y.NodeList) { key = str._yuid; } if (this._handles[key]) { delete this._handles[key]; this.fire(EV_REMOVE_HANDLE, { handle: str }); } return this; }, /** * @method addHandle * @description Add a handle to a drag element. Drag only initiates when a mousedown happens on this element. * @param {String} str The selector to test for a valid handle. Must be a child of the element. * @return {Self} * @chainable */ addHandle: function(str) { if (!this._handles) { this._handles = {}; } var key = str; if (str instanceof Y.Node || str instanceof Y.NodeList) { key = str._yuid; } this._handles[key] = str; this.fire(EV_ADD_HANDLE, { handle: str }); return this; }, /** * @method removeInvalid * @description Remove an invalid handle added by addInvalid * @param {String} str The invalid handle to remove from the internal list. * @return {Self} * @chainable */ removeInvalid: function(str) { if (this._invalids[str]) { this._invalids[str] = null; delete this._invalids[str]; this.fire(EV_REMOVE_INVALID, { handle: str }); } return this; }, /** * @method addInvalid * @description Add a selector string to test the handle against. If the test passes the drag operation will not continue. * @param {String} str The selector to test against to determine if this is an invalid drag handle. * @return {Self} * @chainable */ addInvalid: function(str) { if (Y.Lang.isString(str)) { this._invalids[str] = true; this.fire(EV_ADD_INVALID, { handle: str }); } return this; }, /** * @private * @method initializer * @description Internal init handler */ initializer: function(cfg) { this.get(NODE).dd = this; if (!this.get(NODE).get('id')) { var id = Y.stamp(this.get(NODE)); this.get(NODE).set('id', id); } this.actXY = []; this._invalids = Y.clone(this._invalidsDefault, true); this._createEvents(); if (!this.get(DRAG_NODE)) { this.set(DRAG_NODE, this.get(NODE)); } //Fix for #2528096 //Don't prep the DD instance until all plugins are loaded. this.on('initializedChange', Y.bind(this._prep, this)); //Shouldn't have to do this.. this.set('groups', this.get('groups')); }, /** * @private * @method _prep * @description Attach event listners and add classname */ _prep: function() { this._dragThreshMet = false; var node = this.get(NODE); node.addClass(DDM.CSS_PREFIX + '-draggable'); node.on(Drag.START_EVENT, Y.bind(this._handleMouseDownEvent, this)); node.on('mouseup', Y.bind(this._handleMouseUp, this)); node.on('dragstart', Y.bind(this._fixDragStart, this)); }, /** * @private * @method _unprep * @description Detach event listeners and remove classname */ _unprep: function() { var node = this.get(NODE); node.removeClass(DDM.CSS_PREFIX + '-draggable'); node.detachAll('mouseup'); node.detachAll('dragstart'); node.detachAll(Drag.START_EVENT); this.mouseXY = []; this.deltaXY = [0,0]; this.startXY = []; this.nodeXY = []; this.lastXY = []; this.actXY = []; this.realXY = []; }, /** * @method start * @description Starts the drag operation * @return {Self} * @chainable */ start: function() { if (!this.get('lock') && !this.get(DRAGGING)) { var node = this.get(NODE), ow, oh, xy; this._startTime = (new Date()).getTime(); DDM._start(); node.addClass(DDM.CSS_PREFIX + '-dragging'); this.fire(EV_START, { pageX: this.nodeXY[0], pageY: this.nodeXY[1], startTime: this._startTime }); node = this.get(DRAG_NODE); xy = this.nodeXY; ow = node.get(OFFSET_WIDTH); oh = node.get(OFFSET_HEIGHT); if (this.get('startCentered')) { this._setStartPosition([xy[0] + (ow / 2), xy[1] + (oh / 2)]); } this.region = { '0': xy[0], '1': xy[1], area: 0, top: xy[1], right: xy[0] + ow, bottom: xy[1] + oh, left: xy[0] }; this.set(DRAGGING, true); } return this; }, /** * @method end * @description Ends the drag operation * @return {Self} * @chainable */ end: function() { this._endTime = (new Date()).getTime(); if (this._clickTimeout) { this._clickTimeout.cancel(); } this._dragThreshMet = this._fromTimeout = false; if (!this.get('lock') && this.get(DRAGGING)) { this.fire(EV_END, { pageX: this.lastXY[0], pageY: this.lastXY[1], startTime: this._startTime, endTime: this._endTime }); } this.get(NODE).removeClass(DDM.CSS_PREFIX + '-dragging'); this.set(DRAGGING, false); this.deltaXY = [0, 0]; return this; }, /** * @private * @method _defEndFn * @description Handler for fixing the selection in IE */ _defEndFn: function(e) { this._fixIEMouseUp(); this._ev_md = null; }, /** * @private * @method _prevEndFn * @description Handler for preventing the drag:end event. It will reset the node back to it's start position */ _prevEndFn: function(e) { this._fixIEMouseUp(); //Bug #1852577 this.get(DRAG_NODE).setXY(this.nodeXY); this._ev_md = null; this.region = null; }, /** * @private * @method _align * @description Calculates the offsets and set's the XY that the element will move to. * @param {Array} xy The xy coords to align with. */ _align: function(xy) { this.fire(EV_ALIGN, {pageX: xy[0], pageY: xy[1] }); }, /** * @private * @method _defAlignFn * @description Calculates the offsets and set's the XY that the element will move to. * @param {EventFacade} e The drag:align event. */ _defAlignFn: function(e) { this.actXY = [e.pageX - this.deltaXY[0], e.pageY - this.deltaXY[1]]; }, /** * @private * @method _alignNode * @description This method performs the alignment before the element move. * @param {Array} eXY The XY to move the element to, usually comes from the mousemove DOM event. */ _alignNode: function(eXY) { this._align(eXY); this._moveNode(); }, /** * @private * @method _moveNode * @description This method performs the actual element move. */ _moveNode: function(scroll) { //if (!this.get(DRAGGING)) { // return; //} var diffXY = [], diffXY2 = [], startXY = this.nodeXY, xy = this.actXY; diffXY[0] = (xy[0] - this.lastXY[0]); diffXY[1] = (xy[1] - this.lastXY[1]); diffXY2[0] = (xy[0] - this.nodeXY[0]); diffXY2[1] = (xy[1] - this.nodeXY[1]); this.region = { '0': xy[0], '1': xy[1], area: 0, top: xy[1], right: xy[0] + this.get(DRAG_NODE).get(OFFSET_WIDTH), bottom: xy[1] + this.get(DRAG_NODE).get(OFFSET_HEIGHT), left: xy[0] }; this.fire(EV_DRAG, { pageX: xy[0], pageY: xy[1], scroll: scroll, info: { start: startXY, xy: xy, delta: diffXY, offset: diffXY2 } }); this.lastXY = xy; }, /** * @private * @method _defDragFn * @description Default function for drag:drag. Fired from _moveNode. * @param {EventFacade} ev The drag:drag event */ _defDragFn: function(e) { if (this.get('move')) { if (e.scroll) { e.scroll.node.set('scrollTop', e.scroll.top); e.scroll.node.set('scrollLeft', e.scroll.left); } this.get(DRAG_NODE).setXY([e.pageX, e.pageY]); this.realXY = [e.pageX, e.pageY]; } }, /** * @private * @method _move * @description Fired from DragDropMgr (DDM) on mousemove. * @param {EventFacade} ev The mousemove DOM event */ _move: function(ev) { if (this.get('lock')) { return false; } else { this.mouseXY = [ev.pageX, ev.pageY]; if (!this._dragThreshMet) { var diffX = Math.abs(this.startXY[0] - ev.pageX), diffY = Math.abs(this.startXY[1] - ev.pageY); if (diffX > this.get('clickPixelThresh') || diffY > this.get('clickPixelThresh')) { this._dragThreshMet = true; this.start(); this._alignNode([ev.pageX, ev.pageY]); } } else { if (this._clickTimeout) { this._clickTimeout.cancel(); } this._alignNode([ev.pageX, ev.pageY]); } } }, /** * @method stopDrag * @description Method will forcefully stop a drag operation. For example calling this from inside an ESC keypress handler will stop this drag. * @return {Self} * @chainable */ stopDrag: function() { if (this.get(DRAGGING)) { DDM._end(); } return this; }, /** * @private * @method destructor * @description Lifecycle destructor, unreg the drag from the DDM and remove listeners */ destructor: function() { this._unprep(); if (this.target) { this.target.destroy(); } DDM._unregDrag(this); } }); Y.namespace('DD'); Y.DD.Drag = Drag; }, '@VERSION@' ,{requires:['dd-ddm-base'], skinnable:false});
// moment.js // version : 1.5.0 // author : Tim Wood // license : MIT // momentjs.com (function(a, b) { function u(a, b) { this._d = a, this._isUTC = !!b; } function v(a, b) { var c = a + ""; while (c.length < b) c = "0" + c; return c; } function w(b, c, d, e) { var f = typeof c == "string", g = f ? {} : c, h, i, j, k; return f && e && (g[c] = +e), h = (g.ms || g.milliseconds || 0) + (g.s || g.seconds || 0) * 1e3 + (g.m || g.minutes || 0) * 6e4 + (g.h || g.hours || 0) * 36e5, i = (g.d || g.days || 0) + (g.w || g.weeks || 0) * 7, j = (g.M || g.months || 0) + (g.y || g.years || 0) * 12, h && b.setTime(+b + h * d), i && b.setDate(b.getDate() + i * d), j && (k = b.getDate(), b.setDate(1), b.setMonth(b.getMonth() + j * d), b.setDate(Math.min((new a(b.getFullYear(), b.getMonth() + 1, 0)).getDate(), k))), b; } function x(a) { return Object.prototype.toString.call(a) === "[object Array]"; } function y(b) { return new a(b[0], b[1] || 0, b[2] || 1, b[3] || 0, b[4] || 0, b[5] || 0, b[6] || 0); } function z(b, d) { function r(d) { var j, s; switch (d) { case "M": return e + 1; case "Mo": return e + 1 + p(e + 1); case "MM": return v(e + 1, 2); case "MMM": return c.monthsShort[e]; case "MMMM": return c.months[e]; case "D": return f; case "Do": return f + p(f); case "DD": return v(f, 2); case "DDD": return j = new a(g, e, f), s = new a(g, 0, 1), ~~((j - s) / 864e5 + 1.5); case "DDDo": return j = r("DDD"), j + p(j); case "DDDD": return v(r("DDD"), 3); case "d": return h; case "do": return h + p(h); case "ddd": return c.weekdaysShort[h]; case "dddd": return c.weekdays[h]; case "w": return j = new a(g, e, f - h + 5), s = new a(j.getFullYear(), 0, 4), ~~((j - s) / 864e5 / 7 + 1.5); case "wo": return j = r("w"), j + p(j); case "ww": return v(r("w"), 2); case "YY": return v(g % 100, 2); case "YYYY": return g; case "a": return i > 11 ? q.pm : q.am; case "A": return i > 11 ? q.PM : q.AM; case "H": return i; case "HH": return v(i, 2); case "h": return i % 12 || 12; case "hh": return v(i % 12 || 12, 2); case "m": return m; case "mm": return v(m, 2); case "s": return n; case "ss": return v(n, 2); case "zz": case "z": return (b._d.toString().match(l) || [ "" ])[0].replace(k, ""); case "Z": return (o < 0 ? "-" : "+") + v(~~(Math.abs(o) / 60), 2) + ":" + v(~~(Math.abs(o) % 60), 2); case "ZZ": return (o < 0 ? "-" : "+") + v(~~(10 * Math.abs(o) / 6), 4); case "L": case "LL": case "LLL": case "LLLL": case "LT": return z(b, c.longDateFormat[d]); default: return d.replace(/(^\[)|(\\)|\]$/g, ""); } } var e = b.month(), f = b.date(), g = b.year(), h = b.day(), i = b.hours(), m = b.minutes(), n = b.seconds(), o = -b.zone(), p = c.ordinal, q = c.meridiem; return d.replace(j, r); } function A(b, d) { function p(a, b) { var d; switch (a) { case "M": case "MM": e[1] = ~~b - 1; break; case "MMM": case "MMMM": for (d = 0; d < 12; d++) if (c.monthsParse[d].test(b)) { e[1] = d; break; } break; case "D": case "DD": case "DDD": case "DDDD": e[2] = ~~b; break; case "YY": b = ~~b, e[0] = b + (b > 70 ? 1900 : 2e3); break; case "YYYY": e[0] = ~~Math.abs(b); break; case "a": case "A": o = b.toLowerCase() === "pm"; break; case "H": case "HH": case "h": case "hh": e[3] = ~~b; break; case "m": case "mm": e[4] = ~~b; break; case "s": case "ss": e[5] = ~~b; break; case "Z": case "ZZ": h = !0, d = (b || "").match(r), d && d[1] && (f = ~~d[1]), d && d[2] && (g = ~~d[2]), d && d[0] === "+" && (f = -f, g = -g); } } var e = [ 0, 0, 1, 0, 0, 0, 0 ], f = 0, g = 0, h = !1, i = b.match(n), j = d.match(m), k = Math.min(i.length, j.length), l, o; for (l = 0; l < k; l++) p(j[l], i[l]); return o && e[3] < 12 && (e[3] += 12), o === !1 && e[3] === 12 && (e[3] = 0), e[3] += f, e[4] += g, h ? new a(a.UTC.apply({}, e)) : y(e); } function B(a, b) { var c = Math.min(a.length, b.length), d = Math.abs(a.length - b.length), e = 0, f; for (f = 0; f < c; f++) ~~a[f] !== ~~b[f] && e++; return e + d; } function C(a, b) { var c, d = a.match(n), e = [], f = 99, g, h, i; for (g = 0; g < b.length; g++) h = A(a, b[g]), i = B(d, z(new u(h), b[g]).match(n)), i < f && (f = i, c = h); return c; } function D(b) { var c = "YYYY-MM-DDT", d; if (o.exec(b)) { for (d = 0; d < 3; d++) if (q[d][1].exec(b)) { c += q[d][0]; break; } return A(b, c + "Z"); } return new a(b); } function E(a, b, d) { var e = c.relativeTime[a]; return typeof e == "function" ? e(b || 1, !!d, a) : e.replace(/%d/i, b || 1); } function F(a, b) { var c = d(Math.abs(a) / 1e3), e = d(c / 60), f = d(e / 60), g = d(f / 24), h = d(g / 365), i = c < 45 && [ "s", c ] || e === 1 && [ "m" ] || e < 45 && [ "mm", e ] || f === 1 && [ "h" ] || f < 22 && [ "hh", f ] || g === 1 && [ "d" ] || g <= 25 && [ "dd", g ] || g <= 45 && [ "M" ] || g < 345 && [ "MM", d(g / 30) ] || h === 1 && [ "y" ] || [ "yy", h ]; return i[2] = b, E.apply({}, i); } function G(a, b) { c.fn[a] = function(a) { var c = this._isUTC ? "UTC" : ""; return a != null ? (this._d["set" + c + b](a), this) : this._d["get" + c + b](); }; } var c, d = Math.round, e = {}, f = typeof module != "undefined", g = "months|monthsShort|monthsParse|weekdays|weekdaysShort|longDateFormat|calendar|relativeTime|ordinal|meridiem".split("|"), h, i = /^\/?Date\((\-?\d+)/i, j = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|dddd?|do?|w[o|w]?|YYYY|YY|a|A|hh?|HH?|mm?|ss?|zz?|ZZ?|LT|LL?L?L?)/g, k = /[^A-Z]/g, l = /\([A-Za-z ]+\)|:[0-9]{2} [A-Z]{3} /g, m = /(\\)?(MM?M?M?|dd?d?d|DD?D?D?|YYYY|YY|a|A|hh?|HH?|mm?|ss?|ZZ?|T)/g, n = /(\\)?([0-9]+|([a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+|([\+\-]\d\d:?\d\d))/gi, o = /\d{4}.\d\d.\d\d(T(\d\d(.\d\d(.\d\d)?)?)?([\+\-]\d\d:?\d\d)?)?/, p = "YYYY-MM-DDTHH:mm:ssZ", q = [ [ "HH:mm:ss", /T\d\d:\d\d:\d\d/ ], [ "HH:mm", /T\d\d:\d\d/ ], [ "HH", /T\d\d/ ] ], r = /([\+\-]|\d\d)/gi, s = "1.5.0", t = "Month|Date|Hours|Minutes|Seconds|Milliseconds".split("|"); c = function(c, d) { if (c === null || c === "") return null; var e, f; return c && c._d instanceof a ? e = new a(+c._d) : d ? x(d) ? e = C(c, d) : e = A(c, d) : (f = i.exec(c), e = c === b ? new a : f ? new a(+f[1]) : c instanceof a ? c : x(c) ? y(c) : typeof c == "string" ? D(c) : new a(c)), new u(e); }, c.utc = function(b, d) { return x(b) ? new u(new a(a.UTC.apply({}, b)), !0) : d && b ? c(b + " 0", d + " Z").utc() : c(b).utc(); }, c.humanizeDuration = function(a, b, d) { var e = +a, f = c.relativeTime, g; switch (b) { case "seconds": e *= 1e3; break; case "minutes": e *= 6e4; break; case "hours": e *= 36e5; break; case "days": e *= 864e5; break; case "weeks": e *= 6048e5; break; case "months": e *= 2592e6; break; case "years": e *= 31536e6; break; default: d = !!b; } return g = F(e, !d), d ? (e <= 0 ? f.past : f.future).replace(/%s/i, g) : g; }, c.version = s, c.defaultFormat = p, c.lang = function(a, b) { var d, h, i, j = []; if (b) { for (d = 0; d < 12; d++) j[d] = new RegExp("^" + b.months[d] + "|^" + b.monthsShort[d].replace(".", ""), "i"); b.monthsParse = b.monthsParse || j, e[a] = b; } if (e[a]) for (d = 0; d < g.length; d++) h = g[d], c[h] = e[a][h] || c[h]; else f && (i = require("./lang/" + a), c.lang(a, i)); }, c.lang("en", { months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort: "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort: "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), longDateFormat: { LT: "h:mm A", L: "MM/DD/YYYY", LL: "MMMM D YYYY", LLL: "MMMM D YYYY LT", LLLL: "dddd, MMMM D YYYY LT" }, meridiem: { AM: "AM", am: "am", PM: "PM", pm: "pm" }, calendar: { sameDay: "[Today at] LT", nextDay: "[Tomorrow at] LT", nextWeek: "dddd [at] LT", lastDay: "[Yesterday at] LT", lastWeek: "[last] dddd [at] LT", sameElse: "L" }, relativeTime: { future: "in %s", past: "%s ago", s: "a few seconds", m: "a minute", mm: "%d minutes", h: "an hour", hh: "%d hours", d: "a day", dd: "%d days", M: "a month", MM: "%d months", y: "a year", yy: "%d years" }, ordinal: function(a) { var b = a % 10; return ~~(a % 100 / 10) === 1 ? "th" : b === 1 ? "st" : b === 2 ? "nd" : b === 3 ? "rd" : "th"; } }), c.isMoment = function(a) { return a instanceof u; }, c.fn = u.prototype = { clone: function() { return c(this); }, valueOf: function() { return +this._d; }, "native": function() { return this._d; }, toString: function() { return this._d.toString(); }, toDate: function() { return this._d; }, utc: function() { return this._isUTC = !0, this; }, local: function() { return this._isUTC = !1, this; }, format: function(a) { return z(this, a ? a : c.defaultFormat); }, add: function(a, b) { return this._d = w(this._d, a, 1, b), this; }, subtract: function(a, b) { return this._d = w(this._d, a, -1, b), this; }, diff: function(a, b, e) { var f = c(a), g = (this.zone() - f.zone()) * 6e4, h = this._d - f._d - g, i = this.year() - f.year(), j = this.month() - f.month(), k = this.date() - f.date(), l; return b === "months" ? l = i * 12 + j + k / 30 : b === "years" ? l = i + j / 12 : l = b === "seconds" ? h / 1e3 : b === "minutes" ? h / 6e4 : b === "hours" ? h / 36e5 : b === "days" ? h / 864e5 : b === "weeks" ? h / 6048e5 : h, e ? l : d(l); }, from: function(a, b) { return c.humanizeDuration(this.diff(a), !b); }, fromNow: function(a) { return this.from(c(), a); }, calendar: function() { var a = this.diff(c().sod(), "days", !0), b = c.calendar, d = b.sameElse, e = a < -6 ? d : a < -1 ? b.lastWeek : a < 0 ? b.lastDay : a < 1 ? b.sameDay : a < 2 ? b.nextDay : a < 7 ? b.nextWeek : d; return this.format(typeof e == "function" ? e.apply(this) : e); }, isLeapYear: function() { var a = this.year(); return a % 4 === 0 && a % 100 !== 0 || a % 400 === 0; }, isDST: function() { return this.zone() < c([ this.year() ]).zone() || this.zone() < c([ this.year(), 5 ]).zone(); }, day: function(a) { var b = this._d.getDay(); return a == null ? b : this.add({ d: a - b }); }, sod: function() { return this.clone().hours(0).minutes(0).seconds(0).milliseconds(0); }, eod: function() { return this.sod().add({ d: 1, ms: -1 }); }, zone: function() { return this._isUTC ? 0 : this._d.getTimezoneOffset(); }, daysInMonth: function() { return this.clone().month(this.month() + 1).date(0).date(); } }; for (h = 0; h < t.length; h++) G(t[h].toLowerCase(), t[h]); G("year", "FullYear"), f && (module.exports = c), typeof window != "undefined" && (window.moment = c), typeof define == "function" && define.amd && define("moment", [], function() { return c; }); })(Date);
/*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, document, undefined) { 'use strict'; Foundation.libs.dropdown = { name : 'dropdown', version : '4.3.0', settings : { activeClass: 'open', is_hover: false, opened: function(){}, closed: function(){} }, init : function (scope, method, options) { this.scope = scope || this.scope; Foundation.inherit(this, 'throttle scrollLeft data_options'); if (typeof method === 'object') { $.extend(true, this.settings, method); } if (typeof method !== 'string') { if (!this.settings.init) { this.events(); } return this.settings.init; } else { return this[method].call(this, options); } }, events : function () { var self = this; $(this.scope) .on('click.fndtn.dropdown', '[data-dropdown]', function (e) { var settings = $.extend({}, self.settings, self.data_options($(this))); e.preventDefault(); if (!settings.is_hover) self.toggle($(this)); }) .on('mouseenter', '[data-dropdown]', function (e) { var settings = $.extend({}, self.settings, self.data_options($(this))); if (settings.is_hover) self.toggle($(this)); }) .on('mouseleave', '[data-dropdown-content]', function (e) { var target = $('[data-dropdown="' + $(this).attr('id') + '"]'), settings = $.extend({}, self.settings, self.data_options(target)); if (settings.is_hover) self.close.call(self, $(this)); }) .on('opened.fndtn.dropdown', '[data-dropdown-content]', this.settings.opened) .on('closed.fndtn.dropdown', '[data-dropdown-content]', this.settings.closed); $(document).on('click.fndtn.dropdown', function (e) { var parent = $(e.target).closest('[data-dropdown-content]'); if ($(e.target).data('dropdown')) { return; } if (parent.length > 0 && ($(e.target).is('[data-dropdown-content]') || $.contains(parent.first()[0], e.target))) { e.stopPropagation(); return; } self.close.call(self, $('[data-dropdown-content]')); }); $(window).on('resize.fndtn.dropdown', self.throttle(function () { self.resize.call(self); }, 50)).trigger('resize'); this.settings.init = true; }, close: function (dropdown) { var self = this; dropdown.each(function () { if ($(this).hasClass(self.settings.activeClass)) { $(this) .css(Foundation.rtl ? 'right':'left', '-99999px') .removeClass(self.settings.activeClass); $(this).trigger('closed'); } }); }, open: function (dropdown, target) { this .css(dropdown .addClass(this.settings.activeClass), target); dropdown.trigger('opened'); }, toggle : function (target) { var dropdown = $('#' + target.data('dropdown')); this.close.call(this, $('[data-dropdown-content]').not(dropdown)); if (dropdown.hasClass(this.settings.activeClass)) { this.close.call(this, dropdown); } else { this.close.call(this, $('[data-dropdown-content]')) this.open.call(this, dropdown, target); } }, resize : function () { var dropdown = $('[data-dropdown-content].open'), target = $("[data-dropdown='" + dropdown.attr('id') + "']"); if (dropdown.length && target.length) { this.css(dropdown, target); } }, css : function (dropdown, target) { var offset_parent = dropdown.offsetParent(); // if (offset_parent.length > 0 && /body/i.test(dropdown.offsetParent()[0].nodeName)) { var position = target.offset(); position.top -= offset_parent.offset().top; position.left -= offset_parent.offset().left; // } else { // var position = target.position(); // } if (this.small()) { dropdown.css({ position : 'absolute', width: '95%', left: '2.5%', 'max-width': 'none', top: position.top + this.outerHeight(target) }); } else { if (!Foundation.rtl && $(window).width() > this.outerWidth(dropdown) + target.offset().left) { var left = position.left; if (dropdown.hasClass('right')) { dropdown.removeClass('right'); } } else { if (!dropdown.hasClass('right')) { dropdown.addClass('right'); } var left = position.left - (this.outerWidth(dropdown) - this.outerWidth(target)); } dropdown.attr('style', '').css({ position : 'absolute', top: position.top + this.outerHeight(target), left: left }); } return dropdown; }, small : function () { return $(window).width() < 768 || $('html').hasClass('lt-ie9'); }, off: function () { $(this.scope).off('.fndtn.dropdown'); $('html, body').off('.fndtn.dropdown'); $(window).off('.fndtn.dropdown'); $('[data-dropdown-content]').off('.fndtn.dropdown'); this.settings.init = false; }, reflow : function () {} }; }(Foundation.zj, this, this.document));
(function(){ "use strict"; var fs = require('fs'); // you'll probably load configuration from config var cfg = { ssl: true, port: 8080, ssl_key: '/path/to/you/ssl.key', ssl_cert: '/path/to/you/ssl.crt' }; var httpServ = ( cfg.ssl ) ? require('https') : require('http'); var WebSocketServer = require('../').Server; var app = null; // dummy request processing var processRequest = function( req, res ) { res.writeHead(200); res.end("All glory to WebSockets!\n"); }; if ( cfg.ssl ) { app = httpServ.createServer({ // providing server with SSL key/cert key: fs.readFileSync( cfg.ssl_key ), cert: fs.readFileSync( cfg.ssl_cert ) }, processRequest ).listen( cfg.port ); } else { app = httpServ.createServer( processRequest ).listen( cfg.port ); } // passing or reference to web server so WS would knew port and SSL capabilities var wss = new WebSocketServer( { server: app } ); wss.on( 'connection', function ( wsConnect ) { wsConnect.on( 'message', function ( message ) { console.log( message ); }); }); }());
YUI.add('datasource-io', function (Y, NAME) { /** * Provides a DataSource implementation which can be used to retrieve data via the IO Utility. * * @module datasource * @submodule datasource-io */ /** * IO subclass for the DataSource Utility. * @class DataSource.IO * @extends DataSource.Local * @constructor */ var DSIO = function() { DSIO.superclass.constructor.apply(this, arguments); }; ///////////////////////////////////////////////////////////////////////////// // // DataSource.IO static properties // ///////////////////////////////////////////////////////////////////////////// Y.mix(DSIO, { /** * Class name. * * @property NAME * @type String * @static * @final * @value "dataSourceIO" */ NAME: "dataSourceIO", ///////////////////////////////////////////////////////////////////////////// // // DataSource.IO Attributes // ///////////////////////////////////////////////////////////////////////////// ATTRS: { /** * Pointer to IO Utility. * * @attribute io * @type Y.io * @default Y.io */ io: { value: Y.io, cloneDefaultValue: false }, /** * Default IO Config. * * @attribute ioConfig * @type Object * @default null */ ioConfig: { value: null } } }); Y.extend(DSIO, Y.DataSource.Local, { /** * Internal init() handler. * * @method initializer * @param config {Object} Config object. * @private */ initializer: function(config) { this._queue = {interval:null, conn:null, requests:[]}; }, /** * IO success callback. * * @method successHandler * @param id {String} Transaction ID. * @param response {String} Response. * @param e {Event.Facade} Event facade. * @private */ successHandler: function (id, response, e) { var defIOConfig = this.get("ioConfig"), payload = e.details[0]; delete Y.DataSource.Local.transactions[e.tId]; payload.data = response; this.fire("data", payload); Y.log("Received IO data response for \"" + e.request + "\"", "info", "datasource-io"); if (defIOConfig && defIOConfig.on && defIOConfig.on.success) { defIOConfig.on.success.apply(defIOConfig.context || Y, arguments); } }, /** * IO failure callback. * * @method failureHandler * @param id {String} Transaction ID. * @param response {String} Response. * @param e {Event.Facade} Event facade. * @private */ failureHandler: function (id, response, e) { var defIOConfig = this.get("ioConfig"), payload = e.details[0]; delete Y.DataSource.Local.transactions[e.tId]; payload.error = new Error("IO data failure"); Y.log("IO data failure", "error", "datasource-io"); payload.data = response; this.fire("data", payload); Y.log("Received IO data failure for \"" + e.request + "\"", "info", "datasource-io"); if (defIOConfig && defIOConfig.on && defIOConfig.on.failure) { defIOConfig.on.failure.apply(defIOConfig.context || Y, arguments); } }, /** * @property _queue * @description Object literal to manage asynchronous request/response * cycles enabled if queue needs to be managed (asyncMode/ioConnMode): * <dl> * <dt>interval {Number}</dt> * <dd>Interval ID of in-progress queue.</dd> * <dt>conn</dt> * <dd>In-progress connection identifier (if applicable).</dd> * <dt>requests {Object[]}</dt> * <dd>Array of queued request objects: {request:request, callback:callback}.</dd> * </dl> * @type Object * @default {interval:null, conn:null, requests:[]} * @private */ _queue: null, /** * Passes query string to IO. Fires <code>response</code> event when * response is received asynchronously. * * @method _defRequestFn * @param e {Event.Facade} Event Facade with the following properties: * <dl> * <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd> * <dt>request (Object)</dt> <dd>The request.</dd> * <dt>callback (Object)</dt> <dd>The callback object with the following properties: * <dl> * <dt>success (Function)</dt> <dd>Success handler.</dd> * <dt>failure (Function)</dt> <dd>Failure handler.</dd> * </dl> * </dd> * <dt>cfg (Object)</dt> <dd>Configuration object.</dd> * </dl> * @protected */ _defRequestFn: function(e) { var uri = this.get("source"), io = this.get("io"), defIOConfig = this.get("ioConfig"), request = e.request, cfg = Y.merge(defIOConfig, e.cfg, { on: Y.merge(defIOConfig, { success: this.successHandler, failure: this.failureHandler }), context: this, "arguments": e }); // Support for POST transactions if(Y.Lang.isString(request)) { if(cfg.method && (cfg.method.toUpperCase() === "POST")) { cfg.data = cfg.data ? cfg.data+request : request; } else { uri += request; } } Y.DataSource.Local.transactions[e.tId] = io(uri, cfg); return e.tId; } }); Y.DataSource.IO = DSIO; }, '@VERSION@', {"requires": ["datasource-local", "io-base"]});
/** * Copyright (c) 2008-2011 The Open Source Geospatial Foundation * * Published under the BSD license. * See http://svn.geoext.org/core/trunk/geoext/license.txt for the full text * of the license. */ /** * @require OpenLayers/Control/SelectFeature.js * @require OpenLayers/Layer/Vector.js * @require OpenLayers/BaseTypes/Class.js */ /** api: (define) * module = GeoExt.grid * class = FeatureSelectionModel * base_link = `Ext.grid.RowSelectionModel <http://dev.sencha.com/deploy/dev/docs/?class=Ext.grid.RowSelectionModel>`_ */ Ext.namespace('GeoExt.grid'); /** api: constructor * .. class:: FeatureSelectionModel * * A row selection model which enables automatic selection of features * in the map when rows are selected in the grid and vice-versa. */ /** api: example * Sample code to create a feature grid with a feature selection model: * * .. code-block:: javascript * * var gridPanel = new Ext.grid.GridPanel({ * title: "Feature Grid", * region: "east", * store: store, * width: 320, * columns: [{ * header: "Name", * width: 200, * dataIndex: "name" * }, { * header: "Elevation", * width: 100, * dataIndex: "elevation" * }], * sm: new GeoExt.grid.FeatureSelectionModel() * }); */ GeoExt.grid.FeatureSelectionModelMixin = function() { return { /** api: config[autoActivateControl] * ``Boolean`` If true the select feature control is activated and * deactivated when binding and unbinding. Defaults to true. */ autoActivateControl: true, /** api: config[layerFromStore] * ``Boolean`` If true, and if the constructor is passed neither a * layer nor a select feature control, a select feature control is * created using the layer found in the grid's store. Set it to * false if you want to manually bind the selection model to a * layer. Defaults to true. */ layerFromStore: true, /** api: config[selectControl] * * ``OpenLayers.Control.SelectFeature`` A select feature control. If not * provided one will be created. If provided any "layer" config option * will be ignored, and its "multiple" option will be used to configure * the selectionModel. If an ``Object`` is provided here, it will be * passed as config to the SelectFeature constructor, and the "layer" * config option will be used for the layer. */ /** private: property[selectControl] * ``OpenLayers.Control.SelectFeature`` The select feature control * instance. */ selectControl: null, /** api: config[layer] * ``OpenLayers.Layer.Vector`` The vector layer used for the creation of * the select feature control, it must already be added to the map. If not * provided, the layer bound to the grid's store, if any, will be used. */ /** private: property[bound] * ``Boolean`` Flag indicating if the selection model is bound. */ bound: false, /** private: property[superclass] * ``Ext.grid.AbstractSelectionModel`` Our superclass. */ superclass: null, /** private: property[selectedFeatures] * ``Array`` An array to store the selected features. */ selectedFeatures: [], /** api: config[autoPanMapOnSelection] * ``Boolean`` If true the map will recenter on feature selection * so that the selected features are visible. Defaults to false. */ autoPanMapOnSelection: false, /** private */ constructor: function(config) { config = config || {}; if(config.selectControl instanceof OpenLayers.Control.SelectFeature) { if(!config.singleSelect) { var ctrl = config.selectControl; config.singleSelect = !(ctrl.multiple || !!ctrl.multipleKey); } } else if(config.layer instanceof OpenLayers.Layer.Vector) { this.selectControl = this.createSelectControl( config.layer, config.selectControl ); delete config.layer; delete config.selectControl; } if (config.autoPanMapOnSelection) { this.autoPanMapOnSelection = true; delete config.autoPanMapOnSelection; } this.superclass = arguments.callee.superclass; this.superclass.constructor.call(this, config); }, /** private: method[initEvents] * * Called after this.grid is defined */ initEvents: function() { this.superclass.initEvents.call(this); if(this.layerFromStore) { var layer = this.grid.getStore() && this.grid.getStore().layer; if(layer && !(this.selectControl instanceof OpenLayers.Control.SelectFeature)) { this.selectControl = this.createSelectControl( layer, this.selectControl ); } } if(this.selectControl) { this.bind(this.selectControl); } }, /** private: createSelectControl * :param layer: ``OpenLayers.Layer.Vector`` The vector layer. * :param config: ``Object`` The select feature control config. * * Create the select feature control. */ createSelectControl: function(layer, config) { config = config || {}; var singleSelect = config.singleSelect !== undefined ? config.singleSelect : this.singleSelect; config = OpenLayers.Util.extend({ toggle: true, multipleKey: singleSelect ? null : (Ext.isMac ? "metaKey" : "ctrlKey") }, config); var selectControl = new OpenLayers.Control.SelectFeature( layer, config ); layer.map.addControl(selectControl); return selectControl; }, /** api: method[bind] * * :param obj: ``OpenLayers.Layer.Vector`` or * ``OpenLayers.Control.SelectFeature`` The object this selection model * should be bound to, either a vector layer or a select feature * control. * :param options: ``Object`` An object with a "controlConfig" * property referencing the configuration object to pass to the * ``OpenLayers.Control.SelectFeature`` constructor. * :return: ``OpenLayers.Control.SelectFeature`` The select feature * control this selection model uses. * * Bind the selection model to a layer or a SelectFeature control. */ bind: function(obj, options) { if(!this.bound) { options = options || {}; this.selectControl = obj; if(obj instanceof OpenLayers.Layer.Vector) { this.selectControl = this.createSelectControl( obj, options.controlConfig ); } if(this.autoActivateControl) { this.selectControl.activate(); } var layers = this.getLayers(); for(var i = 0, len = layers.length; i < len; i++) { layers[i].events.on({ featureselected: this.featureSelected, featureunselected: this.featureUnselected, scope: this }); } this.on("rowselect", this.rowSelected, this); this.on("rowdeselect", this.rowDeselected, this); this.bound = true; } return this.selectControl; }, /** api: method[unbind] * :return: ``OpenLayers.Control.SelectFeature`` The select feature * control this selection model used. * * Unbind the selection model from the layer or SelectFeature control. */ unbind: function() { var selectControl = this.selectControl; if(this.bound) { var layers = this.getLayers(); for(var i = 0, len = layers.length; i < len; i++) { layers[i].events.un({ featureselected: this.featureSelected, featureunselected: this.featureUnselected, scope: this }); } this.un("rowselect", this.rowSelected, this); this.un("rowdeselect", this.rowDeselected, this); if(this.autoActivateControl) { selectControl.deactivate(); } this.selectControl = null; this.bound = false; } return selectControl; }, /** private: method[featureSelected] * :param evt: ``Object`` An object with a feature property referencing * the selected feature. */ featureSelected: function(evt) { if(!this._selecting) { var store = this.grid.store; var row = store.findBy(function(record, id) { return record.getFeature() == evt.feature; }); if(row != -1 && !this.isSelected(row)) { this._selecting = true; this.selectRow(row, !this.singleSelect); this._selecting = false; // focus the row in the grid to ensure it is visible this.grid.getView().focusRow(row); } } }, /** private: method[featureUnselected] * :param evt: ``Object`` An object with a feature property referencing * the unselected feature. */ featureUnselected: function(evt) { if(!this._selecting) { var store = this.grid.store; var row = store.findBy(function(record, id) { return record.getFeature() == evt.feature; }); if(row != -1 && this.isSelected(row)) { this._selecting = true; this.deselectRow(row); this._selecting = false; this.grid.getView().focusRow(row); } } }, /** private: method[rowSelected] * :param model: ``Ext.grid.RowSelectModel`` The row select model. * :param row: ``Integer`` The row index. * :param record: ``Ext.data.Record`` The record. */ rowSelected: function(model, row, record) { var feature = record.getFeature(); if(!this._selecting && feature) { var layers = this.getLayers(); for(var i = 0, len = layers.length; i < len; i++) { if(layers[i].selectedFeatures.indexOf(feature) == -1) { this._selecting = true; this.selectControl.select(feature); this._selecting = false; this.selectedFeatures.push(feature); break; } } if(this.autoPanMapOnSelection) { this.recenterToSelectionExtent(); } } }, /** private: method[rowDeselected] * :param model: ``Ext.grid.RowSelectModel`` The row select model. * :param row: ``Integer`` The row index. * :param record: ``Ext.data.Record`` The record. */ rowDeselected: function(model, row, record) { var feature = record.getFeature(); if(!this._selecting && feature) { var layers = this.getLayers(); for(var i = 0, len = layers.length; i < len; i++) { if(layers[i].selectedFeatures.indexOf(feature) != -1) { this._selecting = true; this.selectControl.unselect(feature); this._selecting = false; OpenLayers.Util.removeItem(this.selectedFeatures, feature); break; } } if(this.autoPanMapOnSelection && this.selectedFeatures.length > 0) { this.recenterToSelectionExtent(); } } }, /** private: method[getLayers] * Return the layers attached to the select feature control. */ getLayers: function() { return this.selectControl.layers || [this.selectControl.layer]; }, /** * private: method[recenterToSelectionExtent] * centers the map in order to display all * selected features */ recenterToSelectionExtent: function() { var map = this.selectControl.map; var selectionExtent = this.getSelectionExtent(); var selectionExtentZoom = map.getZoomForExtent(selectionExtent, false); if(selectionExtentZoom > map.getZoom()) { map.setCenter(selectionExtent.getCenterLonLat()); } else { map.zoomToExtent(selectionExtent); } }, /** api: method[getSelectionExtent] * :return: ``OpenLayers.Bounds`` or null if the layer has no features with * geometries * * Calculates the max extent which includes all selected features. */ getSelectionExtent: function () { var maxExtent = null; var features = this.selectedFeatures; if(features && (features.length > 0)) { var geometry = null; for(var i=0, len=features.length; i<len; i++) { geometry = features[i].geometry; if (geometry) { if (maxExtent === null) { maxExtent = new OpenLayers.Bounds(); } maxExtent.extend(geometry.getBounds()); } } } return maxExtent; } }; }; GeoExt.grid.FeatureSelectionModel = Ext.extend( Ext.grid.RowSelectionModel, new GeoExt.grid.FeatureSelectionModelMixin );
/*! * jQuery UI Accordion 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: Accordion //>>group: Widgets // jscs:disable maximumLineLength //>>description: Displays collapsible content panels for presenting information in a limited amount of space. // jscs:enable maximumLineLength //>>docs: http://api.jqueryui.com/accordion/ //>>demos: http://jqueryui.com/accordion/ //>>css.structure: ../../themes/base/core.css //>>css.structure: ../../themes/base/accordion.css //>>css.theme: ../../themes/base/theme.css ( function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "../version", "../keycode", "../unique-id", "../widget" ], factory ); } else { // Browser globals factory( jQuery ); } }( function( $ ) { return $.widget( "ui.accordion", { version: "1.12.1", options: { active: 0, animate: {}, classes: { "ui-accordion-header": "ui-corner-top", "ui-accordion-header-collapsed": "ui-corner-all", "ui-accordion-content": "ui-corner-bottom" }, collapsible: false, event: "click", header: "> li > :first-child, > :not(li):even", heightStyle: "auto", icons: { activeHeader: "ui-icon-triangle-1-s", header: "ui-icon-triangle-1-e" }, // Callbacks activate: null, beforeActivate: null }, hideProps: { borderTopWidth: "hide", borderBottomWidth: "hide", paddingTop: "hide", paddingBottom: "hide", height: "hide" }, showProps: { borderTopWidth: "show", borderBottomWidth: "show", paddingTop: "show", paddingBottom: "show", height: "show" }, _create: function() { var options = this.options; this.prevShow = this.prevHide = $(); this._addClass( "ui-accordion", "ui-widget ui-helper-reset" ); this.element.attr( "role", "tablist" ); // Don't allow collapsible: false and active: false / null if ( !options.collapsible && ( options.active === false || options.active == null ) ) { options.active = 0; } this._processPanels(); // handle negative values if ( options.active < 0 ) { options.active += this.headers.length; } this._refresh(); }, _getCreateEventData: function() { return { header: this.active, panel: !this.active.length ? $() : this.active.next() }; }, _createIcons: function() { var icon, children, icons = this.options.icons; if ( icons ) { icon = $( "<span>" ); this._addClass( icon, "ui-accordion-header-icon", "ui-icon " + icons.header ); icon.prependTo( this.headers ); children = this.active.children( ".ui-accordion-header-icon" ); this._removeClass( children, icons.header ) ._addClass( children, null, icons.activeHeader ) ._addClass( this.headers, "ui-accordion-icons" ); } }, _destroyIcons: function() { this._removeClass( this.headers, "ui-accordion-icons" ); this.headers.children( ".ui-accordion-header-icon" ).remove(); }, _destroy: function() { var contents; // Clean up main element this.element.removeAttr( "role" ); // Clean up headers this.headers .removeAttr( "role aria-expanded aria-selected aria-controls tabIndex" ) .removeUniqueId(); this._destroyIcons(); // Clean up content panels contents = this.headers.next() .css( "display", "" ) .removeAttr( "role aria-hidden aria-labelledby" ) .removeUniqueId(); if ( this.options.heightStyle !== "content" ) { contents.css( "height", "" ); } }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "event" ) { if ( this.options.event ) { this._off( this.headers, this.options.event ); } this._setupEvents( value ); } this._super( key, value ); // Setting collapsible: false while collapsed; open first panel if ( key === "collapsible" && !value && this.options.active === false ) { this._activate( 0 ); } if ( key === "icons" ) { this._destroyIcons(); if ( value ) { this._createIcons(); } } }, _setOptionDisabled: function( value ) { this._super( value ); this.element.attr( "aria-disabled", value ); // Support: IE8 Only // #5332 / #6059 - opacity doesn't cascade to positioned elements in IE // so we need to add the disabled class to the headers and panels this._toggleClass( null, "ui-state-disabled", !!value ); this._toggleClass( this.headers.add( this.headers.next() ), null, "ui-state-disabled", !!value ); }, _keydown: function( event ) { if ( event.altKey || event.ctrlKey ) { return; } var keyCode = $.ui.keyCode, length = this.headers.length, currentIndex = this.headers.index( event.target ), toFocus = false; switch ( event.keyCode ) { case keyCode.RIGHT: case keyCode.DOWN: toFocus = this.headers[ ( currentIndex + 1 ) % length ]; break; case keyCode.LEFT: case keyCode.UP: toFocus = this.headers[ ( currentIndex - 1 + length ) % length ]; break; case keyCode.SPACE: case keyCode.ENTER: this._eventHandler( event ); break; case keyCode.HOME: toFocus = this.headers[ 0 ]; break; case keyCode.END: toFocus = this.headers[ length - 1 ]; break; } if ( toFocus ) { $( event.target ).attr( "tabIndex", -1 ); $( toFocus ).attr( "tabIndex", 0 ); $( toFocus ).trigger( "focus" ); event.preventDefault(); } }, _panelKeyDown: function( event ) { if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) { $( event.currentTarget ).prev().trigger( "focus" ); } }, refresh: function() { var options = this.options; this._processPanels(); // Was collapsed or no panel if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) { options.active = false; this.active = $(); // active false only when collapsible is true } else if ( options.active === false ) { this._activate( 0 ); // was active, but active panel is gone } else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { // all remaining panel are disabled if ( this.headers.length === this.headers.find( ".ui-state-disabled" ).length ) { options.active = false; this.active = $(); // activate previous panel } else { this._activate( Math.max( 0, options.active - 1 ) ); } // was active, active panel still exists } else { // make sure active index is correct options.active = this.headers.index( this.active ); } this._destroyIcons(); this._refresh(); }, _processPanels: function() { var prevHeaders = this.headers, prevPanels = this.panels; this.headers = this.element.find( this.options.header ); this._addClass( this.headers, "ui-accordion-header ui-accordion-header-collapsed", "ui-state-default" ); this.panels = this.headers.next().filter( ":not(.ui-accordion-content-active)" ).hide(); this._addClass( this.panels, "ui-accordion-content", "ui-helper-reset ui-widget-content" ); // Avoid memory leaks (#10056) if ( prevPanels ) { this._off( prevHeaders.not( this.headers ) ); this._off( prevPanels.not( this.panels ) ); } }, _refresh: function() { var maxHeight, options = this.options, heightStyle = options.heightStyle, parent = this.element.parent(); this.active = this._findActive( options.active ); this._addClass( this.active, "ui-accordion-header-active", "ui-state-active" ) ._removeClass( this.active, "ui-accordion-header-collapsed" ); this._addClass( this.active.next(), "ui-accordion-content-active" ); this.active.next().show(); this.headers .attr( "role", "tab" ) .each( function() { var header = $( this ), headerId = header.uniqueId().attr( "id" ), panel = header.next(), panelId = panel.uniqueId().attr( "id" ); header.attr( "aria-controls", panelId ); panel.attr( "aria-labelledby", headerId ); } ) .next() .attr( "role", "tabpanel" ); this.headers .not( this.active ) .attr( { "aria-selected": "false", "aria-expanded": "false", tabIndex: -1 } ) .next() .attr( { "aria-hidden": "true" } ) .hide(); // Make sure at least one header is in the tab order if ( !this.active.length ) { this.headers.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active.attr( { "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 } ) .next() .attr( { "aria-hidden": "false" } ); } this._createIcons(); this._setupEvents( options.event ); if ( heightStyle === "fill" ) { maxHeight = parent.height(); this.element.siblings( ":visible" ).each( function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); } ); this.headers.each( function() { maxHeight -= $( this ).outerHeight( true ); } ); this.headers.next() .each( function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); } ) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.headers.next() .each( function() { var isVisible = $( this ).is( ":visible" ); if ( !isVisible ) { $( this ).show(); } maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() ); if ( !isVisible ) { $( this ).hide(); } } ) .height( maxHeight ); } }, _activate: function( index ) { var active = this._findActive( index )[ 0 ]; // Trying to activate the already active panel if ( active === this.active[ 0 ] ) { return; } // Trying to collapse, simulate a click on the currently active header active = active || this.active[ 0 ]; this._eventHandler( { target: active, currentTarget: active, preventDefault: $.noop } ); }, _findActive: function( selector ) { return typeof selector === "number" ? this.headers.eq( selector ) : $(); }, _setupEvents: function( event ) { var events = { keydown: "_keydown" }; if ( event ) { $.each( event.split( " " ), function( index, eventName ) { events[ eventName ] = "_eventHandler"; } ); } this._off( this.headers.add( this.headers.next() ) ); this._on( this.headers, events ); this._on( this.headers.next(), { keydown: "_panelKeyDown" } ); this._hoverable( this.headers ); this._focusable( this.headers ); }, _eventHandler: function( event ) { var activeChildren, clickedChildren, options = this.options, active = this.active, clicked = $( event.currentTarget ), clickedIsActive = clicked[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : clicked.next(), toHide = active.next(), eventData = { oldHeader: active, oldPanel: toHide, newHeader: collapsing ? $() : clicked, newPanel: toShow }; event.preventDefault(); if ( // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.headers.index( clicked ); // When the call to ._toggle() comes after the class changes // it causes a very odd bug in IE 8 (see #6720) this.active = clickedIsActive ? $() : clicked; this._toggle( eventData ); // Switch classes // corner classes on the previously active header stay after the animation this._removeClass( active, "ui-accordion-header-active", "ui-state-active" ); if ( options.icons ) { activeChildren = active.children( ".ui-accordion-header-icon" ); this._removeClass( activeChildren, null, options.icons.activeHeader ) ._addClass( activeChildren, null, options.icons.header ); } if ( !clickedIsActive ) { this._removeClass( clicked, "ui-accordion-header-collapsed" ) ._addClass( clicked, "ui-accordion-header-active", "ui-state-active" ); if ( options.icons ) { clickedChildren = clicked.children( ".ui-accordion-header-icon" ); this._removeClass( clickedChildren, null, options.icons.header ) ._addClass( clickedChildren, null, options.icons.activeHeader ); } this._addClass( clicked.next(), "ui-accordion-content-active" ); } }, _toggle: function( data ) { var toShow = data.newPanel, toHide = this.prevShow.length ? this.prevShow : data.oldPanel; // Handle activating a panel during the animation for another activation this.prevShow.add( this.prevHide ).stop( true, true ); this.prevShow = toShow; this.prevHide = toHide; if ( this.options.animate ) { this._animate( toShow, toHide, data ); } else { toHide.hide(); toShow.show(); this._toggleComplete( data ); } toHide.attr( { "aria-hidden": "true" } ); toHide.prev().attr( { "aria-selected": "false", "aria-expanded": "false" } ); // if we're switching panels, remove the old header from the tab order // if we're opening from collapsed state, remove the previous header from the tab order // if we're collapsing, then keep the collapsing header in the tab order if ( toShow.length && toHide.length ) { toHide.prev().attr( { "tabIndex": -1, "aria-expanded": "false" } ); } else if ( toShow.length ) { this.headers.filter( function() { return parseInt( $( this ).attr( "tabIndex" ), 10 ) === 0; } ) .attr( "tabIndex", -1 ); } toShow .attr( "aria-hidden", "false" ) .prev() .attr( { "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 } ); }, _animate: function( toShow, toHide, data ) { var total, easing, duration, that = this, adjust = 0, boxSizing = toShow.css( "box-sizing" ), down = toShow.length && ( !toHide.length || ( toShow.index() < toHide.index() ) ), animate = this.options.animate || {}, options = down && animate.down || animate, complete = function() { that._toggleComplete( data ); }; if ( typeof options === "number" ) { duration = options; } if ( typeof options === "string" ) { easing = options; } // fall back from options to animation in case of partial down settings easing = easing || options.easing || animate.easing; duration = duration || options.duration || animate.duration; if ( !toHide.length ) { return toShow.animate( this.showProps, duration, easing, complete ); } if ( !toShow.length ) { return toHide.animate( this.hideProps, duration, easing, complete ); } total = toShow.show().outerHeight(); toHide.animate( this.hideProps, { duration: duration, easing: easing, step: function( now, fx ) { fx.now = Math.round( now ); } } ); toShow .hide() .animate( this.showProps, { duration: duration, easing: easing, complete: complete, step: function( now, fx ) { fx.now = Math.round( now ); if ( fx.prop !== "height" ) { if ( boxSizing === "content-box" ) { adjust += fx.now; } } else if ( that.options.heightStyle !== "content" ) { fx.now = Math.round( total - toHide.outerHeight() - adjust ); adjust = 0; } } } ); }, _toggleComplete: function( data ) { var toHide = data.oldPanel, prev = toHide.prev(); this._removeClass( toHide, "ui-accordion-content-active" ); this._removeClass( prev, "ui-accordion-header-active" ) ._addClass( prev, "ui-accordion-header-collapsed" ); // Work around for rendering bug in IE (#5421) if ( toHide.length ) { toHide.parent()[ 0 ].className = toHide.parent()[ 0 ].className; } this._trigger( "activate", null, data ); } } ); } ) );
// convert array-like object into array var GLOBAL = require('./GLOBAL') function toArray (value) { if (value == null) return [] var kind = typeof value if (value.length == null || kind === 'string' || kind === 'function' || value instanceof RegExp || value === GLOBAL ) { // string, regexp, function have .length but user probably just want // to wrap value into array.. return [value] } else { if (Array.isArray(value)) return value // window returns true on isObject in IE7 and may have length // property. `typeof NodeList` returns function on Safari so // we can't use it (#58) var res = [] var n = value.length while (n--) res[n] = value[n] return res } } module.exports = toArray
'use strict'; var Flatbush = require('flatbush'); module.exports = linematch; module.exports.default = linematch; function linematch(lines1, lines2, threshold) { var segments = linesToSegments(lines1); var segments2 = linesToSegments(lines2); var index = new Flatbush(segments2.length / 4); for (var i = 0; i < segments2.length; i += 4) { index.add( Math.min(segments2[i + 0], segments2[i + 2]), Math.min(segments2[i + 1], segments2[i + 3]), Math.max(segments2[i + 0], segments2[i + 2]), Math.max(segments2[i + 1], segments2[i + 3]) ); } index.finish(); var diff = []; var last; while (segments.length) { var by = segments.pop(); var bx = segments.pop(); var ay = segments.pop(); var ax = segments.pop(); var other = index.search( Math.min(ax, bx) - threshold, // minX Math.min(ay, by) - threshold, // minY Math.max(ax, bx) + threshold, // maxX Math.max(ay, by) + threshold // maxY ); var overlap = false; // loop through segments close to the current one, looking for matches; // if a match found, unmatched parts of the segment will be added to the queue for (var j = 0; j < other.length; j++) { var k = other[j] * 4; var matched = matchSegment( ax, ay, bx, by, segments2[k + 0], segments2[k + 1], segments2[k + 2], segments2[k + 3], threshold, segments ); if (matched) { overlap = true; break; } } // if segment didn't match any other segments, add it to the diff if (!overlap) { // join segment with previous one if possible var p = last && last[last.length - 1]; if (p && p[0] === ax && p[1] === ay) { last.push([bx, by]); } else { last = [[ax, ay], [bx, by]]; diff.push(last); } } } return diff; } function linesToSegments(lines) { var segments = []; for (var i = 0; i < lines.length; i++) { var line = lines[i]; for (var j = line.length - 1; j > 0; j--) { var a = line[j - 1]; var b = line[j]; if (a[0] !== b[0] || a[1] !== b[1]) { addSegment(segments, a[0], a[1], b[0], b[1]); } } } return segments; } // subtract segment [c, d] from [a, b] within threshold r function matchSegment(ax, ay, bx, by, cx, cy, dx, dy, r, result) { var len = result.length; var ap = closePoint(ax, ay, cx, cy, dx, dy, r); var bp = closePoint(bx, by, cx, cy, dx, dy, r); // a----b // c---ap---bp---d if (ap !== null && bp !== null) return true; // fully covered var cp = closePoint(cx, cy, ax, ay, bx, by, r); var dp = closePoint(dx, dy, ax, ay, bx, by, r); if (cp !== null && cp === dp) return false; // degenerate case, no overlap var cpx, cpy, dpx, dpy; if (cp !== null) { cpx = interp(ax, bx, cp); cpy = interp(ay, by, cp); } if (dp !== null) { dpx = interp(ax, bx, dp); dpy = interp(ay, by, dp); } if (cp !== null && dp !== null) { if (cpx === dpx && cpy === dpy) return false; // degenerate case // a---cp---dp---b // c----d if (cp < dp) { if (!equals(ax, ay, cpx, cpy)) addSegment(result, ax, ay, cpx, cpy); if (!equals(dpx, dpy, bx, by)) addSegment(result, dpx, dpy, bx, by); // a---dp---cp---b // d----c } else { if (!equals(ax, ay, dpx, dpy)) addSegment(result, ax, ay, dpx, dpy); if (!equals(cpx, cpy, bx, by)) addSegment(result, cpx, cpy, bx, by); } } else if (cp !== null) { // a----cp---b // d---ap---c if (ap !== null && !equals(ax, ay, cpx, cpy)) addSegment(result, cpx, cpy, bx, by); // a---cp---b // c----bp---d else if (bp !== null && !equals(cpx, cpy, bx, by)) addSegment(result, ax, ay, cpx, cpy); } else if (dp !== null) { // a---dp---b // d----bp---c if (bp !== null && !equals(dpx, dpy, bx, by)) addSegment(result, ax, ay, dpx, dpy); // a----dp---b // c---ap---d else if (ap !== null && !equals(ax, ay, dpx, dpy)) addSegment(result, dpx, dpy, bx, by); } return result.length !== len; // segment processed } function addSegment(arr, ax, ay, bx, by) { arr.push(ax); arr.push(ay); arr.push(bx); arr.push(by); } function interp(a, b, t) { return a + (b - a) * t; } // find a closest point from a given point p to a segment [a, b] // if it's within given square distance r function closePoint(px, py, ax, ay, bx, by, r) { var x = ax, y = ay, dx = bx - x, dy = by - y; if (dx !== 0 || dy !== 0) { var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy); if (t >= 1) { x = bx; y = by; t = 1; } else if (t > 0) { x += dx * t; y += dy * t; } else { t = 0; } } dx = px - x; dy = py - y; return dx * dx + dy * dy < r * r ? t : null; } function equals(ax, ay, bx, by) { var dx = Math.abs(ax - bx); var dy = Math.abs(ay - by); return dx < 1e-12 && dy < 1e-12; }
'use strict'; var fs = require('fs'); var path = require('path'); var http = require('http'); var https = require('https'); var expect = require('expect.js'); var request = require('request'); var express = require('express'); var constants = require('constants'); var requireHttps = require('../index'); describe('require-https', function () { var app; before(function () { app = express(); app.use(requireHttps()); app.get('/', function (req, res) { res.json({ hello: 'world' }); }); app.use(function (err, req, res, next) { res.sendStatus(err.status || 500); }); }); it('should complain when https is not used', function (done) { var server = http.createServer(app); server.listen(1234, '127.0.0.1', function () { request('http://127.0.0.1:1234/', { json: true}, function (error, response, body) { expect(response.statusCode).to.be(403); server.close(done); }); }); }); it('should allow requests to pass when https is used', function (done) { var server = https.createServer({ secureProtocol: 'SSLv23_method', // disable insecure SSLv2 and SSLv3 secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3, key: fs.readFileSync(path.join(__dirname, 'server.key')), cert: fs.readFileSync(path.join(__dirname, 'server.crt')) }, app); server.listen(1234, '127.0.0.1', function () { request('https://127.0.0.1:1234/', { strictSSL: false, json: true }, function (error, response, body) { expect(response.statusCode).to.be(200); expect(body.hello).to.be('world'); server.close(done); }); }); }); });
'use strict'; var expect = require('chai').expect, serviceUrlFinder = require('./index'); describe('serviceUrlFinder', function() { it('discovers service URL overrides on SERVICE_NAME_URL', function() { process.env['SOME_SERVICE_URL'] = 'service://1.3.1.3:666'; expect(serviceUrlFinder('some-service', 666)).to.equal('service://1.3.1.3:666'); delete process.env['SOME_SERVICE_URL']; }); it('discovers docker URLs on SERVICE_NAME_PORT_9999_TCP', function() { process.env['SOME_SERVICE_PORT_666_TCP'] = 'tcp://1.3.3.1:666'; expect(serviceUrlFinder('some-service', 666)).to.equal('tcp://1.3.3.1:666'); delete process.env['SOME_SERVICE_PORT_666_TCP']; }); it('discovers docker URLs on SERVICE_NAME_PORT_9999_UDP', function() { process.env['SOME_SERVICE_PORT_666_UDP'] = 'udp://1.3.3.1:666'; expect(serviceUrlFinder('some-service', 666)).to.equal('udp://1.3.3.1:666'); delete process.env['SOME_SERVICE_PORT_666_UDP']; }); it('falls back to defaultHost if all other options fail', function() { expect(serviceUrlFinder('some-service', 666, '1.3.1.3')).to.equal('some-service://1.3.1.3:666'); }); it('falls back to 127.0.0.1 if defaultHost was not supplied', function() { expect(serviceUrlFinder('some-service', 666)).to.equal('some-service://127.0.0.1:666'); }); });
/*! * NsWeb Angular Gruntfile * @author Jovica Čonkić */ 'use strict'; /** * Livereload and connect variables */ var LIVERELOAD_PORT = 35729; var serveStatic = require('serve-static'); var rewrite = require('connect-modrewrite'); var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT }); var mountFolder = function (connect, dir) { return serveStatic(require('path').resolve(dir.toString())); }; /** * Grunt module */ module.exports = function (grunt) { var version = grunt.option('semver') || 'patch'; /** * Dynamically load npm tasks */ require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); /** * NsWeb Angular Grunt config */ grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), /** * Set project info */ project: { src: 'app/assets', app: 'app', dist: 'dist', dist_src: 'dist/assets', e2e_test: 'e2e-tests', unit_test: 'unit-tests', index: [ '<%- project.app %>/index.html' ], assets: '<%- project.app %>/assets', css: [ 'src/scss/style.scss' ], js: [ '<%- project.src %>/js/*.js' ] }, /** * Injector * https://github.com/klei/grunt-injector * Inject references to files into other files * (think scripts and stylesheets into an html file) */ injector: { options: { ignorePath: ['<%- project.app %>/', '<%- project.dist %>/'], addRootSlash: false, template: '<%- project.app %>/index.html' }, dev: { files: { '<%- project.app %>/index.html': [ '<%- project.assets %>/js/**/*.js', '<%- project.assets %>/app/**/*.js', '<%- project.assets %>/css/*.css' ] } }, dist: { options: { min: true }, files: { '<%- project.dist %>/index.html': [ '<%- project.dist_src %>/js/**/*.js', '<%- project.dist_src %>/app/**/*.js', '<%- project.dist_src %>/css/*.css' ] } }, bower: { options: { starttag: '<!-- bower:{{ext}} -->', endtag: '<!-- endbower -->', min: true }, files: { '<%- project.app %>/index.html': 'bower.json' } } }, /** * Project banner * Dynamically appended to CSS/JS files * Inherits text from package.json */ tag: { banner: '/*!\n' + ' * <%- pkg.name %>\n' + ' * <%- pkg.title %>\n' + ' * <%- pkg.url %>\n' + ' * @author <%- pkg.author %>\n' + ' * @version <%- pkg.version %>\n' + ' * Copyright <%- pkg.copyright %>. <%- pkg.license %> licensed.\n' + ' */\n' }, /** * Bump * https://github.com/vojtajina/grunt-bump * Bump package version, create tag, commit, push . */ bump: { options: { files: ['package.json', 'config.json'] } }, /** * Files revisioning * https://github.com/yeoman/grunt-filerev * Static asset revisioning through file content hash */ filerev: { dist: { options: { encoding: 'utf8', algorithm: 'md5', length: 8 }, files: [{ src: [ '<%- project.dist_src %>/app/**/*.js', '<%- project.dist_src %>/js/**/*.js', '<%- project.dist_src %>/css/**/*.css' ] }] } }, /** * Connect port/livereload * https://github.com/gruntjs/grunt-contrib-connect * Starts a local webserver and injects * livereload snippet */ connect: { options: { port: 9000, hostname: '*' }, livereload: { options: { base: 'app', middleware: function (connect, options) { var rules = [ '!\\.html|\\.js|\\.css|\\.svg|\\.jp(e?)g|\\.png|\\.gif$ /index.html [L]' ]; return [ rewrite(rules), lrSnippet, mountFolder(connect, options.base) ]; } } }, test: { options: { base: 'app', middleware: function (connect, options) { var rules = [ '!\\.html|\\.js|\\.css|\\.svg|\\.jp(e?)g|\\.png|\\.gif$ /index.html [L]' ]; return [ rewrite(rules), mountFolder(connect, options.base) ]; } } } }, /** * Copy * https://github.com/gruntjs/grunt-contrib-copy * Copy files and folders */ copy: { main: { expand: true, cwd: '<%- project.app %>/', src: ['**/*', '!**/assets/css/**', '!**/assets/js/**', '!**/assets/app/**/*.js'], dest: '<%- project.dist %>', }, }, /** * NG Constant * https://github.com/werk85/grunt-ng-constant * Create angular constants */ ngconstant: { dev: { options: { dest: '<%- project.assets %>/js/config.js', wrap: "(function () {\n'use strict';\n {%= __ngModule %} })();", name: 'config', space: ' ' }, constants: function () { var pkg = grunt.file.readJSON('config.json'); pkg.env = 'DEV'; pkg.description = 'We are in development!'; return { envPackage: pkg }; }, values: { debug: false } }, dist: { options: { dest: '<%- project.assets %>/js/config.js', wrap: "(function () {\n'use strict';\n {%= __ngModule %} })();", name: 'config', space: ' ' }, constants: function () { var pkg = grunt.file.readJSON('config.json'); pkg.env = 'PROD'; pkg.description = 'We are in production!'; return { envPackage: pkg }; }, values: { debug: false } } }, /** * HTMLmin * https://github.com/gruntjs/grunt-contrib-htmlmin * Minify HTML */ htmlmin: { dist: { options: { removeComments: true, collapseWhitespace: true }, files: [{ expand: true, cwd: '<%- project.dist %>/', src: '*.html', dest: '<%- project.dist %>/' }, { expand: true, cwd: '<%- project.dist_src %>/app/', src: '**/*.html', dest: '<%- project.dist_src %>/app/' }] } }, /** * JSHint * https://github.com/gruntjs/grunt-contrib-jshint * Manage the options inside .jshintrc file */ jshint: { files: [ '<%- project.src %>/js/{,*/}*.js', '<%- project.src %>/app/{,*/}*.js', '<%- project.e2e_test %>/specs/{,*/}*.js', '<%- project.unit_test %>/specs/{,*/}*.js' ], options: { jshintrc: '.jshintrc' } }, /** * Uglify (minify) JavaScript files * https://github.com/gruntjs/grunt-contrib-uglify * Compresses and minifies all JavaScript files */ uglify: { options: { banner: "<%- tag.banner %>", report: 'min', mangle: true, compress: { sequences: true, dead_code: true, conditionals: true, booleans: true, unused: true, if_return: true, join_vars: true, drop_console: true } }, dist: { files: [ { expand: true, cwd: '<%- project.src %>/js/', src: '**/*.js', dest: '<%- project.dist_src %>/js/', rename: function(destBase, destPath) { return destBase+destPath.replace('.js', '.min.js'); } }, { expand: true, cwd: '<%- project.src %>/app/', src: '**/*.js', dest: '<%- project.dist_src %>/app/', rename: function(destBase, destPath) { return destBase+destPath.replace('.js', '.min.js'); } } ] } }, /** * Minify PNG and JPEG images * https://github.com/gruntjs/grunt-contrib-imagemin * Compresses and minify images */ imagemin: { dist: { options: { optimizationLevel: 3, progressive: true, interlaced: true }, files: [{ expand: true, cwd: '<%- project.dist_src %>/images/', src: ['**/*.{png,PNG,jpg,JPG,jpeg,JPEG,gif,GIF}'], dest: '<%- project.dist_src %>/images/' }, { expand: true, cwd: '<%- project.dist %>/', src: ['*.{png,PNG,jpg,JPG,jpeg,JPEG,gif,GIF,ico,ICO}'], dest: '<%- project.dist %>/' }] } }, /** * Clean * https://github.com/gruntjs/grunt-contrib-clean * Clean files and folders */ clean: { dist: [ '<%- project.dist %>' ] }, /** * Compile Sass/SCSS files * https://github.com/gruntjs/grunt-contrib-sass * Compiles all Sass/SCSS files and appends project banner */ sass: { dev: { options: { compass: true, noCache: true, style: 'expanded' }, files: { '<%- project.assets %>/css/style.css': '<%- project.css %>' } }, dist: { options: { compass: true, noCache: true, sourcemap: 'none', style: 'compressed' }, files: { '<%- project.dist_src %>/css/style.min.css': '<%- project.css %>' } } }, /** * Opens the web server in the browser * https://github.com/jsoverson/grunt-open */ open: { server: { path: 'http://localhost:<%- connect.options.port %>' } }, /** * Runs tasks against changed watched files * https://github.com/gruntjs/grunt-contrib-watch * Watching development files and run concat/compile tasks * Livereload the browser once complete */ watch: { scripts: { files: [ '<%- project.assets %>/js/{,*/}*.js', '<%- project.assets %>/app/{,*/}*.js', '<%- project.e2e_test %>/specs/{,*/}*.js', '<%- project.unit_test %>/specs/{,*/}*.js' ], tasks: ['jshint'], options: { spawn: false } }, karma: { files: [ '<%- project.src %>/js/{,*/}*.js', '<%- project.src %>/app/{,*/}*.js', '<%- project.e2e_test %>/specs/{,*/}*.js', '<%- project.unit_test %>/specs/{,*/}*.js' ], tasks: ['karma:continuous:run'] }, sass: { files: 'src/scss/{,*/}*.{scss,sass}', tasks: ['sass:dev'] }, livereload: { options: { livereload: LIVERELOAD_PORT }, files: [ '<%- project.app %>/{,*/}*.html', '<%- project.assets %>/app/{,*/}*.html', '<%- project.assets %>/css/{,*/}*.css', '<%- project.assets %>/js/{,*/}*.js', '<%- project.assets %>/app/{,*/}*.js', '<%- project.assets %>/images/{,*/}*.{png,PNG,jpg,JPG,jpeg,JPEG,gif,GIF,webp,WEBP,svg,SVG}' ] } }, /** * Runs shell commands * https://github.com/sindresorhus/grunt-shell * Webdriver-manager update command */ shell: { protractor_update: { options: { stdout: true }, command: 'node node_modules/protractor/bin/webdriver-manager update' } }, /** * Runs karma unit tests * https://github.com/karma-runner/grunt-karma */ karma: { options: { configFile: '<%- project.unit_test %>/karma.conf.js', }, unit: { port: 9000, singleRun: true, browsers: ['Chrome', 'Firefox'] }, continuous: { reporters: 'dots', singleRun: false, browsers: ['PhantomJS'], background: true } }, /** * Grunt plugin for running Protractor runner * https://github.com/teerapap/grunt-protractor-runner * Run protractor described tests */ protractor: { options: { configFile: "node_modules/protractor/example/conf.js", noColor: true, debug: false, args: { } }, e2e: { options: { configFile: "<%- project.e2e_test %>/protractor.conf.js", keepAlive: false } } } }); /** * Default task * Run `grunt` on the command line */ grunt.registerTask('default', [ 'sass:dev', 'ngconstant:dev', 'jshint', 'injector:dev', 'injector:bower', 'connect:livereload', 'open', 'karma:continuous:start', 'watch' ]); /** * Build task * Run `grunt build` on the command line * Then clean, copy, minify and optimize content for distribution */ grunt.registerTask('build', [ 'clean', 'bump-only:'+ version, 'sass:dist', 'test', 'copy', 'jshint', 'ngconstant:dist', 'uglify', 'filerev:dist', 'injector:dist', 'injector:bower', 'imagemin:dist', 'htmlmin:dist' ]); /** * Test task * Run `grunt e2e-test` on the command line * Then test all described tests using protractor selenium wrapper */ grunt.registerTask('test', [ 'shell:protractor_update', 'jshint', 'connect:test', 'protractor:e2e', 'karma:unit' ]); };
require('../css/index.scss')
var _ = require('lodash'); var bodyParser = require('body-parser'); var express = require('express'); var request = require('superagent'); var LineBot = require('line-bot-sdk'); var client = LineBot.client({ channelID: 'YOUR_CHANNEL_ID', channelSecret: 'YOUR_CHANNEL_SECRET', channelMID: 'YOUR_CHANNEL_MID' }); var app = express(); app.set('port', (process.env.PORT || 5000)); app.use(bodyParser.urlencoded({ extended: false, limit: 2 * 1024 * 1024 })); app.use(bodyParser.json({ limit: 2 * 1024 * 1024 })); app.post('/', function (req, res) { console.log(req.body.result); var receives = client.createReceivesFromJSON(req.body); _.each(receives, function(receive){ if(receive.isMessage()){ if(receive.isText()){ if(receive.getText()==='me'){ client.getUserProfile(receive.getFromMid()) .then(function onResult(res){ if(res.status === 200){ var contacts = res.body.contacts; if(contacts.length > 0){ client.sendText(receive.getFromMid(), 'Hi!, you\'re ' + contacts[0].displayName); } } }, function onError(err){ console.error(err); }); } else { client.sendText(receive.getFromMid(), receive.getText()); } }else if(receive.isImage()){ client.sendText(receive.getFromMid(), 'Thanks for the image!'); }else if(receive.isVideo()){ client.sendText(receive.getFromMid(), 'Thanks for the video!'); }else if(receive.isAudio()){ client.sendText(receive.getFromMid(), 'Thanks for the audio!'); }else if(receive.isLocation()){ client.sendLocation( receive.getFromMid(), receive.getText() + receive.getAddress(), receive.getLatitude(), receive.getLongitude() ); }else if(receive.isSticker()){ // This only works if the BOT account have the same sticker too client.sendSticker( receive.getFromMid(), receive.getStkId(), receive.getStkPkgId(), receive.getStkVer() ); }else if(receive.isContact()){ client.sendText(receive.getFromMid(), 'Thanks for the contact'); }else{ console.error('found unknown message type'); } }else if(receive.isOperation()){ console.log('found operation'); }else { console.error('invalid receive type'); } }); res.send('ok'); }); app.listen(app.get('port'), function () { console.log('Listening on port ' + app.get('port')); });
import React from 'react'; import PropTypes from 'prop-types'; import { Loading } from '../common'; import { Student } from '../../containers/ViewStudents'; const StudentListView = ({ loading, studentIds, studentGroupNodeId, hasPermissions }) => { if (loading) { return <Loading />; } if (!studentIds.length) { return <div>No Students Found!</div>; } return ( <tbody> {studentIds.map((id) => { return ( <Student studentNodeId={id} key={id} studentGroupNodeId={studentGroupNodeId} hasPermissions={hasPermissions} /> ); })} </tbody> ); }; StudentListView.propTypes = { studentIds: PropTypes.array, studentGroupNodeId: PropTypes.string, loading: PropTypes.bool, hasPermissions: PropTypes.bool, }; export { StudentListView };
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-bump'); grunt.initConfig({ /** * Increments the version number, etc. */ bump: { options: { files: [ "package.json" ], commit: true, commitMessage: 'chore(release): v%VERSION%', commitFiles: [ "package.json" ], createTag: true, tagName: 'v%VERSION%', tagMessage: 'Version %VERSION%', push: true, pushTo: 'origin' } }, }); };
//----------------------------------------------------------------------------- // Allows the elegant retrieval of a JSON value using a starting reference, // an evaluated string, and a configurable return value or behaviour when not // found. // // Saves you from the repition of 'if... exists...' LOC. //----------------------------------------------------------------------------- (function() { "use strict"; //--------------------------------------------------------------------------- // native node libraries //--------------------------------------------------------------------------- var assert = require('assert'); //--------------------------------------------------------------------------- // npm libraries //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // lib //--------------------------------------------------------------------------- var dryify = require('../dryify.min.js'); describe("dryify.traverse(json, callback)", function() { it("should pass in the non-function values of a JSON object in expected order", function() { // fixture data var json = [{ key0: [{ key2: [{ key3: false }] }], key1: false }]; dryify.traverse(json, function(v, i, path) { if (v === false) { v = i; } return v; }); assert.equal(json[0].key0[0].key2[0].key3, 0); assert.equal(json[0].key1, 1); }); }); }.call(this));
'use strict'; /*eslint-disable no-unused-vars*/ var test = require('tap').test, inferKind = require('../../../lib/infer/kind')(), parse = require('../../../lib/parsers/javascript'); function toComment(fn, filename) { return parse({ file: filename, source: fn instanceof Function ? '(' + fn.toString() + ')' : fn })[0]; } test('inferKind', function (t) { t.equal(inferKind({ kind: 'class', tags: [] }).kind, 'class', 'explicit'); t.equal(inferKind(toComment(function () { /** function */ function foo() { } foo(); })).kind, 'function', 'inferred function'); t.equal(inferKind(toComment(function () { /** function */ var foo = function () { }; foo(); })).kind, 'function', 'inferred var function'); t.equal(inferKind(toComment( 'class Foo { /** set b */ set b(v) { } }' )).kind, 'member', 'member via set'); t.equal(inferKind(toComment( 'var foo = { /** thing */ b: function(v) { } }' )).kind, 'function', 'function via set'); t.equal(inferKind(toComment( 'class Foo { /** get b */ get b() { } }' )).kind, 'member', 'member via get'); t.equal(inferKind(toComment( 'class Foo { /** b */ b(v) { } }' )).kind, 'function', 'normal function as part of class'); t.equal(inferKind(toComment(function () { /** class */ function Foo() { } })).kind, 'class', 'class via uppercase'); t.equal(inferKind(toComment(function () { /** undefined */ })).kind, undefined, 'undetectable'); t.equal(inferKind(toComment( '/**' + ' * This is a constant called foo' + ' */' + 'const foo = "bar";')).kind, 'constant', 'constant via const'); t.end(); });
'use strict' const got = require('got') const config = require('./config') const util = require('./util') const Team = require('./schema').Team /** * Handles the /oauth page */ async function route(ctx) { await util.login(ctx.state, ctx.session) const code = ctx.request.query.code const oauthKey = ctx.request.query.state // If you don't have all these things you probably shouldn't be here if (!ctx.state.loggedIn || !ctx.state.oauthKey || !oauthKey || !code) { return ctx.redirect('/') } ctx.state.success = false // Check that the oauth request is legit using the oauthKey generated on login if (oauthKey === ctx.state.oauthKey) { // Get the access token const response = await got('https://slack.com/api/oauth.access', { json: true, form: true, timeout: 5000, query: { /* eslint-disable camelcase */ client_id: config.get('slack:id'), client_secret: config.get('slack:secret'), /* eslint-enable camelcase */ code } }) // Normalise the response object .then(res => res.body) .catch(err => ({ok: false, err})) if (response.warning) { util.log('warn', new Error(response.warning)) } if (response.ok) { // Add or update the team await Team.findByIdAndUpdate( response.team_id, { _id: response.team_id, name: response.team_name, accessToken: response.access_token, botUserId: response.bot.bot_user_id, botAccessToken: response.bot.bot_access_token }, { upsert: true } ).exec() ctx.state.success = true } else { util.log('error', new Error(response.error)) } } await ctx.render('oauth') } module.exports = route
require('app/core'); require('app/views/login'); App.reopen({ store: DS.Store.create(), ApplicationController: Em.Controller.extend(), ApplicationView: Em.View.extend({ templateName: 'application' }), Router: Ember.Router.extend({ enableLogging: true, location: 'hash', root: Ember.Route.extend({ gotoLogin: Ember.Route.transitionTo('login'), index: Em.Route.extend({ route: '/', redirectsTo: 'login' }), login: Ember.Route.extend({ route: '/login', connectOutlets: function(router, context) { return router.get('applicationController').connectOutlet({name: 'login'}); }, enter: function() { console.log('entered login'); }, exit: function() { console.log('exited login'); }, }) }) }) }); $(function() { App.initialize(); });
// Generate an arbitrary wave-form // from a left-right function. var _ = require('lodash'), wav = require('wav'), streamBuffers = require("stream-buffers"), fs = require('fs'); function Function(opts) { _.extend(this, { file: null, // path to file. offset: 0, buffer: null, left: null, right: null, counter: 0 }, opts); } Function.prototype.tick = function(vector, frames) { for (var i = 0; i < frames; i++) { this.counter ++; vector.write(0, i, this.left(this.counter)) vector.write(1, i, this.right(this.counter)) } }; module.exports = Function;
/* jslint undef: true */ /* global window, document, $ */ /* ---------------------------------------------------------------- * camera.js * * Made by shash7 * https://github.com/shash7/camera * * Licensed under the MIT license * * Api usage : * * var camera = new Camera(); * camera.start(); * camera.snap(); * camera.stop(); * ---------------------------------------------------------------- */ ;(function(window, document, undefined) { 'use strict'; function camera(opts) { opts = opts || {}; /* ---------------------------------------------------------------- * globals * ---------------------------------------------------------------- */ var permission = false; var api = false; var localStream = null; var active = false; var filters = {}; var currentFilter = 'grayscale'; var timer = null; var resource = { audio : false, video : true }; // DOM elements var canvas; var video; var body; var snapButton; var container; var hidden; var closeButton; // Canvas contexts var ctx; var hiddenCtx; // Options var onSuccess = null; var onError = null; var onSnap = null; var fps = 33; var baseDimension = 64; var mirror = true; // Control variables. Don't mess around with 'em var buttonActive = false; var previewWidth = 128; var previewHeight = 100; // Default filters filters.grayscale = function(img) { var d = img.data; for (var i=0; i<d.length; i+=4) { var r = d[i]; var g = d[i+1]; var b = d[i+2]; // CIE luminance for the RGB // The human eye is bad at seeing red and blue, so we de-emphasize them. var v = 0.2126*r + 0.7152*g + 0.0722*b; d[i] = d[i+1] = d[i+2] = v; } return img; }; filters.brightness = function(img, adjustment) { adjustment = adjustment || 50; var d = img.data; for (var i=0; i<d.length; i+=4) { d[i] += adjustment; d[i+1] += adjustment; d[i+2] += adjustment; } return img; }; /* ---------------------------------------------------------------- * private functions * ---------------------------------------------------------------- */ function setOptions(opts) { onSuccess = opts.onSuccess || null; onError = opts.onError || null; onSnap = opts.onSnap || null; currentFilter = opts.filter || ''; if(opts.mirror !== undefined) { // Because false is a falsy value so I used undefined if(!opts.mirror) { mirror = false; } } fps = 1000/opts.fps || 33; } function hasGetUserMedia() { var result = !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); if(result) { navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; return true; } else { return false; } } function createNodes() { body = document.getElementsByTagName('body')[0]; container = document.createElement('div'); container.className = 'camera-container'; canvas = document.createElement('canvas'); canvas.className = 'camera-preview'; container.appendChild(canvas); snapButton = document.createElement('div'); snapButton.className = 'camera-snap-button'; closeButton = document.createElement('button'); closeButton.className = 'camera-close-button icon-cross'; container.appendChild(closeButton); container.appendChild(snapButton); canvas.width = previewWidth; canvas.height = previewHeight; body.appendChild(container); video = document.createElement('video'); body.appendChild(video); video.className = 'camera-hidden'; hidden = document.createElement('canvas'); } function getDimensions() { var width = video.videoWidth || baseDimension; var height = video.videoHeight || baseDimension; var ratio = 1; if(width > height) { ratio = width/height; height = baseDimension; width = ratio*baseDimension; } else { ratio = height/width; width = baseDimension; height = ratio*baseDimension; } previewWidth = width; previewHeight = height; } function play(stream) { localStream = stream; // Setup video and play if (video.mozSrcObject !== undefined) { video.mozSrcObject = stream; } else { video.src = (window.URL && window.URL.createObjectURL(stream)) || stream; } video.play(); } function bindListners() { video.addEventListener('play', drawVideo, false); snapButton.addEventListener('click', takePhoto, false); closeButton.addEventListener('click', stop, false); } function unbindListners() { video.removeEventListener('play', drawVideo, false); snapButton.removeEventListener('click', takePhoto, false); closeButton.removeEventListener('click', stop, false); } function takePhoto(e) { if(!buttonActive) { snap(); buttonActive = true; setTimeout(function() { buttonActive = false; }, 200); } } function drawVideo() { var invert = 1; if(mirror) { ctx.scale(-1,1); invert = -1; } // Every 33 milliseconds copy the video image to the canvas timer = setInterval(function() { // This try-catch block is only for firefox try { ctx.drawImage(video, 0, 0, previewWidth * invert, previewHeight); // TODO add proper support for covulated filters var arr = [ 1/9,1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9]; // applyConvolutedFilter(imageData, arr, ctx); if(currentFilter) { var imageData = ctx.getImageData(0,0,previewWidth,previewHeight); applyFilter(imageData, ctx); } } catch (e) { if (e.name == "NS_ERROR_NOT_AVAILABLE") { // Wait for sometime then draw again, courtesy of firefox. // Taken from http://stackoverflow.com/questions/18580844/firefox-drawimagevideo-fails-with-ns-error-not-available-component-is-not-av // Also, overrides fps // Also, inverting won't work for firefox mirror = false; setTimeout(drawVideo, 500); } else { throw e; } } }, fps); } function applyFilter(img, context) { var imageData = filters[currentFilter](img); context.putImageData(imageData, 0, 0); } function applyConvolutedFilter(img, weights, context, opaque) { var side = Math.round(Math.sqrt(weights.length)); var halfSide = Math.floor(side/2); var src = img.data; var sw = img.width; var sh = img.height; // pad output by the convolution matrix var w = sw; var h = sh; var output = img; var dst = output.data; // go through the destination image pixels var alphaFac = opaque ? 1 : 0; for (var y=0; y<h; y++) { for (var x=0; x<w; x++) { var sy = y; var sx = x; var dstOff = (y*w+x)*4; // calculate the weighed sum of the source image pixels that // fall under the convolution matrix var r=0, g=0, b=0, a=0; for (var cy=0; cy<side; cy++) { for (var cx=0; cx<side; cx++) { var scy = sy + cy - halfSide; var scx = sx + cx - halfSide; if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) { var srcOff = (scy*sw+scx)*4; var wt = weights[cy*side+cx]; r += src[srcOff] * wt; g += src[srcOff+1] * wt; b += src[srcOff+2] * wt; a += src[srcOff+3] * wt; } } } dst[dstOff] = r; dst[dstOff+1] = g; dst[dstOff+2] = b; dst[dstOff+3] = a + alphaFac*(255-a); } } context.putImageData(output, 0, 0); } function successCallback(stream) { if (typeof onSuccess === "function") { onSuccess(stream); } else { createNodes(); bindListners(); ctx = canvas.getContext('2d'); play(stream); } } function errorCallback(error) { if (typeof onSuccess === "function") { onError(stream); } else { return error; } } /* ---------------------------------------------------------------- * public functions * ---------------------------------------------------------------- */ function start() { if(active) { console.log(active); } if(active === false) { // Weird, eh? var result = hasGetUserMedia(); if(result) { setOptions(opts); navigator.getUserMedia(resource, successCallback, errorCallback); active = true; } else { return false; } } } function snap() { hidden.width = video.videoWidth; hidden.height = video.videoHeight; hiddenCtx = hiddenCtx || hidden.getContext('2d'); var invert = 1; if(mirror) { hiddenCtx.scale(-1,1); invert = -1; } hiddenCtx.fillRect(0, 0, video.videoWidth, video.videoHeight); hiddenCtx.drawImage(video, 0, 0, video.videoWidth * invert, video.videoHeight); if(currentFilter) { var imageData = hiddenCtx.getImageData(0,0,video.videoWidth,video.videoHeight); applyFilter(imageData, hiddenCtx); } var dataURL = hidden.toDataURL(); if(onSnap) { onSnap(dataURL); } console.log(dataURL); return dataURL; } function stop() { clearInterval(timer); unbindListners(); while (container.firstChild) { container.removeChild(container.firstChild); } localStream.stop(); active = false; } return { snap : snap, start : start, stop : stop }; } window.Camera = camera; })(window, document);
var TWEEN_CONST = require('../const'); var ResetTweenData = function (resetFromLoop) { var data = this.data; for (var i = 0; i < this.totalData; i++) { var tweenData = data[i]; tweenData.progress = 0; tweenData.elapsed = 0; tweenData.repeatCounter = (tweenData.repeat === -1) ? 999999999999 : tweenData.repeat; if (resetFromLoop) { tweenData.start = tweenData.getStartValue(tweenData.target, tweenData.key, tweenData.start); tweenData.end = tweenData.getEndValue(tweenData.target, tweenData.key, tweenData.end); tweenData.current = tweenData.start; tweenData.state = TWEEN_CONST.PLAYING_FORWARD; } else if (tweenData.delay > 0) { tweenData.elapsed = tweenData.delay; tweenData.state = TWEEN_CONST.DELAY; } else { tweenData.state = TWEEN_CONST.PENDING_RENDER; } } }; module.exports = ResetTweenData;
/* * Copyright 2014-2015 MarkLogic Corporation * * 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. */ var exutil = require('./example-util.js'); //a real application would require without the 'exutil.' namespace var marklogic = exutil.require('marklogic'); var db = marklogic.createDatabaseClient(exutil.restWriterConnection); var timestamp = (new Date()).toISOString(); console.log('Transform a document on the client'); db.documents.read('/countries/uv.json') .result(function(documents) { var documentBefore = documents[0]; console.log('before: '+ documentBefore.content.name+' on '+ documentBefore.content.timestamp ); documentBefore.content.timestamp = timestamp; return db.documents.write(documentBefore).result(); }) .then(function(response) { var uri = response.documents[0].uri; console.log('modified: '+uri); return db.documents.read(uri).result(); }) .then(function(documents) { var documentAfter = documents[0]; console.log('after: '+ documentAfter.content.name+' on '+ documentAfter.content.timestamp ); console.log('done'); exutil.succeeded(); }) .catch(function(error) { console.log(JSON.stringify(error)); exutil.failed(); });
import Dispatcher from '../dispatchers/Dispatcher' const moment = require('moment'); export async function createBrew (beerName) { let raw = { "beerName": beerName, "startDate": moment(), "endDate": "9999-09-09T03:00:00.000Z", "userId": "580d60ce308e440011e556ca" }; let data = new FormData(); data.append("json", JSON.stringify(raw)); let request = new Request('http://birrapp-back.herokuapp.com/api/brews',{ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: 'POST', body: JSON.stringify(raw) }); let response = await fetch(request); let responseJson = await response.json(); Dispatcher.dispatch({ type: 'CREATE_BREW', beer: responseJson }); }; export async function deleteBrew (id) { let request = new Request('https://birrapp-back.herokuapp.com/api/brews/'+id,{ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: 'DELETE' }); await fetch(request); Dispatcher.dispatch({ type: 'DELETE_BREW', 'id': id }) }; export function changeBrew (id,name) { Dispatcher.dispatch({ type: 'CHANGE_BREW', 'id': id, 'name': name }) };
//TODO: Disable buttons during configured form save. // Variables. var app = angular.module("umbraco"); // Associate directive/controller. app.directive("formulateConfiguredFormDesigner", directive); app.controller("formulate.configuredFormDesigner", controller); // Directive. function directive(formulateDirectives) { return { restrict: "E", template: formulateDirectives.get("configuredFormDesigner/designer.html"), controller: "formulate.configuredFormDesigner" }; } // Controller. function controller($scope, $routeParams, $route, formulateTrees, formulateConfiguredForms, $location, formulateTemplates, editorService, formulateLayouts) { // Variables. var id = $routeParams.id; var isNew = id === "null"; var parentId = $routeParams.under; var hasParent = !!parentId; var services = { formulateTrees: formulateTrees, formulateConfiguredForms: formulateConfiguredForms, formulateTemplates: formulateTemplates, editorService: editorService, formulateLayouts: formulateLayouts, $scope: $scope, $route: $route, $location: $location }; // Set scope variables. $scope.isNew = isNew; $scope.info = { conFormName: null }; $scope.parentId = null; $scope.template = { id: null, templates: [] }; if (!isNew) { $scope.conFormId = id; } if (hasParent) { $scope.parentId = parentId; } // Set scope functions. $scope.save = getSaveConfiguredForm(services); $scope.canSave = getCanSave(services); $scope.pickLayout = getPickLayout(services); // Initializes configured form. initializeConfiguredForm({ id: id, isNew: isNew }, services); // Handle events. handleConfiguredFormMoves(services); // Populate templates. populateTemplates(services); } // Populate the templates. function populateTemplates(services) { services.formulateTemplates.getTemplates().then(function (data) { services.$scope.template.templates = data.map(function (item) { return { id: item.id, name: item.name }; }); }); } // Handles updating a configured form when it's moved. function handleConfiguredFormMoves(services) { var $scope = services.$scope; $scope.$on("formulateEntityMoved", function(event, data) { var id = data.id; var newPath = data.path; if ($scope.conFormId === id) { // Store new path. $scope.conFormPath = newPath; // Activate in tree. services.formulateTrees.activateEntity(data); } }); } // Saves the configured form. function getSaveConfiguredForm(services) { return function () { // Variables. var $scope = services.$scope; var parentId = getParentId($scope); // Get configured form data. var conFormData = { parentId: parentId, conFormId: $scope.conFormId, name: $scope.info.conFormName, layoutId: $scope.layoutId, templateId: $scope.template.id }; // Persist configured form on server. services.formulateConfiguredForms.persistConfiguredForm(conFormData) .then(function(responseData) { // Configured form is no longer new. var isNew = $scope.isNew; $scope.isNew = false; // Prevent "discard" notification. $scope.formulateConfiguredFormDesigner.$dirty = false; // Redirect or reload page. if (isNew) { var url = "/formulate/formulate/editConfiguredForm/" + responseData.id; services.$location.url(url); } else { // Even existing configured forms reload (e.g., to get new data). services.$route.reload(); } }); }; } // Gets the ID path to the configured form. function getConfiguredFormPath($scope) { var path = $scope.conFormPath; if (!path) { path = []; } return path; } // Gets the ID of the configured form's parent. function getParentId($scope) { if ($scope.parentId) { return $scope.parentId; } var path = getConfiguredFormPath($scope); var parentId = path.length > 0 ? path[path.length - 2] : null; return parentId; } // Initializes the configured form. function initializeConfiguredForm(options, services) { // Variables. var id = options.id; var $scope = services.$scope; var isNew = options.isNew; // Is this a new configured form? if (isNew) { // The configured form can be saved now. $scope.initialized = true; } else { // Disable configured form saving until the data is populated. $scope.initialized = false; // Get the configured form info. services.formulateConfiguredForms.getConfiguredFormInfo(id) .then(function(conForm) { // Update tree. services.formulateTrees.activateEntity(conForm); // Set the configured form info. $scope.conFormId = conForm.conFormId; $scope.info.conFormName = conForm.name; $scope.conFormPath = conForm.path; $scope.layoutId = conForm.layoutId; $scope.template.id = conForm.templateId; // The configured form can be saved now. $scope.initialized = true; // Refresh layout info. refreshLayoutInfo(conForm.layoutId, services); }); } } // Returns the function that indicates whether or not the configured form can be saved. function getCanSave(services) { return function() { return services.$scope.initialized; }; } // Returns the function that allows the user to pick a form. function getPickLayout(services) { var editorService = services.editorService; var $scope = services.$scope; return function () { var layouts = $scope.layoutId ? [$scope.layoutId] : []; editorService.open({ layouts: layouts, view: "../App_Plugins/formulate/dialogs/pickLayout.html", close: function() { editorService.close(); }, submit: function(data) { // If no layout was chosen, unchoose layout. if (!data.length) { $scope.layoutId = null; $scope.layoutName = null; editorService.close(); return; } // Store layout. var layoutId = data[0]; $scope.layoutId = layoutId; // Refresh layout information. refreshLayoutInfo(layoutId, services); editorService.close(); } }); }; } // Gets the layout name and sets it on the scope. function refreshLayoutInfo(layoutId, services) { if (!layoutId) { return; } services.formulateLayouts.getLayoutInfo(layoutId).then(function (data) { services.$scope.layoutName = data.name; }); }
'use strict'; module.exports = { db: 'mongodb://localhost/experiment-test', port: 3001, app: { title: 'Experiment - Test Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
class VuePlugin { constructor (config) { this.config = config } apply (compiler) { compiler.plugin('done', stats => { if (this.config.spinner) { this.config.spinner.stop() } }) } } export default config => { return new VuePlugin(config) }
/** * Appfy is a JavaScript toolkit that saves your time to build Single Page Applications. It totally modular and based on MEAN stack concept. * * Software licensed under MIT, maintained by Appfy Co and its contributors. Feel free to open an issue or make a PR. * Check out documentation and full list of contributors in https://github.com/Appfy * * Copyright © 2016 Appfy Co <help@appfy.org> * * 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. **/ (function () { 'use strict'; /** * @ngdoc overview * @name appfy.module * @description * Appfy based modules. This module is auto generated by the CLI. Dont touch this file. **/ angular.module('appfy.module', [ 'angular.morris', 'appfy.wiki', 'home' ]); })();
module.exports = function(grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Tasks grunt.initConfig({ less: { development: { options: { paths: ["assets/css/less"] }, files: { "assets/css/specStatus.css": "assets/css/less/specStatus.less" } } }, watch: { less: { files: ['assets/css/less/*.less'], tasks: ['less'], options: { nospawn: true } } } }); grunt.registerTask('default', ['less']); grunt.registerTask('watch-css', ['default','watch']); };
const NODE_LIST_CLASSES = { '[object HTMLCollection]': true, '[object NodeList]': true, '[object RadioNodeList]': true } // .type values for elements which can appear in .elements and should be ignored const IGNORED_ELEMENT_TYPES = { 'button': true, 'fieldset': true, 'reset': true, 'submit': true } const CHECKED_INPUT_TYPES = { 'checkbox': true, 'radio': true } const TRIM_RE = /^\s+|\s+$/g const {slice} = Array.prototype const {toString} = Object.prototype /** * @param {HTMLFormElement} form * @param {Object} [options] * @return {Object.<string,boolean|string|string[]>} an object containing * submittable value(s) held in the form's .elements collection, with * properties named as per element names or ids. */ export default function getFormData(form, options) { if (!form) { throw new Error(`A form is required by getFormData, was given form=${form}`) } options = { includeDisabled: false, trim: false, ...options } let data = {} let elementName let elementNames = [] let elementNameLookup = {} // Get unique submittable element names for the form for (let i = 0, l = form.elements.length; i < l; i++) { let element = form.elements[i] if (IGNORED_ELEMENT_TYPES[element.type] || (element.disabled && !options.includeDisabled)) { continue } elementName = element.name || element.id if (elementName && !elementNameLookup[elementName]) { elementNames.push(elementName) elementNameLookup[elementName] = true } } // Extract element data name-by-name for consistent handling of special cases // around elements which contain multiple inputs. for (let i = 0, l = elementNames.length; i < l; i++) { elementName = elementNames[i] let value = getFieldData(form, elementName, options) if (value != null) { data[elementName] = value } } return data } /** * @param {HTMLFormElement} form * @param {string} fieldName * @param {Object} [options] * @return {?(boolean|string|string[]|File|File[])} submittable value(s) in the * form for a named element from its .elements collection, or null if there * was no element with that name, or the element had no submittable value(s). */ export function getFieldData(form, fieldName, options) { if (!form) { throw new Error(`A form is required by getFieldData, was given form=${form}`) } if (!fieldName && toString.call(fieldName) !== '[object String]') { throw new Error(`A field name is required by getFieldData, was given fieldName=${fieldName}`) } options = { includeDisabled: false, trim: false, ...options } let element = form.elements[fieldName] if (!element || (element.disabled && !options.includeDisabled)) { return null } if (!NODE_LIST_CLASSES[toString.call(element)]) { return getFormElementValue(element, options.trim) } // Deal with multiple form controls which have the same name let data = [] let allRadios = true for (let i = 0, l = element.length; i < l; i++) { if (element[i].disabled && !options.includeDisabled) { continue } if (allRadios && element[i].type !== 'radio') { allRadios = false } let value = getFormElementValue(element[i], options.trim) if (value != null) { data = data.concat(value) } } // Special case for an element with multiple same-named inputs which were all // radio buttons: if there was a selected value, only return the value. if (allRadios && data.length === 1) { return data[0] } return (data.length > 0 ? data : null) } /** * @param {HTMLElement} element a form element. * @param {boolean} [trim] should values for text entry inputs be trimmed? * @return {?(boolean|string|string[]|File|File[])} the element's submittable * value(s), or null if it had none. */ function getFormElementValue(element, trim) { let value = null let {type} = element if (type === 'select-one') { if (element.options.length) { value = element.options[element.selectedIndex].value } return value } if (type === 'select-multiple') { value = [] for (let i = 0, l = element.options.length; i < l; i++) { if (element.options[i].selected) { value.push(element.options[i].value) } } if (value.length === 0) { value = null } return value } // If a file input doesn't have a files attribute, fall through to using its // value attribute. if (type === 'file' && 'files' in element) { if (element.multiple) { value = slice.call(element.files) if (value.length === 0) { value = null } } else { // Should be null if not present, according to the spec value = element.files[0] } return value } if (!CHECKED_INPUT_TYPES[type]) { value = (trim ? element.value.replace(TRIM_RE, '') : element.value) } else if (element.checked) { if (type === 'checkbox' && !element.hasAttribute('value')) { value = true } else { value = element.value } } return value } // For UMD build access to getFieldData getFormData.getFieldData = getFieldData
'use strict'; var View = require('view.js'); var O = require('observable.js'); var Button = require('button.js'); var Splitter = require('splitter.js'); var CodeView = require('codeview.js'); var StackView = require('stackview.js'); var LocalsView = require('localsview.js'); var ConsoleView = require('consoleview.js'); var handleKeys = require('eventutils.js').handleKeys; var scheduler = require('scheduler.js'); var Anim = require('anim.js').newClass(scheduler); //---------------------------------------------------------------- // Chrome & Fill base classes //---------------------------------------------------------------- // background typically used by instrumentation in the app // var Chrome = View.subclass({ $class: 'chrome', font: '12px "Lucida Grande", "Helvetica", sans-serif', fontWeight: 'bold', userSelect: 'none', background: 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAX0lEQVQYV42POw7AMAhDQerA/U/WoYOPwlApJeE7FilSiI154RtYQkpEYsdrdgwzvPZ4baUubWE8WK725JHDfBJSyoBfK9SYdnAkdHxhBNJgUKOX2p3A7N/0mtPOofQBFAg1MebnsAUAAAAASUVORK5CYII=), #d8d8d8' }); var Fill = View.subclass({ $class: 'fill', position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, boxSizing: 'border-box' }); //---------------------------------------------------------------- // Section //---------------------------------------------------------------- var sectionTitleHeight = 20; var SectionTitle = Chrome.subclass({ $class: 'section-title', boxSizing: 'border-box', height: sectionTitleHeight, borderStyle: 'solid', borderWidth: 1, borderColor: '#f2f2f2 #999 #999 #f2f2f2', padding: '2px 5px', color: '#333', position: 'absolute', left: 0, right: 0, boxShadow: '0 3px 3px -1px white', /* #f0f0f0 */ '.empty > ?': { boxShadow: 'none' } }); var SectionBody = Fill.subclass({ $class: 'section-body', marginTop: sectionTitleHeight, overflowY: 'auto', overflowX: 'hidden' }); var SectionMask = Fill.subclass({ $class: 'section-mask', top: '100%', height: 0, // not disabled backgroundColor: '#ddd', opacity: '0', '.disabled > ?': { top: sectionTitleHeight, height: 'auto', bottom: 0, opacity: '0.70', transition: 'opacity 0.5s cubic-bezier(0.5, 0, 0.8, 0.5)' } }); var SectionView = View.subclass({ $class: 'section', borderWidth: 0, background: 'white', // #eaeaea // Interferes with splitter transition animation: // transition: 'background-color 0.15s' overflow: 'hidden' }); SectionView.initialize = function (_title, _body, _disable) { var titleView = SectionTitle.create(); var bodyView = SectionBody.create(); View.initialize.call(this, titleView, bodyView, SectionMask.create() ); this.activate(function (title) { titleView.setContent(title); }, _title); this.activate(function (body) { bodyView.setContent(body); this.enableClass('empty', !body); }.bind(this), _body); this.activate(this.disable.bind(this), _disable); }; // grey out and prevent clicking on controls // SectionView.disable = function (isDisabled) { this.enableClass('disabled', !!isDisabled); }; //---------------------------------------------------------------- // Toolbar //---------------------------------------------------------------- var ButtonArt = View.subclass({ $class: 'art', border: '0px solid #a0a0a0', '.enabled > ?': { borderColor: '#333', boxShadow: '2px 2px 4px rgba(0,0,0,.4)' }, '.enabled:hover > ?': { boxShadow: 'none' }, '.enabled:active > ?': { boxShadow: '1px 1px 1px #fff' } }); // Console Button label var ConsoleLine = ButtonArt.subclass({ borderColor: 'inherit', borderBottomWidth: 1, width: 7, height: 2, boxShadow: 'none' }); var ConsoleLabel = ButtonArt.subclass({ // this element is a bordered rectangle width: 8, height: 12, borderWidth: 2, margin: '4px 4px', padding: '0 1px' }); function createConsoleLabel() { return ConsoleLabel.create( ConsoleLine.create(), ConsoleLine.create({width: 3}), ConsoleLine.create({width: 5}) ); } function createGoLabel() { return [ {paddingLeft: 3, paddingTop: 1}, "\u25b6" ]; } var FileNameView = View.subclass({ font: '12px "Menlo", "Monaco", sans-serif', padding: '2px 4px 1px', border: '1px solid #AAA', borderColor: '#BBB #F0F0F0 #F0F0F0 #BBB', borderRadius: 3, cssFloat: 'right', margin: '3px 10px' }); //---------------------------------------------------------------- // ToolbarView //---------------------------------------------------------------- var ToolbarView = Chrome.subclass({ $class: 'toolbar', boxSizing: 'border-box', borderTop: '1px solid #f0f0f0', borderBottom: '1px solid #999', padding: '0 0 0 4px' }); ToolbarView.buttons = [ {id: 'restart', content: "\u21bb", title: "Restart target process"}, {id: 'pause', content: '||', title: "Pause execution"}, {id: 'go', content: createGoLabel(), title: "Resume execution"}, {id: 'stepOver', content: "\u21e3", title: "Step over function calls"}, {id: 'stepIn', content: "\u21e2", title: "Step into function calls"}, {id: 'stepOut', content: "\u21e0", title: "Step out of function"}, {id: 'console', content: createConsoleLabel(), title: "View console output"} ]; ToolbarView.initialize = function (onclick, enabledSet, fileName) { View.initialize.call(this); // id -> view var map = Object.create(null); var views = this.buttons.map(function (b) { return map[b.id] = Button.create(b.content, { fontFamily: 'Helvetica, sans-serif', $onclick: onclick, $clickArg: b.id, $title: b.title }); }); this.append(views); var nameView = FileNameView.create(); this.activate(function (name) { nameView.setContent(name); }, fileName); this.append(nameView); // Enable listed IDs; disable all others this.activate(function (names) { for (var k in map) { map[k].enable( names.indexOf(k) >= 0 ); } }, enabledSet); this.simulate = function (id) { if (map[id]) { map[id].flash(); onclick(id); } }; }; //---------------------------------------------------------------- // OverlayView //---------------------------------------------------------------- var OverlayContent = View.subclass({ $class: 'overlay-content', position: 'absolute', marginLeft: 'auto', marginRight: 'auto', left: 0, right: 0, width: '70%', minWidth: 380, top: '20%', height: '60%', maxHeight: 300, overflow: 'hidden', border: '4px solid #6384A7', borderRadius: 7, background: '#FFF', font: '14px Helvetica' }); var OverlayText = Fill.subclass({ $class: 'overlay-text', padding: 20, overflow: 'scroll' }); var OverlayButton = Button.subclass({ $class: 'overlay-button', position: 'absolute', top: 2, right: 2, fontSize: 25, lineHeight: 21, margin: 0, color: '#a53f3f', textShadow: '1px 1px 2px rgba(71,32,32,0.22)' }); var OverlayView = Fill.subclass({ $class: 'overlay', display: 'none', backgroundColor: 'rgba(194, 194, 194, 0.6)' }); OverlayView.initialize = function (text) { View.initialize.call(this); var button = OverlayButton.create("\u2297", { $onclick: this.toggle.bind(this), $title: 'Close window' }); this.append( OverlayContent.create( OverlayText.create(text), button ) ); this.shown = false; this.e.onmousedown = function (evt) { if (evt.eventPhase == evt.AT_TARGET) { this.show(false); evt.preventDefault(); evt.stopPropagation(); } }.bind(this); }; OverlayView.show = function (bOn) { bOn = !!bOn; if (bOn == this.shown) { return; } this.shown = bOn; var a = Anim.create(this.e, 'show-hide'); if (bOn) { this.unHandle = handleKeys(document.body, 'keydown', false, { 'U+001B': this.show.bind(this, false) }); a.css({ display: 'block', opacity: '0' }) .cssTransition({opacity: '1'}, 500); } else { this.unHandle(); a.cssTransition({opacity: '0'}, 250) .css({display: 'none'}); } a.start(); }; OverlayView.toggle = function () { this.show(!this.shown); }; //---------------------------------------------------------------- // MDBView //---------------------------------------------------------------- //---------------- stack ---------------- function modeToStackTitle(mode) { switch (mode) { case 'pause': return 'Paused at:'; case 'run': return 'Running...'; case 'exit': return 'Exited'; case 'down': return 'Connecting...'; case 'busy': return 'Target not responding...'; default: return 'Error...'; } } var StackPane = SectionView.subclass(); StackPane.initialize = function (mdb) { var stackTitle = O.func(modeToStackTitle, mdb.mode); var stack = StackView.create( O.func(function (mode, stack) { switch (mode) { case 'exit': return 'Target process has exited'; case 'error': return 'Internal error'; default: return (stack ? stack : 'Loading...'); } }, mdb.mode, mdb.stack) ); var disabled = O.func(function (mode) { return mode != 'pause'; }, mdb.mode); SectionView.initialize.call(this, stackTitle, stack, disabled); this.selection = stack.selection; }; //---------------- locals ---------------- // // Display the local variables for the currently-selected stack frame var LocalsPane = SectionView.subclass(); LocalsPane.initialize = function (mdb, stack) { var data = null; var locals = O.func(function (sel, fetchLocals) { if (!sel) { // nothing to show (exited, not connected) return undefined; } return fetchLocals(sel.index + 1); }, stack.selection, mdb.fetchLocals); var localsView = LocalsView.create(mdb, locals); var localsDisabled = O.func(function (mode, data) { return mode != 'pause' || !data; }, mdb.mode, locals); SectionView.initialize.call(this, 'Local Variables', localsView, localsDisabled); }; //---------------- code ---------------- // // Display the source code corresponding to the most-recently selected stack // frame. Update filename and breakpoints when source text is updated. Flag // the current line of execution. function clone(a) { var o = Object.create(Object.getPrototypeOf(a)); for (var k in a) { o[k] = a[k]; } return o; } // return an observable that gets/sets the breakpoints for a particular file // function extractFileBPs(mdb, file) { var recent; var o = O.func(function (bps) { recent = bps; return bps && bps[file]; }, mdb.breakpoints); o.setValue = function (fileBPs) { var value = clone(recent); value[file] = fileBPs; mdb.breakpoints.setValue(value); }; return o; } var CodePane = CodeView.subclass(); CodePane.initialize = function (mdb, stack) { CodeView.initialize.call(this, {borderLeft: '1px solid #666'}); var currentFile; // Update CodeView and return name of currently-displayed file. // this.fileName = O.func(function (sel, fetchSource, mode) { var frame = sel && sel.frame; var file = frame && frame.file; var source; if (file) { source = fetchSource(file); if (typeof source == "string") { if (currentFile != file) { currentFile = file; this.setText(source, extractFileBPs(mdb, file)); } this.flagLine(mode == 'pause' ? frame.line : null); } } return currentFile; }.bind(this), stack.selection, mdb.fetchSource, mdb.mode); this.activate(this.filename); // keep codeview updated }; //---------------- console ---------------- var ConsolePane = SectionView.subclass(); ConsolePane.initialize = function (mdb) { SectionView.initialize.call(this, 'Console', ConsoleView.create(mdb)); this.size = O.slot('0%'); this.sizeWhenOpen = '38%'; this.toggle = function () { var v = this.size.getValue(); if (v == '0%') { v = this.sizeWhenOpen; } else { this.sizeWhenOpen = v; v = '0%'; } this.size.setValue(v); }; }; //---------------- toolbar ---------------- function modeToButtons (mode) { switch (mode) { case 'pause': return ['restart', 'go', 'stepOver', 'stepIn', 'stepOut', 'console']; case 'run': return ['pause', 'restart', 'console']; case 'busy': return ['restart', 'console']; case 'exit': return ['restart', 'console']; default: return ['console']; } } var ToolbarPane = ToolbarView.subclass(); ToolbarPane.initialize = function (mdb, code, console) { var onbutton = function (name) { if (name == 'console') { console.toggle(); } else { mdb.action(name); } }; var enabled = O.func(modeToButtons, mdb.mode); ToolbarView.initialize.call(this, onbutton, enabled, code.fileName); }; //---------------- overlay ---------------- var Key = View.subclass({ cssFloat: 'right', minWidth: 16, minHeight: 19, font: '9px Monaco, Courier, monospace', lineHeight: 19, padding: '0 1px 0 2px', color: '#FFF', background: '#595E74', border: '2px solid #212124', borderRadius: 3, borderTopColor: '#8287AF', borderLeftColor: '#8287AF', margin: '0 2px', textAlign: 'center' }); var TTKey = Key.subclass({ $tag: 'tt', fontWeight: 'bold', font: 'bold 14px Courier', lineHeight: 19 }); function createOverlay() { var H1 = View.subclass({fontWeight: 'bold', fontSize: '125%'}); var HR = View.subclass({$tag: 'hr'}); var Table = View.subclass({$tag: 'table'}); var TR = View.subclass({$tag: 'tr'}); var TH = View.subclass({$tag: 'th', textAlign: 'right', padding: 5}); var TD = View.subclass({$tag: 'td', padding: 5}); function row(key, desc) { return TR.create( TH.create(key), TD.create(desc) ); } function CA(key) { return [ TTKey.create(key), Key.create('alt'), Key.create('ctl') ]; } var text = [ H1.create( 'Keyboard Shortcuts' ), HR.create(), Table.create( row( CA('\u2193'), 'Step over function calls'), row( CA('\u2192'), 'Step into function calls'), row( CA('\u2190'), 'Step out of current function'), row( CA('enter'), 'Continue execution'), row( CA('space'), 'Open/close console'), row( TTKey.create('?'), 'Show/dismiss this dialog') ) ]; return OverlayView.create(text); } //---------------- shortcuts ---------------- function installShortcuts(toolbar, overlay) { // trapping `keydown` prevents default behavior (otherwise, // the focused element might scroll). handleKeys(document.body, 'keydown', true, { A_C_Down: function () { toolbar.simulate('stepOver'); }, A_C_Right: function () { toolbar.simulate('stepIn'); }, A_C_Left: function () { toolbar.simulate('stepOut'); }, A_C_Enter: function () { toolbar.simulate('go'); }, 'A_C_U+0020': function () { toolbar.simulate('console'); } }); handleKeys(document.body, 'keypress', false, { '?': function () { // ignore if any element has focus... if (document.activeElement !== document.body) { return false; } overlay.toggle(); return true; }.bind(this) }); } //---------------- MDBView ---------------- var MDBView = Fill.subclass({ $class: 'mdb' }); MDBView.initialize = function (mdb) { View.initialize.call(this); var stack = StackPane.create(mdb); var locals = LocalsPane.create(mdb, stack); var code = CodePane.create(mdb, stack); var console = ConsolePane.create(mdb); var toolbar = ToolbarPane.create(mdb, code, console); var overlay = createOverlay(); installShortcuts(toolbar, overlay); this.append( Splitter.create({ $bottomSize: console.size, $bottom: console, $top: Splitter.create({ $topSize: 32, $top: toolbar, $bottom: Splitter.create({ $leftSize: O.slot('30%'), $right: code, $left: Splitter.create({ $topSize: O.slot('50%'), $top: stack, $bottom: locals})})})}), overlay); }; module.exports = MDBView;
/** * Broadcast updates to client when the model changes */ 'use strict'; var Timeoff = require('./timeOff.model'); exports.register = function(socket) { Timeoff.schema.post('save', function (doc) { onSave(socket, doc); }); Timeoff.schema.post('remove', function (doc) { onRemove(socket, doc); }); } function onSave(socket, doc, cb) { socket.emit('timeOff:save', doc); } function onRemove(socket, doc, cb) { socket.emit('timeOff:remove', doc); }
import markdown from 'markdown-in-js' import withDoc, { components } from '~/lib/with-doc' import { expoteam } from '~/data/team' // import { InternalLink, ExternalLink } from "~/components/text/link"; // import { P } from "~/components/text/paragraph"; // import Image from '~/components/base/image' import { InlineCode } from '~/components/base/code' // import { // TerminalInput, // TerminalOutput // } from "~/components/text/terminal"; // prettier-ignore export default withDoc({ title: 'DocumentPicker', authors: [expoteam], })(markdown(components)` Provides access to the system's UI for selecting documents from the available providers on the user's device. ### Expo.DocumentPicker.getDocumentAsync(options) Display the system UI for choosing a document. #### Arguments - **options (_object_)** -- A map of options: - **type (_string_)** -- The [MIME type](https://en.wikipedia.org/wiki/Media_type) of the documents that are available to be picked. Is also supports wildcards like \`image/*\` to choose any image. To allow any type of document you can use \`*/*\`. Defaults to \`*/*\`. #### Returns If the user cancelled the document picking, returns ${<InlineCode>{`{ type: 'cancel' }`}</InlineCode>}. Otherwise, returns ${<InlineCode>{`{ type: 'success', uri, name, size }`}</InlineCode>} where \`uri\` is a URI to the local document file, \`name\` is its name and \`size\` is its size in bytes. `)
const render = require("preact-render-to-string"); const { h } = require("preact"); module.exports = () => ({ template: { title: "Smoke test", }, render: { interactive({ component, props }) { return render(h(component, props)); }, }, output: "build", paths: { "/": () => require("./layouts/Standalone").default, "/pages": { content: () => require.context("./pages", true, /^\.\/.*\.md$/), layout: () => require("./layouts/Index").default, }, standalone: () => require("./layouts/Standalone").default, demo: { content: () => require.context("./pages", true, /^\.\/.*\.md$/), layout: () => require("./layouts/Page").default, url: ({ sectionName, fileName }) => `/${sectionName}/${fileName}/`, }, }, });
'use strict'; angular.module('bucleApp.core') .directive('customFooter', [ function () { return { templateUrl: 'components/templates/footer.html', replace: true }; } ]) .directive('mainFooter', [ function () { return { templateUrl: 'components/templates/main-footer.html', link: function(scope, element, attrs) { scope.date = new Date(); }, replace: true }; } ]);
export * from "./collision"; export * from "./slice"; export * from "./intersect"; export * from "./union";
describe( 'AppCtrl', function() { describe( 'isCurrentUrl', function() { var AppCtrl, $location, $scope; beforeEach( module( 'app' ) ); beforeEach( inject( function( $controller, $rootScope, $mdSidenav, $mdBottomSheet, $mdDialog, $log, $q) { //$location = _$location_; $scope = $rootScope.$new(); AppCtrl = $controller( 'AppCtrl', { $scope: $scope, $mdSidenav: $mdSidenav, $mdBottomSheet: $mdBottomSheet, $mdDialog: $mdDialog, $log: $log, $q: $q }); })); it( 'should pass a dummy test', inject( function() { expect( AppCtrl ).toBeTruthy(); })); }); });
module.exports = exports = function (app) { var client = app.client; var db = app.database('main').collection('seen'); var conf = app.conf; var log = app.utils.log; var formatPeriod = app.utils.formatPeriod; var cnames = app.cnames; function lastSeen(opt, callback) { var all = false; if(opt.subcmd=='all'){all=true} if (!opt.cmd[0]) {callback(opt.to, "Error: not enough arguments");return;} var nick = opt.cmd.shift(); var patt = RegExp(nick,"i"); var anames = []; var cnamesk = Object.keys(cnames); for(var i=0; i < cnamesk.length; i++) { var lcnames = Object.keys(cnames[cnamesk[i]]); anames = anames.concat(lcnames); } for(var i=0; i < anames.length; i++) { if(patt.test(anames[i])) { callback(opt.to, anames[i]+" last seen: now"); if(!all) {return}; } } db.find({nick: RegExp(nick, "i")}).sort({time: -1}).toArray(function (err, docs) { if (docs.length > 0) { for(var i=0; i<(all?docs.length:1);i++) { var tdif = new Date().getTime() - docs[i].time.getTime(); callback(opt.to, docs[i].nick+": "+formatPeriod(tdif)+" ago"); } } }) } app.cmdRegister('seen', { "f": lastSeen, "h": "Outputs the amount of time since a user was last seen by RowBoe. Use :all to output all users containing a given string.\nExample 1: !seen Amy\nExample 2: !seen:all Bob (outputs Bob, Bob_ Bob1, etc.)", }); // Last seen client.addListener('part', function (channel, nick, reason, message) { db.update({nick: nick}, {$set: { time: new Date(), reason: reason, channel: channel, message: message } }, {upsert: true}) }); client.addListener('quit', function (nick, reason, channels, message) { db.update({nick: nick}, {$set: { time: new Date(), reason: reason, message: message } }, {upsert: true}) }); client.addListener('kick', function (channel, nick, by, reason, message) { db.update({nick: nick}, {$set: { time: new Date(), reason: reason, message: message } }, {upsert: true}) }); client.addListener('nick', function (nick, newnick, channels, message) { db.update({nick: nick}, {$set: { time: new Date(), message: message } }, {upsert: true}) }); }
{ /* global angular, APP_NAME */ angular .module(APP_NAME) .directive('passwordMatch', passwordMatch); passwordMatch.$inject = []; function passwordMatch() { var directive = { restrict: 'A', scope: true, require: 'ngModel', link: linkFn }; return directive; function linkFn(scope, elem, attrs, control) { var checker = function() { //get the value of the first password var e1 = scope.$eval(attrs.ngModel); //get the value of the other password var e2 = scope.$eval(attrs.passwordMatch); return e1 && e2 && e1 === e2 && e1.length >= e2.length; }; scope.$watch(checker, function(n) { //set the form control to valid if both //passwords are the same, else invalid control.$setValidity('passwordMatch', n || false); }); } } }
import_module('Athena.Math'); aab = new Athena.Math.AxisAlignedBox(-1, -1, -1, 1, 1, 1); m = new Athena.Math.Matrix4(); m.makeTransform(new Athena.Math.Vector3(10.0, 20.0, 30.0), Athena.Math.Vector3_UNIT_SCALE, Athena.Math.Quaternion_IDENTITY); aab.transform(m); CHECK(aab.isFinite(), "aab.isFinite()"); CHECK_CLOSE(9.0, aab.minimum.x); CHECK_CLOSE(19.0, aab.minimum.y); CHECK_CLOSE(29.0, aab.minimum.z); CHECK_CLOSE(11.0, aab.maximum.x); CHECK_CLOSE(21.0, aab.maximum.y); CHECK_CLOSE(31.0, aab.maximum.z); aab = new Athena.Math.AxisAlignedBox(-1, -1, -1, 1, 1, 1); m = new Athena.Math.Matrix4(); m.makeTransform(Athena.Math.Vector3_ZERO, new Athena.Math.Vector3(2.0, 3.0, 4.0), Athena.Math.Quaternion_IDENTITY); aab.transform(m); CHECK(aab.isFinite(), "aab.isFinite()"); CHECK_CLOSE(-2.0, aab.minimum.x); CHECK_CLOSE(-3.0, aab.minimum.y); CHECK_CLOSE(-4.0, aab.minimum.z); CHECK_CLOSE(2.0, aab.maximum.x); CHECK_CLOSE(3.0, aab.maximum.y); CHECK_CLOSE(4.0, aab.maximum.z); aab = new Athena.Math.AxisAlignedBox(-1, -1, -1, 1, 1, 1); m = new Athena.Math.Matrix4(); m.makeTransform(Athena.Math.Vector3_ZERO, Athena.Math.Vector3_UNIT_SCALE, new Athena.Math.Quaternion(Math.PI / 4, Athena.Math.Vector3_UNIT_Y)); aab.transform(m); CHECK(aab.isFinite(), "aab.isFinite()"); CHECK_CLOSE(-1.414, aab.minimum.x, 0.001); CHECK_CLOSE(-1.0, aab.minimum.y); CHECK_CLOSE(-1.414, aab.minimum.z, 0.001); CHECK_CLOSE(1.414, aab.maximum.x, 0.001); CHECK_CLOSE(1.0, aab.maximum.y); CHECK_CLOSE(1.414, aab.maximum.z, 0.001);
var importsStartupClientIndex = function () { var template = `### /imports/startup/client/index.coffee ### DEBUG = true console.log '/imports/startup/client/index.coffee is loaded' if DEBUG ` return template } module.exports = importsStartupClientIndex
const _ = require('../../../utils/under-dash'); const BaseXform = require('../base-xform'); class PageMarginsXform extends BaseXform { get tag() { return 'pageMargins'; } render(xmlStream, model) { if (model) { const attributes = { left: model.left, right: model.right, top: model.top, bottom: model.bottom, header: model.header, footer: model.footer, }; if (_.some(attributes, value => value !== undefined)) { xmlStream.leafNode(this.tag, attributes); } } } parseOpen(node) { switch (node.name) { case this.tag: this.model = { left: parseFloat(node.attributes.left || 0.7), right: parseFloat(node.attributes.right || 0.7), top: parseFloat(node.attributes.top || 0.75), bottom: parseFloat(node.attributes.bottom || 0.75), header: parseFloat(node.attributes.header || 0.3), footer: parseFloat(node.attributes.footer || 0.3), }; return true; default: return false; } } parseText() {} parseClose() { return false; } } module.exports = PageMarginsXform;
/** * @fileoverview Rule to flag when exporting a React Class while also calling a function on it * @author Naman Goel * @copyright 2014 Nicholas C. Zakas. All rights reserved. */ import type {Context, Rules, EslintNode} from './types' function getFinalArg(node: EslintNode): ?string{ if(node.arguments.length === 1 && node.arguments[0].type === 'Identifier'){ return node.arguments[0].name } if(node.arguments.length === 1 && node.arguments[0].type === 'CallExpression'){ return getFinalArg(node.arguments[0]) } } function isReactComponent(node: EslintNode): boolean { if(node.type === 'MemberExpression'){ return node.object.type === 'Identifier' && node.object.name === 'React' && node.property.type === 'Identifier' && node.property.name === 'Component' } return node.type === 'Identifier' && node.name === 'Component' } function isReactClass(node: EslintNode): boolean { if(node.type === 'ClassDeclaration' && node.superClass && isReactComponent(node.superClass)){ return true } return false } const getFinalParent = node => !node.parent ? node : getFinalParent(node.parent) //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ export default function(context: Context): Rules { return { 'ExportDefaultDeclaration': function(node){ if(node.declaration.type === 'CallExpression' && node.declaration.callee.type === 'Identifier' && node.declaration.arguments.length === 1){ var arg = getFinalArg(node.declaration) getFinalParent(node).body .filter(isReactClass) .forEach(function(classDecl){ if(classDecl.id.name === arg){ context.report(node, 'Use temp variable to set correct type on export') } }) } } , 'AssignmentExpression': function(node){ if(node.operator === '=' && node.left.type === 'MemberExpression' && node.left.object.type === 'Identifier' && node.left.object.name === 'module' && node.right.type === 'CallExpression' && node.right.callee.type === 'Identifier' && node.right.arguments.length === 1){ var arg = getFinalArg(node.right) getFinalParent(node).body .filter(isReactClass) .forEach(function(classDecl){ if(classDecl.id.name === arg){ context.report(node, 'Use temp variable to set correct type on export') } }) } } } } export const schema: Array<any> = []
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8 12.5v-9l6 4.5-6 4.5z" }), 'VideoLibrary');
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.charting.themes.Julie"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dojox.charting.themes.Julie"] = true; dojo.provide("dojox.charting.themes.Julie"); dojo.require("dojox.gfx.gradutils"); dojo.require("dojox.charting.Theme"); // created by Julie Santilli (function(){ var dc = dojox.charting, themes = dc.themes, Theme = dc.Theme, g = Theme.generateGradient, defaultFill = {type: "linear", space: "shape", x1: 0, y1: 0, x2: 0, y2: 100}; themes.Julie = new dc.Theme({ seriesThemes: [ {fill: g(defaultFill, "#59a0bd", "#497c91"), stroke: {color: "#22627d"}}, // blue {fill: g(defaultFill, "#8d88c7", "#6c6d8e"), stroke: {color: "#8a84c5"}}, // purple {fill: g(defaultFill, "#85a54a", "#768b4e"), stroke: {color: "#5b6d1f"}}, // green {fill: g(defaultFill, "#e8e667", "#c6c361"), stroke: {color: "#918e38"}}, // yellow {fill: g(defaultFill, "#e9c756", "#c7a223"), stroke: {color: "#947b30"}}, // orange {fill: g(defaultFill, "#a05a5a", "#815454"), stroke: {color: "#572828"}}, // red {fill: g(defaultFill, "#b17044", "#72543e"), stroke: {color: "#74482e"}}, // brown {fill: g(defaultFill, "#a5a5a5", "#727272"), stroke: {color: "#535353"}}, // grey {fill: g(defaultFill, "#9dc7d9", "#59a0bd"), stroke: {color: "#22627d"}}, // blue {fill: g(defaultFill, "#b7b3da", "#8681b3"), stroke: {color: "#8a84c5"}}, // purple {fill: g(defaultFill, "#a8c179", "#85a54a"), stroke: {color: "#5b6d1f"}}, // green {fill: g(defaultFill, "#eeea99", "#d6d456"), stroke: {color: "#918e38"}}, // yellow {fill: g(defaultFill, "#ebcf81", "#e9c756"), stroke: {color: "#947b30"}}, // orange {fill: g(defaultFill, "#c99999", "#a05a5a"), stroke: {color: "#572828"}}, // red {fill: g(defaultFill, "#c28b69", "#7d5437"), stroke: {color: "#74482e"}}, // brown {fill: g(defaultFill, "#bebebe", "#8c8c8c"), stroke: {color: "#535353"}}, // grey {fill: g(defaultFill, "#c7e0e9", "#92baca"), stroke: {color: "#22627d"}}, // blue {fill: g(defaultFill, "#c9c6e4", "#ada9d6"), stroke: {color: "#8a84c5"}}, // purple {fill: g(defaultFill, "#c0d0a0", "#98ab74"), stroke: {color: "#5b6d1f"}}, // green {fill: g(defaultFill, "#f0eebb", "#dcd87c"), stroke: {color: "#918e38"}}, // yellow {fill: g(defaultFill, "#efdeb0", "#ebcf81"), stroke: {color: "#947b30"}}, // orange {fill: g(defaultFill, "#ddc0c0", "#c99999"), stroke: {color: "#572828"}}, // red {fill: g(defaultFill, "#cfb09b", "#c28b69"), stroke: {color: "#74482e"}}, // brown {fill: g(defaultFill, "#d8d8d8", "#bebebe"), stroke: {color: "#535353"}}, // grey {fill: g(defaultFill, "#ddeff5", "#a5c4cd"), stroke: {color: "#22627d"}}, // blue {fill: g(defaultFill, "#dedcf0", "#b3afd3"), stroke: {color: "#8a84c5"}}, // purple {fill: g(defaultFill, "#dfe9ca", "#c0d0a0"), stroke: {color: "#5b6d1f"}}, // green {fill: g(defaultFill, "#f8f7db", "#e5e28f"), stroke: {color: "#918e38"}}, // yellow {fill: g(defaultFill, "#f7f0d8", "#cfbd88"), stroke: {color: "#947b30"}}, // orange {fill: g(defaultFill, "#eedede", "#caafaf"), stroke: {color: "#572828"}}, // red {fill: g(defaultFill, "#e3cdbf", "#cfb09b"), stroke: {color: "#74482e"}}, // brown {fill: g(defaultFill, "#efefef", "#cacaca"), stroke: {color: "#535353"}} // grey ] }); themes.Julie.next = function(elementType, mixin, doPost){ if(elementType == "line" || elementType == "area"){ var s = this.seriesThemes[this._current % this.seriesThemes.length]; s.fill.space = "plot"; var theme = Theme.prototype.next.apply(this, arguments); s.fill.space = "shape"; return theme; } return Theme.prototype.next.apply(this, arguments); }; themes.Julie.post = function(theme, elementType){ theme = Theme.prototype.post.apply(this, arguments); if(elementType == "slice" && theme.series.fill && theme.series.fill.type == "radial"){ theme.series.fill = dojox.gfx.gradutils.reverse(theme.series.fill); } return theme; }; })(); }
/* // // CASE for Alasql.js // Date: 03.11.2014 // (c) 2014, Andrey Gershun // */ yy.CaseValue = function (params) { return yy.extend(this, params); }; yy.CaseValue.prototype.toString = function () { var s = 'CASE '; if (this.expression) s += this.expression.toString(); if (this.whens) { s += this.whens .map(function (w) { return ' WHEN ' + w.when.toString() + ' THEN ' + w.then.toString(); }) .join(); } s += ' END'; return s; }; yy.CaseValue.prototype.findAggregator = function (query) { // console.log(this.toString()); if (this.expression && this.expression.findAggregator) this.expression.findAggregator(query); if (this.whens && this.whens.length > 0) { this.whens.forEach(function (w) { if (w.when.findAggregator) w.when.findAggregator(query); if (w.then.findAggregator) w.then.findAggregator(query); }); } if (this.elses && this.elses.findAggregator) this.elses.findAggregator(query); }; yy.CaseValue.prototype.toJS = function (context, tableid, defcols) { var s = '((function(' + context + ',params,alasql){var y,r;'; if (this.expression) { // this.expression.toJS(context, tableid) s += 'v=' + this.expression.toJS(context, tableid, defcols) + ';'; s += (this.whens || []) .map(function (w) { return ( ' if(v==' + w.when.toJS(context, tableid, defcols) + ') {r=' + w.then.toJS(context, tableid, defcols) + '}' ); }) .join(' else '); if (this.elses) s += ' else {r=' + this.elses.toJS(context, tableid, defcols) + '}'; } else { s += (this.whens || []) .map(function (w) { return ( ' if(' + w.when.toJS(context, tableid, defcols) + ') {r=' + w.then.toJS(context, tableid, defcols) + '}' ); }) .join(' else '); if (this.elses) s += ' else {r=' + this.elses.toJS(context, tableid, defcols) + '}'; } // TODO remove bind from CASE s += ';return r;}).bind(this))(' + context + ',params,alasql)'; return s; };
'use strict'; /** * *App level module with it's dependencies * */ angular.module('app', [ 'ui.router', 'ui.bootstrap' ]);
'use strict'; const values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]; const cardTypes = ["D", "C", "H", "S"]; const symbols = { "D": "♦", "H": "♥", "S": "♠", "C": "♣", }; class blackjackGame extends Rooms.botGame { constructor(room) { super(room); this.currentPlayer = null; this.allowJoins = true; this.state = "signups"; this.gameId = "blackjack"; this.gameName = "Blackjack"; this.answerCommand = "special"; this.dealer = new blackjackGamePlayer({name: "Blackjack Game Dealer", userid: "blackjackgamedealer"}); } onJoin (user) { if(!this.allowJoins || this.state !== "signups") return; if(this.userList.includes(user.userid)) return user.sendTo("You have already joined!"); this.users[user.userid] = new blackjackGamePlayer(user); this.userList.push(user.userid); user.sendTo("You have joined the game of " + this.gameName + "."); } shuffleDeck () { let deck = []; values.forEach((v) =>{ cardTypes.forEach((t) => { deck.push({"value": v, "type": t}); }); }); return this.deck = deck.randomize(); } onStart () { if(this.userList.length < 1 || this.state === "started") return false; this.state = "started"; this.shuffleDeck(); let cardQueue = this.userList.concat(this.userList); let self = this; // give dealer two cards this.giveCard("blackjackgamedealer"); this.giveCard("blackjackgamedealer"); // deal 2 cards for each player; cardQueue.forEach((u, index) => { self.giveCard(toId(u), index < this.userList.length); }); this.sendRoom("Dealer's top card: [" + symbols[this.dealer.hand[0].type] + this.dealer.hand[0].value + "]."); this.setNextPlayer(); this.initTurn(); } initTurn () { let player = this.users[this.currentPlayer]; player.sendHand(); this.sendRoom(player.name + "'s turn. (" + this.room.commandCharacter[0] + "hit or " + this.room.commandCharacter[0] + "stay.)"); let self = this; this.timer = setTimeout(() => { this.users[this.currentPlayer].completedTurn = true; if (self.eliminate()) { self.initTurn(); } }, 90000); } giveCard (userid, announce) { let card = this.deck.shift(); if (!this.deck.length) this.shuffleDeck(); let player = userid === "blackjackgamedealer" ? this.dealer : this.users[userid]; player.receiveCard(card); if (announce) this.sendRoom(player.name + "'s top card: [" + symbols[card.type] + card.value + "]."); } onHit (user) { if (this.state !== "started" || user.userid !== this.currentPlayer) return false; let player = this.users[user.userid]; this.giveCard(user.userid); player.sendHand(); if (player.total > 21) { this.sendRoom(player.name + " has busted with " + player.total + "."); this.onTurnEnd(user); } } onTurnEnd (user) { if (this.state !== "started" || (user && user.userid !== this.currentPlayer)) return false; this.users[this.currentPlayer].completedTurn = true; clearTimeout(this.timer); if (!this.setNextPlayer()) return this.onEnd(); this.initTurn(); } setNextPlayer () { if(this.userList.length === 0) return false; // get first player in the list this.currentPlayer = this.userList.shift(); // put current player at the end of the list this.userList.push(this.currentPlayer); // check if all players have moved if (this.users[this.currentPlayer].completedTurn) return false; return true; } onEnd () { // sum up dealer while (this.dealer.total < 17) { this.giveCard("blackjackgamedealer"); } this.sendRoom("The dealer has " + (this.dealer.total > 21 ? "busted with " : "") + "a total of " + this.dealer.total + "."); // sum up players let passingPlayers = []; for(var p in this.users) { // ignore the dealer's data if(this.users[p].userid === "blackjackgamedealer" || this.users[p].total > 21) continue; if(this.users[p].total > this.dealer.total || this.dealer.total > 21) { passingPlayers.push(this.users[p].name); } } if(!passingPlayers.length) { this.sendRoom("Sorry, no winners this time!"); } else { this.sendRoom("The winner" + (passingPlayers.length > 1 ? "s are" : " is") + ": " + passingPlayers.join(",") + "."); } this.destroy(); } eliminate (userid) { userid = userid || this.currentPlayer; //remove players delete this.users[userid]; this.userList.splice(this.userList.indexOf(userid), 1); if (!this.setNextPlayer()) { this.onEnd(); return false; } return true; } buildPlayerList () { let self = this; let list = this.userList.map((f) => { return self.users[f].name; }).sort().join(", "); return "Players (" + this.userList.length + "): " + list; } } class blackjackGamePlayer extends Rooms.botGamePlayer { constructor (user, game) { super (user); this.hand = []; this.total = 0; this.completedTurn = false; } sendHand () { // build hand let hand = this.hand.sort((a, b) => { // sort by value first if(values.indexOf(a.value) > values.indexOf(b.value)) return 1; if(values.indexOf(a.value) < values.indexOf(b.value)) return -1; // if values are the same, sort by suit if(cardTypes.indexOf(a.type) > cardTypes.indexOf(b.type)) return 1; return -1; }).map((c) => { return "[" + symbols[c.type] + c.value + "]"; }).join(", "); this.user.sendTo("Your hand: " + hand + ". Total: " + this.total); } receiveCard (card) { this.hand.push(card); this.getHandTotal(); } getHandTotal () { let aceCount = 0; let total = 0; this.hand.forEach((c) => { let value = c.value; if(value === "A") { aceCount++; value = 11; } if (["J", "Q", "K"].includes(value)) { value = 10; } total += parseInt(value); }); while (total > 21 && aceCount > 0) { total -= 10; aceCount -= 1; } return this.total = total; } } exports.commands = { blackjack: function (target, room, user) { if (!room || !this.can("games")) return false; if(room.game) return this.send("There is already a game going on in this room! (" + room.game.gameName + ")"); room.game = new blackjackGame(room); this.send("A new game of Blackjack is starting. ``" + room.commandCharacter[0] + "join`` to join the game."); }, blackjackstart: function (target, room, user) { if (!room || !this.can("games") || !room.game || room.game.gameId !== "blackjack") return false; room.game.onStart(); }, blackjackplayers: function (target, room, user) { if (!room || !this.can("games") || !room.game || room.game.gameId !== "blackjack") return false; this.send(room.game.buildPlayerList()); }, blackjackend: function (target, room, user) { if (!room || !this.can("games") || !room.game || room.game.gameId !== "blackjack") return false; room.game.destroy(); this.send("The game of blackjack was forcibly ended."); }, hit: function (target, room, user) { if (!room || !room.game || room.game.gameId !== "blackjack") return false; room.game.onHit(user); }, blackjackjoin: function (target, room, user) { if (!room || !room.game || room.game.gameId !== "blackjack") return false; room.game.onJoin(user); }, blackjackleave: function (target, room, user) { if (!room || !room.game || room.game.gameId !== "blackjack") return false; room.game.onLeave(user); }, stay: function (target, room, user) { if (!room || !room.game || room.game.gameId !== "blackjack") return false; room.game.onTurnEnd(user); }, };
// code style: https://github.com/johnpapa/angular-styleguide (function() { 'use strict'; angular .module('app') .controller('GoogleMapCtrl', GoogleMap); function GoogleMap ($scope) { var vm = $scope; vm.myMarkers = []; vm.mapOptions = { center: new google.maps.LatLng(35.784, -98.670), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }; vm.addMarker = addMarker; vm.setZoomMessage = setZoomMessage; vm.openMarkerInfo = openMarkerInfo; vm.setMarkerPosition = setMarkerPosition; function addMarker($event, $params) { vm.myMarkers.push(new google.maps.Marker({ map: vm.myMap, position: $params[0].latLng })); }; function setZoomMessage(zoom) { vm.zoomMessage = 'You just zoomed to ' + zoom + '!'; }; function openMarkerInfo(marker) { vm.currentMarker = marker; vm.currentMarkerLat = marker.getPosition().lat(); vm.currentMarkerLng = marker.getPosition().lng(); vm.myInfoWindow.open(vm.myMap, marker); }; function setMarkerPosition(marker, lat, lng) { marker.setPosition(new google.maps.LatLng(lat, lng)); }; } })();
"use strict"; ace.define("ace/ext/whitespace", ["require", "exports", "module", "ace/lib/lang"], function (require, exports, module) { "use strict"; var lang = require("../lib/lang"); exports.$detectIndentation = function (lines, fallback) { var stats = []; var changes = []; var tabIndents = 0; var prevSpaces = 0; var max = Math.min(lines.length, 1000); for (var i = 0; i < max; i++) { var line = lines[i]; if (!/^\s*[^*+\-\s]/.test(line)) continue; if (line[0] == "\t") tabIndents++; var spaces = line.match(/^ */)[0].length; if (spaces && line[spaces] != "\t") { var diff = spaces - prevSpaces; if (diff > 0 && !(prevSpaces % diff) && !(spaces % diff)) changes[diff] = (changes[diff] || 0) + 1; stats[spaces] = (stats[spaces] || 0) + 1; } prevSpaces = spaces; while (i < max && line[line.length - 1] == "\\") { line = lines[i++]; } } function getScore(indent) { var score = 0; for (var i = indent; i < stats.length; i += indent) { score += stats[i] || 0; }return score; } var changesTotal = changes.reduce(function (a, b) { return a + b; }, 0); var first = { score: 0, length: 0 }; var spaceIndents = 0; for (var i = 1; i < 12; i++) { var score = getScore(i); if (i == 1) { spaceIndents = score; score = stats[1] ? 0.9 : 0.8; if (!stats.length) score = 0; } else score /= spaceIndents; if (changes[i]) score += changes[i] / changesTotal; if (score > first.score) first = { score: score, length: i }; } if (first.score && first.score > 1.4) var tabLength = first.length; if (tabIndents > spaceIndents + 1) return { ch: "\t", length: tabLength }; if (spaceIndents > tabIndents + 1) return { ch: " ", length: tabLength }; }; exports.detectIndentation = function (session) { var lines = session.getLines(0, 1000); var indent = exports.$detectIndentation(lines) || {}; if (indent.ch) session.setUseSoftTabs(indent.ch == " "); if (indent.length) session.setTabSize(indent.length); return indent; }; exports.trimTrailingSpace = function (session, trimEmpty) { var doc = session.getDocument(); var lines = doc.getAllLines(); var min = trimEmpty ? -1 : 0; for (var i = 0, l = lines.length; i < l; i++) { var line = lines[i]; var index = line.search(/\s+$/); if (index > min) doc.removeInLine(i, index, line.length); } }; exports.convertIndentation = function (session, ch, len) { var oldCh = session.getTabString()[0]; var oldLen = session.getTabSize(); if (!len) len = oldLen; if (!ch) ch = oldCh; var tab = ch == "\t" ? ch : lang.stringRepeat(ch, len); var doc = session.doc; var lines = doc.getAllLines(); var cache = {}; var spaceCache = {}; for (var i = 0, l = lines.length; i < l; i++) { var line = lines[i]; var match = line.match(/^\s*/)[0]; if (match) { var w = session.$getStringScreenWidth(match)[0]; var tabCount = Math.floor(w / oldLen); var reminder = w % oldLen; var toInsert = cache[tabCount] || (cache[tabCount] = lang.stringRepeat(tab, tabCount)); toInsert += spaceCache[reminder] || (spaceCache[reminder] = lang.stringRepeat(" ", reminder)); if (toInsert != match) { doc.removeInLine(i, 0, match.length); doc.insertInLine({ row: i, column: 0 }, toInsert); } } } session.setTabSize(len); session.setUseSoftTabs(ch == " "); }; exports.$parseStringArg = function (text) { var indent = {}; if (/t/.test(text)) indent.ch = "\t";else if (/s/.test(text)) indent.ch = " "; var m = text.match(/\d+/); if (m) indent.length = parseInt(m[0], 10); return indent; }; exports.$parseArg = function (arg) { if (!arg) return {}; if (typeof arg == "string") return exports.$parseStringArg(arg); if (typeof arg.text == "string") return exports.$parseStringArg(arg.text); return arg; }; exports.commands = [{ name: "detectIndentation", exec: function exec(editor) { exports.detectIndentation(editor.session); } }, { name: "trimTrailingSpace", exec: function exec(editor) { exports.trimTrailingSpace(editor.session); } }, { name: "convertIndentation", exec: function exec(editor, arg) { var indent = exports.$parseArg(arg); exports.convertIndentation(editor.session, indent.ch, indent.length); } }, { name: "setIndentation", exec: function exec(editor, arg) { var indent = exports.$parseArg(arg); indent.length && editor.session.setTabSize(indent.length); indent.ch && editor.session.setUseSoftTabs(indent.ch == " "); } }]; }); (function () { ace.require(["ace/ext/whitespace"], function () {}); })();
var indexRoutes = require('./routes/index') , helloRoutes = require('./routes/hello') module.exports = function (app) { // App entry route app.get('/', indexRoutes.index); // "Hello" example route app.get('/hello/dump-request-headers', helloRoutes.dumpRequest); };
import Vue from 'vue' import VueRouter from 'vue-router' import MovieIndex from '../views/movie/index.vue' import MovieShow from '../views/movie/show.vue' Vue.use(VueRouter) const router = new VueRouter({ mode: 'history', routes: [ { path: '/', component: MovieIndex }, { path:'/movie/:id',component:MovieShow} ] }) export default router
import score from '../../src/lib/score'; /* eslint-disable prefer-arrow-callback, func-names */ chai.should(); describe('scoring', function () { it('prefers more ratings given similar scores', function () { score(4.7, 10).should.be.below(score(4.5, 1000)); }); it('prefers a higher score given similar number of ratings', function () { score(4.7, 1000).should.be.below(score(4.8, 900)); }); });
var express = require('express'); var myAbout = require('../controllers/about.js'); var huffman = require('../controllers/huffman/huffman.js'); var router = express.Router(); var retData = { title: '哈夫曼编码', author: 'margaret', encodeString: null }; /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', retData); }); //Deal posted encoding form router.post('/Encoding', huffman.encode); //Deal posted decoding form router.post('/Decoding', huffman.decode); //add about module router.get('/about',myAbout.about); module.exports = router;
/*! * Copyright(c) 2015 Shelloid Systems LLP. * MIT Licensed */ /** @roles ["admin"] */ exports.index = listUsers; /** @sql.selectInvited SELECT a.email email, a.name name, a.regd_at regd_at, a.validated validated, b.email who_invited, a.svc svc FROM interested_users a LEFT JOIN interested_users b ON b.ref_code = a.who_invited */ function listUsers(req, res, ctx){ var db = req.db("invitedb"); db .selectInvited([]) .success(function (rows) { var data = []; for(var i=0;i<rows.length;i++){ var row = rows[i]; data.push([row.email, row.name, row.regd_at, row.validated == 1 ? true : false, row.who_invited, row.svc]); } res.send({data:data}); }) .execute(); }
function increase_quantity(cart_item_id){ var q = $('#quantity_' + cart_item_id); var x = parseInt(q.val()); q.val(x + 1); update_quantity(cart_item_id); } function decrease_quantity(cart_item_id){ var q = $('#quantity_' + cart_item_id); var x = parseInt(q.val()); q.val(x - 1); update_quantity(cart_item_id); } function update_quantity(cart_item_id){ var q = $('#quantity_' + cart_item_id); var url = '/admin/cart_items/' + cart_item_id; var params = { method: 'PATCH', credentials: 'include', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': document.head.querySelector("[name=csrf-token]").content }, body: JSON.stringify({ quantity: q.val() }) }; fetch(url, params).then(function(response) { return response.text() }).then(function(response) { var script = document.createElement('script'); script.text = response; document.head.appendChild(script).parentNode.removeChild(script); }).catch(function(ex) { console.log('parsing failed', ex) }) } $('input[name="cart_item_id"]').change(function(){ var search_path = window.location.search; var total_url; if (this.checked) { total_url = '/admin/cart_items/total' + search_path + '&add_id=' + this.value; } else { total_url = '/admin/cart_items/total' + search_path + '&remove_id=' + this.value; } var params = { credentials: 'include', headers: { 'Accept': 'application/javascript', 'X-CSRF-Token': document.head.querySelector("[name=csrf-token]").content } }; fetch(total_url, params).then(function(response) { return response.text() }).then(function(response) { var script = document.createElement('script'); script.text = response; document.head.appendChild(script).parentNode.removeChild(script); }).catch(function(ex) { console.log('parsing failed', ex) }) }); $('.xx_popup').popup({ popup: '.ui.popup' }); $('#user_id').dropdown({ onChange: function(value, text, $selectedItem){ var path = new URL(window.location.href); path.searchParams.delete('good_type'); path.searchParams.delete('good_id'); console.log(path) path.searchParams.set('user_id', value); window.location.href = path; } });
angular.module('ionic-chat-app', [ 'ionic', 'ionic-chat-app-services', 'ionic-chat-app-controllers', 'ionic-chat-app-directives' ]) .run(function ($ionicPlatform) { $ionicPlatform.ready(function () { if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { StatusBar.styleDefault(); } }) }) .config(function ($stateProvider, $urlRouterProvider) { // Configure the routing $stateProvider // Each tab has its own nav history stack: .state('app', { url: '/app', abstract: true, templateUrl: "templates/tabs.html" }) .state('app.node', { url: '/node', views: { 'node-view': { templateUrl: 'templates/app-chat.html', controller: 'ChatController', resolve: { chatRoom: function () { return 'node'; } } } } }) .state('app.javascript', { url: '/javascript', views: { 'javascript-view': { templateUrl: 'templates/app-chat.html', controller: 'ChatController', resolve: { chatRoom: function () { return 'javascript'; } } } } }) .state('app.haskell', { url: '/haskell', views: { 'haskell-view': { templateUrl: 'templates/app-chat.html', controller: 'ChatController', resolve: { chatRoom: function () { return 'haskell'; } } } } }) .state('app.erlang', { url: '/erlang', views: { 'erlang-view': { templateUrl: 'templates/app-chat.html', controller: 'ChatController', resolve: { chatRoom: function () { return 'erlang'; } } } } }) .state('app.scala', { url: '/scala', views: { 'scala-view': { templateUrl: 'templates/app-chat.html', controller: 'ChatController', resolve: { chatRoom: function () { return 'scala'; } } } } }); $urlRouterProvider.otherwise('/app/node'); }) .directive('Chat', function (ChatService) { console.log('Loverzxcr'); return { restrict: 'E', replace: true, templateUrl: 'templates/app-chat.html', scope: { 'chatRoom': "=" }, controller: function ($scope, ChatService) { console.log('love'); var connection = ChatService.connect($scope.chatRoom); // The chat messages $scope.messages = []; // Notify whenever a new user connects ChatService.on.userConnected(function (user) { $scope.messages.push({ name: 'Chat Bot', text: 'A new user has connected!' }); $scope.$apply(); }); // Whenever a new message appears, append it ChatService.on.messageReceived(function (message) { message.external = true; $scope.messages.push(message); $scope.$apply(); }); $scope.inputMessage = ''; $scope.onSend = function () { $scope.messages.push({ name: 'Me', text: $scope.inputMessage }); // Send the message to the server ChatService.emit({ name: 'Anonymous', text: $scope.inputMessage }); // Clear the chatbox $scope.inputMessage = ''; } } } });
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('route-instructions', 'Integration | Component | route instructions', { integration: true }); test('it renders', function (assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{route-instructions}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#route-instructions}} template block text {{/route-instructions}} `); assert.equal(this.$().text().trim(), 'template block text'); });
const saurus = require('saurus') exports.run = async (bot, msg, args) => { if (!bot.utils.hasEmbedPermission(msg.channel)) { return msg.error('No permission to use embed in this channel!') } const parsed = bot.utils.parseArgs(args, ['a']) if (!parsed.leftover.length) { return msg.error('You must specify something to search!') } const antonyms = parsed.options.a const query = parsed.leftover.join(' ') const source = 'Thesaurus.com' await msg.edit(`${consts.p}Searching for \`${query}\` on ${source}\u2026`) const res = await saurus(query) if (!res) { return msg.error('No matches found!') } if (antonyms && (!res.antonyms || !res.antonyms.length)) { return msg.error(`No antonyms found for \`${query}\``) } else if (!antonyms && (!res.synonyms || !res.synonyms.length)) { return msg.error(`No synonyms found for \`${query}\``) } let title = ` of ${query}` let description if (antonyms) { title = 'Antonyms' + title description = res.antonyms.join(', ') } else { title = 'Synonyms' + title description = res.synonyms.join(', ') } return msg.edit(`First search result of \`${query}\` on ${source}:`, { embed: bot.utils.embed( title, description, [], { footer: source, footerIcon: 'https://the.fiery.me/JZ3W.png', color: '#fba824' } ) }) } exports.info = { name: 'thesaurus', usage: 'thesaurus [options] <query>', description: 'Looks up a word on Thesaurus.com (showing synonyms by default)', aliases: ['syn', 'synonyms'], options: [ { name: '-a', usage: '-a', description: 'Shows antonyms instead' } ] }
module.exports = function (path) { return "!" + path; };
import React from 'react'; import './Tips.css'; function Tips(props) { return ( <div className="Tips"> {props.children} </div> ); } export default Tips;
var fs = require('fs'), Q = require('q'), path = require('path'); /** Scans the provided directories for JavaScript files dirsConfig: [{ dir: String, // A directory name to scan recursively (relative to basedir) first: [String], // Include these files (relative to dir) in order before any other scanned files exclude: [String], // Ignore these files (relative to dir) entirely last: [String] // Include these files (relative to dir) in order after any other scanned files }] basedir: String Outputted filepaths will be relative to this directory. It should usually be your public folder. callback: function(error, files: [String]) returns: Promise of [String] files Example usage: scanJs([{ "dir": "vendor", "first": ["lib.js"], "exclude": ["browser-specific-polyfill.js"], "last": [] }, { "dir": "js", "first": [], "exclude": [], "last": ["main.js"] }], __dirname, function(err, files) { if (err) throw err; console.log(files); // ['vendor/lib.js', 'vendor/another-lib.js', 'js/dir1/file1.js', 'js/dir2/file2.js', 'js/main.js']; }); **/ module.exports = function scanJs(dirsConfig, basedir, callback) { var jsFilesNestedQ = []; dirsConfig.forEach(function(dirConfig) { var firstFiles = dirConfig.first.map(function(filename) { return dirConfig.dir + '/' + filename; }); var lastFiles = dirConfig.last.map(function(filename) { return dirConfig.dir + '/' + filename; }); jsFilesNestedQ.push(firstFiles); jsFilesNestedQ.push(scanFolder(dirConfig, basedir, path.join(basedir, dirConfig.dir))); jsFilesNestedQ.push(lastFiles); }); return Q.all(jsFilesNestedQ).then(function(jsFilesNested) { var jsFiles = flattenArray(jsFilesNested); if (callback) callback(null, jsFiles); return jsFiles; }, function(err) { if (callback) callback(err); throw err; }); }; function flattenArray(array) { var result = []; array.forEach(function(item) { if (Array.isArray(item)) { Array.prototype.push.apply(result, flattenArray(item)); } else { result.push(item); } }); return result; } function scanFolder(dirConfig, basedir, dirPath) { var filesQ = Q.ninvoke(fs, 'readdir', dirPath); return filesQ.then(function(files) { return Q.all(files.map(function(f) { var fullFilePath = path.join(dirPath, f); return Q.ninvoke(fs, 'stat', fullFilePath).then(function(stat) { return { path: f, fullFilePath: fullFilePath, stat: stat }; }); })); }).then(function(files) { var dirFiles = []; files.forEach(function(file) { var fullFilePath = file.fullFilePath; var stat = file.stat; if (stat.isDirectory()) { dirFiles.push(scanFolder(dirConfig, basedir, fullFilePath)); } else if (path.extname(file.path) === '.js') { var filepath = path.relative(basedir, fullFilePath); var relativeFilepath = path.relative(dirConfig.dir, filepath); filepath = filepath.split(path.sep).join('/'); if (dirConfig.exclude.indexOf(relativeFilepath) === -1 && dirConfig.first.indexOf(relativeFilepath) === -1 && dirConfig.last.indexOf(relativeFilepath) === -1) { dirFiles.push(filepath); } } }); return Q.all(dirFiles); }); }
'use strict'; angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication', function($scope, $http, $location, Authentication) { $scope.authentication = Authentication; // If user is signed in then redirect back home if ($scope.authentication.user) $location.path('/folders'); $scope.signup = function() { $http.post('/auth/signup', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/folders'); }).error(function(response) { $scope.error = response.message; }); }; $scope.signin = function() { $http.post('/auth/signin', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; console.log("usuario autenticado! "); // And redirect to the index page $location.path('/folders'); }).error(function(response) { $scope.error = response.message; }); }; } ]);
/* Nodejs uses Javascript (official name: ECMA script) use: http://jsconsole.com/ */ // define variables with var //////////////////////////// // string var myName = "Joost"; console.log("My name is " + myName); // number var myAge = 28; // not really, but it sounds good console.log("Last year I was", myAge - 1); // this is an array var myToys = ["SAS", "Stata", "nodejs"]; console.log('My first toy is: ' + myToys[0]); // Outputs: My first toy is: SAS // object var me = { name: "Joost", age: 28, hobbies: [ "coding", "testing", "programming", "SAS", "debugging" ] }; // functions //////////// var doIt = function(name) { console.log('Hi ' + name + "!"); // console.log outputs to the log }; // function call doIt("Gators"); // functions var ageBinner = function(age) { // ( expression ) ? => ternary operation: if true, return first item, if false, second item return (age < 28) ? "a young gun" : "an old fart"; }; console.log(me.name + " is " + ageBinner(me.age)); // functions can be arguments to function calls var processPerson = function(ageFn, person) { var retVal = 'Let me tell you something about ' + person.name; var ageType = ageFn(person.age); return retVal + "\n" + "This person is " + ageType; }; // call var profile = processPerson(ageBinner, me); console.log("Profile: " + profile); // objects and functions //////////////////////// // object property can be a function // object, this refers to object itself, notice the argument for function ageBinner var me = { name: "Joost", age: 28, hobbies: [ "coding", "testing", "programming", "SAS", "debugging" ], ageBinner: function(cutoff) { return (this.age < cutoff) ? this.name + " is a young gun" : this.name + " is an old fart"; } }; console.log("Agebinner says: " + me.ageBinner(75)); console.log("Agebinner says: " + me.ageBinner(28)); // array of objects var myStruct = [{ name: "Joost", age: 28, keywords: ["UF", "SAS", "hot tub"] }, { name: "Walter White", age: 52, keywords: ["chemistry", "family man", "enterpreneur"] }]; // function to test if array holds keyword, indexOf returns position (0, 1, 2, ...), or -1 if not in array var personHasKeyword = function(person, keyword) { return (person.keywords.indexOf(keyword) > -1) ? true : false; }; //loop through objects in array -- use of anonymous (unnamed) function // each element in myStruct is passed as an argument (called item) in the anonymous function myStruct.forEach(function(item) { console.log('item', item); var isFamilyMan = personHasKeyword(item, "family man") ? " is a family man" : " is no family man"; console.log(item.name + isFamilyMan); });
/** * app/script/app * Application main script. * @author Keenan Staffieri */ console.log('Main application script loaded.')
/** * Created by Administrator on 2016/9/19. */ var crypto = require('crypto'); function pwdMd5(pwd) { var hash = crypto.createHash("md5"); hash.update(pwd); //直接对"123456"字符串加密 return hash.digest('hex'); } exports.pwdMd5=pwdMd5;
version https://git-lfs.github.com/spec/v1 oid sha256:0ff5cad3aefefd4a18f6ea80f78a7999c825056be6c35134b3a815b3eb2cfe12 size 759
"use strict"; var CONSTANT_PREFIX = "var getMessages = function (){\n"; CONSTANT_PREFIX += " var r = function(val, args){\n"; CONSTANT_PREFIX += " for(var x = 0;x<args.length;x++){\n"; CONSTANT_PREFIX += " val = val.replace('{'+x+'}', args[x]);\n"; CONSTANT_PREFIX += " }\n"; CONSTANT_PREFIX += " return val;\n"; CONSTANT_PREFIX += " };\n"; CONSTANT_PREFIX += " var p = function() {\n"; CONSTANT_PREFIX += " var val = arguments[0];\n"; CONSTANT_PREFIX += " var ret;\n"; CONSTANT_PREFIX += " if(val.indexOf('{0}') != -1)\n"; CONSTANT_PREFIX += " ret = function(){return r(val,arguments);}\n"; CONSTANT_PREFIX += " else ret = function(){return val;}\n"; CONSTANT_PREFIX += " for(var x = 1; x < arguments.length;x++) {\n"; CONSTANT_PREFIX += " for(var a in arguments[x])\n"; CONSTANT_PREFIX += " ret[a] = arguments[x][a];\n"; CONSTANT_PREFIX += " }\n"; CONSTANT_PREFIX += " return ret;\n"; CONSTANT_PREFIX += " };\n"; CONSTANT_PREFIX += " return ("; var CONSTANT_SUFFIX = " );\n"; CONSTANT_SUFFIX += "};\n"; var Node = require('./Node'); var processor = require('./processor'); var minimatch = require('minimatch'); var os = require('os'); var findFirstMatchingConfig = function(configsMap, fileName) { if(typeof configsMap === 'string') { //no map - single config to prepend/append to every processed file return configsMap; } //test if the current processed file matches a glob pattern in the additions map keys. //If match is found - use the value as the chosen config. The first match found - wins var result = ""; //TODO: this has side effects, prefer Array.prototype.find for newer node versions Object.keys(configsMap).some(function(pattern) { if(minimatch(fileName, pattern)) { result = configsMap[pattern]; return true; } }); return result; }; var createSpringMessagesPreprocessor = function(args, config, logger, helper) { config = config || {}; var log = logger.create("preprocessor.spring-messages"); var defaultOptions = { prefix: "", // Used for boilerplate, for example wrap in a define() call suffix: "" // Used for boilerplate, for example, close function calls with ); }; var options = helper.merge(defaultOptions, args.options || {}, config.options || {}); var transformPath = args.transformPath || config.transformPath || function(filepath) { return filepath + ".js"; }; return function(content, file, done) { var fileName = file.originalPath, prefix = findFirstMatchingConfig(options.prefix, fileName), suffix = findFirstMatchingConfig(options.suffix, fileName); log.debug("Processing %s", fileName); file.path = transformPath(fileName); var lines = content.split(os.EOL); var tree = processor.process(lines); done(null, prefix + CONSTANT_PREFIX + Node.render(tree) + CONSTANT_SUFFIX + suffix); }; }; createSpringMessagesPreprocessor.$inject = ['args', 'config.springMessagesPreprocessor', 'logger', 'helper']; module.exports = { 'preprocessor:spring-messages': ["factory", createSpringMessagesPreprocessor] };
var webpack = require('webpack'); module.exports = { entry: './index.js', output: { path: 'public', filename: 'bundle.js', publicPath: '/', }, plugins: process.env.NODE_ENV === 'production' ? [ new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin(), ] : [], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react', }, ], }, };
module.exports = function(app, ProductModel){ // GET /products app.get('/products', (req, res) => { ProductModel.find({}, (err, data) => { if (err) res.sendStatus(404) res.status(200).send(data) }) }) // GET /products/:id app.get('/products/:id', (req, res) => { ProductModel.findById(req.params.id, (err, data) => { if (err) res.sendStatus(404) res.status(200).send(data) }) }) //POST /products app.post('/products', (req, res) => { ProductModel.create(req.body, (err, data) => { if (err) res.sendStatus(404) res.status(201).send(data) }) }) // DELETE /products/:id app.delete('/products/:id', (req, res) => { ProductModel.findByIdAndRemove(req.params.id, (err) => { if (err) res.sendStatus(404) res.sendStatus(204) }) }) // PUT /products/:id app.put('/products/:id', (req, res) => { ProductModel.findByIdAndUpdate(req.params.id, req.body, (err) => { if (err) res.sendStatus(404) res.sendStatus(204) }) }) }
const ftdi = require('../hello_world/hello.js'); const fs = require('fs'); const { Transform } = require('stream'); const protocols = fs.readdirSync('./protocols/').reduce((carry, protocolFile) => { //console.log(protocolFile.substr(0, protocolFile.lastIndexOf('.'))); carry[protocolFile.substr(0, protocolFile.lastIndexOf('.'))] = require('./protocols/' + protocolFile); return carry; }, {}); ftdi.find(0x1781, 0x0c31, function(err, devices) { if(err) { throw(err); } if(devices.length === 0) { console.log('Tellstick not found.'); process.exit(); } var td = new ftdi.FtdiDevice(devices[0]); td.open({ baudrate: td.deviceSettings.productId == 0x0C31 ? 9600 : 4800, databits: 8, stopbits: 1, parity: 'none' }, function(err) { var static = protocols['everflourish'].getCommand(117, 1, methods.TELLSTICK_TURNON); console.log('Send static command:', static); td.write(Buffer.concat([static, Buffer.from([13, 10])]), function(err, bytesSent) { if(err) { throw err; } console.log('Bytes sent:', bytesSent); }); /*td.write(Buffer.from('V+'), function(err) { if(err) { throw err; } console.log('Version info requested'); });*/ }); });
/*! * parse-github-short-url <https://github.com/tunnckoCore/parse-github-short-url> * * Copyright (c) 2015-2016 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk) * Released under the MIT license. */ /* jshint asi:true */ 'use strict' var test = require('assertit') var gh = require('./index') test('should return null if not a string or if empty string', function (done) { test.strictEqual(gh(''), null) test.strictEqual(gh(), null) test.strictEqual(gh(null), null) test.strictEqual(gh(undefined), null) test.strictEqual(gh(123), null) test.strictEqual(gh([1, 2, 3]), null) done() }) test('should return object with `owner` and `branch` when invalid pattern', function (done) { test.strictEqual(gh('https://github.com/jonschlinkert/micromatch').owner, 'https') test.strictEqual(gh('https://github.com/jonschlinkert/micromatch').repo, null) test.strictEqual(gh('https://github.com/jonschlinkert/micromatch').name, null) test.strictEqual(gh('https://github.com/jonschlinkert/micromatch').branch, null) done() }) test('should get user', function (done) { test.strictEqual(gh('assemble/verb#branch').owner, 'assemble') test.strictEqual(gh('assemble/verb#dev').owner, 'assemble') test.strictEqual(gh('assemble/verb').owner, 'assemble') test.strictEqual(gh('assemble').owner, 'assemble') done() }) test('should get version for npm shorthands like `user/repo@version`', function (done) { test.strictEqual(gh('assemble/verb@v1').branch, null) test.strictEqual(gh('assemble/verb@v1').version, 'v1') test.strictEqual(gh('assemble/verb@v3.1.3').branch, null) test.strictEqual(gh('assemble/verb@v3.1.3').version, 'v3.1.3') done() }) test('should get branch for github shorthands like `user/repo#dev`', function (done) { test.strictEqual(gh('assemble/verb#dev').branch, 'dev') test.strictEqual(gh('assemble/verb#dev').version, undefined) test.strictEqual(gh('assemble/verb#feature').branch, 'feature') test.strictEqual(gh('assemble/verb#feature').version, undefined) done() }) test('should get repo name (.name)', function (done) { test.strictEqual(gh('assemble/verb#branch').name, 'verb') test.strictEqual(gh('assemble/verb#dev').name, 'verb') test.strictEqual(gh('assemble/verb').name, 'verb') test.strictEqual(gh('assemble').name, null) done() }) test('should get branch (and get master branch if not defined)', function (done) { test.strictEqual(gh('gulpjs/gulp#branch').branch, 'branch') test.strictEqual(gh('gulpjs/gulp#dev').branch, 'dev') test.strictEqual(gh('gulpjs/gulp').branch, null) test.strictEqual(gh('gulpjs').branch, null) done() }) test('should get a full repo path', function (done) { test.strictEqual(gh('mochajs/mocha#branch').repo, 'mochajs/mocha') test.strictEqual(gh('mochajs/mocha#dev').repo, 'mochajs/mocha') test.strictEqual(gh('mochajs/mocha').repo, 'mochajs/mocha') done() }) test('should know when repo is not defined', function (done) { test.strictEqual(gh('assemble').name, null) test.strictEqual(gh('assemble').repo, null) test.strictEqual(gh('assemble').owner, 'assemble') done() }) test('should allow passing opts that will remain in returned object', function (done) { test.strictEqual(gh('foo', { bar: 'qux' }).name, null) test.strictEqual(gh('foo', { bar: 'qux' }).repo, null) test.strictEqual(gh('foo', { bar: 'qux' }).owner, 'foo') test.strictEqual(gh('foo', { bar: 'qux' }).bar, 'qux') done() })
/* eslint-env mocha */ 'use strict' const Listener = require('../src/listener') const nodes = require('./fixtures/nodes') const waterfall = require('async/waterfall') const PeerInfo = require('peer-info') const PeerId = require('peer-id') const multiaddr = require('multiaddr') const handshake = require('pull-handshake') const Connection = require('interface-connection').Connection const proto = require('../src/protocol') const lp = require('pull-length-prefixed') const pull = require('pull-stream') const multicodec = require('../src/multicodec') const chai = require('chai') const dirtyChai = require('dirty-chai') const expect = chai.expect chai.use(dirtyChai) const sinon = require('sinon') describe('listener', function () { describe(`listen`, function () { let swarm = null let handlerSpy = null let listener = null let stream = null let shake = null let conn = null beforeEach(function (done) { stream = handshake({ timeout: 1000 * 60 }) shake = stream.handshake conn = new Connection(stream) conn.setPeerInfo(new PeerInfo(PeerId .createFromB58String('QmSswe1dCFRepmhjAMR5VfHeokGLcvVggkuDJm7RMfJSrE'))) waterfall([ (cb) => PeerId.createFromJSON(nodes.node4, cb), (peerId, cb) => PeerInfo.create(peerId, cb), (peer, cb) => { swarm = { _peerInfo: peer, handle: sinon.spy((proto, h) => { handlerSpy = sinon.spy(h) }), conns: { QmSswe1dCFRepmhjAMR5VfHeokGLcvVggkuDJm7RMfJSrE: new Connection() } } listener = Listener(swarm, {}, () => {}) listener.listen() cb() } ], done) }) afterEach(() => { listener = null }) it(`should handle HOP`, function (done) { handlerSpy(multicodec.relay, conn) let relayMsg = { type: proto.CircuitRelay.Type.HOP, srcPeer: { id: `QmSswe1dCFRepmhjAMR5VfHeokGLcvVggkuDJm7RMfJSrE`, addrs: [`/ipfs/QmSswe1dCFRepmhjAMR5VfHeokGLcvVggkuDJm7RMfJSrE`] }, dstPeer: { id: `QmQvM2mpqkjyXWbTHSUidUAWN26GgdMphTh9iGDdjgVXCy`, addrs: [`/ipfs/QmQvM2mpqkjyXWbTHSUidUAWN26GgdMphTh9iGDdjgVXCy`] } } listener.hopHandler.handle = (message, conn) => { expect(message.type).to.equal(proto.CircuitRelay.Type.HOP) expect(message.srcPeer.id.toString()).to.equal(relayMsg.srcPeer.id) expect(message.srcPeer.addrs[0].toString()).to.equal(relayMsg.srcPeer.addrs[0]) expect(message.dstPeer.id.toString()).to.equal(relayMsg.dstPeer.id) expect(message.dstPeer.addrs[0].toString()).to.equal(relayMsg.dstPeer.addrs[0]) done() } pull( pull.values([proto.CircuitRelay.encode(relayMsg)]), lp.encode(), pull.collect((err, encoded) => { expect(err).to.not.exist() encoded.forEach((e) => shake.write(e)) }) ) }) it(`should handle STOP`, function (done) { handlerSpy(multicodec.relay, conn) let relayMsg = { type: proto.CircuitRelay.Type.STOP, srcPeer: { id: `QmSswe1dCFRepmhjAMR5VfHeokGLcvVggkuDJm7RMfJSrE`, addrs: [`/ipfs/QmSswe1dCFRepmhjAMR5VfHeokGLcvVggkuDJm7RMfJSrE`] }, dstPeer: { id: `QmQvM2mpqkjyXWbTHSUidUAWN26GgdMphTh9iGDdjgVXCy`, addrs: [`/ipfs/QmQvM2mpqkjyXWbTHSUidUAWN26GgdMphTh9iGDdjgVXCy`] } } listener.stopHandler.handle = (message, conn) => { expect(message.type).to.equal(proto.CircuitRelay.Type.STOP) expect(message.srcPeer.id.toString()).to.equal(relayMsg.srcPeer.id) expect(message.srcPeer.addrs[0].toString()).to.equal(relayMsg.srcPeer.addrs[0]) expect(message.dstPeer.id.toString()).to.equal(relayMsg.dstPeer.id) expect(message.dstPeer.addrs[0].toString()).to.equal(relayMsg.dstPeer.addrs[0]) done() } pull( pull.values([proto.CircuitRelay.encode(relayMsg)]), lp.encode(), pull.collect((err, encoded) => { expect(err).to.not.exist() encoded.forEach((e) => shake.write(e)) }) ) }) it(`should handle CAN_HOP`, function (done) { handlerSpy(multicodec.relay, conn) let relayMsg = { type: proto.CircuitRelay.Type.CAN_HOP, srcPeer: { id: `QmSswe1dCFRepmhjAMR5VfHeokGLcvVggkuDJm7RMfJSrE`, addrs: [`/ipfs/QmSswe1dCFRepmhjAMR5VfHeokGLcvVggkuDJm7RMfJSrE`] }, dstPeer: { id: `QmQvM2mpqkjyXWbTHSUidUAWN26GgdMphTh9iGDdjgVXCy`, addrs: [`/ipfs/QmQvM2mpqkjyXWbTHSUidUAWN26GgdMphTh9iGDdjgVXCy`] } } listener.hopHandler.handle = (message, conn) => { expect(message.type).to.equal(proto.CircuitRelay.Type.CAN_HOP) expect(message.srcPeer.id.toString()).to.equal(relayMsg.srcPeer.id) expect(message.srcPeer.addrs[0].toString()).to.equal(relayMsg.srcPeer.addrs[0]) expect(message.dstPeer.id.toString()).to.equal(relayMsg.dstPeer.id) expect(message.dstPeer.addrs[0].toString()).to.equal(relayMsg.dstPeer.addrs[0]) done() } pull( pull.values([proto.CircuitRelay.encode(relayMsg)]), lp.encode(), pull.collect((err, encoded) => { expect(err).to.not.exist() encoded.forEach((e) => shake.write(e)) }) ) }) it(`should handle invalid message correctly`, function (done) { handlerSpy(multicodec.relay, conn) let relayMsg = { type: 100000, srcPeer: { id: Buffer.from(`QmSswe1dCFRepmhjAMR5VfHeokGLcvVggkuDJm7RMfJSrE`), addrs: [multiaddr(`/ipfs/QmSswe1dCFRepmhjAMR5VfHeokGLcvVggkuDJm7RMfJSrE`).buffer] }, dstPeer: { id: Buffer.from(`QmQvM2mpqkjyXWbTHSUidUAWN26GgdMphTh9iGDdjgVXCy`), addrs: [multiaddr(`/ipfs/QmQvM2mpqkjyXWbTHSUidUAWN26GgdMphTh9iGDdjgVXCy`).buffer] } } pull( pull.values([Buffer.from([relayMsg])]), lp.encode(), pull.collect((err, encoded) => { expect(err).to.not.exist() encoded.forEach((e) => shake.write(e)) }), lp.decodeFromReader(shake, { maxLength: this.maxLength }, (err, msg) => { expect(err).to.not.exist() expect(proto.CircuitRelay.decode(msg).type).to.equal(proto.CircuitRelay.Type.STATUS) expect(proto.CircuitRelay.decode(msg).code).to.equal(proto.CircuitRelay.Status.MALFORMED_MESSAGE) done() }) ) }) }) describe(`getAddrs`, function () { let swarm = null let listener = null let peerInfo = null beforeEach(function (done) { waterfall([ (cb) => PeerId.createFromJSON(nodes.node4, cb), (peerId, cb) => PeerInfo.create(peerId, cb), (peer, cb) => { swarm = { _peerInfo: peer } peerInfo = peer listener = Listener(swarm, {}, () => {}) cb() } ], done) }) afterEach(() => { peerInfo = null }) it(`should return correct addrs`, function () { peerInfo.multiaddrs.add(`/ip4/0.0.0.0/tcp/4002`) peerInfo.multiaddrs.add(`/ip4/127.0.0.1/tcp/4003/ws`) listener.getAddrs((err, addrs) => { expect(err).to.not.exist() expect(addrs).to.deep.equal([ multiaddr(`/p2p-circuit/ip4/0.0.0.0/tcp/4002/ipfs/QmQvM2mpqkjyXWbTHSUidUAWN26GgdMphTh9iGDdjgVXCy`), multiaddr(`/p2p-circuit/ip4/127.0.0.1/tcp/4003/ws/ipfs/QmQvM2mpqkjyXWbTHSUidUAWN26GgdMphTh9iGDdjgVXCy`)]) }) }) it(`don't return default addrs in an explicit p2p-circuit addres`, function () { peerInfo.multiaddrs.add(`/ip4/127.0.0.1/tcp/4003/ws`) peerInfo.multiaddrs.add(`/p2p-circuit/ip4/0.0.0.0/tcp/4002`) listener.getAddrs((err, addrs) => { expect(err).to.not.exist() expect(addrs[0] .toString()) .to.equal(`/p2p-circuit/ip4/0.0.0.0/tcp/4002/ipfs/QmQvM2mpqkjyXWbTHSUidUAWN26GgdMphTh9iGDdjgVXCy`) }) }) }) })
/*! * bootstrap-fileinput v4.3.5 * http://plugins.krajee.com/file-input * * Author: Kartik Visweswaran * Copyright: 2014 - 2016, Kartik Visweswaran, Krajee.com * * Licensed under the BSD 3-Clause * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md */ (function (factory) { "use strict"; //noinspection JSUnresolvedVariable if (typeof define === 'function' && define.amd) { // jshint ignore:line // AMD. Register as an anonymous module. define(['jquery'], factory); // jshint ignore:line } else { // noinspection JSUnresolvedVariable if (typeof module === 'object' && module.exports) { // jshint ignore:line // Node/CommonJS // noinspection JSUnresolvedVariable module.exports = factory(require('jquery')); // jshint ignore:line } else { // Browser globals factory(window.jQuery); } } }(function ($) { "use strict"; $.fn.fileinputLocales = {}; $.fn.fileinputThemes = {}; var NAMESPACE, MODAL_ID, STYLE_SETTING, OBJECT_PARAMS, DEFAULT_PREVIEW, objUrl, compare, isIE, handler, previewCache, getNum, hasFileAPISupport, hasDragDropSupport, hasFileUploadSupport, addCss, tMain1, tMain2, tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse, tModalMain, tModal, tProgress, tSize, tFooter, tActions, tActionDelete, tActionUpload, tActionZoom, tActionDrag, tTagBef, tTagBef1, tTagBef2, tTagAft, tGeneric, tHtml, tImage, tText, tVideo, tAudio, tFlash, tObject, tPdf, tOther, defaultFileActionSettings, defaultLayoutTemplates, defaultPreviewTemplates, defaultPreviewZoomSettings, defaultPreviewTypes, getElement, defaultPreviewSettings, defaultFileTypeSettings, isEmpty, isArray, ifSet, uniqId, htmlEncode, replaceTags, cleanMemory, findFileName, checkFullScreen, toggleFullScreen, moveArray, FileInput; NAMESPACE = '.fileinput'; MODAL_ID = 'kvFileinputModal'; STYLE_SETTING = 'style="width:{width};height:{height};"'; OBJECT_PARAMS = '<param name="controller" value="true" />\n' + '<param name="allowFullScreen" value="true" />\n' + '<param name="allowScriptAccess" value="always" />\n' + '<param name="autoPlay" value="false" />\n' + '<param name="autoStart" value="false" />\n' + '<param name="quality" value="high" />\n'; DEFAULT_PREVIEW = '<div class="file-preview-other">\n' + '<span class="{previewFileIconClass}">{previewFileIcon}</span>\n' + '</div>'; //noinspection JSUnresolvedVariable objUrl = window.URL || window.webkitURL; compare = function (input, str, exact) { return input !== undefined && (exact ? input === str : input.match(str)); }; isIE = function (ver) { // check for IE versions < 11 if (navigator.appName !== 'Microsoft Internet Explorer') { return false; } if (ver === 10) { return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent); } var div = document.createElement("div"), status; div.innerHTML = "<!--[if IE " + ver + "]> <i></i> <![endif]-->"; status = div.getElementsByTagName("i").length; document.body.appendChild(div); div.parentNode.removeChild(div); return status; }; handler = function ($el, event, callback, skipNS) { var ev = skipNS ? event : event.split(' ').join(NAMESPACE + ' ') + NAMESPACE; $el.off(ev).on(ev, callback); }; previewCache = { data: {}, init: function (obj) { var content = obj.initialPreview, id = obj.id; if (content.length > 0 && !isArray(content)) { content = content.split(obj.initialPreviewDelimiter); } previewCache.data[id] = { content: content, config: obj.initialPreviewConfig, tags: obj.initialPreviewThumbTags, delimiter: obj.initialPreviewDelimiter, previewFileType: obj.initialPreviewFileType, previewAsData: obj.initialPreviewAsData, template: obj.previewGenericTemplate, showZoom: obj.fileActionSettings.showZoom, showDrag: obj.fileActionSettings.showDrag, getSize: function (size) { return obj._getSize(size); }, parseTemplate: function (cat, data, fname, ftype, pId, ftr, ind) { var fc = ' file-preview-initial'; return obj._generatePreviewTemplate(cat, data, fname, ftype, pId, false, null, fc, ftr, ind); }, msg: function (n) { return obj._getMsgSelected(n); }, initId: obj.previewInitId, footer: obj._getLayoutTemplate('footer').replace(/\{progress}/g, obj._renderThumbProgress()), isDelete: obj.initialPreviewShowDelete, caption: obj.initialCaption, actions: function (showUpload, showDelete, showZoom, showDrag, disabled, url, key) { return obj._renderFileActions(showUpload, showDelete, showZoom, showDrag, disabled, url, key, true); } }; }, fetch: function (id) { return previewCache.data[id].content.filter(function (n) { return n !== null; }); }, count: function (id, all) { return !!previewCache.data[id] && !!previewCache.data[id].content ? (all ? previewCache.data[id].content.length : previewCache.fetch(id).length) : 0; }, get: function (id, i, isDisabled) { var ind = 'init_' + i, data = previewCache.data[id], config = data.config[i], content = data.content[i], previewId = data.initId + '-' + ind, out, $tmp, frameClass = ' file-preview-initial', cat, cap, ftr, ftype, asData = ifSet('previewAsData', config, data.previewAsData); isDisabled = isDisabled === undefined ? true : isDisabled; /** @namespace config.frameAttr */ /** @namespace config.frameClass */ /** @namespace config.filetype */ if (!content) { return ''; } if (config && config.frameClass) { frameClass += ' ' + config.frameClass; } if (asData) { cat = data.previewAsData ? ifSet('type', config, data.previewFileType || 'generic') : 'generic'; cap = ifSet('caption', config); ftr = previewCache.footer(id, i, isDisabled, (config && config.size || null)); ftype = ifSet('filetype', config, cat); out = data.parseTemplate(cat, content, cap, ftype, previewId, ftr, ind, null); } else { out = data.template .replace(/\{previewId}/g, previewId).replace(/\{frameClass}/g, frameClass) .replace(/\{fileindex}/g, ind).replace(/\{content}/g, data.content[i]) .replace(/\{template}/g, ifSet('type', config, data.previewFileType)) .replace(/\{footer}/g, previewCache.footer(id, i, isDisabled, (config && config.size || null))); } if (data.tags.length && data.tags[i]) { out = replaceTags(out, data.tags[i]); } if (!isEmpty(config) && !isEmpty(config.frameAttr)) { $tmp = $(document.createElement('div')).html(out); $tmp.find('.file-preview-initial').attr(config.frameAttr); out = $tmp.html(); $tmp.remove(); } return out; }, add: function (id, content, config, tags, append) { var data = $.extend(true, {}, previewCache.data[id]), index; if (!isArray(content)) { content = content.split(data.delimiter); } if (append) { index = data.content.push(content) - 1; data.config[index] = config; data.tags[index] = tags; } else { index = content.length - 1; data.content = content; data.config = config; data.tags = tags; } previewCache.data[id] = data; return index; }, set: function (id, content, config, tags, append) { var data = $.extend(true, {}, previewCache.data[id]), i, chk; if (!content || !content.length) { return; } if (!isArray(content)) { content = content.split(data.delimiter); } chk = content.filter(function (n) { return n !== null; }); if (!chk.length) { return; } if (data.content === undefined) { data.content = []; } if (data.config === undefined) { data.config = []; } if (data.tags === undefined) { data.tags = []; } if (append) { for (i = 0; i < content.length; i++) { if (content[i]) { data.content.push(content[i]); } } for (i = 0; i < config.length; i++) { if (config[i]) { data.config.push(config[i]); } } for (i = 0; i < tags.length; i++) { if (tags[i]) { data.tags.push(tags[i]); } } } else { data.content = content; data.config = config; data.tags = tags; } previewCache.data[id] = data; }, unset: function (id, index) { var chk = previewCache.count(id); if (!chk) { return; } if (chk === 1) { previewCache.data[id].content = []; previewCache.data[id].config = []; previewCache.data[id].tags = []; return; } previewCache.data[id].content[index] = null; previewCache.data[id].config[index] = null; previewCache.data[id].tags[index] = null; }, out: function (id) { var html = '', data = previewCache.data[id], caption, len = previewCache.count(id, true); if (len === 0) { return {content: '', caption: ''}; } for (var i = 0; i < len; i++) { html += previewCache.get(id, i); } caption = data.msg(previewCache.count(id)); return {content: '<div class="file-initial-thumbs">' + html + '</div>', caption: caption}; }, footer: function (id, i, isDisabled, size) { var data = previewCache.data[id]; isDisabled = isDisabled === undefined ? true : isDisabled; if (data.config.length === 0 || isEmpty(data.config[i])) { return ''; } var config = data.config[i], caption = ifSet('caption', config), width = ifSet('width', config, 'auto'), url = ifSet('url', config, false), key = ifSet('key', config, null), showDel = ifSet('showDelete', config, true), showZoom = ifSet('showZoom', config, data.showZoom), showDrag = ifSet('showDrag', config, data.showDrag), disabled = (url === false) && isDisabled, actions = data.isDelete ? data.actions(false, showDel, showZoom, showDrag, disabled, url, key) : '', footer = data.footer.replace(/\{actions}/g, actions); return footer.replace(/\{caption}/g, caption).replace(/\{size}/g, data.getSize(size)) .replace(/\{width}/g, width).replace(/\{indicator}/g, '').replace(/\{indicatorTitle}/g, ''); } }; getNum = function (num, def) { def = def || 0; if (typeof num === "number") { return num; } if (typeof num === "string") { num = parseFloat(num); } return isNaN(num) ? def : num; }; hasFileAPISupport = function () { return !!(window.File && window.FileReader); }; hasDragDropSupport = function () { var div = document.createElement('div'); /** @namespace div.draggable */ /** @namespace div.ondragstart */ /** @namespace div.ondrop */ return !isIE(9) && (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined)); }; hasFileUploadSupport = function () { return hasFileAPISupport() && window.FormData; }; addCss = function ($el, css) { $el.removeClass(css).addClass(css); }; defaultFileActionSettings = { showRemove: true, showUpload: true, showZoom: true, showDrag: true, removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>', removeClass: 'btn btn-xs btn-default', removeTitle: 'Remove file', uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>', uploadClass: 'btn btn-xs btn-default', uploadTitle: 'Upload file', zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>', zoomClass: 'btn btn-xs btn-default', zoomTitle: 'View Details', dragIcon: '<i class="glyphicon glyphicon-menu-hamburger"></i>', dragClass: 'text-info', dragTitle: 'Move / Rearrange', dragSettings: {}, indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>', indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>', indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>', indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>', indicatorNewTitle: 'Not uploaded yet', indicatorSuccessTitle: 'Uploaded', indicatorErrorTitle: 'Upload Error', indicatorLoadingTitle: 'Uploading ...' }; tMain1 = '{preview}\n' + '<div class="kv-upload-progress hide"></div>\n' + '<div class="input-group {class}">\n' + ' {caption}\n' + ' <div class="input-group-btn">\n' + ' {remove}\n' + ' {cancel}\n' + ' {upload}\n' + ' {browse}\n' + ' </div>\n' + '</div>'; tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n'; tPreview = '<div class="file-preview {class}">\n' + ' {close}' + ' <div class="{dropClass}">\n' + ' <div class="file-preview-thumbnails">\n' + ' </div>\n' + ' <div class="clearfix"></div>' + ' <div class="file-preview-status text-center text-success"></div>\n' + ' <div class="kv-fileinput-error"></div>\n' + ' </div>\n' + '</div>'; tClose = '<div class="close fileinput-remove">&times;</div>\n'; tFileIcon = '<i class="glyphicon glyphicon-file kv-caption-icon"></i>'; tCaption = '<div tabindex="500" class="form-control file-caption {class}">\n' + ' <div class="file-caption-name"></div>\n' + '</div>\n'; //noinspection HtmlUnknownAttribute tBtnDefault = '<button type="{type}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</button>'; //noinspection HtmlUnknownAttribute tBtnLink = '<a href="{href}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</a>'; //noinspection HtmlUnknownAttribute tBtnBrowse = '<div tabindex="500" class="{css}" {status}>{icon} {label}</div>'; tModalMain = '<div id="' + MODAL_ID + '" class="file-zoom-dialog modal fade" tabindex="-1" aria-labelledby="' + MODAL_ID + 'Label"></div>'; tModal = '<div class="modal-dialog modal-lg" role="document">\n' + ' <div class="modal-content">\n' + ' <div class="modal-header">\n' + ' <div class="kv-zoom-actions pull-right">{toggleheader}{fullscreen}{borderless}{close}</div>\n' + ' <h3 class="modal-title">{heading} <small><span class="kv-zoom-title"></span></small></h3>\n' + ' </div>\n' + ' <div class="modal-body">\n' + ' <div class="floating-buttons"></div>\n' + ' <div class="kv-zoom-body file-zoom-content"></div>\n' + '{prev} {next}\n' + ' </div>\n' + ' </div>\n' + '</div>\n'; tProgress = '<div class="progress">\n' + ' <div class="{class}" role="progressbar"' + ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' + ' {percent}%\n' + ' </div>\n' + '</div>'; tSize = ' <br><samp>({sizeText})</samp>'; tFooter = '<div class="file-thumbnail-footer">\n' + ' <div class="file-footer-caption" title="{caption}">{caption}{size}</div>\n' + ' {progress} {actions}\n' + '</div>'; tActions = '<div class="file-actions">\n' + ' <div class="file-footer-buttons">\n' + ' {upload} {delete} {zoom} {other}' + ' </div>\n' + ' {drag}\n' + ' <div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>\n' + ' <div class="clearfix"></div>\n' + '</div>'; //noinspection HtmlUnknownAttribute tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' + 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n'; tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' + '{uploadIcon}</button>'; tActionZoom = '<button type="button" class="kv-file-zoom {zoomClass}" title="{zoomTitle}">{zoomIcon}</button>'; tActionDrag = '<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>'; tTagBef = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' + ' data-template="{template}"'; tTagBef1 = tTagBef + '><div class="kv-file-content">\n'; tTagBef2 = tTagBef + ' title="{caption}" ' + STYLE_SETTING + '><div class="kv-file-content">\n'; tTagAft = '</div>{footer}\n</div>\n'; tGeneric = '{content}\n'; tHtml = '<div class="kv-preview-data file-preview-html" title="{caption}" ' + STYLE_SETTING + '>{data}</div>\n'; tImage = '<img src="{data}" class="kv-preview-data file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n'; tText = '<textarea class="kv-preview-data file-preview-text" title="{caption}" readonly ' + STYLE_SETTING + '>{data}</textarea>\n'; tVideo = '<video class="kv-preview-data" width="{width}" height="{height}" controls>\n' + '<source src="{data}" type="{type}">\n' + DEFAULT_PREVIEW + '\n</video>\n'; tAudio = '<audio class="kv-preview-data" controls>\n<source src="' + '{data}' + '" type="{type}">\n' + DEFAULT_PREVIEW + '\n</audio>\n'; tFlash = '<object class="kv-preview-data file-object" type="application/x-shockwave-flash" ' + 'width="{width}" height="{height}" data="{data}">\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n</object>\n'; tObject = '<object class="kv-preview-data file-object" data="{data}" type="{type}" width="{width}" height="{height}">\n' + '<param name="movie" value="{caption}" />\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n</object>\n'; tPdf = '<embed class="kv-preview-data" src="{data}" width="{width}" height="{height}" type="application/pdf">\n'; tOther = '<div class="kv-preview-data file-preview-other-frame">\n' + DEFAULT_PREVIEW + '\n</div>\n'; defaultLayoutTemplates = { main1: tMain1, main2: tMain2, preview: tPreview, close: tClose, fileIcon: tFileIcon, caption: tCaption, modalMain: tModalMain, modal: tModal, progress: tProgress, size: tSize, footer: tFooter, actions: tActions, actionDelete: tActionDelete, actionUpload: tActionUpload, actionZoom: tActionZoom, actionDrag: tActionDrag, btnDefault: tBtnDefault, btnLink: tBtnLink, btnBrowse: tBtnBrowse }; defaultPreviewTemplates = { generic: tTagBef1 + tGeneric + tTagAft, html: tTagBef1 + tHtml + tTagAft, image: tTagBef1 + tImage + tTagAft, text: tTagBef1 + tText + tTagAft, video: tTagBef2 + tVideo + tTagAft, audio: tTagBef2 + tAudio + tTagAft, flash: tTagBef2 + tFlash + tTagAft, object: tTagBef2 + tObject + tTagAft, pdf: tTagBef2 + tPdf + tTagAft, other: tTagBef2 + tOther + tTagAft }; defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object']; defaultPreviewSettings = { image: {width: "auto", height: "160px"}, html: {width: "213px", height: "160px"}, text: {width: "213px", height: "160px"}, video: {width: "213px", height: "160px"}, audio: {width: "213px", height: "80px"}, flash: {width: "213px", height: "160px"}, object: {width: "160px", height: "160px"}, pdf: {width: "160px", height: "160px"}, other: {width: "160px", height: "160px"} }; defaultPreviewZoomSettings = { image: {width: "100%", height: "100%"}, html: {width: "100%", height: "100%", 'min-height': "480px"}, text: {width: "100%", height: "100%", 'min-height': "480px"}, video: {width: "auto", height: "100%", 'max-width': "100%"}, audio: {width: "100%", height: "30px"}, flash: {width: "auto", height: "480px"}, object: {width: "auto", height: "100%", 'min-height': "480px"}, pdf: {width: "100%", height: "100%", 'min-height': "480px"}, other: {width: "auto", height: "100%", 'min-height': "480px"} }; defaultFileTypeSettings = { image: function (vType, vName) { return compare(vType, 'image.*') || compare(vName, /\.(gif|png|jpe?g)$/i); }, html: function (vType, vName) { return compare(vType, 'text/html') || compare(vName, /\.(htm|html)$/i); }, text: function (vType, vName) { return compare(vType, 'text.*') || compare(vName, /\.(xml|javascript)$/i) || compare(vName, /\.(txt|md|csv|nfo|ini|json|php|js|css)$/i); }, video: function (vType, vName) { return compare(vType, 'video.*') && (compare(vType, /(ogg|mp4|mp?g|webm|3gp)$/i) || compare(vName, /\.(og?|mp4|webm|mp?g|3gp)$/i)); }, audio: function (vType, vName) { return compare(vType, 'audio.*') && (compare(vName, /(ogg|mp3|mp?g|wav)$/i) || compare(vName, /\.(og?|mp3|mp?g|wav)$/i)); }, flash: function (vType, vName) { return compare(vType, 'application/x-shockwave-flash', true) || compare(vName, /\.(swf)$/i); }, pdf: function (vType, vName) { return compare(vType, 'application/pdf', true) || compare(vName, /\.(pdf)$/i); }, object: function () { return true; }, other: function () { return true; } }; isEmpty = function (value, trim) { return value === undefined || value === null || value.length === 0 || (trim && $.trim(value) === ''); }; isArray = function (a) { return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]'; }; ifSet = function (needle, haystack, def) { def = def || ''; return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def; }; getElement = function (options, param, value) { return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]); }; uniqId = function () { return Math.round(new Date().getTime() + (Math.random() * 100)); }; htmlEncode = function (str) { return str.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); }; replaceTags = function (str, tags) { var out = str; if (!tags) { return out; } $.each(tags, function (key, value) { if (typeof value === "function") { value = value(); } out = out.split(key).join(value); }); return out; }; cleanMemory = function ($thumb) { var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src'); /** @namespace objUrl.revokeObjectURL */ objUrl.revokeObjectURL(data); }; findFileName = function (filePath) { var sepIndex = filePath.lastIndexOf('/'); if (sepIndex === -1) { sepIndex = filePath.lastIndexOf('\\'); } return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop(); }; checkFullScreen = function () { //noinspection JSUnresolvedVariable return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement; }; toggleFullScreen = function (maximize) { if (maximize && !checkFullScreen()) { /** @namespace document.documentElement.requestFullscreen */ /** @namespace document.documentElement.msRequestFullscreen */ /** @namespace document.documentElement.mozRequestFullScreen */ /** @namespace document.documentElement.webkitRequestFullscreen */ /** @namespace Element.ALLOW_KEYBOARD_INPUT */ if (document.documentElement.requestFullscreen) { document.documentElement.requestFullscreen(); } else if (document.documentElement.msRequestFullscreen) { document.documentElement.msRequestFullscreen(); } else if (document.documentElement.mozRequestFullScreen) { document.documentElement.mozRequestFullScreen(); } else if (document.documentElement.webkitRequestFullscreen) { document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); } } else { /** @namespace document.exitFullscreen */ /** @namespace document.msExitFullscreen */ /** @namespace document.mozCancelFullScreen */ /** @namespace document.webkitExitFullscreen */ if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } } }; moveArray = function (arr, oldIndex, newIndex) { if (newIndex >= arr.length) { var k = newIndex - arr.length; while ((k--) + 1) { arr.push(undefined); } } arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]); return arr; }; FileInput = function (element, options) { var self = this; self.$element = $(element); if (!self._validate()) { return; } self.isPreviewable = hasFileAPISupport(); self.isIE9 = isIE(9); self.isIE10 = isIE(10); if (self.isPreviewable || self.isIE9) { self._init(options); self._listen(); } else { self.$element.removeClass('file-loading'); } }; FileInput.prototype = { constructor: FileInput, _init: function (options) { var self = this, $el = self.$element, t; $.each(options, function (key, value) { switch (key) { case 'minFileCount': case 'maxFileCount': case 'maxFileSize': self[key] = getNum(value); break; default: self[key] = value; break; } }); self.fileInputCleared = false; self.fileBatchCompleted = true; if (!self.isPreviewable) { self.showPreview = false; } self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data'; self.reader = null; self.formdata = {}; self.clearStack(); self.uploadCount = 0; self.uploadStatus = {}; self.uploadLog = []; self.uploadAsyncCount = 0; self.loadedImages = []; self.totalImagesCount = 0; self.ajaxRequests = []; self.isError = false; self.ajaxAborted = false; self.cancelling = false; t = self._getLayoutTemplate('progress'); self.progressTemplate = t.replace('{class}', self.progressClass); self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass); self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass); self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled; self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly'); self.isUploadable = hasFileUploadSupport() && !isEmpty(self.uploadUrl); self.isClickable = self.browseOnZoneClick && self.showPreview && (self.isUploadable && self.dropZoneEnabled || !isEmpty(self.defaultPreviewContent)); self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self._slugDefault; self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2'); self.captionTemplate = self._getLayoutTemplate('caption'); self.previewGenericTemplate = self._getPreviewTemplate('generic'); if (self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) { self.imageCanvas = document.createElement('canvas'); self.imageCanvasContext = self.imageCanvas.getContext('2d'); } if (isEmpty(self.$element.attr('id'))) { self.$element.attr('id', uniqId()); } if (self.$container === undefined) { self.$container = self._createContainer(); } else { self._refreshContainer(); } self.$dropZone = self.$container.find('.file-drop-zone'); self.$progress = self.$container.find('.kv-upload-progress'); self.$btnUpload = self.$container.find('.fileinput-upload'); self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption')); self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name')); self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview')); self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails')); self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status')); self.$errorContainer = getElement(options, 'elErrorContainer', self.$previewContainer.find('.kv-fileinput-error')); if (!isEmpty(self.msgErrorClass)) { addCss(self.$errorContainer, self.msgErrorClass); } self.$errorContainer.hide(); self.fileActionSettings = $.extend(true, defaultFileActionSettings, options.fileActionSettings); self.previewInitId = "preview-" + uniqId(); self.id = self.$element.attr('id'); previewCache.init(self); self._initPreview(true); self._initPreviewActions(); self.options = options; self._setFileDropZoneTitle(); self.$element.removeClass('file-loading'); if (self.$element.attr('disabled')) { self.disable(); } self._initZoom(); }, _validate: function () { var self = this, $exception; if (self.$element.attr('type') === 'file') { return true; } $exception = '<div class="help-block alert alert-warning">' + '<h4>Invalid Input Type</h4>' + 'You must set an input <code>type = file</code> for <b>bootstrap-fileinput</b> plugin to initialize.' + '</div>'; self.$element.after($exception); return false; }, _errorsExist: function () { var self = this, $err; if (self.$errorContainer.find('li').length) { return true; } $err = $(document.createElement('div')).html(self.$errorContainer.html()); $err.find('span.kv-error-close').remove(); $err.find('ul').remove(); return $.trim($err.text()).length ? true : false; }, _errorHandler: function (evt, caption) { var self = this, err = evt.target.error; /** @namespace err.NOT_FOUND_ERR */ /** @namespace err.SECURITY_ERR */ /** @namespace err.NOT_READABLE_ERR */ if (err.code === err.NOT_FOUND_ERR) { self._showError(self.msgFileNotFound.replace('{name}', caption)); } else if (err.code === err.SECURITY_ERR) { self._showError(self.msgFileSecured.replace('{name}', caption)); } else if (err.code === err.NOT_READABLE_ERR) { self._showError(self.msgFileNotReadable.replace('{name}', caption)); } else if (err.code === err.ABORT_ERR) { self._showError(self.msgFilePreviewAborted.replace('{name}', caption)); } else { self._showError(self.msgFilePreviewError.replace('{name}', caption)); } }, _addError: function (msg) { var self = this, $error = self.$errorContainer; if (msg && $error.length) { $error.html(self.errorCloseButton + msg); handler($error.find('.kv-error-close'), 'click', function () { $error.fadeOut('slow'); }); } }, _resetErrors: function (fade) { var self = this, $error = self.$errorContainer; self.isError = false; self.$container.removeClass('has-error'); $error.html(''); if (fade) { $error.fadeOut('slow'); } else { $error.hide(); } }, _showFolderError: function (folders) { var self = this, $error = self.$errorContainer, msg; if (!folders) { return; } msg = self.msgFoldersNotAllowed.replace(/\{n}/g, folders); self._addError(msg); addCss(self.$container, 'has-error'); $error.fadeIn(800); self._raise('filefoldererror', [folders, msg]); }, _showUploadError: function (msg, params, event) { var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', e = params && params.id ? '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>'; if ($error.find('ul').length === 0) { self._addError('<ul>' + e + '</ul>'); } else { $error.find('ul').append(e); } $error.fadeIn(800); self._raise(ev, [params, msg]); self.$container.removeClass('file-input-new'); addCss(self.$container, 'has-error'); return true; }, _showError: function (msg, params, event) { var self = this, $error = self.$errorContainer, ev = event || 'fileerror'; params = params || {}; params.reader = self.reader; self._addError(msg); $error.fadeIn(800); self._raise(ev, [params, msg]); if (!self.isUploadable) { self._clearFileInput(); } self.$container.removeClass('file-input-new'); addCss(self.$container, 'has-error'); self.$btnUpload.attr('disabled', true); return true; }, _noFilesError: function (params) { var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle, msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label), $error = self.$errorContainer; self._addError(msg); self.isError = true; self._updateFileDetails(0); $error.fadeIn(800); self._raise('fileerror', [params, msg]); self._clearFileInput(); addCss(self.$container, 'has-error'); }, _parseError: function (jqXHR, errorThrown, fileName) { /** @namespace jqXHR.responseJSON */ var self = this, errMsg = $.trim(errorThrown + ''), dot = errMsg.slice(-1) === '.' ? '' : '.', text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ? jqXHR.responseJSON.error : jqXHR.responseText; if (self.cancelling && self.msgUploadAborted) { errMsg = self.msgUploadAborted; } if (self.showAjaxErrorDetails && text) { text = $.trim(text.replace(/\n\s*\n/g, '\n')); text = text.length > 0 ? '<pre>' + text + '</pre>' : ''; errMsg += dot + text; } else { errMsg += dot; } self.cancelling = false; return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg; }, _parseFileType: function (file) { var self = this, isValid, vType, cat, i; for (i = 0; i < defaultPreviewTypes.length; i += 1) { cat = defaultPreviewTypes[i]; isValid = ifSet(cat, self.fileTypeSettings, defaultFileTypeSettings[cat]); vType = isValid(file.type, file.name) ? cat : ''; if (!isEmpty(vType)) { return vType; } } return 'other'; }, _parseFilePreviewIcon: function (content, fname) { var self = this, proceed, ext, icn = self.previewFileIcon; if (fname && fname.indexOf('.') > -1) { ext = fname.split('.').pop(); if (self.previewFileIconSettings && self.previewFileIconSettings[ext]) { icn = self.previewFileIconSettings[ext]; } if (self.previewFileExtSettings) { $.each(self.previewFileExtSettings, function (key, func) { if (self.previewFileIconSettings[key] && func(ext)) { icn = self.previewFileIconSettings[key]; return; } proceed = true; }); } } if (content.indexOf('{previewFileIcon}') > -1) { return content.replace(/\{previewFileIconClass}/g, self.previewFileIconClass).replace( /\{previewFileIcon}/g, icn); } return content; }, _raise: function (event, params) { var self = this, e = $.Event(event); if (params !== undefined) { self.$element.trigger(e, params); } else { self.$element.trigger(e); } if (e.isDefaultPrevented()) { return false; } if (!e.result) { return e.result; } switch (event) { // ignore these events case 'filebatchuploadcomplete': case 'filebatchuploadsuccess': case 'fileuploaded': case 'fileclear': case 'filecleared': case 'filereset': case 'fileerror': case 'filefoldererror': case 'fileuploaderror': case 'filebatchuploaderror': case 'filedeleteerror': case 'filecustomerror': case 'filesuccessremove': break; // receive data response via `filecustomerror` event` default: self.ajaxAborted = e.result; break; } return true; }, _listenFullScreen: function (isFullScreen) { var self = this, $modal = self.$modal, $btnFull, $btnBord; if (!$modal || !$modal.length) { return; } $btnFull = $modal && $modal.find('.btn-fullscreen'); $btnBord = $modal && $modal.find('.btn-borderless'); if (!$btnFull.length || !$btnBord.length) { return; } $btnFull.removeClass('active').attr('aria-pressed', 'false'); $btnBord.removeClass('active').attr('aria-pressed', 'false'); if (isFullScreen) { $btnFull.addClass('active').attr('aria-pressed', 'true'); } else { $btnBord.addClass('active').attr('aria-pressed', 'true'); } if ($modal.hasClass('file-zoom-fullscreen')) { self._maximizeZoomDialog(); } else { if (isFullScreen) { self._maximizeZoomDialog(); } else { $btnBord.removeClass('active').attr('aria-pressed', 'false'); } } }, _listen: function () { var self = this, $el = self.$element, $form = $el.closest('form'), $cont = self.$container; handler($el, 'change', $.proxy(self._change, self)); if (self.showBrowse) { handler(self.$btnFile, 'click', $.proxy(self._browse, self)); } handler($form, 'reset', $.proxy(self.reset, self)); handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self)); handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self)); self._initDragDrop(); if (!self.isUploadable) { handler($form, 'submit', $.proxy(self._submitForm, self)); } handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self)); handler($(window), 'resize', function () { self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight); }); handler($(document), 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange', function () { self._listenFullScreen(checkFullScreen()); }); self._initClickable(); }, _initClickable: function () { var self = this, $zone; if (!self.isClickable) { return; } $zone = self.isUploadable ? self.$dropZone : self.$preview.find('.file-default-preview'); addCss($zone, 'clickable'); $zone.attr('tabindex', -1); handler($zone, 'click', function (e) { var $target = $(e.target); if (!$target.parents('.file-preview-thumbnails').length || $target.parents( '.file-default-preview').length) { self.$element.trigger('click'); $zone.blur(); } }); }, _initDragDrop: function () { var self = this, $zone = self.$dropZone; if (self.isUploadable && self.dropZoneEnabled && self.showPreview) { handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self)); handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self)); handler($zone, 'drop', $.proxy(self._zoneDrop, self)); handler($(document), 'dragenter dragover drop', self._zoneDragDropInit); } }, _zoneDragDropInit: function (e) { e.stopPropagation(); e.preventDefault(); }, _zoneDragEnter: function (e) { var self = this, hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1; self._zoneDragDropInit(e); if (self.isDisabled || !hasFiles) { e.originalEvent.dataTransfer.effectAllowed = 'none'; e.originalEvent.dataTransfer.dropEffect = 'none'; return; } addCss(self.$dropZone, 'file-highlighted'); }, _zoneDragLeave: function (e) { var self = this; self._zoneDragDropInit(e); if (self.isDisabled) { return; } self.$dropZone.removeClass('file-highlighted'); }, _zoneDrop: function (e) { var self = this; e.preventDefault(); /** @namespace e.originalEvent.dataTransfer */ if (self.isDisabled || isEmpty(e.originalEvent.dataTransfer.files)) { return; } self._change(e, 'dragdrop'); self.$dropZone.removeClass('file-highlighted'); }, _uploadClick: function (e) { var self = this, $btn = self.$container.find('.fileinput-upload'), $form, isEnabled = !$btn.hasClass('disabled') && isEmpty($btn.attr('disabled')); if (e && e.isDefaultPrevented()) { return; } if (!self.isUploadable) { if (isEnabled && $btn.attr('type') !== 'submit') { $form = $btn.closest('form'); // downgrade to normal form submit if possible if ($form.length) { $form.trigger('submit'); } e.preventDefault(); } return; } e.preventDefault(); if (isEnabled) { self.upload(); } }, _submitForm: function () { var self = this, $el = self.$element, files = $el.get(0).files; if (files && self.minFileCount > 0 && self._getFileCount(files.length) < self.minFileCount) { self._noFilesError({}); return false; } return !self._abort({}); }, _clearPreview: function () { var self = this, $thumbs = !self.showUploadedThumbs ? self.$preview.find('.file-preview-frame') : self.$preview.find('.file-preview-frame:not(.file-preview-success)'); $thumbs.remove(); if (!self.$preview.find('.file-preview-frame').length || !self.showPreview) { self._resetUpload(); } self._validateDefaultPreview(); }, _initSortable: function () { var self = this, $preview = self.$preview, $el, settings; if (!window.KvSortable) { return; } $el = $preview.find('.file-initial-thumbs'); //noinspection JSUnusedGlobalSymbols settings = { handle: '.drag-handle-init', dataIdAttr: 'data-preview-id', draggable: '.file-preview-initial', onSort: function (e) { var oldIndex = e.oldIndex, newIndex = e.newIndex; self.initialPreview = moveArray(self.initialPreview, oldIndex, newIndex); self.initialPreviewConfig = moveArray(self.initialPreviewConfig, oldIndex, newIndex); previewCache.init(self); self._raise('filesorted', { previewId: $(e.item).attr('id'), 'oldIndex': oldIndex, 'newIndex': newIndex, stack: self.initialPreviewConfig }); } }; if ($el.data('kvsortable')) { $el.kvsortable('destroy'); } $.extend(true, settings, self.fileActionSettings.dragSettings); $el.kvsortable(settings); }, _initPreview: function (isInit) { var self = this, cap = self.initialCaption || '', out; if (!previewCache.count(self.id)) { self._clearPreview(); if (isInit) { self._setCaption(cap); } else { self._initCaption(); } return; } out = previewCache.out(self.id); cap = isInit && self.initialCaption ? self.initialCaption : out.caption; self.$preview.html(out.content); self._setCaption(cap); self._initSortable(); if (!isEmpty(out.content)) { self.$container.removeClass('file-input-new'); } }, _getZoomButton: function (type) { var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type], title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ', params = title + (type === 'close' ? ' data-dismiss="modal" aria-hidden="true"' : ''); if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') { params += ' data-toggle="button" aria-pressed="false" autocomplete="off"'; } return '<button type="button" class="' + css + ' btn-' + type + '"' + params + '>' + label + '</button>'; }, _getModalContent: function () { var self = this; return self._getLayoutTemplate('modal') .replace(/\{heading}/g, self.msgZoomModalHeading) .replace(/\{prev}/g, self._getZoomButton('prev')) .replace(/\{next}/g, self._getZoomButton('next')) .replace(/\{toggleheader}/g, self._getZoomButton('toggleheader')) .replace(/\{fullscreen}/g, self._getZoomButton('fullscreen')) .replace(/\{borderless}/g, self._getZoomButton('borderless')) .replace(/\{close}/g, self._getZoomButton('close')); }, _listenModalEvent: function (event) { var self = this, $modal = self.$modal, getParams = function (e) { return { sourceEvent: e, previewId: $modal.data('previewId'), modal: $modal }; }; $modal.on(event + '.bs.modal', function (e) { var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'); self._raise('filezoom' + event, getParams(e)); if (event === 'shown') { $btnBord.removeClass('active').attr('aria-pressed', 'false'); $btnFull.removeClass('active').attr('aria-pressed', 'false'); if ($modal.hasClass('file-zoom-fullscreen')) { self._maximizeZoomDialog(); if (checkFullScreen()) { $btnFull.addClass('active').attr('aria-pressed', 'true'); } else { $btnBord.addClass('active').attr('aria-pressed', 'true'); } } } }); }, _initZoom: function () { var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + MODAL_ID; self.$modal = $(modalId); if (!self.$modal || !self.$modal.length) { $dialog = $(document.createElement('div')).html(modalMain).insertAfter(self.$container); self.$modal = $('#' + MODAL_ID).insertBefore($dialog); $dialog.remove(); } self.$modal.html(self._getModalContent()); self._listenModalEvent('show'); self._listenModalEvent('shown'); self._listenModalEvent('hide'); self._listenModalEvent('hidden'); self._listenModalEvent('loaded'); }, _initZoomButtons: function () { var self = this, previewId = self.$modal.data('previewId') || '', $first, $last, frames = self.$preview.find('.file-preview-frame').toArray(), len = frames.length, $prev = self.$modal.find('.btn-prev'), $next = self.$modal.find('.btn-next'); if (!len) { return; } $first = $(frames[0]); $last = $(frames[len - 1]); $prev.removeAttr('disabled'); $next.removeAttr('disabled'); if ($first.length && $first.attr('id') === previewId) { $prev.attr('disabled', true); } if ($last.length && $last.attr('id') === previewId) { $next.attr('disabled', true); } }, _maximizeZoomDialog: function () { var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'), $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'), h = $(window).height(), diff = 0; $modal.addClass('file-zoom-fullscreen'); if ($head && $head.length) { h -= $head.outerHeight(true); } if ($foot && $foot.length) { h -= $foot.outerHeight(true); } if ($body && $body.length) { diff = $body.outerHeight(true) - $body.height(); h -= diff; } $modal.find('.kv-zoom-body').height(h); }, _resizeZoomDialog: function (fullScreen) { var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'); if ($modal.hasClass('file-zoom-fullscreen')) { toggleFullScreen(false); if (!fullScreen) { if (!$btnFull.hasClass('active')) { $modal.removeClass('file-zoom-fullscreen'); self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight); } else { $btnFull.removeClass('active').attr('aria-pressed', 'false'); } } else { if (!$btnFull.hasClass('active')) { $modal.removeClass('file-zoom-fullscreen'); self._resizeZoomDialog(true); if ($btnBord.hasClass('active')) { $btnBord.removeClass('active').attr('aria-pressed', 'false'); } } } } else { if (!fullScreen) { self._maximizeZoomDialog(); return; } toggleFullScreen(true); } $modal.focus(); }, _setZoomContent: function ($preview, animate) { var self = this, $content, tmplt, body, title, $body, $dataEl, config, previewId = $preview.attr('id'), $modal = self.$modal, $prev = $modal.find('.btn-prev'), $next = $modal.find('.btn-next'), $tmp, $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'), $btnTogh = $modal.find('.btn-toggleheader'); tmplt = $preview.data('template') || 'generic'; $content = $preview.find('.kv-file-content'); body = $content.length ? $content.html() : ''; title = $preview.find('.file-footer-caption').text() || ''; $modal.find('.kv-zoom-title').html(title); $body = $modal.find('.kv-zoom-body'); if (animate) { $tmp = $body.clone().insertAfter($body); $body.html(body).hide(); $tmp.fadeOut('fast', function () { $body.fadeIn('fast'); $tmp.remove(); }); } else { $body.html(body); } config = self.previewZoomSettings[tmplt]; if (config) { $dataEl = $body.find('.kv-preview-data'); addCss($dataEl, 'file-zoom-detail'); $.each(config, function (key, value) { $dataEl.css(key, value); if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) { $dataEl.removeAttr(key); } }); } $modal.data('previewId', previewId); handler($prev, 'click', function () { self._zoomSlideShow('prev', previewId); }); handler($next, 'click', function () { self._zoomSlideShow('next', previewId); }); handler($btnFull, 'click', function () { self._resizeZoomDialog(true); }); handler($btnBord, 'click', function () { self._resizeZoomDialog(false); }); handler($btnTogh, 'click', function () { var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'), ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) { var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight; if ($modal.hasClass('file-zoom-fullscreen')) { h = $body.outerHeight(true); if (!height) { h = h - $header.outerHeight(true); } } $body.css('height', height ? h + height : h); }; if ($header.is(':visible')) { ht = $header.outerHeight(true); $header.slideUp('slow', function () { $actions.find('.btn').appendTo($floatBar); resize(ht); }); } else { $floatBar.find('.btn').appendTo($actions); $header.slideDown('slow', function () { resize(); }); } $modal.focus(); }); handler($modal, 'keydown', function (e) { var key = e.which || e.keyCode; if (key === 37 && !$prev.attr('disabled')) { self._zoomSlideShow('prev', previewId); } if (key === 39 && !$next.attr('disabled')) { self._zoomSlideShow('next', previewId); } }); }, _zoomPreview: function ($btn) { var self = this, $preview; if (!$btn.length) { throw 'Cannot zoom to detailed preview!'; } self.$modal.html(self._getModalContent()); $preview = $btn.closest('.file-preview-frame'); self._setZoomContent($preview); self.$modal.modal('show'); self._initZoomButtons(); }, _zoomSlideShow: function (dir, previewId) { var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i, frames = self.$preview.find('.file-preview-frame').toArray(), len = frames.length, out; if ($btn.attr('disabled')) { return; } for (i = 0; i < len; i++) { if ($(frames[i]).attr('id') === previewId) { out = dir === 'prev' ? i - 1 : i + 1; break; } } if (out < 0 || out >= len || !frames[out]) { return; } $targFrame = $(frames[out]); if ($targFrame.length) { self._setZoomContent($targFrame, true); } self._initZoomButtons(); self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal}); }, _initZoomButton: function () { var self = this; self.$preview.find('.kv-file-zoom').each(function () { var $el = $(this); handler($el, 'click', function () { self._zoomPreview($el); }); }); }, _initPreviewActions: function () { var self = this, deleteExtraData = self.deleteExtraData || {}, resetProgress = function () { var hasFiles = self.isUploadable ? previewCache.count(self.id) : self.$element.get(0).files.length; if (self.$preview.find('.kv-file-remove').length === 0 && !hasFiles) { self.reset(); self.initialCaption = ''; } }; self._initZoomButton(); self.$preview.find('.kv-file-remove').each(function () { var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'); if (isEmpty(vUrl) || vKey === undefined) { return; } var $frame = $el.closest('.file-preview-frame'), cache = previewCache.data[self.id], settings, params, index = $frame.data('fileindex'), config, extraData; index = parseInt(index.replace('init_', '')); config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index]; extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra; if (typeof extraData === "function") { extraData = extraData(); } params = {id: $el.attr('id'), key: vKey, extra: extraData}; settings = $.extend(true, {}, { url: vUrl, type: 'POST', dataType: 'json', data: $.extend(true, {}, {key: vKey}, extraData), beforeSend: function (jqXHR) { self.ajaxAborted = false; self._raise('filepredelete', [vKey, jqXHR, extraData]); if (self.ajaxAborted) { jqXHR.abort(); } else { addCss($frame, 'file-uploading'); addCss($el, 'disabled'); } }, success: function (data, textStatus, jqXHR) { var n, cap; if (isEmpty(data) || isEmpty(data.error)) { previewCache.unset(self.id, index); n = previewCache.count(self.id); cap = n > 0 ? self._getMsgSelected(n) : ''; self._raise('filedeleted', [vKey, jqXHR, extraData]); self._setCaption(cap); } else { params.jqXHR = jqXHR; params.response = data; self._showError(data.error, params, 'filedeleteerror'); $frame.removeClass('file-uploading'); $el.removeClass('disabled'); resetProgress(); return; } $frame.removeClass('file-uploading').addClass('file-deleted'); $frame.fadeOut('slow', function () { self._clearObjects($frame); $frame.remove(); resetProgress(); if (!n && self.getFileStack().length === 0) { self._setCaption(''); self.reset(); } }); }, error: function (jqXHR, textStatus, errorThrown) { var errMsg = self._parseError(jqXHR, errorThrown); params.jqXHR = jqXHR; params.response = {}; self._showError(errMsg, params, 'filedeleteerror'); $frame.removeClass('file-uploading'); resetProgress(); } }, self.ajaxDeleteSettings); handler($el, 'click', function () { if (!self._validateMinCount()) { return false; } $.ajax(settings); }); }); }, _clearObjects: function ($el) { $el.find('video audio').each(function () { this.pause(); $(this).remove(); }); $el.find('img object div').each(function () { $(this).remove(); }); }, _clearFileInput: function () { var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl; if (isEmpty($el.val())) { return; } // Fix for IE ver < 11, that does not clear file inputs. Requires a sequence of steps to prevent IE // crashing but still allow clearing of the file input. if (self.isIE9 || self.isIE10) { $srcFrm = $el.closest('form'); $tmpFrm = $(document.createElement('form')); $tmpEl = $(document.createElement('div')); $el.before($tmpEl); if ($srcFrm.length) { $srcFrm.after($tmpFrm); } else { $tmpEl.after($tmpFrm); } $tmpFrm.append($el).trigger('reset'); $tmpEl.before($el).remove(); $tmpFrm.remove(); } else { // normal input clear behavior for other sane browsers $el.val(''); } self.fileInputCleared = true; }, _resetUpload: function () { var self = this; self.uploadCache = {content: [], config: [], tags: [], append: true}; self.uploadCount = 0; self.uploadStatus = {}; self.uploadLog = []; self.uploadAsyncCount = 0; self.loadedImages = []; self.totalImagesCount = 0; self.$btnUpload.removeAttr('disabled'); self._setProgress(0); addCss(self.$progress, 'hide'); self._resetErrors(false); self.ajaxAborted = false; self.ajaxRequests = []; self._resetCanvas(); }, _resetCanvas: function () { var self = this; if (self.canvas && self.imageCanvasContext) { self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height); } }, _hasInitialPreview: function () { var self = this; return !self.overwriteInitial && previewCache.count(self.id); }, _resetPreview: function () { var self = this, out, cap; if (previewCache.count(self.id)) { out = previewCache.out(self.id); self.$preview.html(out.content); cap = self.initialCaption ? self.initialCaption : out.caption; self._setCaption(cap); } else { self._clearPreview(); self._initCaption(); } if (self.showPreview) { self._initZoom(); self._initSortable(); } }, _clearDefaultPreview: function () { var self = this; self.$preview.find('.file-default-preview').remove(); }, _validateDefaultPreview: function () { var self = this; if (!self.showPreview || isEmpty(self.defaultPreviewContent)) { return; } self.$preview.html('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>'); self.$container.removeClass('file-input-new'); self._initClickable(); }, _resetPreviewThumbs: function (isAjax) { var self = this, out; if (isAjax) { self._clearPreview(); self.clearStack(); return; } if (self._hasInitialPreview()) { out = previewCache.out(self.id); self.$preview.html(out.content); self._setCaption(out.caption); self._initPreviewActions(); } else { self._clearPreview(); } }, _getLayoutTemplate: function (t) { var self = this, template = ifSet(t, self.layoutTemplates, defaultLayoutTemplates[t]); if (isEmpty(self.customLayoutTags)) { return template; } return replaceTags(template, self.customLayoutTags); }, _getPreviewTemplate: function (t) { var self = this, template = ifSet(t, self.previewTemplates, defaultPreviewTemplates[t]); if (isEmpty(self.customPreviewTags)) { return template; } return replaceTags(template, self.customPreviewTags); }, _getOutData: function (jqXHR, responseData, filesData) { var self = this; jqXHR = jqXHR || {}; responseData = responseData || {}; filesData = filesData || self.filestack.slice(0) || {}; return { form: self.formdata, files: filesData, filenames: self.filenames, filescount: self.getFilesCount(), extra: self._getExtraData(), response: responseData, reader: self.reader, jqXHR: jqXHR }; }, _getMsgSelected: function (n) { var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural; return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected; }, _getThumbs: function (css) { css = css || ''; return this.$preview.find('.file-preview-frame:not(.file-preview-initial)' + css); }, _getExtraData: function (previewId, index) { var self = this, data = self.uploadExtraData; if (typeof self.uploadExtraData === "function") { data = self.uploadExtraData(previewId, index); } return data; }, _initXhr: function (xhrobj, previewId, fileCount) { var self = this; if (xhrobj.upload) { xhrobj.upload.addEventListener('progress', function (event) { var pct = 0, total = event.total, position = event.loaded || event.position; /** @namespace event.lengthComputable */ if (event.lengthComputable) { pct = Math.floor(position / total * 100); } if (previewId) { self._setAsyncUploadStatus(previewId, pct, fileCount); } else { self._setProgress(pct); } }, false); } return xhrobj; }, _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) { var self = this, settings; self._raise('filepreajax', [previewId, index]); self._uploadExtra(previewId, index); settings = $.extend(true, {}, { xhr: function () { var xhrobj = $.ajaxSettings.xhr(); return self._initXhr(xhrobj, previewId, self.getFileStack().length); }, url: self.uploadUrl, type: 'POST', dataType: 'json', data: self.formdata, cache: false, processData: false, contentType: false, beforeSend: fnBefore, success: fnSuccess, complete: fnComplete, error: fnError }, self.ajaxSettings); self.ajaxRequests.push($.ajax(settings)); }, _initUploadSuccess: function (out, $thumb, allFiles) { var self = this, append, data, index, $newThumb, content, config, tags, i, mergeArray = function (prop, content) { if (!(self[prop] instanceof Array)) { self[prop] = []; } if (content && content.length) { self[prop] = self[prop].concat(content); } }; if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) { return; } if (out.initialPreview !== undefined && out.initialPreview.length > 0) { self.hasInitData = true; content = out.initialPreview || []; config = out.initialPreviewConfig || []; tags = out.initialPreviewThumbTags || []; append = out.append === undefined || out.append ? true : false; if (content.length > 0 && !isArray(content)) { content = content.split(self.initialPreviewDelimiter); } self.overwriteInitial = false; mergeArray('initialPreview', content); mergeArray('initialPreviewConfig', config); mergeArray('initialPreviewThumbTags', tags); if ($thumb !== undefined) { if (!allFiles) { index = previewCache.add(self.id, content, config[0], tags[0], append); data = previewCache.get(self.id, index, false); $newThumb = $(data).hide(); $thumb.after($newThumb).fadeOut('slow', function () { $newThumb.fadeIn('slow').css('display:inline-block'); self._initPreviewActions(); self._clearFileInput(); $thumb.remove(); }); } else { i = $thumb.attr('data-fileindex'); self.uploadCache.content[i] = content[0]; self.uploadCache.config[i] = config[0] || []; self.uploadCache.tags[i] = tags[0] || []; self.uploadCache.append = append; } } else { previewCache.set(self.id, content, config, tags, append); self._initPreview(); self._initPreviewActions(); } } }, _initSuccessThumbs: function () { var self = this; if (!self.showPreview) { return; } self._getThumbs('.file-preview-success').each(function () { var $thumb = $(this), $remove = $thumb.find('.kv-file-remove'); $remove.removeAttr('disabled'); handler($remove, 'click', function () { var out = self._raise('filesuccessremove', [$thumb.attr('id'), $thumb.data('fileindex')]); cleanMemory($thumb); if (out === false) { return; } $thumb.fadeOut('slow', function () { $thumb.remove(); if (!self.$preview.find('.file-preview-frame').length) { self.reset(); } }); }); }); }, _checkAsyncComplete: function () { var self = this, previewId, i; for (i = 0; i < self.filestack.length; i++) { if (self.filestack[i]) { previewId = self.previewInitId + "-" + i; if ($.inArray(previewId, self.uploadLog) === -1) { return false; } } } return (self.uploadAsyncCount === self.uploadLog.length); }, _uploadExtra: function (previewId, index) { var self = this, data = self._getExtraData(previewId, index); if (data.length === 0) { return; } $.each(data, function (key, value) { self.formdata.append(key, value); }); }, _uploadSingle: function (i, files, allFiles) { var self = this, total = self.getFileStack().length, formdata = new FormData(), outData, previewId = self.previewInitId + "-" + i, $thumb, chkComplete, $btnUpload, $btnDelete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData), fnBefore, fnSuccess, fnComplete, fnError, updateUploadLog, params = {id: previewId, index: i}; self.formdata = formdata; if (self.showPreview) { $thumb = $('#' + previewId + ':not(.file-preview-initial)'); $btnUpload = $thumb.find('.kv-file-upload'); $btnDelete = $thumb.find('.kv-file-remove'); $('#' + previewId).find('.file-thumb-progress').removeClass('hide'); } if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self._abort(params)) { return; } updateUploadLog = function (i, previewId) { self.updateStack(i, undefined); self.uploadLog.push(previewId); if (self._checkAsyncComplete()) { self.fileBatchCompleted = true; } }; chkComplete = function () { var u = self.uploadCache; if (!self.fileBatchCompleted) { return; } setTimeout(function () { if (self.showPreview) { previewCache.set(self.id, u.content, u.config, u.tags, u.append); if (self.hasInitData) { self._initPreview(); self._initPreviewActions(); } } self.unlock(); self._clearFileInput(); self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]); self.uploadCount = 0; self.uploadStatus = {}; self.uploadLog = []; self._setProgress(101); }, 100); }; fnBefore = function (jqXHR) { outData = self._getOutData(jqXHR); self.fileBatchCompleted = false; if (self.showPreview) { if (!$thumb.hasClass('file-preview-success')) { self._setThumbStatus($thumb, 'Loading'); addCss($thumb, 'file-uploading'); } $btnUpload.attr('disabled', true); $btnDelete.attr('disabled', true); } if (!allFiles) { self.lock(); } self._raise('filepreupload', [outData, previewId, i]); $.extend(true, params, outData); if (self._abort(params)) { jqXHR.abort(); self._setProgressCancelled(); } }; fnSuccess = function (data, textStatus, jqXHR) { var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId; outData = self._getOutData(jqXHR, data); $.extend(true, params, outData); setTimeout(function () { if (isEmpty(data) || isEmpty(data.error)) { if (self.showPreview) { self._setThumbStatus($thumb, 'Success'); $btnUpload.hide(); self._initUploadSuccess(data, $thumb, allFiles); } self._raise('fileuploaded', [outData, pid, i]); if (!allFiles) { self.updateStack(i, undefined); } else { updateUploadLog(i, pid); } } else { self._showUploadError(data.error, params); self._setPreviewError($thumb, i); if (allFiles) { updateUploadLog(i, pid); } } }, 100); }; fnComplete = function () { setTimeout(function () { if (self.showPreview) { $btnUpload.removeAttr('disabled'); $btnDelete.removeAttr('disabled'); $thumb.removeClass('file-uploading'); self._setProgress(101, $('#' + previewId).find('.file-thumb-progress')); } if (!allFiles) { self.unlock(false); self._clearFileInput(); } else { chkComplete(); } self._initSuccessThumbs(); }, 100); }; fnError = function (jqXHR, textStatus, errorThrown) { var errMsg = self._parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null)); setTimeout(function () { if (allFiles) { updateUploadLog(i, previewId); } self.uploadStatus[previewId] = 100; self._setPreviewError($thumb, i); $.extend(true, params, self._getOutData(jqXHR)); self._showUploadError(errMsg, params); }, 100); }; formdata.append(self.uploadFileAttr, files[i], self.filenames[i]); formdata.append('file_id', i); self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i); }, _uploadBatch: function () { var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError, fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData), setAllUploaded; self.formdata = new FormData(); if (total === 0 || !hasPostData || self._abort(params)) { return; } setAllUploaded = function () { $.each(files, function (key) { self.updateStack(key, undefined); }); self._clearFileInput(); }; fnBefore = function (jqXHR) { self.lock(); var outData = self._getOutData(jqXHR); if (self.showPreview) { self._getThumbs().each(function () { var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'); if (!$thumb.hasClass('file-preview-success')) { self._setThumbStatus($thumb, 'Loading'); addCss($thumb, 'file-uploading'); } $btnUpload.attr('disabled', true); $btnDelete.attr('disabled', true); }); } self._raise('filebatchpreupload', [outData]); if (self._abort(outData)) { jqXHR.abort(); self._setProgressCancelled(); } }; fnSuccess = function (data, textStatus, jqXHR) { /** @namespace data.errorkeys */ var outData = self._getOutData(jqXHR, data), $thumbs = self._getThumbs(':not(.file-preview-error)'), key = 0, keys = isEmpty(data) || isEmpty(data.errorkeys) ? [] : data.errorkeys; if (isEmpty(data) || isEmpty(data.error)) { self._raise('filebatchuploadsuccess', [outData]); setAllUploaded(); if (self.showPreview) { $thumbs.each(function () { var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'); $thumb.find('.kv-file-upload').hide(); self._setThumbStatus($thumb, 'Success'); $thumb.removeClass('file-uploading'); $btnUpload.removeAttr('disabled'); }); self._initUploadSuccess(data); } else { self.reset(); } } else { if (self.showPreview) { $thumbs.each(function () { var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'), $btnUpload = $thumb.find('.kv-file-upload'); $thumb.removeClass('file-uploading'); $btnUpload.removeAttr('disabled'); $btnDelete.removeAttr('disabled'); if (keys.length === 0) { self._setPreviewError($thumb); return; } if ($.inArray(key, keys) !== -1) { self._setPreviewError($thumb); } else { $thumb.find('.kv-file-upload').hide(); self._setThumbStatus($thumb, 'Success'); self.updateStack(key, undefined); } key++; }); self._initUploadSuccess(data); } self._showUploadError(data.error, outData, 'filebatchuploaderror'); } }; fnComplete = function () { self._setProgress(101); self.unlock(); self._initSuccessThumbs(); self._clearFileInput(); self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]); }; fnError = function (jqXHR, textStatus, errorThrown) { var outData = self._getOutData(jqXHR), errMsg = self._parseError(jqXHR, errorThrown); self._showUploadError(errMsg, outData, 'filebatchuploaderror'); self.uploadFileCount = total - 1; if (!self.showPreview) { return; } self._getThumbs().each(function () { var $thumb = $(this), key = $thumb.attr('data-fileindex'); $thumb.removeClass('file-uploading'); if (self.filestack[key] !== undefined) { self._setPreviewError($thumb); } }); self._getThumbs().removeClass('file-uploading'); self._getThumbs(' .kv-file-upload').removeAttr('disabled'); self._getThumbs(' .kv-file-delete').removeAttr('disabled'); }; $.each(files, function (key, data) { if (!isEmpty(files[key])) { self.formdata.append(self.uploadFileAttr, data, self.filenames[key]); } }); self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError); }, _uploadExtraOnly: function () { var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError; self.formdata = new FormData(); if (self._abort(params)) { return; } fnBefore = function (jqXHR) { self.lock(); var outData = self._getOutData(jqXHR); self._raise('filebatchpreupload', [outData]); self._setProgress(50); params.data = outData; params.xhr = jqXHR; if (self._abort(params)) { jqXHR.abort(); self._setProgressCancelled(); } }; fnSuccess = function (data, textStatus, jqXHR) { var outData = self._getOutData(jqXHR, data); if (isEmpty(data) || isEmpty(data.error)) { self._raise('filebatchuploadsuccess', [outData]); self._clearFileInput(); self._initUploadSuccess(data); } else { self._showUploadError(data.error, outData, 'filebatchuploaderror'); } }; fnComplete = function () { self._setProgress(101); self.unlock(); self._clearFileInput(); self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]); }; fnError = function (jqXHR, textStatus, errorThrown) { var outData = self._getOutData(jqXHR), errMsg = self._parseError(jqXHR, errorThrown); params.data = outData; self._showUploadError(errMsg, outData, 'filebatchuploaderror'); }; self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError); }, _initFileActions: function () { var self = this; if (!self.showPreview) { return; } self._initZoomButton(); self.$preview.find('.kv-file-remove').each(function () { var $el = $(this), $frame = $el.closest('.file-preview-frame'), hasError, id = $frame.attr('id'), ind = $frame.attr('data-fileindex'), n, cap, status; handler($el, 'click', function () { status = self._raise('filepreremove', [id, ind]); if (status === false || !self._validateMinCount()) { return false; } hasError = $frame.hasClass('file-preview-error'); cleanMemory($frame); $frame.fadeOut('slow', function () { self.updateStack(ind, undefined); self._clearObjects($frame); $frame.remove(); if (id && hasError) { self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () { $(this).remove(); if (!self._errorsExist()) { self._resetErrors(); } }); } self._clearFileInput(); var filestack = self.getFileStack(true), chk = previewCache.count(self.id), len = filestack.length, hasThumb = self.showPreview && self.$preview.find('.file-preview-frame').length; if (len === 0 && chk === 0 && !hasThumb) { self.reset(); } else { n = chk + len; cap = n > 1 ? self._getMsgSelected(n) : (filestack[0] ? self._getFileNames()[0] : ''); self._setCaption(cap); } self._raise('fileremoved', [id, ind]); }); }); }); self.$preview.find('.kv-file-upload').each(function () { var $el = $(this); handler($el, 'click', function () { var $frame = $el.closest('.file-preview-frame'), ind = $frame.attr('data-fileindex'); if (!$frame.hasClass('file-preview-error')) { self._uploadSingle(ind, self.filestack, false); } }); }); }, _hideFileIcon: function () { if (this.overwriteInitial) { this.$captionContainer.find('.kv-caption-icon').hide(); } }, _showFileIcon: function () { this.$captionContainer.find('.kv-caption-icon').show(); }, _getSize: function (bytes) { var size = parseFloat(bytes); if (bytes === null || isNaN(size)) { return ''; } var self = this, i, func = self.fileSizeGetter, sizes, out; if (typeof func === 'function') { out = func(bytes); } else { i = Math.floor(Math.log(size) / Math.log(1024)); sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i]; } return self._getLayoutTemplate('size').replace('{sizeText}', out); }, _generatePreviewTemplate: function (cat, data, fname, ftype, previewId, isError, size, frameClass, foot, ind) { var self = this, tmplt = self._getPreviewTemplate(cat), content, sText, css = frameClass || '', config = ifSet(cat, self.previewSettings, defaultPreviewSettings[cat]), caption = self.slug(fname), footer = foot || self._renderFileFooter(caption, size, config.width, isError); ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1); tmplt = self._parseFilePreviewIcon(tmplt, fname); if (cat === 'text' || cat === 'html') { sText = cat === 'text' ? htmlEncode(data) : data; content = tmplt.replace(/\{previewId}/g, previewId).replace(/\{caption}/g, caption) .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height) .replace(/\{frameClass}/g, css).replace(/\{cat}/g, ftype) .replace(/\{footer}/g, footer).replace(/\{fileindex}/g, ind) .replace(/\{data}/g, sText).replace(/\{template}/g, cat); } else { content = tmplt.replace(/\{previewId}/g, previewId).replace(/\{caption}/g, caption) .replace(/\{frameClass}/g, css).replace(/\{type}/g, ftype).replace(/\{fileindex}/g, ind) .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height) .replace(/\{footer}/g, footer).replace(/\{data}/g, data).replace(/\{template}/g, cat); } return content; }, _previewDefault: function (file, previewId, isDisabled) { var self = this, $preview = self.$preview, $previewLive = $preview.find('.file-live-thumbs'); if (!self.showPreview) { return; } var fname = file ? file.name : '', ftype = file ? file.type : '', content, isError = isDisabled === true && !self.isUploadable, data = objUrl.createObjectURL(file); self._clearDefaultPreview(); content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, isError, file.size); if (!$previewLive.length) { $previewLive = $(document.createElement('div')).addClass('file-live-thumbs').appendTo($preview); } $previewLive.append("\n" + content); if (isDisabled === true && self.isUploadable) { self._setThumbStatus($('#' + previewId), 'Error'); } }, _previewFile: function (i, file, theFile, previewId, data) { if (!this.showPreview) { return; } var self = this, cat = self._parseFileType(file), fname = file ? file.name : '', caption = self.slug(fname), types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, $preview = self.$preview, chkTypes = types && types.indexOf(cat) >= 0, $previewLive = $preview.find('.file-live-thumbs'), iData = (cat === 'text' || cat === 'html' || cat === 'image') ? theFile.target.result : data, content, chkMimes = mimes && mimes.indexOf(file.type) !== -1; if (!$previewLive.length) { $previewLive = $(document.createElement('div')).addClass('file-live-thumbs').appendTo($preview); } /** @namespace window.DOMPurify */ if (cat === 'html' && self.purifyHtml && window.DOMPurify) { iData = window.DOMPurify.sanitize(iData); } if (chkTypes || chkMimes) { content = self._generatePreviewTemplate(cat, iData, fname, file.type, previewId, false, file.size); self._clearDefaultPreview(); $previewLive.append("\n" + content); self._validateImage(i, previewId, caption, file.type); } else { self._previewDefault(file, previewId); } self._initSortable(); }, _slugDefault: function (text) { return isEmpty(text) ? '' : String(text).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_'); }, _readFiles: function (files) { this.reader = new FileReader(); var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader, $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading, msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings, ctr = self.filestack.length, readFile, maxPreviewSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize), canPreview = $preview.length && (!maxPreviewSize || isNaN(maxPreviewSize)), throwError = function (msg, file, previewId, index) { var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}), p2 = {id: previewId, index: index, file: file, files: files}; self._previewDefault(file, previewId, true); if (self.isUploadable) { self.addToStack(undefined); } setTimeout(function () { readFile(index + 1); }, 100); self._initFileActions(); if (self.removeFromPreviewOnError) { $('#' + previewId).remove(); } return self.isUploadable ? self._showUploadError(msg, p1) : self._showError(msg, p2); }; self.loadedImages = []; self.totalImagesCount = 0; $.each(files, function (key, file) { var func = self.fileTypeSettings.image || defaultFileTypeSettings.image; if (func && func(file.type)) { self.totalImagesCount++; } }); readFile = function (i) { if (isEmpty($el.attr('multiple'))) { numFiles = 1; } if (i >= numFiles) { if (self.isUploadable && self.filestack.length > 0) { self._raise('filebatchselected', [self.getFileStack()]); } else { self._raise('filebatchselected', [files]); } $container.removeClass('file-thumb-loading'); $status.html(''); return; } var node = ctr + i, previewId = previewInitId + "-" + node, isText, isImage, file = files[i], caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '', previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk, fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '), fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', '); if (!isEmpty(fileExt)) { fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i'); } fileSize = fileSize.toFixed(2); if (self.maxFileSize > 0 && fileSize > self.maxFileSize) { msg = self.msgSizeTooLarge.replace('{name}', caption) .replace('{size}', fileSize) .replace('{maxSize}', self.maxFileSize); self.isError = throwError(msg, file, previewId, i); return; } if (!isEmpty(fileTypes) && isArray(fileTypes)) { for (j = 0; j < fileTypes.length; j += 1) { typ = fileTypes[j]; checkFile = settings[typ]; chk = (checkFile !== undefined && checkFile(file.type, caption)); fileCount += isEmpty(chk) ? 0 : chk.length; } if (fileCount === 0) { msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes); self.isError = throwError(msg, file, previewId, i); return; } } if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) { chk = compare(caption, fileExtExpr); fileCount += isEmpty(chk) ? 0 : chk.length; if (fileCount === 0) { msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}', strExt); self.isError = throwError(msg, file, previewId, i); return; } } if (!self.showPreview) { self.addToStack(file); setTimeout(function () { readFile(i + 1); }, 100); self._raise('fileloaded', [file, previewId, i, reader]); return; } if (!canPreview && fileSize > maxPreviewSize) { self.addToStack(file); $container.addClass('file-thumb-loading'); self._previewDefault(file, previewId); self._initFileActions(); self._updateFileDetails(numFiles); readFile(i + 1); return; } if ($preview.length && FileReader !== undefined) { $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles)); $container.addClass('file-thumb-loading'); reader.onerror = function (evt) { self._errorHandler(evt, caption); }; reader.onload = function (theFile) { self._previewFile(i, file, theFile, previewId, previewData); self._initFileActions(); }; reader.onloadend = function () { msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles) .replace('{percent}', 50).replace('{name}', caption); setTimeout(function () { $status.html(msg); self._updateFileDetails(numFiles); readFile(i + 1); }, 100); self._raise('fileloaded', [file, previewId, i, reader]); }; reader.onprogress = function (data) { if (data.lengthComputable) { var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact); msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles) .replace('{percent}', progress).replace('{name}', caption); setTimeout(function () { $status.html(msg); }, 100); } }; isText = ifSet('text', settings, defaultFileTypeSettings.text); isImage = ifSet('image', settings, defaultFileTypeSettings.image); if (isText(file.type, caption)) { reader.readAsText(file, self.textEncoding); } else { if (isImage(file.type, caption)) { reader.readAsDataURL(file); } else { reader.readAsArrayBuffer(file); } } } else { self._previewDefault(file, previewId); setTimeout(function () { readFile(i + 1); self._updateFileDetails(numFiles); }, 100); self._raise('fileloaded', [file, previewId, i, reader]); } self.addToStack(file); }; readFile(0); self._updateFileDetails(numFiles, false); }, _updateFileDetails: function (numFiles) { var self = this, $el = self.$element, fileStack = self.getFileStack(), name = (isIE(9) && findFileName($el.val())) || ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '', label = self.slug(name), n = self.isUploadable ? fileStack.length : numFiles, nFiles = previewCache.count(self.id) + n, log = n > 1 ? self._getMsgSelected(nFiles) : label; if (self.isError) { self.$previewContainer.removeClass('file-thumb-loading'); self.$previewStatus.html(''); self.$captionContainer.find('.kv-caption-icon').hide(); } else { self._showFileIcon(); } self._setCaption(log, self.isError); self.$container.removeClass('file-input-new file-input-ajax-new'); if (arguments.length === 1) { self._raise('fileselect', [numFiles, label]); } if (previewCache.count(self.id)) { self._initPreviewActions(); } }, _setThumbStatus: function ($thumb, status) { var self = this; if (!self.showPreview) { return; } var icon = 'indicator' + status, msg = icon + 'Title', css = 'file-preview-' + status.toLowerCase(), $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings; $thumb.removeClass('file-preview-success file-preview-error file-preview-loading'); if (status === 'Error') { $thumb.find('.kv-file-upload').attr('disabled', true); } if (status === 'Success') { $thumb.find('.file-drag-handle').remove(); $indicator.css('margin-left', 0); } $indicator.html(config[icon]); $indicator.attr('title', config[msg]); $thumb.addClass(css); }, _setProgressCancelled: function () { var self = this; self._setProgress(101, self.$progress, self.msgCancelled); }, _setProgress: function (p, $el, error) { var self = this, pct = Math.min(p, 100), template = pct < 100 ? self.progressTemplate : (error ? self.progressErrorTemplate : (p <= 100 ? self.progressTemplate : self.progressCompleteTemplate)), pctLimit = self.progressUploadThreshold; $el = $el || self.$progress; if (!isEmpty(template)) { if (pctLimit && pct > pctLimit && p <= 100) { var out = template.replace('{percent}', pctLimit).replace('{percent}', pctLimit).replace('{percent}%', self.msgUploadThreshold); $el.html(out); } else { $el.html(template.replace(/\{percent}/g, pct)); } if (error) { $el.find('[role="progressbar"]').html(error); } } }, _setFileDropZoneTitle: function () { var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles; if (self.isClickable) { strFiles = isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural; title += self.dropZoneClickTitle.replace('{files}', strFiles); } $zone.find('.' + self.dropZoneTitleClass).remove(); if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) { return; } if ($zone.find('.file-preview-frame').length === 0 && isEmpty(self.defaultPreviewContent)) { $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>'); } self.$container.removeClass('file-input-new'); addCss(self.$container, 'file-input-ajax-new'); }, _setAsyncUploadStatus: function (previewId, pct, total) { var self = this, sum = 0; self._setProgress(pct, $('#' + previewId).find('.file-thumb-progress')); self.uploadStatus[previewId] = pct; $.each(self.uploadStatus, function (key, value) { sum += value; }); self._setProgress(Math.floor(sum / total)); }, _validateMinCount: function () { var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length; if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) { self._noFilesError({}); return false; } return true; }, _getFileCount: function (fileCount) { var self = this, addCount = 0; if (self.validateInitialCount && !self.overwriteInitial) { addCount = previewCache.count(self.id); fileCount += addCount; } return fileCount; }, _getFileName: function (file) { return file && file.name ? this.slug(file.name) : undefined; }, _getFileNames: function (skipNull) { var self = this; return self.filenames.filter(function (n) { return (skipNull ? n !== undefined : n !== undefined && n !== null); }); }, _setPreviewError: function ($thumb, i, val) { var self = this; if (i !== undefined) { self.updateStack(i, val); } if (self.removeFromPreviewOnError) { $thumb.remove(); } else { self._setThumbStatus($thumb, 'Error'); } }, _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) { var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type], $imgEl, isValid; if (isEmpty(limit) || !$img.length) { return; } $imgEl = $img[0]; dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height; isValid = chk === 'Small' ? dim >= limit : dim <= limit; if (isValid) { return; } msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit); self._showUploadError(msg, params); self._setPreviewError($thumb, i, null); }, _validateImage: function (i, previewId, fname, ftype) { var self = this, $preview = self.$preview, params, w1, w2, $thumb = $preview.find("#" + previewId), $img = $thumb.find('img'); fname = fname || 'Untitled'; if (!$img.length) { return; } handler($img, 'load', function () { w1 = $thumb.width(); w2 = $preview.width(); if (w1 > w2) { $img.css('width', '100%'); $thumb.css('width', '97%'); } params = {ind: i, id: previewId}; self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params); self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params); if (!self.resizeImage) { self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params); self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params); } self._raise('fileimageloaded', [previewId]); self.loadedImages.push({ind: i, img: $img, thumb: $thumb, pid: previewId, typ: ftype}); self._validateAllImages(); objUrl.revokeObjectURL($img.attr('src')); }); }, _validateAllImages: function () { var self = this, i, config, $img, $thumb, pid, ind, params = {}, errFunc; if (self.loadedImages.length !== self.totalImagesCount) { return; } self._raise('fileimagesloaded'); if (!self.resizeImage) { return; } errFunc = self.isUploadable ? self._showUploadError : self._showError; for (i = 0; i < self.loadedImages.length; i++) { config = self.loadedImages[i]; $img = config.img; $thumb = config.thumb; pid = config.pid; ind = config.ind; params = {id: pid, 'index': ind}; if (!self._getResizedImage($img[0], config.typ, pid, ind)) { errFunc(self.msgImageResizeError, params, 'fileimageresizeerror'); self._setPreviewError($thumb, ind); } } self._raise('fileimagesresized'); }, _getResizedImage: function (image, type, pid, ind) { var self = this, width = image.naturalWidth, height = image.naturalHeight, ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height, isValidImage = (width && height), chkWidth, chkHeight, canvas = self.imageCanvas, context = self.imageCanvasContext; if (!isValidImage) { return false; } if (width === maxWidth && height === maxHeight) { return true; } type = type || self.resizeDefaultImageType; chkWidth = width > maxWidth; chkHeight = height > maxHeight; if (self.resizePreference === 'width') { ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1); } else { ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1); } self._resetCanvas(); width *= ratio; height *= ratio; canvas.width = width; canvas.height = height; try { context.drawImage(image, 0, 0, width, height); canvas.toBlob(function (blob) { self._raise('fileimageresized', [pid, ind]); self.filestack[ind] = blob; }, type, self.resizeQuality); return true; } catch (err) { return false; } }, _initBrowse: function ($container) { var self = this; if (self.showBrowse) { self.$btnFile = $container.find('.btn-file'); self.$btnFile.append(self.$element); } else { self.$element.hide(); } }, _initCaption: function () { var self = this, cap = self.initialCaption || ''; if (self.overwriteInitial || isEmpty(cap)) { self.$caption.html(''); return false; } self._setCaption(cap); return true; }, _setCaption: function (content, isError) { var self = this, title, out, n, cap, stack = self.getFileStack(); if (!self.$caption.length) { return; } if (isError) { title = $('<div>' + self.msgValidationError + '</div>').text(); n = stack.length; if (n) { cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n); } else { cap = self._getMsgSelected(self.msgNo); } out = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon + (isEmpty(content) ? cap : content) + '</span>'; } else { if (isEmpty(content)) { return; } title = $('<div>' + content + '</div>').text(); out = self._getLayoutTemplate('fileIcon') + title; } self.$caption.html(out); self.$caption.attr('title', title); self.$captionContainer.find('.file-caption-ellipsis').attr('title', title); }, _createContainer: function () { var self = this, $container = $(document.createElement("div")) .attr({"class": 'file-input file-input-new'}) .html(self._renderMain()); self.$element.before($container); self._initBrowse($container); if (self.theme) { $container.addClass('theme-' + self.theme); } return $container; }, _refreshContainer: function () { var self = this, $container = self.$container; $container.before(self.$element); $container.html(self._renderMain()); self._initBrowse($container); }, _renderMain: function () { var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : 'file-drop-disabled', close = !self.showClose ? '' : self._getLayoutTemplate('close'), preview = !self.showPreview ? '' : self._getLayoutTemplate('preview') .replace(/\{class}/g, self.previewClass) .replace(/\{dropClass}/g, dropCss), css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass, caption = self.captionTemplate.replace(/\{class}/g, css + ' kv-fileinput-caption'); return self.mainTemplate.replace(/\{class}/g, self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : '')) .replace(/\{preview}/g, preview) .replace(/\{close}/g, close) .replace(/\{caption}/g, caption) .replace(/\{upload}/g, self._renderButton('upload')) .replace(/\{remove}/g, self._renderButton('remove')) .replace(/\{cancel}/g, self._renderButton('cancel')) .replace(/\{browse}/g, self._renderButton('browse')); }, _renderButton: function (type) { var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'], title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'], status = self.isDisabled ? ' disabled' : '', btnType = 'button'; switch (type) { case 'remove': if (!self.showRemove) { return ''; } break; case 'cancel': if (!self.showCancel) { return ''; } css += ' hide'; break; case 'upload': if (!self.showUpload) { return ''; } if (self.isUploadable && !self.isDisabled) { tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl); } else { btnType = 'submit'; } break; case 'browse': if (!self.showBrowse) { return ''; } tmplt = self._getLayoutTemplate('btnBrowse'); break; default: return ''; } css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button'; if (!isEmpty(label)) { label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>'; } return tmplt.replace('{type}', btnType).replace('{css}', css).replace('{title}', title) .replace('{status}', status).replace('{icon}', icon).replace('{label}', label); }, _renderThumbProgress: function () { return '<div class="file-thumb-progress hide">' + this.progressTemplate.replace(/\{percent}/g, '0') + '</div>'; }, _renderFileFooter: function (caption, size, width, isError) { var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag, upl = config.showUpload, zoom = config.showZoom, out, template = self._getLayoutTemplate('footer'), indicator = isError ? config.indicatorError : config.indicatorNew, title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle; size = self._getSize(size); if (self.isUploadable) { out = template.replace(/\{actions}/g, self._renderFileActions(upl, rem, zoom, drg, false, false, false)) .replace(/\{caption}/g, caption).replace(/\{size}/g, size).replace(/\{width}/g, width) .replace(/\{progress}/g, self._renderThumbProgress()).replace(/\{indicator}/g, indicator) .replace(/\{indicatorTitle}/g, title); } else { out = template.replace(/\{actions}/g, self._renderFileActions(false, false, zoom, drg, false, false, false)) .replace(/\{caption}/g, caption).replace(/\{size}/g, size).replace(/\{width}/g, width) .replace(/\{progress}/g, '').replace(/\{indicator}/g, indicator) .replace(/\{indicatorTitle}/g, title); } out = replaceTags(out, self.previewThumbTags); return out; }, _renderFileActions: function (showUpload, showDelete, showZoom, showDrag, disabled, url, key, isInit) { if (!showUpload && !showDelete && !showZoom && !showDrag) { return ''; } var self = this, vUrl = url === false ? '' : ' data-url="' + url + '"', vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnZoom = '', btnDrag = '', css, template = self._getLayoutTemplate('actions'), config = self.fileActionSettings, otherButtons = self.otherActionButtons.replace(/\{dataKey}/g, vKey), removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass; if (showDelete) { btnDelete = self._getLayoutTemplate('actionDelete') .replace(/\{removeClass}/g, removeClass) .replace(/\{removeIcon}/g, config.removeIcon) .replace(/\{removeTitle}/g, config.removeTitle) .replace(/\{dataUrl}/g, vUrl) .replace(/\{dataKey}/g, vKey); } if (showUpload) { btnUpload = self._getLayoutTemplate('actionUpload') .replace(/\{uploadClass}/g, config.uploadClass) .replace(/\{uploadIcon}/g, config.uploadIcon) .replace(/\{uploadTitle}/g, config.uploadTitle); } if (showZoom) { btnZoom = self._getLayoutTemplate('actionZoom') .replace(/\{zoomClass}/g, config.zoomClass) .replace(/\{zoomIcon}/g, config.zoomIcon) .replace(/\{zoomTitle}/g, config.zoomTitle); } if (showDrag && isInit) { css = 'drag-handle-init ' + config.dragClass; btnDrag = self._getLayoutTemplate('actionDrag').replace(/\{dragClass}/g, css) .replace(/\{dragTitle}/g, config.dragTitle) .replace(/\{dragIcon}/g, config.dragIcon); } return template.replace(/\{delete}/g, btnDelete) .replace(/\{upload}/g, btnUpload) .replace(/\{zoom}/g, btnZoom) .replace(/\{drag}/g, btnDrag) .replace(/\{other}/g, otherButtons); }, _browse: function (e) { var self = this; self._raise('filebrowse'); if (e && e.isDefaultPrevented()) { return; } if (self.isError && !self.isUploadable) { self.clear(); } self.$captionContainer.focus(); }, _change: function (e) { var self = this, $el = self.$element; if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix self.fileInputCleared = false; return; } self.fileInputCleared = false; var tfiles, msg, total, isDragDrop = arguments.length > 1, isAjaxUpload = self.isUploadable, i = 0, f, n, len, files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, ctr = self.filestack.length, isSingleUpload = isEmpty($el.attr('multiple')), flagSingle = (isSingleUpload && ctr > 0), folders = 0, throwError = function (mesg, file, previewId, index) { var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}), p2 = {id: previewId, index: index, file: file, files: files}; return self.isUploadable ? self._showUploadError(mesg, p1) : self._showError(mesg, p2); }; self.reader = null; self._resetUpload(); self._hideFileIcon(); if (self.isUploadable) { self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove(); } if (isDragDrop) { tfiles = []; while (files[i]) { f = files[i]; if (!f.type && f.size % 4096 === 0) { folders++; } else { tfiles.push(f); } i++; } } else { if (e.target.files === undefined) { tfiles = e.target && e.target.value ? [ {name: e.target.value.replace(/^.+\\/, '')} ] : []; } else { tfiles = e.target.files; } } if (isEmpty(tfiles) || tfiles.length === 0) { if (!isAjaxUpload) { self.clear(); } self._showFolderError(folders); self._raise('fileselectnone'); return; } self._resetErrors(); len = tfiles.length; total = self._getFileCount(self.isUploadable ? (self.getFileStack().length + len) : len); if (self.maxFileCount > 0 && total > self.maxFileCount) { if (!self.autoReplace || len > self.maxFileCount) { n = (self.autoReplace && len > self.maxFileCount) ? len : total; msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n); self.isError = throwError(msg, null, null, null); self.$captionContainer.find('.kv-caption-icon').hide(); self._setCaption('', true); self.$container.removeClass('file-input-new file-input-ajax-new'); return; } if (total > self.maxFileCount) { self._resetPreviewThumbs(isAjaxUpload); } } else { if (!isAjaxUpload || flagSingle) { self._resetPreviewThumbs(false); if (flagSingle) { self.clearStack(); } } else { if (isAjaxUpload && ctr === 0 && (!previewCache.count(self.id) || self.overwriteInitial)) { self._resetPreviewThumbs(true); } } } if (self.isPreviewable) { self._readFiles(tfiles); } else { self._updateFileDetails(1); } self._showFolderError(folders); }, _abort: function (params) { var self = this, data; if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) { data = $.extend(true, {}, self._getOutData(), params); data.abortData = self.ajaxAborted.data || {}; data.abortMessage = self.ajaxAborted.message; self.cancel(); self._setProgress(101, self.$progress, self.msgCancelled); self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror'); return true; } return false; }, _resetFileStack: function () { var self = this, i = 0, newstack = [], newnames = []; self._getThumbs().each(function () { var $thumb = $(this), ind = $thumb.attr('data-fileindex'), file = self.filestack[ind]; if (ind === -1) { return; } if (file !== undefined) { newstack[i] = file; newnames[i] = self._getFileName(file); $thumb.attr({ 'id': self.previewInitId + '-' + i, 'data-fileindex': i }); i++; } else { $thumb.attr({ 'id': 'uploaded-' + uniqId(), 'data-fileindex': '-1' }); } }); self.filestack = newstack; self.filenames = newnames; }, clearStack: function () { var self = this; self.filestack = []; self.filenames = []; return self.$element; }, updateStack: function (i, file) { var self = this; self.filestack[i] = file; self.filenames[i] = self._getFileName(file); return self.$element; }, addToStack: function (file) { var self = this; self.filestack.push(file); self.filenames.push(self._getFileName(file)); return self.$element; }, getFileStack: function (skipNull) { var self = this; return self.filestack.filter(function (n) { return (skipNull ? n !== undefined : n !== undefined && n !== null); }); }, getFilesCount: function () { var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length; return self._getFileCount(len); }, lock: function () { var self = this; self._resetErrors(); self.disable(); if (self.showRemove) { addCss(self.$container.find('.fileinput-remove'), 'hide'); } if (self.showCancel) { self.$container.find('.fileinput-cancel').removeClass('hide'); } self._raise('filelock', [self.filestack, self._getExtraData()]); return self.$element; }, unlock: function (reset) { var self = this; if (reset === undefined) { reset = true; } self.enable(); if (self.showCancel) { addCss(self.$container.find('.fileinput-cancel'), 'hide'); } if (self.showRemove) { self.$container.find('.fileinput-remove').removeClass('hide'); } if (reset) { self._resetFileStack(); } self._raise('fileunlock', [self.filestack, self._getExtraData()]); return self.$element; }, cancel: function () { var self = this, xhr = self.ajaxRequests, len = xhr.length, i; if (len > 0) { for (i = 0; i < len; i += 1) { self.cancelling = true; xhr[i].abort(); } } self._setProgressCancelled(); self._getThumbs().each(function () { var $thumb = $(this), ind = $thumb.attr('data-fileindex'); $thumb.removeClass('file-uploading'); if (self.filestack[ind] !== undefined) { $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled'); $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled'); } self.unlock(); }); return self.$element; }, clear: function () { var self = this, cap; self.$btnUpload.removeAttr('disabled'); self._getThumbs().find('video,audio,img').each(function () { cleanMemory($(this)); }); self._resetUpload(); self.clearStack(); self._clearFileInput(); self._resetErrors(true); self._raise('fileclear'); if (self._hasInitialPreview()) { self._showFileIcon(); self._resetPreview(); self._initPreviewActions(); self.$container.removeClass('file-input-new'); } else { self._getThumbs().each(function () { self._clearObjects($(this)); }); if (self.isUploadable) { previewCache.data[self.id] = {}; } self.$preview.html(''); cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : ''; self.$caption.html(cap); self.$caption.attr('title', ''); addCss(self.$container, 'file-input-new'); self._validateDefaultPreview(); } if (self.$container.find('.file-preview-frame').length === 0) { if (!self._initCaption()) { self.$captionContainer.find('.kv-caption-icon').hide(); } } self._hideFileIcon(); self._raise('filecleared'); self.$captionContainer.focus(); self._setFileDropZoneTitle(); return self.$element; }, reset: function () { var self = this; self._resetPreview(); self.$container.find('.fileinput-filename').text(''); self._raise('filereset'); addCss(self.$container, 'file-input-new'); if (self.$preview.find('.file-preview-frame').length || self.isUploadable && self.dropZoneEnabled) { self.$container.removeClass('file-input-new'); } self._setFileDropZoneTitle(); self.clearStack(); self.formdata = {}; return self.$element; }, disable: function () { var self = this; self.isDisabled = true; self._raise('filedisabled'); self.$element.attr('disabled', 'disabled'); self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled"); self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").attr( "disabled", true); self._initDragDrop(); return self.$element; }, enable: function () { var self = this; self.isDisabled = false; self._raise('fileenabled'); self.$element.removeAttr('disabled'); self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled"); self.$container.find( ".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled"); self._initDragDrop(); return self.$element; }, upload: function () { var self = this, totLen = self.getFileStack().length, params = {}, i, outData, len, hasExtraData = !$.isEmptyObject(self._getExtraData()); if (self.minFileCount > 0 && self._getFileCount(totLen) < self.minFileCount) { self._noFilesError(params); return; } if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) { return; } self._resetUpload(); self.$progress.removeClass('hide'); self.uploadCount = 0; self.uploadStatus = {}; self.uploadLog = []; self.lock(); self._setProgress(2); if (totLen === 0 && hasExtraData) { self._uploadExtraOnly(); return; } len = self.filestack.length; self.hasInitData = false; if (self.uploadAsync) { outData = self._getOutData(); self._raise('filebatchpreupload', [outData]); self.fileBatchCompleted = false; self.uploadCache = {content: [], config: [], tags: [], append: true}; self.uploadAsyncCount = self.getFileStack().length; for (i = 0; i < len; i++) { self.uploadCache.content[i] = null; self.uploadCache.config[i] = null; self.uploadCache.tags[i] = null; } for (i = 0; i < len; i++) { if (self.filestack[i] !== undefined) { self._uploadSingle(i, self.filestack, true); } } return; } self._uploadBatch(); return self.$element; }, destroy: function () { var self = this, $cont = self.$container; $cont.find('.file-drop-zone').off(); self.$element.insertBefore($cont).off(NAMESPACE).removeData(); $cont.off().remove(); return self.$element; }, refresh: function (options) { var self = this, $el = self.$element; options = options ? $.extend(true, {}, self.options, options) : self.options; self.destroy(); $el.fileinput(options); if ($el.val()) { $el.trigger('change.fileinput'); } return $el; } }; $.fn.fileinput = function (option) { if (!hasFileAPISupport() && !isIE(9)) { return; } var args = Array.apply(null, arguments), retvals = []; args.shift(); this.each(function () { var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option, theme = options.theme || self.data('theme'), l = {}, t = {}, lang = options.language || self.data('language') || 'en', opts; if (!data) { if (theme) { t = $.fn.fileinputThemes[theme] || {}; } if (lang !== 'en' && !isEmpty($.fn.fileinputLocales[lang])) { l = $.fn.fileinputLocales[lang] || {}; } opts = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data()); data = new FileInput(this, opts); self.data('fileinput', data); } if (typeof option === 'string') { retvals.push(data[option].apply(data, args)); } }); switch (retvals.length) { case 0: return this; case 1: return retvals[0]; default: return retvals; } }; $.fn.fileinput.defaults = { language: 'en', showCaption: true, showBrowse: true, showPreview: true, showRemove: true, showUpload: true, showCancel: true, showClose: true, showUploadedThumbs: true, browseOnZoneClick: false, autoReplace: false, previewClass: '', captionClass: '', mainClass: 'file-caption-main', mainTemplate: null, purifyHtml: true, fileSizeGetter: null, initialCaption: '', initialPreview: [], initialPreviewDelimiter: '*$$*', initialPreviewAsData: false, initialPreviewFileType: 'image', initialPreviewConfig: [], initialPreviewThumbTags: [], previewThumbTags: {}, initialPreviewShowDelete: true, removeFromPreviewOnError: false, deleteUrl: '', deleteExtraData: {}, overwriteInitial: true, layoutTemplates: defaultLayoutTemplates, previewTemplates: defaultPreviewTemplates, previewZoomSettings: defaultPreviewZoomSettings, previewZoomButtonIcons: { prev: '<i class="glyphicon glyphicon-triangle-left"></i>', next: '<i class="glyphicon glyphicon-triangle-right"></i>', toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>', fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>', borderless: '<i class="glyphicon glyphicon-resize-full"></i>', close: '<i class="glyphicon glyphicon-remove"></i>' }, previewZoomButtonClasses: { prev: 'btn btn-navigate', next: 'btn btn-navigate', toggleheader: 'btn btn-default btn-header-toggle', fullscreen: 'btn btn-default', borderless: 'btn btn-default', close: 'btn btn-default' }, allowedPreviewTypes: defaultPreviewTypes, allowedPreviewMimeTypes: null, allowedFileTypes: null, allowedFileExtensions: null, defaultPreviewContent: null, customLayoutTags: {}, customPreviewTags: {}, previewSettings: defaultPreviewSettings, fileTypeSettings: defaultFileTypeSettings, previewFileIcon: '<i class="glyphicon glyphicon-file"></i>', previewFileIconClass: 'file-other-icon', previewFileIconSettings: {}, previewFileExtSettings: {}, buttonLabelClass: 'hidden-xs', browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;', browseClass: 'btn btn-primary', removeIcon: '<i class="glyphicon glyphicon-trash"></i>', removeClass: 'btn btn-default', cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>', cancelClass: 'btn btn-default', uploadIcon: '<i class="glyphicon glyphicon-upload"></i>', uploadClass: 'btn btn-default', uploadUrl: null, uploadAsync: true, uploadExtraData: {}, zoomModalHeight: 480, minImageWidth: null, minImageHeight: null, maxImageWidth: null, maxImageHeight: null, resizeImage: false, resizePreference: 'width', resizeQuality: 0.92, resizeDefaultImageType: 'image/jpeg', maxFileSize: 0, maxFilePreviewSize: 25600, // 25 MB minFileCount: 0, maxFileCount: 0, validateInitialCount: false, msgValidationErrorClass: 'text-danger', msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ', msgErrorClass: 'file-error-message', progressThumbClass: "progress-bar progress-bar-success progress-bar-striped active", progressClass: "progress-bar progress-bar-success progress-bar-striped active", progressCompleteClass: "progress-bar progress-bar-success", progressErrorClass: "progress-bar progress-bar-danger", progressUploadThreshold: 99, previewFileType: 'image', elCaptionContainer: null, elCaptionText: null, elPreviewContainer: null, elPreviewImage: null, elPreviewStatus: null, elErrorContainer: null, errorCloseButton: '<span class="close kv-error-close">&times;</span>', slugCallback: null, dropZoneEnabled: true, dropZoneTitleClass: 'file-drop-zone-title', fileActionSettings: {}, otherActionButtons: '', textEncoding: 'UTF-8', ajaxSettings: {}, ajaxDeleteSettings: {}, showAjaxErrorDetails: true }; $.fn.fileinputLocales.en = { fileSingle: 'file', filePlural: 'files', browseLabel: 'Browse &hellip;', removeLabel: 'Remove', removeTitle: 'Clear selected files', cancelLabel: 'Cancel', cancelTitle: 'Abort ongoing upload', uploadLabel: 'Upload', uploadTitle: 'Upload selected files', msgNo: 'No', msgNoFilesSelected: 'No files selected', msgCancelled: 'Cancelled', msgZoomModalHeading: 'Detailed Preview', msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.', msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.', msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.', msgFileNotFound: 'File "{name}" not found!', msgFileSecured: 'Security restrictions prevent reading the file "{name}".', msgFileNotReadable: 'File "{name}" is not readable.', msgFilePreviewAborted: 'File preview aborted for "{name}".', msgFilePreviewError: 'An error occurred while reading the file "{name}".', msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.', msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.', msgUploadAborted: 'The file upload was aborted', msgUploadThreshold: 'Processing...', msgValidationError: 'Validation Error', msgLoading: 'Loading file {index} of {files} &hellip;', msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.', msgSelected: '{n} {files} selected', msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.', msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.', msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.', msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.', msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.', msgImageResizeError: 'Could not get the image dimensions to resize.', msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>', dropZoneTitle: 'Drag & drop files here &hellip;', dropZoneClickTitle: '<br>(or click to select {files})', previewZoomButtonTitles: { prev: 'View previous file', next: 'View next file', toggleheader: 'Toggle header', fullscreen: 'Toggle full screen', borderless: 'Toggle borderless mode', close: 'Close detailed preview' } }; $.fn.fileinputLocales['es'] = { fileSingle: 'archivo', filePlural: 'archivos', browseLabel: 'Examinar &hellip;', removeLabel: 'Quitar', removeTitle: 'Quitar archivos seleccionados', cancelLabel: 'Cancelar', cancelTitle: 'Abortar la subida en curso', uploadLabel: 'Subir archivo', uploadTitle: 'Subir archivos seleccionados', msgNo: 'No', msgNoFilesSelected: '', msgCancelled: 'Cancelado', msgZoomModalHeading: 'Vista previa detallada', msgSizeTooLarge: 'Archivo "{name}" (<b>{size} KB</b>) excede el tamaño máximo permitido de <b>{maxSize} KB</b>.', msgFilesTooLess: 'Debe seleccionar al menos <b>{n}</b> {files} a cargar.', msgFilesTooMany: 'El número de archivos seleccionados a cargar <b>({n})</b> excede el límite máximo permitido de <b>{m}</b>.', msgFileNotFound: 'Archivo "{name}" no encontrado.', msgFileSecured: 'No es posible acceder al archivo "{name}" porque estará siendo usado por otra aplicación o no tengamos permisos de lectura.', msgFileNotReadable: 'No es posible acceder al archivo "{name}".', msgFilePreviewAborted: 'Previsualización del archivo "{name}" cancelada.', msgFilePreviewError: 'Ocurrió un error mientras se leía el archivo "{name}".', msgInvalidFileType: 'Tipo de archivo no válido para "{name}". Sólo archivos "{types}" son permitidos.', msgInvalidFileExtension: 'Extensión de archivo no válido para "{name}". Sólo archivos "{extensions}" son permitidos.', msgUploadAborted: 'La carga de archivos se ha cancelado', msgUploadThreshold: 'Processing...', msgValidationError: 'Error de validacion', msgLoading: 'Subiendo archivo {index} de {files} &hellip;', msgProgress: 'Subiendo archivo {index} de {files} - {name} - {percent}% completado.', msgSelected: '{n} {files} seleccionado(s)', msgFoldersNotAllowed: 'Arrastre y suelte únicamente archivos. Omitida(s) {n} carpeta(s).', msgImageWidthSmall: 'El ancho de la imagen "{name}" debe ser al menos {size} px.', msgImageHeightSmall: 'La altura de la imagen "{name}" debe ser al menos {size} px.', msgImageWidthLarge: 'El ancho de la imagen "{name}" no puede exceder de {size} px.', msgImageHeightLarge: 'La altura de la imagen "{name}" no puede exceder de {size} px.', msgImageResizeError: 'No se pudo obtener las dimensiones de imagen para cambiar el tamaño.', msgImageResizeException: 'Error al cambiar el tamaño de la imagen.<pre>{errors}</pre>', dropZoneTitle: 'Arrastre y suelte aquí los archivos &hellip;', dropZoneClickTitle: '<br>(o haga click para seleccionar {files})', fileActionSettings: { removeTitle: 'Eliminar archivo', uploadTitle: 'Subir archivo', zoomTitle: 'Ver detalles', dragTitle: 'Mover / Arreglar de nuevo', indicatorNewTitle: 'No subido todavía', indicatorSuccessTitle: 'Subido', indicatorErrorTitle: 'Subir Error', indicatorLoadingTitle: 'Subiendo ...' }, previewZoomButtonTitles: { prev: 'Ver archivo anterior', next: 'Ver archivo siguiente', toggleheader: 'Activar encabezado', fullscreen: 'Activar pantalla completa', borderless: 'Activar el modo sin bordes', close: 'Cerrar vista detallada' } }; $.fn.fileinput.Constructor = FileInput; /** * Convert automatically file inputs with class 'file' into a bootstrap fileinput control. */ $(document).ready(function () { var $input = $('input.file[type=file]'); if ($input.length) { $input.fileinput(); } }); }));
// Finnish 'use strict'; var fi = function() {} fi.code = 'fi'; fi.data = { GEN_Help_0 : 'Already have a wallet somewhere?', GEN_Help_MetaMask : 'So easy! Keys stay in MetaMask, not on a phishing site! Try it today.', GEN_Warning_1 : '**Do not lose it!** It cannot be recovered if you lose it.', GEN_Warning_2 : '**Do not share it!** Your funds will be stolen if you use this file on a malicious/phishing site.', GEN_Warning_3 : '**Make a backup!** Secure it like the millions of dollars it may one day be worth.', GAS_Price_1 : 'Not So Fast', GAS_Price_2 : 'Fast', GAS_Price_3 : 'Fast AF', CONTRACT_Helper_1 : 'Please change the address to your own Multisig Contract Address.', CONTRACT_Warning_1 : 'You are about to **deploy a contract**.', CONTRACT_Warning_2 : 'It will be deployed on the following network:', CONTRACT_Warning_3 : 'You are about to **execute a function on contract**.', SEND_Helper_Contract : 'In most cases you should leave this as 0.', SEND_ViewOnly : 'You cannot send with only your address. You must use one of the other options to unlock your wallet in order to send.', SEND_LoadTokens : 'Load Tokens', SEND_CustomAddrMsg : 'A message regarding', SWAP_Warning_1 : 'Warning! You do not have enough funds to complete this swap.', SWAP_Warning_2 : 'Please add more funds to your wallet or access a different wallet.', X_Advanced : 'Advanced Users Only.', X_HelpfulLinks : 'Helpful Links & FAQs', X_HelpfulLinks_1 : 'How to Access your Wallet', X_HelpfulLinks_2 : 'I lost my private key', X_HelpfulLinks_3 : 'My private key opens a different address', X_HelpfulLinks_4 : 'Migrating to/from MyEtherWallet', X_Network : 'Network', // aka "node" or "chain" - used in the dropdown in header X_Network_Custom : 'Add Custom Network / Node', DOMAIN_Buy : 'Buy the domain', DOMAIN_BuyItNow : 'Price to buy the domain immediately:', DOMAIN_bid : 'Bid for the domain', DOMAIN_bid_0 : 'You are currently winning this auction with the highest bid. You can bid higher if you want, but it will delay the close of the auction for 24 hours.', DOMAIN_bid_1 : 'Bid at least', DOMAIN_bid_2 : 'on the domain.', DOMAIN_bid_3 : 'You will win the domain if no higher bids are placed within the next 24 hours.', DOMAIN_bid_4 : 'Note that the domain has a locked value of', DOMAIN_bid_5 : 'As part of the sale you will receive the deed with this value but cannot claim it unless you release the name.', DOMAIN_Finish_1 : 'Not related to that auction', DOMAIN_Finish_2 : 'This address is neither the winner nor the seller of the auction.', DOMAIN_Finish_3 : 'Finish the auction', DOMAIN_Finish_4 : 'Finish the auction to allocate the domain to the winner and the funds to the seller.', DOMAIN_Finish_5 : 'Click your TX hash to see if you successfully transferred the domain to DomainSale.', DOMAIN_offer_4 : 'Offer For Sale:', DOMAIN_offer_5 : 'Set either of both of the prices below to offer your domain for sale. Remember that any funds you have locked in the domain\'s deed will go to the buyer and 10% of the funds when sold goes to referrers.', DOMAIN_offer_7 : 'Alter Your Offer for:', DOMAIN_offer_8 : 'Change either of both of the prices below to alter your domain sale offer. Remember that any funds you have locked in the domain\'s deed will go to the buyer and 10% of the funds when sold goes to referrers.', DOMAIN_offer_9 : 'Buy price', DOMAIN_offer_10 : 'This is the price at which someone can buy the domain immediately. 0 means that the domain cannot be purchased immediately.', DOMAIN_offer_11 : 'This is the price at which someone can start an auction for the domain. 0 means that the domain will not be available for auction.', DOMAIN_offer_12 : 'Offer your domain', DOMAIN_offer_13 : 'Alter your sale', DOMAIN_offer_14 : 'Cancel your sale', DOMAIN_offer_15 : 'You can cancel your domain sale, which will return the domain to you with no charge. This is only available before any bids have been received for the domain.', ENS_WrongAddress_1 : 'The wallet you unlocked does not own the name ', ENS_WrongAddress_2 : 'Please unlock the wallet with address ', ENS_Finalize : 'Finalize', ENS_Finalize_content : 'Finalizing this name assigns the ENS name to the winning bidder. The winner will be refunded the difference between their bid and the next-highest bid. If you are the only bidder, you will be refunded all but 0.01 ETH. Any non-winners will also be refunded.', ENS_Finalize_content_1 : 'You are about to finalize the auction & claim the name:', ENS_Helper_1 : 'What is the process like?', ENS_Helper_2 : '1) Preparation', ENS_Helper_3 : 'Decide which account you wish to own the name & ensure that you have multiple backups of that account.', ENS_Helper_4 : 'Decide the maximum amount of ETH you are willing to pay for the name (your <u>Bid Amount</u>). Ensure that the account has enough to cover your bid + 0.01 ETH for gas.', ENS_Helper_5 : '2) Start an Auction / Place a Bid', ENS_Helper_6 : 'Bidding period lasts 3 days (72 hours).', ENS_Helper_7 : 'You will enter the <u>name</u>, <u>Actual Bid Amount</u>, <u>Bid Mask</u>, which is protected by a <u>Secret Phrase</u>.', ENS_Helper_8 : 'This places your bid, but this information is kept secret until you reveal it.', ENS_Helper_9 : '3) Reveal your Bid', ENS_Helper_10 : '**If you do not reveal your bid, you will not be refunded.**', ENS_Helper_11 : 'Reveal Period lasts 2 days (48 hours).', ENS_Helper_12 : 'You will unlock your account, enter the <u>Bid Amount</u>, and the <u>Secret Phrase</u>.', ENS_Helper_13 : 'In the event that two parties bid exactly the same amount, the first bid revealed will win.', ENS_Helper_14 : '4) Finalize the Auction', ENS_Helper_15 : 'Once the auction has ended (after 5 days / 120 hours), the winner needs to finalize the auction in order to claim their new name.', ENS_Helper_16 : 'The winner will be refunded the difference between their bid and the next-highest bid. If you are the only bidder, you will be refunded all but 0.01 ETH.', ENS_Helper_17 : 'More Information', ENS_Helper_18 : 'The auction for this registrar is a blind auction, and is described in', ENS_Helper_19 : 'Basically, no one can see *anything* during the auction.', ENS_Helper_20 : 'ENS: Read the Docs', ENS_Helper_21 : 'Announcing the Ethereum Name Service Relaunch Date!', ENS_Helper_22 : 'Knowledge Base: ENS', ENS_Helper_23 : 'Debugging a [BAD INSTRUCTION] Reveal', ENS_Helper_24 : 'Please try the above before relying on support for reveal issues as we are severely backlogged on support tickets. We\'re so sorry. :(', EOS_01 : '**Generate EOS Key-pair**', EOS_02 : '**Register / Map your EOS Key**', EOS_03 : 'Select `register`', EOS_04 : 'Enter your **EOS Public Key** <--- CAREFUL! EOS PUBLIC KEY!', EOS_05 : 'Fund EOS Contract on Send Page', EOS_06 : 'Go to Send Ether & Tokens Page', EOS_07 : 'Unlock same wallet you are unlocking here.', EOS_08 : 'Send Amount you want to Contribute to `0xd0a6E6C54DbC68Db5db3A091B171A77407Ff7ccf`', EOS_09 : 'Claim EOS Tokens', EOS_10 : 'Select `claimAll`.', /* Onboarding */ ONBOARD_welcome_title : 'Welcome to MyEtherWallet.com', ONBOARD_welcome_content__1 : 'Please take some time to understand this for your own safety. 🙏', ONBOARD_welcome_content__2 : 'Your funds will be stolen if you do not heed these warnings.', ONBOARD_welcome_content__3 : 'We know this click-through stuff is annoying. We are sorry.', ONBOARD_welcome_content__4 : 'What is MEW? ', ONBOARD_welcome_content__5 : 'MyEtherWallet is a free, open-source, client-side interface.', ONBOARD_welcome_content__6 : 'We allow you to interact directly with the blockchain while remaining in full control of your keys &amp; your funds.', ONBOARD_welcome_content__7 : '**You** and **only you** are responsible for your security.', ONBOARD_welcome_content__8 : 'We cannot recover your funds or freeze your account if you visit a phishing site or lose your private key.', ONBOARD_bank_title : 'MyEtherWallet is not a Bank', ONBOARD_bank_content__1 : 'When you open an account with a bank or exchange, they create an account for you in their system.', ONBOARD_bank_content__2 : 'The bank keeps track of your personal information, account passwords, balances, transactions and ultimately your money.', ONBOARD_bank_content__3 : 'The bank charge fees to manage your account and provide services, like refunding transactions when your card gets stolen.', ONBOARD_bank_content__4 : 'The bank allows you to write a check or charge your debit card to send money, go online to check your balance, reset your password, and get a new debit card if you lose it.', ONBOARD_bank_content__5 : 'You have an account *with the bank or exchange* and they decide how much money you can send, where you can send it, and how long to hold on a suspicious deposit. All for a fee.', ONBOARD_welcome_title__alt : 'Introduction', ONBOARD_interface_title : 'MyEtherWallet is an Interface', ONBOARD_interface_content__1 : 'When you create an account on MyEtherWallet you are generating a cryptographic set of numbers: your private key and your public key (address).', ONBOARD_interface_content__2 : 'The handling of your keys happens entirely on your computer, inside your browser.', ONBOARD_interface_content__3 : 'We never transmit, receive or store your private key, password, or other account information.', ONBOARD_interface_content__4 : 'We do not charge a transaction fee.', ONBOARD_interface_content__5 : 'You are simply using our **interface** to interact **directly with the blockchain**.', ONBOARD_interface_content__6 : 'If you send your *public key (address)* to someone, they can send you ETH or tokens. 👍', ONBOARD_interface_content__7 : 'If you send your *private key* to someone, they now have full control of your account. 👎', ONBOARD_bank_title__alt : 'MEW isn\'t a Bank', ONBOARD_blockchain_title__alt : 'WTF is a Blockchain?', ONBOARD_blockchain_skip : 'I already know what a blockchain is...', ONBOARD_blockchain_title : 'Wait, WTF is a Blockchain?', ONBOARD_blockchain_content__1 : 'The blockchain is like a huge, global, decentralized spreadsheet.', ONBOARD_blockchain_content__2 : 'It keeps track of who sent how many coins to whom, and what the balance of every account is.', ONBOARD_blockchain_content__3 : 'It is stored and maintained by thousands of people (miners) across the globe who have special computers.', ONBOARD_blockchain_content__4 : 'The blocks in the blockchain are made up of all the individual transactions sent from MyEtherWallet, MetaMask, Exodus, Mist, Geth, Parity, and everywhere else.', ONBOARD_blockchain_content__5 : 'When you see your balance on MyEtherWallet.com or view your transactions on [etherscan.io](https://etherscan.io), you are seeing data on the blockchain, not in our personal systems.', ONBOARD_blockchain_content__6 : 'Again: **we are not a bank**.', ONBOARD_interface_title__alt : 'MEW is an Interface', ONBOARD_why_title__alt : 'But...why does this matter?', ONBOARD_why_title : 'Why are you making me read all this?', ONBOARD_why_content__1 : 'Because we need you to understand that we **cannot**...', ONBOARD_why_content__2 : 'Access your account or send your funds for you X.', ONBOARD_why_content__3 : 'Recover or change your private key.', ONBOARD_why_content__4 : 'Recover or reset your password.', ONBOARD_why_content__5 : 'Reverse, cancel, or refund transactions.', ONBOARD_why_content__6 : 'Freeze accounts.', ONBOARD_why_content__7 : '**You** and **only you** are responsible for your security.', ONBOARD_why_content__8 : 'Be diligent to keep your private key and password safe. Your private key is sometimes called your mnemonic phrase, keystore file, UTC file, JSON file, wallet file.', ONBOARD_why_content__9 : 'If you lose your private key or password, no one can recover it.', ONBOARD_why_content__10 : 'If you enter your private key on a phishing website, you will have **all your funds taken**.', ONBOARD_blockchain_title__alt : 'WTF is a Blockchain?', ONBOARD_point_title__alt : 'What\'s the Point of MEW then?', ONBOARD_whymew_title : 'If MyEtherWallet can\'t do those things, what\'s the point?', ONBOARD_whymew_content__1 : 'Because that is the point of decentralization and the blockchain.', ONBOARD_whymew_content__2 : 'You don\'t have to rely on your bank, government, or anyone else when you want to move your funds.', ONBOARD_whymew_content__3 : 'You don\'t have to rely on the security of an exchange or bank to keep your funds safe.', ONBOARD_whymew_content__4 : 'If you don\'t find these things valuable, ask yourself why you think the blockchain and cryptocurrencies are valuable. 😉', ONBOARD_whymew_content__5 : 'If you don\'t like the sound of this, consider using [Coinbase](https://www.coinbase.com/) or [Blockchain.info](https://blockchain.info/wallet/#/signup). They have more familiar accounts with usernames & passwords.', ONBOARD_whymew_content__6 : 'If you are scared but want to use MEW, [get a hardware wallet](https://kb.myetherwallet.com/hardware-wallets/hardware-wallet-recommendations.html)! These keep your keys secure.', ONBOARD_why_title__alt : 'But...why?', ONBOARD_secure_title : 'How To Protect Yourself & Your Funds', ONBOARD_secure_1_title : 'How To Protect Yourself from Phishers', ONBOARD_secure_1_content__1 : 'Phishers send you a message with a link to a website that looks just like MyEtherWallet, EtherDelta, Paypal, or your bank, but is not the real website. They steal your information and then steal your money.', ONBOARD_secure_1_content__2 : 'Install [EAL](https://chrome.google.com/webstore/detail/etheraddresslookup/pdknmigbbbhmllnmgdfalmedcmcefdfn) or [MetaMask](https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn) or [Cryptonite by Metacert](https://chrome.google.com/webstore/detail/cryptonite-by-metacert/keghdcpemohlojlglbiegihkljkgnige) or the [MyEtherWallet Chrome Extension](https://chrome.google.com/webstore/detail/myetherwallet-cx/nlbmnnijcnlegkjjpcfjclmcfggfefdm) to block malicious websites.', ONBOARD_secure_1_content__3 : 'Always check the URL: `https://vintage.myetherwallet.com`.', ONBOARD_secure_1_content__4 : 'Always make sure the URL bar has `MYETHERWALLET INC` in green.', ONBOARD_secure_1_content__5 : 'Do not trust messages or links sent to you randomly via email, Slack, Reddit, Twitter, etc.', ONBOARD_secure_1_content__6 : 'Always navigate directly to a site before you enter information. Do not enter information after clicking a link from a message or email.', ONBOARD_secure_1_content__7 : '[Install an AdBlocker](https://chrome.google.com/webstore/detail/ublock-origin/cjpalhdlnbpafiamejdnhcphjbkeiagm?hl=en) and do not click ads on your search engine (e.g. Google).', ONBOARD_point_title__alt_2 : 'What\'s the point?', ONBOARD_secure_2_title : 'How To Protect Yourself from Scams', ONBOARD_secure_2_content__1 : 'People will try to get you to give them money in return for nothing.', ONBOARD_secure_2_content__2 : 'If it is too good to be true, it probably is.', ONBOARD_secure_2_content__3 : 'Research before sending money to someone or some project. Look for information on a variety of websites and forums. Be wary.', ONBOARD_secure_2_content__4 : 'Ask questions when you don\'t understand something or it doesn\'t seem right.', ONBOARD_secure_2_content__5 : 'Don\'t let fear, FUD, or FOMO win over common sense. If something is very urgent, ask yourself "why?". It may be to create FOMO or prevent you from doing research.', ONBOARD_secure_3_title__alt : 'Phuck Phishers', ONBOARD_secure_3_title : 'How To Protect Yourself from Loss', ONBOARD_secure_3_content__1 : 'If you lose your private key or password, it is gone forever. Don\'t lose it.', ONBOARD_secure_3_content__2 : 'Make a backup of your private key and password. Do NOT just store it on your computer. Print it out on a piece of paper or save it to a USB drive.', ONBOARD_secure_3_content__3 : 'Store this paper or USB drive in a different physical location. A backup is not useful if it is destroyed by a fire or flood along with your laptop.', ONBOARD_secure_3_content__4 : 'Do not store your private key in Dropbox, Google Drive, or other cloud storage. If that account is compromised, your funds will be stolen.', ONBOARD_secure_3_content__5 : 'If you have more than 1-week\'s worth of pay worth of cryptocurrency, get a hardware wallet. No excuses. It\'s worth it. I promise.', ONBOARD_secure_3_content__6 : '[Even more Security Tips!](https://kb.myetherwallet.com/getting-started/protecting-yourself-and-your-funds.html)', ONBOARD_secure_2_title__alt_2 : 'Screw Scams', ONBOARD_final_title__alt : 'One more click & you\'re done! 🤘', ONBOARD_final_title : 'Alright, I\'m done lecturing you!', ONBOARD_final_subtitle : 'Sorry for being like this. Onwards!', ONBOARD_final_content__1 : 'Create a wallet', ONBOARD_final_content__2 : 'Get a hardware wallet', ONBOARD_final_content__3 : 'How to Set up MEW + MetaMask', ONBOARD_final_content__4 : 'How to Run MEW Offline / Locally', ONBOARD_final_content__5 : 'How to Send via Ledger hardware wallet', ONBOARD_final_content__6 : 'How to Send via TREZOR hardware wallet', ONBOARD_final_content__7 : 'How to Send via MetaMask', ONBOARD_final_content__8 : 'Learn More or Contact Us', ONBOARD_final_content__9 : 'OMG, please just let me send FFS.', ONBOARD_resume : 'It looks like you didn\'t finish reading through these slides last time. ProTip: Finish reading through the slides 😉', HELP_2a_Title : 'How do I save/backup my wallet? ', /* New Generics */ x_CancelReplaceTx : 'Cancel or Replace Transaction', x_CancelTx : 'Cancel Transaction', x_PasswordDesc : 'This password * encrypts * your private key. This does not act as a seed to generate your keys. **You will need this password + your private key to unlock your wallet.**', x_ReadMore : 'Read More', x_ReplaceTx : 'Replace Transaction', x_TransHash : 'Transaction Hash', x_TXFee : 'TX Fee', x_TxHash : 'TX Hash', /* Check TX Status */ NAV_CheckTxStatus : 'Check TX Status', NAV_TxStatus : 'TX Status', tx_Details : 'Transaction Details', tx_Summary : 'During times of high volume (like during ICOs) transactions can be pending for hours, if not days. This tool aims to give you the ability to find and "cancel" / replace these TXs. ** This is not typically something you can do. It should not be relied upon & will only work when the TX Pools are full. [Please, read about this tool here.](https://kb.myetherwallet.com/transactions/check-status-of-ethereum-transaction.html)**', tx_notFound : 'Transaction Not Found', tx_notFound_1 : 'This TX cannot be found in the TX Pool of the node you are connected to.', tx_notFound_2 : 'If you just sent the transaction, please wait 15 seconds and press the "Check TX Status" button again. ', tx_notFound_3 : 'It could still be in the TX Pool of a different node, waiting to be mined.', tx_notFound_4 : 'Please use the dropdown in the top-right & select a different ETH node (e.g. `ETH (Etherscan.io)` or `ETH (Infura.io)` or `ETH (MyEtherWallet)`) and check again.', tx_foundInPending : 'Pending Transaction Found', tx_foundInPending_1 : 'Your transaction was located in the TX Pool of the node you are connected to. ', tx_foundInPending_2 : 'It is currently pending (waiting to be mined). ', tx_foundInPending_3 : 'There is a chance you can "cancel" or replace this transaction. Unlock your wallet below.', tx_FoundOnChain : 'Transaction Found', tx_FoundOnChain_1 : 'Your transaction was successfully mined and is on the blockchain.', tx_FoundOnChain_2 : '**If you see a red `( ! )`, a `BAD INSTRUCTION` or `OUT OF GAS` error message**, it means that the transaction was not successfully *sent*. You cannot cancel or replace this transaction. Instead, send a new transaction. If you received an "Out of Gas" error, you should double the gas limit you specified originally.', tx_FoundOnChain_3 : '**If you do not see any errors, your transaction was successfully sent.** Your ETH or Tokens are where you sent them. If you cannot see this ETH or Tokens credited in your other wallet / exchange account, and it has been 24+ hours since you sent, please [contact that service](https://kb.myetherwallet.com/diving-deeper/ethereum-list-of-support-and-communities.html). Send them the *link* to your transaction and ask them, nicely, to look into your situation.', /* Gen Wallet Updates */ GEN_Help_1 : 'Use your', GEN_Help_2 : 'to access your account.', GEN_Help_3 : 'Your device * is * your wallet.', GEN_Help_4 : 'Guides & FAQ', GEN_Help_5 : 'How to Create a Wallet', GEN_Help_6 : 'Getting Started', GEN_Help_7 : 'Keep it safe · Make a backup · Don\'t share it with anyone · Don\'t lose it · It cannot be recovered if you lose it.', GEN_Help_8 : 'Not Downloading a File? ', GEN_Help_9 : 'Try using Google Chrome ', GEN_Help_10 : 'Right click & save file as. Filename: ', GEN_Help_11 : 'Don\'t open this file on your computer ', GEN_Help_12 : 'Use it to unlock your wallet via MyEtherWallet (or Mist, Geth, Parity and other wallet clients.) ', GEN_Help_13 : 'How to Back Up Your Keystore File ', GEN_Help_14 : 'What are these Different Formats? ', GEN_Help_15 : 'Preventing loss &amp; theft of your funds.', GEN_Help_16 : 'What are these Different Formats?', GEN_Help_17 : 'Why Should I?', GEN_Help_18 : 'To have a secondary backup.', GEN_Help_19 : 'In case you ever forget your password.', GEN_Help_20 : 'Cold Storage', GET_ConfButton : 'I understand. Continue.', GEN_Label_5 : 'Save Your `Private Key`. ', GEN_Unlock : 'Unlock your wallet to see your address', GAS_PRICE_Desc : 'Gas Price is the amount you pay per unit of gas. `TX fee = gas price * gas limit` & is paid to miners for including your TX in a block. Higher the gas price = faster transaction, but more expensive. Default is `41 GWEI`.', GAS_LIMIT_Desc : 'Gas limit is the amount of gas to send with your TX. `TX fee` = gas price * gas limit & is paid to miners for including your TX in a block. Increasing this number will not get your TX mined faster. Sending ETH = `21000`. Sending Tokens = ~`200000`.', NONCE_Desc : 'The nonce is the number of transactions sent from a given address. It ensures transactions are sent in order & not more than once.', TXFEE_Desc : 'The TX Fee is paid to miners for including your TX in a block. Is is the `gas limit` * `gas price`. [You can convert GWEI -> ETH here](https://vintage.myetherwallet.com/helpers.html)', /* Navigation*/ NAV_AddWallet : 'Lisää Lompakko ', NAV_BulkGenerate : 'Massa Generoi ', NAV_Contact : 'Yhteystiedot ', NAV_Contracts : 'Contracts ', NAV_DeployContract : 'Deploy Contract ', NAV_DeployContract : 'Ota Käyttöön Sopimus ', NAV_ENS : 'ENS', NAV_GenerateWallet_alt : 'New Wallet ', NAV_GenerateWallet : 'Luo Lompakko ', NAV_Help : 'Apua ', NAV_InteractContract : 'Interact with Contract ', NAV_Multisig : 'Multisig ', NAV_MyWallets : 'Minun Lompakkoni ', NAV_Offline : 'Lähetä Offlinena ', NAV_SendEther : 'Lähetä Etheriä ja Tokeneita ', NAV_SendTokens : 'Lähetä Tokeneita ', NAV_SignMsg : 'Sign Message ', NAV_Swap : 'Swap ', NAV_ViewWallet : 'Tarkastele Lompakon Tietoja ', NAV_YourWallets : 'Sinun Lompakkosi ', /* General */ x_Access : 'Access ', x_AddessDesc : 'Your Address can also be known as you `Account #` or your `Public Key`. It is what you share with people so they can send you Ether or Tokens. Find the colorful address icon. Make sure it matches your paper wallet & whenever you enter your address somewhere. Saatat tuntea tämän "Tilinumeronasi" tai "Julkisena Salausavaimenasi". Tämä on se jonka jaat ihmisille, jotta he voivat lähettää sinulle ETHiä. Tuo kuvake on helppo tapa tunnistaa sinun osoitteesi. ', x_Address : 'Sinun osoitteesi ', x_Cancel : 'Peruuta ', x_CSV : 'CSV tiedosto (salaamaton) ', x_Download : 'Lataa ', x_Json : 'JSON Tiedosto (salaamaton) ', x_JsonDesc : 'Tämä on salaamaton JSON tiedosto yksityisestä salausavaimestasi. Tämä tarkoittaa että et tarvitse salasanaa mutta kuka tahansa joka löytää JSON tiedostosi saa pääsyn lompakkoosi ja sen sisältämään Etheriin ilman salasanaa. ', x_Keystore : 'Avainsäilö Tiedosto (UTC / JSON · Suositeltu · Salattu) ', x_Keystore2 : 'Avainsäilö Tiedosto (UTC / JSON) ', x_KeystoreDesc : 'Tämä Avainsäilö tiedosto vastaa sitä tiedostoformaattia jota Mist käyttävät, joten voit helposti importata sen tulevaisuudessa. Se on suositeltu tiedostomuoto ladata ja varmuuskopioida. ', x_MetaMask : 'MetaMask / Mist ', x_Mnemonic : 'Mnemonic Phrase ', x_ParityPhrase : 'Parity Phrase ', x_Password : 'Salasana ', x_Print : 'Tulosta Paperi Lompakko ', x_PrintDesc : 'ProTip: Klikkaa Tulosta ja tallenna tämä PDF:nä, vaikka et omistaisikaan tulostinta! ', x_PrintShort : 'Tulosta ', x_PrivKey : 'Yksityinen salausavain (salaamaton) ', x_PrivKey2 : 'Yksityinen salausavain ', x_PrivKeyDesc : 'Tämä on salaamaton versio sinun yksityisestä salausavaimestasi, tarkoittaen että salasanaa ei tarvita. Jos joku sattuisi löytämään sinun salaamattoman yksityisen salausavaimesi, he pääsisivät käsiksi sinun lompakkoosi ilman salasanaa. Tästä syystä salatut versiot ovat yleensä suositeltuja. ', x_Save : 'Tallenna ', x_TXT : 'TXT tiedosto (salaamaton) ', x_Wallet : 'Lompakko ', x_Wallet : 'Wallet ', /* Header */ MEW_Warning_1 : 'Tarkista URL aina ennen kuin avaat lompakkosi tai luot uuden lompakon. Varo tietojen-kalastelu sivustoja! ', CX_Warning_1 : 'Varmista että sinulla on **ulkoiset varmuuskopiot** kaikista lompakoista joita säilytät täällä. Monia asioita voi tapahtua joiden seurauksena voit menettää tietoja tässä Chrome Laajennuksessa, mukaan lukien laajennuksen asennuksen poistaminen tai uudelleenasennus. Tämä laajennus on keino jolla saat helpon pääsyn lompakkoosi, **ei** keino varmuuskopioida niitä. ', MEW_Tagline : 'Avoimen Lähdekoodin JavaScript Ether Lompakko ', CX_Tagline : 'Avoimen Lähdekoodin JavaScript Chrome Laajennus ', /* Footer */ FOOTER_1 : 'Avoimen lähdekoodin, javascript työkalu Ethereum lompakkojen luomista & varojen siirtoja varten. ', FOOTER_1b : 'Luonut ', FOOTER_2 : 'Lahjoituksia arvostetaan suuresti: ', FOOTER_3 : 'Lompakon luomisen tarjoaa ', FOOTER_4 : 'Vastuuvapauslauseke / Disclaimer ', /* Sidebar */ sidebar_AccountInfo : 'Tilin Tiedot ', sidebar_AccountAddr : 'Tilin Osoite ', sidebar_AccountBal : 'Tilin Saldo ', sidebar_TokenBal : 'Tokenien Saldo ', sidebar_Equiv : 'Vastaavat Arvot ', sidebar_TransHistory : 'Siirto Historia ', sidebar_donation : 'MyEtherWallet on ilmainen, avoimen lähdekoodin palvelu joka on omistautunut sinun yksityisyyteesi ja turvallisuuteesi. Mitä enemmän lahjoituksia me vastaanotamme, sitä enemmän aikaa me käytämme uusien toimintojen luomiseksi, kuunnellen teidän palautettanne ja antaen teille juuri sitä mitä te tahdotte. Me olemme vain kaksi ihmistä jotka koittavat muuttaa maailmaa. Auta meitä? ', sidebar_donate : 'Lahjoita ', sidebar_thanks : 'KIITOS!!! ', sidebar_DisplayOnTrezor : 'Display address on TREZOR', sidebar_DisplayOnLedger : 'Display address on Ledger', /* Decrypt Panel */ decrypt_Access : 'Kuinka haluaisit saada pääsyn lompakkoosi? ', decrypt_Title : 'Valitse yksityisen salausavaimesi muoto: ', decrypt_Select : 'Valitse Lompakko: ', /* Add Wallet */ ADD_Label_1 : 'Mitä tahtoisit tehdä? ', ADD_Radio_1 : 'Luo Uusi Lompakko ', ADD_Radio_2 : 'Valitse Lompakko Tiedostosi (Avainsäilö / JSON) ', ADD_Radio_2_alt : 'Valitse Lompakko Tiedostosi ', ADD_Radio_2_short : 'VALITSE LOMPAKKO TIEDOSTO... ', ADD_Radio_3 : 'Liitä/Kirjoita Yksityinen Salausavaimesi ', ADD_Radio_4 : 'Lisää Tili Jota Seurata ', ADD_Radio_5 : 'Paste Your Mnemonic ', ADD_Radio_5_Path : 'Select HD derivation path ', ADD_Radio_5_woTrezor : '(Jaxx, Metamask, Exodus, imToken)', ADD_Radio_5_withTrezor : '(Jaxx, Metamask, Exodus, imToken, TREZOR)', ADD_Radio_5_PathAlternative : '(Ledger)', ADD_Radio_5_PathTrezor : '(TREZOR)', ADD_Radio_5_PathCustom : 'Custom', ADD_Label_2 : 'Luo Kutsumanimi: ', ADD_Label_3 : 'Lompakkosi on salattu, ole hyvä ja syötä salasanasi ', ADD_Label_4 : 'Lisää Tili Jota Seurata ', ADD_Warning_1 : 'Voit lisätä minkä tahansa tilin jota "seurata" lompakkojen välilehdessä ilman yksityisen salausavaimesi lähettämistä. Tämä ** ei ** tarkoita että sinulla olisi pääsy tähän lompakkoon, tai että voit siirtää Etheriä siitä. ', ADD_Label_5 : 'Syötä Osoite ', ADD_Label_6 : 'Avaa Sinun Lompakkosi ', ADD_Label_6_short : 'Avaa ', ADD_Label_7 : 'Lisää Tili ', ADD_Label_8 : 'Password (optional): ', /* Generate Wallets */ GEN_desc : 'Jos tahdot luoda useita lompakoita, voit tehdä sen täältä ', GEN_Label_1 : 'Syötä vahva salasana (vähintään 9 merkkiä) ', GEN_Placeholder_1 : 'ÄLÄ unohda tallentaa tätä! ', GEN_SuccessMsg : 'Onnistui! Sinun lompakkosi on luotu. ', GEN_Label_2 : 'Tallenna Avainsäilö tai Yksityinen salausavaimesi. Älä unohda yllä olevaa salasanaasi. ', GEN_Label_3 : 'Tallenna Osoitteesi. ', GEN_Label_4 : 'Valinnainen: Tulosta paperi lompakkosi, tai säilö QR koodi versio. ', /* Bulk Generate Wallets */ BULK_Label_1 : 'Kuinka Monta Lompakkoa Luodaan ', BULK_Label_2 : 'Luo Lompakot ', BULK_SuccessMsg : 'Onnistui! Sinun lompakkosi on luotu. ', /* Sending Ether and Tokens */ SEND_addr : 'Osoitteeseen ', SEND_amount : 'Summa Joka Lähetetään ', SEND_amount_short : 'Summa ', SEND_custom : 'Mukautettu ', SEND_gas : 'Gas ', SEND_TransferTotal : 'Lähetä Koko Saldo ', SEND_generate : 'Luo Allekirjoitettu Siirto ', SEND_raw : 'Käsittelemätön Siirto ', SEND_signed : 'Allekirjoitettu Siirto ', SEND_trans : 'Lähetä Siirto ', SEND_custom : 'Add Custom Token ', SENDModal_Title : 'Varoitus! ', /* full sentence reads "You are about to send "10 ETH" to address "0x1234". Are you sure you want to do this? " */ SENDModal_Content_1 : 'Olet lähettämässä ', SENDModal_Content_2 : 'osoitteeseen ', SENDModal_Content_3 : 'Oletko varma että haluat tehdä tämän? ', SENDModal_Content_4 : 'HUOMAUTUS: Jos kohtaat virheen, sinun täytyy todennäköisesti lisätä ETHiä tilillesi kattaaksesi siirron vaatiman gasin hinnan. Gas maksetaan ETHeinä. ', SENDModal_No : 'En, vie minut pois täältä! ', SENDModal_Yes : 'Kyllä, olen varma! Toteuta siirto. ', /* Tokens */ TOKEN_Addr : 'Token Contract Osoite ', TOKEN_Symbol : 'Token Tunnus ', TOKEN_Dec : 'Desimaalit ', TOKEN_hide : 'Hide Tokens ', TOKEN_show : 'Show All Tokens ', /* Send Transaction */ TRANS_desc : 'Jos haluat lähettää Tokeneita, ole hyvä ja käytä "Lähetä Tokeneita" sivua. ', TRANS_warning : 'Jos käytät "Vain ETH" tai "Vain ETC" Toimintoja, niin lähetät sopimuksen kautta. Joillakin palveluilla on vaikeuksia hyväksyä näitä siirtoja. Lue lisää. ', TRANS_advanced : '+Edistynyt: Lisää Tietoja ', TRANS_data : 'Tiedot ', TRANS_gas : 'Gas Limit ', TRANS_sendInfo : 'Tavallinen siirto käyttäen 21000 gasia maksaa 0.000441 ETHiä. Me käytämme hieman-yli-minimin gasin hintaa 0.000000021 ETHiä varmistaaksemme että se louhitaan nopeasti. Me emme veloita siirto maksua. ', /* Send Transaction Modals */ TRANSModal_Title : '"Vain ETH" ja "Vain ETC" Siirrot ', TRANSModal_Content_0 : 'Huomautus erilaisista siirroista ja eri palveluista: ', TRANSModal_Content_1 : '**ETH (Tavallinen Siirto): ** Tämä luo oletusarvoisen siirron osoitteesta toiseen. Siinä on oletus gasina 21000. On todennäköistä että kaikki ETH joka lähetetään tällä tavalla, toistetaan ETC ketjussa. ', TRANSModal_Content_2 : '**Vain ETH: ** Tämä lähettää [Timon Rappin toiston suojaus sopimuksen kautta (kuten VB on suositellut)](https://blog.ethereum.org/2016/07/26/onward_from_the_hard_fork/) niin että sinä lähetät vain **ETH** ketjussa. ', TRANSModal_Content_3 : '**Only ETC: ** Tämä lähettää [Timon Rappin toiston suojaus sopimuksen kautta (kuten VB on suositellut)](https://blog.ethereum.org/2016/07/26/onward_from_the_hard_fork/) niin että sinä lähetät vain **ETC** ketjussa. ', TRANSModal_Content_4 : '**Coinbase & ShapeShift: ** Lähetä ainoastaan käyttäen Tavallista Siirtoa. Jos lähetät käyttäen "Vain" sopimuksia, sinun täytyy olla yhteydessä heidän asiakastukensa henkilöstöön jotta he joko manuaalisesti lisäävät sinun saldosi tai palauttavat rahasi. [Voit kokeilla myös ShapeShiftin "split" työkalua.](https://split.shapeshift.io/) ', TRANSModal_Content_5 : '**Kraken & Poloniex:** Ei tunnettuja ongelmia. Käytä mitä vain. ', TRANSModal_Yes : 'Siistiä, nyt ymmärrän. ', TRANSModal_No : 'Voi ei, olen entistä enemmän hämilläni. Auttakaa minua. ', /* Offline Transaction */ OFFLINE_Title : 'Luo ja Lähetä Offline Siirto ', OFFLINE_Desc : 'Offline siirtojen luonti voidaan tehdä kolmella eri vaiheella. Teet vaiheet 1 ja 3 käyttäen verkkoon yhdistettyä (online) tietokonetta, ja vaiheen 2 käyttäen offline/airgappattua tietokonetta. Tämä varmistaa ettei sinun yksityinen salausavaimesi ole kosketuksissa internettiin yhdistetyn laitteen kanssa. ', OFFLLINE_Step1_Title : 'Vaihe 1: Luo Tiedot (Online Tietokone) ', OFFLINE_Step1_Button : 'Luo Tiedot ', OFFLINE_Step1_Label_1 : 'Osoitteesta ', OFFLINE_Step1_Label_2 : 'Huomautus: Tämä on MISTÄ osoitteesta, ei MIHIN osoitteeseen. Nonce luodaan osoitteesta josta siirto on peräisin. Jos käytetään airgappattua tietokonetta, se olisi kylmä-varasto tilin osoite. ', OFFLINE_Step2_Title : 'Vaihe 2: Luo Siirto (Offline Tietokone) ', OFFLINE_Step2_Label_1 : 'Osoitteeseen ', OFFLINE_Step2_Label_2 : 'Arvo / Määrä Joka Lähetetään ', OFFLINE_Step2_Label_3 : 'Gasin hinta ', OFFLINE_Step2_Label_3b : 'Tämä näytettiin kohdassa Vaihe 1 sinun verkkoon yhdistetyssä tietokoneessasi. ', OFFLINE_Step2_Label_4 : 'Gas Raja ', OFFLINE_Step2_Label_4b : '21000 on oletusarvoinen gas raja. Kun lähetät sopimuksiin tai lisäät tietoa, saattaa tämä määrä joutua olemaan eri. Kaikki käyttämätön gas palautetaan sinulle. ', OFFLINE_Step2_Label_5 : 'Nonce ', OFFLINE_Step2_Label_5b : 'Tämä näytettiin kohdassa Vaihe 1 sinun verkkoon yhdistetyssä tietokoneessasi. ', OFFLINE_Step2_Label_6 : 'Tiedot ', OFFLINE_Step2_Label_6b : 'Tämä on valinnainen. Tietoja käytetään usein kun varoja lähetetään sopimuksiin. ', OFFLINE_Step2_Label_7 : 'Syötä / Valitse Yksityinen salausavaimesi / JSON. ', OFFLINE_Step3_Title : 'Vaihe 3: Lähetä / Julkaise Siirto (Verkkoon yhdistetty (online) tietokone) ', OFFLINE_Step3_Label_1 : 'Liitä allekirjoitettu siirto Vaiheesta 2 tähän ja paina "LÄHETÄ SIIRTO" nappia. ', /* Deploy Contracts */ DEP_generate : 'Generoi Bytecode ', DEP_generated : 'Generoitu Bytecode ', DEP_signtx : 'Allekirjoita Siirto ', DEP_interface : 'Generoitu Rajapinta ', /* My Wallet */ MYWAL_Nick : 'Lompakon Kutsumanimi ', MYWAL_Address : 'Lompakon Osoite ', MYWAL_Bal : 'Saldo ', MYWAL_Edit : 'Muokkaa ', MYWAL_View : 'Katso ', MYWAL_Remove : 'Poista ', MYWAL_RemoveWal : 'Poista Lompakko: ', MYWAL_WatchOnly : 'Sinun Seuraa-Ainoastaan Tilisi ', MYWAL_Viewing : 'Tarkastellaan Lompakkoa ', MYWAL_Hide : 'Piilota Lompakon Tiedot ', MYWAL_Edit_2 : 'Muokkaa Lompakkoa ', MYWAL_Name : 'Lompakon Nimi ', MYWAL_Content_1 : 'Varoitus! Olet poistamassa lompakkoasi. ', MYWAL_Content_2 : 'Varmista että olet **tallentanut tähän lompakkoon liittyvät yksityisen salausavaimesi/JSON tiedostosi ja salasanasi** ennen kuin poistat sen. ', MYWAL_Content_3 : 'Jos tahdot käyttää tätä lompakkoa MyEtherWallet CX:si kanssa tulevaisuudessa, sinun täytyy manuaalisesti uudelleen-lisätä se käyttäen yksityistä salausavaintasi/JSONia ja salasanaa. ', /* View Wallet Details */ VIEWWALLET_Subtitle : 'Tämä antaa sinun ladata eri versiota yksityisistä salausavaimistasi ja uudelleen-tulostaa paperi lompakkosi. Saatat tahtoa tehdä tämän [tuodaksesi sinun tilisi Gethiin/Mistiin](http://ethereum.stackexchange.com/questions/465/how-to-import-a-plain-private-key-into-geth/). Jos haluat tarkistaa saldosi, me suosittelemme käyttämään blockchain exploreria kuten [etherscan.io](https://etherscan.io/). ', VIEWWALLET_Subtitle_Short : 'Tämä antaa sinun ladata eri versiota yksityisistä salausavaimistasi ja uudelleen-tulostaa paperi lompakkosi. ', VIEWWALLET_SuccessMsg : 'Onnistui! Tässä ovat lompakkosi yksityiskohdat. ', VIEWWALLET_ShowPrivKey : '(show)', VIEWWALLET_HidePrivKey : '(hide)', /* Chrome Extension */ CX_error_1 : 'Sinulla ei ole lompakkoja tallennettuna. Klikkaa ["Lisää Lompakko"](/cx-wallet.html#add-wallet) lisätäksesi! ', CX_quicksend : 'PikaLähetä ', // if no appropriate translation, just use "Send" /* Node Switcher */ NODE_Title : 'Set Up Your Custom Node', NODE_Subtitle : 'To connect to a local node...', NODE_Warning : 'Your node must be HTTPS in order to connect to it via MyEtherWallet.com. You can [download the MyEtherWallet repo & run it locally](https://github.com/kvhnuke/etherwallet/releases/latest) to connect to any node. Or, get free SSL certificate via [LetsEncrypt](https://letsencrypt.org/)', NODE_Name : 'Node Name', NODE_Port : 'Node Port', NODE_CTA : 'Save & Use Custom Node', /* Contracts */ CONTRACT_Title : 'Contract Address ', CONTRACT_Title_2 : 'Select Existing Contract ', CONTRACT_Json : 'ABI / JSON Interface ', CONTRACT_Interact_Title : 'Read / Write Contract ', CONTRACT_Interact_CTA : 'Select a function ', CONTRACT_ByteCode : 'Byte Code ', CONTRACT_Read : 'READ ', CONTRACT_Write : 'WRITE ', DEP_generate : 'Generate Bytecode ', DEP_generated : 'Generated Bytecode ', DEP_signtx : 'Sign Transaction ', DEP_interface : 'Generated Interface ', /* Swap / Exchange */ SWAP_rates : "Current Rates ", SWAP_init_1 : "I want to swap my ", SWAP_init_2 : " for ", // "I want to swap my X ETH for X BTC" SWAP_init_CTA : "Let's do this! ", // or "Continue" SWAP_information : "Your Information ", SWAP_send_amt : "Amount to send ", SWAP_rec_amt : "Amount to receive ", SWAP_your_rate : "Your rate ", SWAP_rec_add : "Your Receiving Address ", SWAP_start_CTA : "Start Swap ", SWAP_ref_num : "Your reference number ", SWAP_time : "Time remaining to send ", SWAP_elapsed : "Time elapsed since sent ", SWAP_progress_1 : "Order Initiated ", SWAP_progress_2 : "Waiting for your ", // Waiting for your BTC... SWAP_progress_3 : "Received! ", // ETH Received! SWAP_progress_4 : "Sending your {{orderResult.output.currency}} ", SWAP_progress_5 : "Order Complete ", SWAP_order_CTA : "Please send ", // Please send 1 ETH... SWAP_unlock : "Unlock your wallet to send ETH or Tokens directly from this page. ", /* Sign Message */ MSG_message : 'Message ', MSG_date : 'Date ', MSG_signature : 'Signature ', MSG_verify : 'Verify Message ', MSG_info1 : 'Include the current date so the signature cannot be reused on a different date. ', MSG_info2 : 'Include your nickname and where you use the nickname so someone else cannot use it. ', MSG_info3 : 'Include a specific reason for the message so it cannot be reused for a different purpose. ', /* Mnemonic */ MNEM_1 : 'Please select the address you would like to interact with. ', MNEM_2 : 'Your single HD mnemonic phrase can access a number of wallets / addresses. Please select the address you would like to interact with at this time. ', MNEM_more : 'More Addresses ', MNEM_prev : 'Previous Addresses ', /* Hardware wallets */ x_Ledger : 'Ledger Wallet ', ADD_Ledger_1 : 'Connect your Ledger Wallet ', ADD_Ledger_2 : 'Open the Ethereum application (or a contract application) ', ADD_Ledger_2_Exp : 'Open the Expanse application (or a contract application) ', ADD_Ledger_2_Ubq : 'Open the Ubiq application (or a contract application) ', ADD_Ledger_3 : 'Verify that Browser Support is enabled in Settings ', ADD_Ledger_4 : 'If no Browser Support is found in settings, verify that you have [Firmware >1.2](https://www.ledgerwallet.com/apps/manager) ', ADD_Ledger_0a : 'Please use MyEtherWallet on a secure (SSL / HTTPS) connection to connect. ', ADD_Ledger_0b : 'Re-open MyEtherWallet using [Chrome](https://www.google.com/chrome/browser/desktop/) or [Opera](https://www.opera.com/) ', ADD_Ledger_scan : 'Connect to Ledger Wallet ', ADD_MetaMask : 'Connect to MetaMask ', x_Trezor : 'TREZOR ', ADD_Trezor_scan : 'Connect to TREZOR ', ADD_Trezor_select : 'This is a TREZOR seed ', x_DigitalBitbox : 'Digital Bitbox ', ADD_DigitalBitbox_0a : 'Re-open MyEtherWallet on a secure (SSL) connection ', ADD_DigitalBitbox_0b : 'Re-open MyEtherWallet using [Chrome](https://www.google.com/chrome/browser/desktop/) or [Opera](https://www.opera.com/) ', ADD_DigitalBitbox_scan : 'Connect your Digital Bitbox ', x_Secalot : 'Secalot ', ADD_Secalot_0a : 'Re-open MyEtherWallet on a secure (SSL) connection ', ADD_Secalot_0b : 'Re-open MyEtherWallet using [Chrome](https://www.google.com/chrome/browser/desktop/) or [Opera](https://www.opera.com/) ', ADD_Secalot_scan : 'Connect your Secalot ', /* Chrome Extension */ CX_error_1 : 'You don\'t have any wallets saved. Click ["Add Wallet"](/cx-wallet.html#add-wallet) to add one! ', CX_quicksend : 'QuickSend ', // if no appropriate translation, just use "Send" /* Misc */ FOOTER_1b : 'Created by ', FOOTER_4 : 'Disclaimer ', ERROR_0 : '(error_01) Ole hyvä ja syötä kelpaava summa. Please enter a valid amount.', // 0 ERROR_1 : '(error_02) Salasanasi pitää olla vähintään 9 merkkiä pitkä. Ole hyvä ja varmista että käytät vahvaa salasanaa. Your password must be at least 9 characters. Please ensure it is a strong password.', // 1 ERROR_2 : '(error_03) Pahoittelut! Emme tunnista tämänlaista lompakko tiedostoa. Sorry! We don\'t recognize this type of wallet file.', // 2 ERROR_3 : '(error_04) Tämä ei ole validi lompakko tiedosto. This is not a valid wallet file.', // 3 ERROR_4 : '(error_05) Tätä yksikköä ei ole olemassa, ole hyvä ja käytä jotain seuraavista yksiköistä This unit doesn\'t exists, please use the one of the following units', // 4 ERROR_5 : '(error_06) Virheellinen osoite. Please enter a valid address.', // 5 ERROR_6 : '(error_07) Virheellinen salasana. Please enter a valid password.', // 6 ERROR_7 : '(error_08) Virheellinen summa. Please enter valid decimals (Must be an integer. Try 0-18.)', // 7 ERROR_8 : '(error_09) Virheellinen gas raja.Please enter a valid gas limit (Must be an integer. Try 21000-4000000.)', // 8 ERROR_9 : '(error_10) Virheellinen tieto arvo. Please enter a valid data value (Must be hex.)', // 9 ERROR_10 : '(error_11) Virheellinen gasin määrä. Try 20 GWEI / 20000000000 WEI.) Please enter a valid gas price. (Must be an integer. Try 20 GWEI / 20000000000 WEI.)', ERROR_11 : '(error_12) Virheellinen nonce. (Must be integer.) ', ERROR_12 : '(error_13) Virheellinen allekirjoitettu siirto. Invalid signed transaction.', // 12 ERROR_13 : '(error_14) Lompakko tällä kutsumanimellä on jo olemassa. A wallet with this nickname already exists.', // 13 ERROR_14 : '(error_15) Lompakkoa ei löytynyt. Wallet not found.', // 14 ERROR_15 : '(error_16) Ei näytä että ehdotusta tällä ID:llä olisi vielä olemassa tai tapahtui virhe ehdotusta luettaessa. Whoops. It doesn\'t look like a proposal with this ID exists yet or there is an error reading this proposal.', // 15 - NOT USED ERROR_16 : '(error_17) Lompakko jolla on tämä osoite on jo muistissa. Ole hyvä ja tarkista oma lompakko sivusi. A wallet with this address already exists in storage. Please check your wallets page.', // 16 ERROR_17 : '(error_18) Riittämätön saldo gas * hinta + arvo. Sinulla täytyy olla vähintään 0.01 ETHiä tililläsi kattaaksesi gasin hinnan. Ole hyvä ja lisää hieman ETHiä ja kokeile uudelleen. Insufficient balance. Your gas limit * gas price + amount to send exceeds your current balance. Send more ETH to your account or use the "Send Entire Balance" button. If you believe this is in error, try pressing generate again. Required (d+) and got: (d+). [Learn More.](https://kb.myetherwallet.com/transactions/transactions-not-showing-or-pending.html)', // 17 ERROR_18 : '(error_19) Kaikki gas käytettäisiin tässä siirrossa. Tämä tarkoittaa että olet jo äänestänyt tässä ehdotuksessa tai debaatti aika on jo päättynyt. All gas would be used on this transaction. This means you have already voted on this proposal or the debate period has ended.', // 18 ERROR_19 : '(error_20) Virheellinen merkki Please enter a valid symbol', // 19 ERROR_20 : '(error_21) Not a valid ERC-20 token', // 20 ERROR_21 : '(error_22) Could not estimate gas. There are not enough funds in the account, or the receiving contract address would throw an error. Feel free to manually set the gas and proceed. The error message upon sending may be more informative.', // 21 ERROR_22 : '(error_23) Please enter a valid node name', // 22 ERROR_23 : '(error_24) Please enter a valid URL. If you are on https, your URL must be https', // 23 ERROR_24 : '(error_25) Please enter a valid port.', // 24 ERROR_25 : '(error_26) Please enter a valid chain ID.', // 25 ERROR_26 : '(error_27) Please enter a valid ABI.', // 26 ERROR_27 : '(error_28) Minimum amount: 0.01. Max amount:', // 27 ERROR_28 : '(error_29) You need this `Keystore File + Password` or the `Private Key` (next page) to access this wallet in the future. ', // 28 ERROR_29 : '(error_30) Please enter a valid user and password.', // 29 ERROR_30 : '(error_31) Please enter a valid name (7+ characters, limited punctuation)', // 30 ERROR_31 : '(error_32) Please enter a valid secret phrase.', // 31 ERROR_32 : '(error_33) Could not connect to the node. Refresh your page, try a different node (top-right corner), check your firewall settings. If custom node, check your configs.', // 32 ERROR_33 : '(error_34) The wallet you have unlocked does not match the owner\'s address.', // 33 ERROR_34 : '(error_35) The name you are attempting to reveal does not match the name you have entered.', // 34 ERROR_35 : '(error_36) Input address is not checksummed. <a href="https://kb.myetherwallet.com/addresses/what-does-checksummed-mean.html" target="_blank" rel="noopener noreferrer">What does that mean?</a>', // 35 ERROR_36 : '(error_37) Please enter a valid TX hash', // 36 ERROR_37 : '(error_38) Please enter valid hex string. Hex only contains: 0x, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, a, b, c, d, e, f', // 37 ERROR_38 : '(error_39) Offer must have either price or reserve set to more than 0', // 38 ERROR_39 : '(error_40) Bid must be more than the specified minimum', // 39 GETH_Balance : '(geth-01) Riittämätön saldo. Insufficient balance. Your gas limit * gas price + amount to send exceeds your current balance. Send more ETH to your account or use the "Send Entire Balance" button. If you believe this is in error, try pressing generate again. Required (d+) and got: (d+). [Learn More.](https://kb.myetherwallet.com/transactions/transactions-not-showing-or-pending.html)', GETH_Cheap : '(geth-02) Gasin hinta liian matala hyväksyttäväksi. Gas price too low for acceptance. Try raising the gas price to 21 GWEI via the dropdown in top-right.', GETH_GasLimit : '(geth-03) Ylittää blockin gas rajan. Exceeds block gas limit. Transaction cost exceeds current gas limit. Limit: (d+), got: (d+). Please lower the gas limit to 21000 (for sending) or 200000 (for sending tokens or contracts) and try again. [Learn More](https://kb.myetherwallet.com/gas/what-is-gas-ethereum.html)', GETH_InsufficientFunds : '(geth-04) Riittämätön saldo gas * hinta + arvo. Insufficient balance. Your gas limit * gas price + amount to send exceeds your current balance. Send more ETH to your account or use the "Send Entire Balance" button. If you believe this is in error, try pressing generate again. Required (d+) and got: (d+). [Learn More.](https://kb.myetherwallet.com/transactions/transactions-not-showing-or-pending.html)', GETH_IntrinsicGas : '(geth-05) Olennainen gas liian pieni. Intrinsic gas too low. Try raising the gas price to 21 GWEI via the dropdown in top-right or the gas limit to 21000 (for sending) or 200000 (for sending tokens or contracts) and try again.', GETH_InvalidSender : '(geth-06) Virheellinen lähettäjä. Invalid sender.', GETH_NegativeValue : '(geth-07) Negatiivinen arvo. Negative value.', GETH_Nonce : "(geth-08) Nonce liian pieni. This TX's [nonce](https://kb.myetherwallet.com/transactions/what-is-nonce.html) is too low. Try incrementing the nonce by pressing the Generate button again, or [replace the pending transaction](https://kb.myetherwallet.com/transactions/check-status-of-ethereum-transaction.html).", GETH_NonExistentAccount : '(geth-09) Tiliä ei ole olemassa tai tilin saldo liian pieni. Account does not exist or account balance too low', PARITY_AlreadyImported : "(parity-01) A transaction with the same hash was already imported. It was probably already broadcast. To avoid duplicate transactions, check your address on [etherscan.io](https://etherscan.io) & wait 10 minutes before attempting to send again. [Learn More.](https://kb.myetherwallet.com/transactions/transactions-not-showing-or-pending.html)", PARITY_GasLimitExceeded : "(parity-02) Transaction cost exceeds current gas limit. Limit: (d+), got: (d+). Please lower the gas limit to 21000 (for sending) or 200000 (for sending tokens or contracts) and try again. [Learn More](https://kb.myetherwallet.com/gas/what-is-gas-ethereum.html)", PARITY_InsufficientBalance : "(parity-03) Insufficient balance. The account you tried to send transaction from does not have enough funds. If you believe this is in error, try using the 'Send Entire Balance' button, or pressing generate again. Required (d+) and got: (d+). [Learn More.](https://kb.myetherwallet.com/transactions/transactions-not-showing-or-pending.html)", PARITY_InsufficientGasPrice : "(parity-04) There is another transaction with same nonce in the queue, or the transaction fee is too low. Try incrementing the nonce by clicking the Generate button again. [Learn More.](https://kb.myetherwallet.com/transactions/transactions-not-showing-or-pending.html)", PARITY_InvalidGasLimit : "(parity-05) Supplied gas limit is beyond limit. Try lowering the gas limit to 21000. [Learn More.](https://kb.myetherwallet.com/gas/what-is-gas-ethereum.html)", PARITY_LimitReached : "(parity-06) There are too many transactions in the queue. Your transaction was dropped due to limit. Try increasing the gas price. [Learn More.](https://kb.myetherwallet.com/transactions/transactions-not-showing-or-pending.html)", PARITY_Old : "(parity-07) There is already a transaction with this [nonce](https://kb.myetherwallet.com/transactions/what-is-nonce.html). Try incrementing the nonce by pressing the Generate button again, or [replace the pending transaction](https://kb.myetherwallet.com/transactions/check-status-of-ethereum-transaction.html).", PARITY_TooCheapToReplace : "(parity-08) TX Fee is too low. It does not satisfy your node's minimal fee (minimal: (d+), got: (d+)). Try increasing the gas price and/or gas limit. [Learn More.](https://kb.myetherwallet.com/transactions/transactions-not-showing-or-pending.html)", SUCCESS_1 : 'Validi osoite ', SUCCESS_2 : 'Lompakon salaus onnistuneesti purettu ', SUCCESS_3 : 'Your TX has been broadcast to the network. This does not mean it has been mined & sent. During times of extreme volume, it may take 3+ hours to send. 1) Check your TX below. 2) If it is pending for hours or disappears, use the Check TX Status Page to replace. 3) Use [ETH Gas Station](https://ethgasstation.info/) to see what gas price is optimal. 4) Save your TX Hash in case you need it later: ', //'Siirto lähetetty. TX Hash ', SUCCESS_4 : 'Lompakkosi lisätty onnistuneesti ', SUCCESS_5 : 'Valittu Tiedosto ', SUCCESS_6 : 'You are successfully connected ', SUCCESS_7 : 'Message Signature Verified', WARN_Send_Link : 'You arrived via a link that has the address, value, gas, data fields, or transaction type (send mode) filled in for you. You can change any information before sending. Unlock your wallet to get started. ', /* Tranlsation Info */ translate_version : '0.4 ', Translator_Desc : 'Kiitos kääntäjillemme... ', TranslatorName_1 : '[Smokyish](https://vintage.myetherwallet.com/?gaslimit=21000&to=0xac9a2c1dd946da64c0dc8e70cec2cfb14304fd4f&value=1.0#send-transaction)', TranslatorAddr_1 : '', /* Translator 1 : Insert Comments Here */ TranslatorName_2 : '', TranslatorAddr_2 : '', /* Translator 2 : Insert Comments Here */ TranslatorName_3 : '', TranslatorAddr_3 : '', /* Translator 3 : Insert Comments Here */ TranslatorName_4 : '', TranslatorAddr_4 : '', /* Translator 4 : Insert Comments Here */ TranslatorName_5 : '', TranslatorAddr_5 : '', /* Translator 5 : Insert Comments Here */ /* Help - Nothing after this point has to be translated. If you feel like being extra helpful, go for it. */ HELP_Warning : 'If you created a wallet -or- downloaded the repo before **Dec. 31st, 2015**, please check your wallets &amp; download a new version of the repo. Click for details. ', HELP_Desc : 'Do you see something missing? Have another question? [Get in touch with us](mailto:support@myetherwallet.com), and we will not only answer your question, we will update this page to be more useful to people in the future! ', HELP_Remind_Title : 'Some reminders ', HELP_Remind_Desc_1 : '**Ethereum, MyEtherWallet.com & MyEtherWallet CX, and some of the underlying Javascript libraries we use are under active development.** While we have thoroughly tested & tens of thousands of wallets have been successfully created by people all over the globe, there is always the remote possibility that something unexpected happens that causes your ETH to be lost. Please do not invest more than you are willing to lose, and please be careful. If something were to happen, we are sorry, but **we are not responsible for the lost Ether**. ', HELP_Remind_Desc_2 : 'MyEtherWallet.com & MyEtherWallet CX are not "web wallets". You do not create an account or give us your Ether to hold onto. All data never leaves your computer/your browser. We make it easy for you to create, save, and access your information and interact with the blockchain. ', HELP_Remind_Desc_3 : 'If you do not save your private key & password, there is no way to recover access to your wallet or the funds it holds. Back them up in multiple physical locations &ndash; not just on your computer! ', HELP_0_Title : '0) I\'m new. What do I do? ', HELP_0_Desc_1 : 'MyEtherWallet gives you the ability to generate new wallets so you can store your Ether yourself, not on an exchange. This process happens entirely on your computer, not our servers. Therefore, when you generate a new wallet, **you are responsible for safely backing it up**. ', HELP_0_Desc_2 : 'Create a new wallet. ', HELP_0_Desc_3 : 'Back the wallet up. ', HELP_0_Desc_4 : 'Verify you have access to this new wallet and have correctly saved all necessary information. ', HELP_0_Desc_5 : 'Transfer Ether to this new wallet. ', HELP_1_Title : '1) How do I create a new wallet? ', HELP_1_Desc_1 : 'Go to the "Generate Wallet" page. ', HELP_1_Desc_2 : 'Go to the "Add Wallet" page & select "Generate New Wallet" ', HELP_1_Desc_3 : 'Enter a strong password. If you think you may forget it, save it somewhere safe. You will need this password to send transactions. ', HELP_1_Desc_4 : 'Click "GENERATE". ', HELP_1_Desc_5 : 'Your wallet has now been generated. ', HELP_2a_Desc_1 : 'You should always back up your wallet externally and in multiple physical locations - like on a USB drive and/or a piece of paper. ', HELP_2a_Desc_2 : 'Save the address. You can keep it to yourself or share it with others. That way, others can transfer ether to you. ', HELP_2a_Desc_3 : 'Save versions of the private key. Do not share it with anyone else. Your private key is necessary when you want to access your Ether to send it! There are 3 types of private keys: ', HELP_2a_Desc_4 : 'Place your address, versions of the private key, and the PDF version of your paper wallet in a folder. Save this on your computer and a USB drive. ', HELP_2a_Desc_5 : 'Print the wallet if you have a printer. Otherwise, write down your private key and address on a piece of paper. Store this as a secure location, separate from your computer and the USB drive. ', HELP_2a_Desc_6 : 'Keep in mind, you must prevent loss of the keys and password due to loss or failure of you hard drive failure, or USB drive, or piece of paper. You also must keep in mind physical loss / damage of an entire area (think fire or flood). ', HELP_2b_Title : '2b) How do I safely / offline / cold storage with MyEtherWallet? ', HELP_2b_Desc_1 : 'Go to [https://github.com/kvhnuke/etherwallet/releases/latest](https://github.com/kvhnuke/etherwallet/releases/latest). ', HELP_2b_Desc_2 : 'Click on `etherwallet-vX.X.X.X.zip`. ', HELP_2b_Desc_3 : 'Move zip to an airgapped computer. ', HELP_2b_Desc_4 : 'Unzip it and double-click `index.html`. ', HELP_2b_Desc_5 : 'Generate a wallet with a strong password. ', HELP_2b_Desc_6 : 'Save the address. Save versions of the private key. Save the password if you might not remember it forever. ', HELP_2b_Desc_7 : 'Store these papers / USBs in multiple physically separate locations. ', HELP_2b_Desc_8 : 'Go to the "View Wallet Info" page and type in your private key / password to ensure they are correct and access your wallet. Check that the address you wrote down is the same. ', HELP_3_Title : '3) How do I verify I have access to my new wallet? ', HELP_3_Desc_1 : '**Before you send any Ether to your new wallet**, you should ensure you have access to it. ', HELP_3_Desc_2 : 'Navigate to the "View Wallet Info" page. ', HELP_3_Desc_3 : 'Navigate to the MyEtherWallet.com "View Wallet Info" page. ', HELP_3_Desc_4 : 'Select your wallet file -or- your private key and unlock your wallet. ', HELP_3_Desc_5 : 'If the wallet is encrypted, a text box will automatically appear. Enter the password. ', HELP_3_Desc_6 : 'Click the "Unlock Wallet" button. ', HELP_3_Desc_7 : 'Your wallet information should show up. Find your account address, next to a colorful, circular icon. This icon visually represents your address. Be certain that the address is the address you have saved to your text document and is on your paper wallet. ', HELP_3_Desc_8 : 'If you are planning on holding a large amount of ether, we recommend that send a small amount of ether from new wallet before depositing a large amount. Send 0.001 ether to your new wallet, access that wallet, send that 0.001 ether to another address, and ensure everything works smoothly. ', HELP_4_Title : '4) How do I send Ether from one wallet to another? ', HELP_4_Desc_1 : 'If you plan to move a large amount of ether, you should test sending a small amount to your wallet first to ensure everything goes as planned. ', HELP_4_Desc_2 : 'Navigate to the "Lähetä Etheriä ja Tokeneita" page. ', HELP_4_Desc_3 : 'Select your wallet file -or- your private key and unlock your wallet. ', HELP_4_Desc_4 : 'If the wallet is encrypted, a text box will automatically appear. Enter the password. ', HELP_4_Desc_5 : 'Click the "Unlock Wallet" button. ', HELP_4_Desc_6 : 'Enter the address you would like to send to in the "To Address:" field. ', HELP_4_Desc_7 : 'Enter the amount you would like to send. You can also click the "Send Entire Balance" link if you would like the transfer the entire balance. ', HELP_4_Desc_9 : 'Click "Generate Transaction". ', HELP_4_Desc_10 : 'A couple more fields will appear. This is your browser generating the transaction. ', HELP_4_Desc_11 : 'Click the blue "Send Transaction" button below that. ', HELP_4_Desc_12 : 'A pop-up will appear. Verify that the amount and the address you are sending to are correct. Then click "Yes, I am sure! Make transaction." button. ', HELP_4_Desc_13 : 'The transaction will be submitted. The TX Hash will display. You can click that TX Hash to see it on the blockchain. ', HELP_4CX_Title : '4) How do I send Ether using MyEtherWallet CX? ', HELP_4CX_Desc_1 : 'First, you need to add a wallet. Once you have done that, you have 2 options: the "QuickSend" functionality from the Chrome Extension icon or the "Lähetä Etheriä ja Tokeneita" page. ', HELP_4CX_Desc_2 : 'QuickSend: ', HELP_4CX_Desc_3 : 'Click the Chrome Extension Icon. ', HELP_4CX_Desc_4 : 'Click the "QuickSend" button. ', HELP_4CX_Desc_5 : 'Select the wallet you wish to send from. ', HELP_4CX_Desc_6 : 'Enter the address you would like to send to in the "To Address:" field. ', HELP_4CX_Desc_7 : 'Enter the amount you would like to send. You can also click the "Send Entire Balance" link if you would like the transfer the entire balance. ', HELP_4CX_Desc_8 : 'Click "Send Transaction". ', HELP_4CX_Desc_9 : 'Verify the address and the amount you are sending is correct. ', HELP_4CX_Desc_10 : 'Enter the password for that wallet. ', HELP_4CX_Desc_11 : 'Click "Send Transaction." ', HELP_4CX_Desc_12 : 'Using "Lähetä Etheriä ja Tokeneita" Page ', HELP_5_Title : '5) How do I run MyEtherWallet.com offline/locally? ', HELP_5_Desc_1 : 'You can run MyEtherWallet.com on your computer instead of from the GitHub servers. You can generate a wallet completely offline and send transactions from the "Offline Transaction" page. ', HELP_5_Desc_7 : 'MyEtherWallet.com is now running entirely on your computer. ', HELP_5_Desc_8 : 'In case you are not familiar, you need to keep the entire folder in order to run the website, not just `index.html`. Don\'t touch or move anything around in the folder. If you are storing a backup of the MyEtherWallet repo for the future, we recommend just storing the ZIP so you can be sure the folder contents stay intact. ', HELP_5_Desc_9 : 'As we are constantly updating MyEtherWallet.com, we recommend you periodically update your saved version of the repo. ', HELP_5CX_Title : '5) How can I install this extension from the repo instead of the Chrome Store? ', HELP_5CX_Desc_2 : 'Click on `chrome-extension-vX.X.X.X.zip` and unzip it. ', HELP_5CX_Desc_3 : 'Go to Google Chrome and find you settings (in the menu in the upper right). ', HELP_5CX_Desc_4 : 'Click "Extensions" on the left. ', HELP_5CX_Desc_5 : 'Check the "Developer Mode" button at the top of that page. ', HELP_5CX_Desc_6 : 'Click the "Load unpacked extension..." button. ', HELP_5CX_Desc_7 : 'Navigate to the now-unzipped folder that you downloaded earlier. Click "select". ', HELP_5CX_Desc_8 : 'The extension should now show up in your extensions and in your Chrome Extension bar. ', HELP_7_Title : '7) How do I send Tokens & add custom tokens? ', HELP_7_Desc_0 : '[Ethplorer.io](https://ethplorer.io/) is a great way to explore tokens and find the decimals of a token. ', HELP_7_Desc_1 : 'Navigate to the "Lähetä Etheriä ja Tokeneita" page. ', HELP_7_Desc_2 : 'Unlock your wallet. ', HELP_7_Desc_3 : 'Enter the address you would like to send to in the "To Address:" field. ', HELP_7_Desc_4 : 'Enter the amount you would like to send. ', HELP_7_Desc_5 : 'Select which token you would like to send. ', HELP_7_Desc_6 : 'If you do not see the token listed: ', HELP_7_Desc_7 : 'Click "Custom". ', HELP_7_Desc_8 : 'Enter the address, name, and decimals of the token. These are provided by the developers of the token and are also needed when you "Add a Watch Token" to Mist. ', HELP_7_Desc_9 : 'Click "Save". ', HELP_7_Desc_10 : 'You can now send that token as well as see it\'s balance in the sidebar. ', HELP_7_Desc_11 : 'Click "Generate Transaction". ', HELP_7_Desc_12 : 'A couple more fields will appear. This is your browser generating the transaction. ', HELP_7_Desc_13 : 'Click the blue "Send Transaction" button below that. ', HELP_7_Desc_14 : 'A pop-up will appear. Verify that the amount and the address you are sending to are correct. Then click "Yes, I am sure! Make transaction." button. ', HELP_7_Desc_15 : 'The transaction will be submitted. The TX Hash will display. You can click that TX Hash to see it on the blockchain. ', HELP_8_Title : '8) What happens if your site goes down? ', HELP_8_Desc_1 : 'MyEtherWallet is not a web wallet. You don\'t have a login and nothing ever gets saved to our servers. It is simply an interface that allows you interact with the blockchain. ', HELP_8_Desc_2 : 'If MyEtherWallet.com goes down, you would have to find another way (like geth or Ethereum Wallet / Mist) to do what we are doing. But you wouldn\'t have to "get" your Ether out of MyEtherWallet because it\'s not in MyEtherWallet. It\'s in whatever wallet your generated via our site. ', HELP_8_Desc_3 : 'You can import your unencrypted private key and your Geth/Mist Format (encrypted) files directly into geth / Ethereum Wallet / Mist very easily now. See question #12 below. ', HELP_8_Desc_4 : 'In addition, the likelihood of us taking MyEtherWallet down is slim to none. It costs us almost nothing to maintain as we aren\'t storing any information. If we do take the domain down, it still is, and always will be, publicly available at [https://github.com/kvhnuke/etherwallet](https://github.com/kvhnuke/etherwallet/tree/gh-pages). You can download the ZIP there and run it locally. ', HELP_8CX_Title : '8) What happens if MyEtherWallet CX disappears? ', HELP_8CX_Desc_1 : 'First, all data is saved on your computer, not our servers. I know it can be confusing, but when you look at the Chrome Extension, you are NOT looking at stuff saved on our servers somewhere - it\'s all saved on your own computer. ', HELP_8CX_Desc_2 : 'That said, it is **very important** that you back up all your information for any new wallets generated with MyEtherWallet CX. That way if anything happens to MyEtherWallet CX or your computer, you still have all the information necessary to access your Ether. See the #2a for how to back up your wallets. ', HELP_8CX_Desc_3 : 'If for some reason MyEtherWallet CX disappears from the Chrome Store, you can find the source on Github and load it manually. See #5 above. ', HELP_9_Title : '9) Is the "Lähetä Etheriä ja Tokeneita" page offline? ', HELP_9_Desc_1 : 'No. It needs the internet in order to get the current gas price, nonce of your account, and broadcast the transaction (aka "send"). However, it only sends the signed transaction. Your private key safely stays with you. We also now provide an "Offline Transaction" page so that you can ensure your private keys are on an offline/airgapped computer at all times. ', HELP_10_Title : '10) How do I make an offline transaction? ', HELP_10_Desc_1 : 'Navigate to the "Offline Transaction" page via your online computer. ', HELP_10_Desc_2 : 'Enter the "From Address". Please note, this is the address you are sending FROM, not TO. This generates the nonce and gas price. ', HELP_10_Desc_3 : 'Move to your offline computer. Enter the "TO ADDRESS" and the "AMOUNT" you wish to send. ', HELP_10_Desc_4 : 'Enter the "GAS PRICE" as it was displayed to you on your online computer in step #1. ', HELP_10_Desc_5 : 'Enter the "NONCE" as it was displayed to you on your online computer in step #1. ', HELP_10_Desc_6 : 'The "GAS LIMIT" has a default value of 21000. This will cover a standard transaction. If you are sending to a contract or are including additional data with your transaction, you will need to increase the gas limit. Any excess gas will be returned to you. ', HELP_10_Desc_7 : 'If you wish, enter some data. If you enter data, you will need to include more than the 21000 default gas limit. All data is in HEX format. ', HELP_10_Desc_8 : 'Select your wallet file -or- your private key and unlock your wallet. ', HELP_10_Desc_9 : 'Press the "GENERATE SIGNED TRANSACTION" button. ', HELP_10_Desc_10 : 'The data field below this button will populate with your signed transaction. Copy this and move it back to your online computer. ', HELP_10_Desc_11 : 'On your online computer, paste the signed transaction into the text field in step #3 and click send. This will broadcast your transaction. ', HELP_12_Title : '12) How do I import a wallet created with MyEtherWallet into geth / Ethereum Wallet / Mist? ', HELP_12_Desc_1 : 'Using an Geth/Mist JSON file from MyEtherWallet v2+.... ', HELP_12_Desc_2 : 'Go to the "View Wallet Info" page. ', HELP_12_Desc_3 : 'Unlock your wallet using your **encrypted** private key or JSON file. ', HELP_12_Desc_4 : 'Go to the "My Wallets" page. ', HELP_12_Desc_5 : 'Select the wallet you want to import into Mist, click the "View" icon, enter your password, and access your wallet. ', HELP_12_Desc_6 : 'Find the "Download JSON file - Geth/Mist Format (encrypted)" section. Press the "Download" button below that. You now have your keystore file. ', HELP_12_Desc_7 : 'Open the Ethereum Wallet application. ', HELP_12_Desc_8 : 'In the menu bar, go "Accounts" -> "Backup" -> "Accounts" ', HELP_12_Desc_9 : 'This will open your keystore folder. Copy the file you just downloaded (`UTC--2016-04-14......../`) into that keystore folder. ', HELP_12_Desc_10 : 'Your account should show up immediately under "Accounts." ', HELP_12_Desc_11 : 'Using your unencrypted private key... ', HELP_12_Desc_12 : 'If you do not already have your unencrypted private key, navigate to the "View Wallet Details" page. ', HELP_12_Desc_13 : 'Select your wallet file -or- enter/paste your private key to unlock your wallet. ', HELP_12_Desc_14 : 'Copy Your Private Key (unencrypted). ', HELP_12_Desc_15 : 'If you are on a Mac: ', HELP_12_Desc_15b : 'If you are on a PC: ', HELP_12_Desc_16 : 'Open Text Edit and paste this private key. ', HELP_12_Desc_17 : 'Go to the menu bar and click "Format" -> "Make Plain Text". ', HELP_12_Desc_18 : 'Save this file to your `desktop/` as `nothing_special_delete_me.txt`. Make sure it says "UTF-8" and "If no extension is provided use .txt" in the save dialog. ', HELP_12_Desc_19 : 'Open terminal and run the following command: `geth account import ~/Desktop/nothing_special_delete_me.txt` ', HELP_12_Desc_20 : 'This will prompt you to make a new password. This is the password you will use in geth / Ethereum Wallet / Mist whenever you send a transaction, so don\'t forget it. ', HELP_12_Desc_21 : 'After successful import, delete `nothing_special_delete_me.txt` ', HELP_12_Desc_22 : 'The next time you open the Ethereum Wallet application, your account will be listed under "Accounts". ', HELP_12_Desc_23 : 'Open Notepad & paste the private key ', HELP_12_Desc_24 : 'Save the file as `nothing_special_delete_me.txt` at `C:` ', HELP_12_Desc_25 : 'Run the command, `geth account import C:\\nothing_special_delete_me.txt` ', HELP_12_Desc_26 : 'This will prompt you to make a new password. This is the password you will use in geth / Ethereum Wallet / Mist whenever you send a transaction, so don\'t forget it. ', HELP_12_Desc_27 : 'After successful import, delete `nothing_special_delete_me.txt` ', HELP_12_Desc_28 : 'The next time you open the Ethereum Wallet application, your account will be listed under "Accounts". ', HELP_13_Title : '13) What does "Insufficient funds. Account you try to send transaction from does not have enough funds. Required XXXXXXXXXXXXXXXXXXX and got: XXXXXXXXXXXXXXXX." Mean? ', HELP_13_Desc_1 : 'This means you do not have enough Ether in your account to cover the cost of gas. Each transaction (including token and contract transactions) require gas and that gas is paid in Ether. The number displayed is the amount required to cover the cost of the transaction in Wei. Take that number, divide by `1000000000000000000`, and subtract the amount of Ether you were trying to send (if you were attempting to send Ether). This will give you the amount of Ether you need to send to that account to make the transaction. ', HELP_14_Title : '14) Some sites randomize (seed) the private key generation via mouse movements. MyEtherWallet.com doesn\'t do this. Is the random number generation for MyEtherWallet safe? ', HELP_14_Desc_1 : 'While the mouse moving thing is clever and we understand why people like it, the reality is window.crypto ensures more entropy than your mouse movements. The mouse movements aren\'t unsafe, it\'s just that we (and tons of other crypto experiments) believe in window.crypto. In addition, MyEtherWallet.com can be used on touch devices. Here\'s a [conversation between an angry redditor and Vitalik Buterin regarding mouse movements v. window.crypto](https://www.reddit.com/r/ethereum/comments/2bilqg/note_there_is_a_paranoid_highsecurity_way_to/cj5sgrm) and here is the [the window.crypto w3 spec](https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto). ', HELP_15_Title : '15) Why hasn\'t the account I just created show up in the blockchain explorer? (ie: etherchain, etherscan) ', HELP_15_Desc_1 : 'Accounts will only show up in a blockchain explorer once the account has activity on it&mdash;for example, once you have transferred some Ether to it. ', HELP_16_Title : '16) How do I check the balance of my account? ', HELP_16_Desc_1 : 'You can use a blockchain explorer like [etherscan.io](https://etherscan.io/). Paste your address into the search bar and it will pull up your address and transaction history. For example, here\'s what our [donation account](https://etherscan.io/address/0xDECAF9CD2367cdbb726E904cD6397eDFcAe6068D) looks like on etherscan.io ', HELP_17_Title : '17) Why isn\'t my balance showing up when I unlock my wallet? ', HELP_17_Desc_1 : 'This is most likely due to the fact that you are behind a firewall. The API that we use to get the balance and convert said balance is often blocked by firewalls for whatever reason. You will still be able to send transactions, you just need to use a different method to see said balance, like etherscan.io ', HELP_18_Title : '18) Where is my geth wallet file? ', HELP_19_Title : '19) Where is my Mist wallet file? ', HELP_19_Desc_1 : 'Mist files are typically found in the file locations above, but it\'s much easier to open Mist, select "Accounts" in the top bar, select "Backup", and select "Accounts". This will open the folder where your files are stored. ', HELP_20_Title : '20) Where is my pre-sale wallet file? ', HELP_20_Desc_1 : 'Wherever you saved it. ;) It also was emailed to you, so check there. Look for the file called `"ethereum_wallet_backup.json"` and select that file. This wallet file will be encrypted with a password that you created during the purchase of the pre-sale. ', HELP_21_Title : '21) Couldn\'t everybody put in random private keys, look for a balance, and send to their own address? ', HELP_21_Desc_1 : 'Short version: yes, but finding an account with a balance would take longer than the universe...so...no. ', HELP_21_Desc_2 : 'Long ELI5 Version: So Ethereum is based on [Public Key Cryptography](https://en.wikipedia.org/wiki/Public-key_cryptography), specifically [Elliptic curve cryptography](https://eprint.iacr.org/2013/734.pdf) which is very widely used, not just in Ethereum. Most servers are protected via ECC. Bitcoin uses the same, as well as SSH and TLS and a lot of other stuff. The Ethereum keys specifically are 256-bit keys, which are stronger than 128-bit and 192-bit, which are also widely used and still considered secure by experts. ', HELP_21_Desc_3 : 'In this you have a private key and a public key. The private key can derive the public key, but the public key cannot be turned back into the private key. The fact that the internet and the world’s secrets are using this cryptography means that if there is a way to go from public key to private key, your lost ether is the least of everyone’s problems. ', HELP_21_Desc_4 : 'Now, that said, YES if someone else has your private key then they can indeed send ether from your account. Just like if someone has your password to your email, they can read and send your email, or the password to your bank account, they could make transfers. You could download the Keystore version of your private key which is the private key that is encrypted with a password. This is like having a password that is also protected by another password. ', HELP_21_Desc_5 : 'And YES, in theory you could just type in a string of 64 hexadecimal characters until you got one that matched. In fact, smart people could write a program to very quickly check random private keys. This is known as "brute-forcing" or "mining" private keys. People have thought about this long and hard. With a few very high end servers, they may be able to check 1M+ keys / second. However, even checking that many per second would not yield access to make the cost of running those servers even close to worthwhile - it is more likely you, and your great-grandchildren, will die before getting a match. ', HELP_21_Desc_6 : 'If you know anything about Bitcoin, [this will put it in perspective:](http://bitcoin.stackexchange.com/questions/32331/two-people-with-same-public-address-how-will-people-network-know-how-to-deliver) *To illustrate how unlikely this is: suppose every satoshi of every bitcoin ever to be generated was sent to its own unique private keys. The probability that among those keys there could be two that would correspond to the same address is roughly one in 100 quintillion. ', HELP_21_Desc_7 : '[If you want something a bit more technical:](http://security.stackexchange.com/questions/25375/why-not-use-larger-cipher-keys/25392#25392) *These numbers have nothing to do with the technology of the devices; they are the maximums that thermodynamics will allow. And they strongly imply that brute-force attacks against 256-bit keys will be infeasible until computers are built from something other than matter and occupy something other than space. ', HELP_21_Desc_8 : 'Of course, this all assumes that keys are generated in a truly random way & with sufficient entropy. The keys generated here meet that criteria, as do Jaxx and Mist/geth. The Ethereum wallets are all pretty good. Keys generated by brainwallets do not, as a person\'s brain is not capable of creating a truly random seed. There have been a number of other issues regarding lack of entropy or seeds not being generated in a truly random way in Bitcoin-land, but that\'s a separate issue that can wait for another day. ', HELP_SecCX_Title : 'Security - MyEtherWallet CX ', HELP_SecCX_Desc_1 : 'Where is this extension saving my information? ', HELP_SecCX_Desc_2 : 'The information you store in this Chrome Extension is saved via [chrome.storage](http://chrome.storage/). - this is the same place your passwords are saved when you save your password in Chrome. ', HELP_SecCX_Desc_3 : 'What information is saved? ', HELP_SecCX_Desc_4 : 'The address, nickname, private key is stored in chrome.storage. The private key is encrypted using the password you set when you added the wallet. The nickname and wallet address is not encrypted. ', HELP_SecCX_Desc_5 : 'Why aren\'t the nickname and wallet address encrypted? ', HELP_SecCX_Desc_6 : 'If we were to encrypt these items, you would need to enter a password each time you wanted to view your account balance or view the nicknames. If this concerns you, we recommend you use MyEtherWallet.com instead of this Chrome Extension. ', HELP_Sec_Title : 'Security ', HELP_Sec_Desc_1 : 'If one of your first questions is "Why should I trust these people?", that is a good thing. Hopefully the following will help ease your fears. ', HELP_Sec_Desc_2 : 'We\'ve been up and running since August 2015. If you search for ["myetherwallet" on reddit](https://www.reddit.com/search?q=myetherwallet), you can see numerous people who use us with great success. ', HELP_Sec_Desc_3 : 'We aren\'t going to take your money or steal your private key(s). There is no malicious code on this site. In fact the "GENERATE WALLET" pages are completely client-side. That means that all the code is executed on ** your computer** and it is never saved and transmitted anywhere. ', HELP_Sec_Desc_4 : 'Check the URL -- This site is being served through GitHub and you can see the source code here: [https://github.com/kvhnuke/etherwallet/tree/gh-pages](https://github.com/kvhnuke/etherwallet/tree/gh-pages) to [https://vintage.myetherwallet.com](https://vintage.myetherwallet.com). ', HELP_Sec_Desc_5 : 'For generating wallets, you can download the [source code and run it locally](https://github.com/kvhnuke/etherwallet/releases/latest). See #5 above. ', HELP_Sec_Desc_6 : 'Generate a test wallet and check and see what network activity is happening. The easiest way for you to do this is to right click on the page and click "inspect element". Go to the "Network" tab. Generate a test wallet. You will see there is no network activity. You may see something happening that looks like data:image/gif and data:image/png. Those are the QR codes being generated...on your computer...by your computer. No bytes were transferred. ', HELP_Sec_Desc_8 : 'If you do not feel comfortable using this tool, then by all means, do not use it. We created this tool as a helpful way for people to generate wallets and make transactions without needing to dive into command line or run a full node. Again, feel free to reach out if you have concerns and we will respond as quickly as possible. Thanks! ', HELP_FAQ_Title : 'More Helpful Answers to Frequent Questions ', HELP_Contact_Title : 'Ways to Get in Touch' }; module.exports = fi;
(function() { 'use strict'; var $likes = $('#likes'), $count = $likes.find('span.count'), $pageId = $likes.data('page-id'), hasLikes = false, database = 'mikebrevoort', collection = 'likes', apiKey = 'O5du5o12UZ4urBz4jxt7imKGPz2YATvV', timer; if (location.hostname.match('mike\.brevoort\.com') && $likes.length) { var likeMover = function() { var $scroll = $(window).scrollTop(); $scroll = $scroll > 250 ? $likes.addClass('moveme') : $likes.removeClass('moveme'); }; $(window).scroll(function() { if (timer) { clearTimeout(timer); } timer = setTimeout(function() { likeMover(); }, 100); }); if (localStorage && localStorage.getItem($pageId)) { var localData = JSON.parse(localStorage.getItem($pageId)); if (localData.counted) { $likes.addClass('counted') .find('i') .toggleClass('icon-heart-empty icon-heart-full'); } } if (sessionStorage && sessionStorage.getItem($pageId)) { var sessionData = JSON.parse(sessionStorage.getItem($pageId)); $count.text(sessionData.count); } else { $.ajax({ url: 'https://api.mongolab.com/api/1/databases/' + database + '/collections/' + collection + '?apiKey=' + apiKey, type: 'GET', contentType: 'application/json', success: function(data) { $.each(data, function(index, value) { if (value.pageId === $pageId) { $count.text(value.count); hasLikes = true; } sessionStorage.setItem(value.pageId, JSON.stringify({count: value.count})); }); if (!hasLikes) { $.ajax({ url: 'https://api.mongolab.com/api/1/databases/' + database + '/collections/' + collection + '?apiKey=' + apiKey, data: JSON.stringify({ pageId: $pageId, count: 0 }), type: 'POST', contentType: 'application/json', success: function() { $count.text('0'); sessionStorage.setItem($pageId, JSON.stringify({count: 0})); } }); } } }); } $likes.on('click', function(e) { var $this = $(this), $num = $count.text(); $this.toggleClass('counted') .find('i') .toggleClass('icon-heart-empty icon-heart-full'); $num = $this.hasClass('counted') ? ++$num : --$num; $count.text($num); sessionStorage.setItem($pageId, JSON.stringify({count: $num})); localStorage.setItem($pageId, JSON.stringify({counted: $this.hasClass('counted') ? true : false})); $.ajax({ url: 'https://api.mongolab.com/api/1/databases/' + database + '/runCommand?apiKey=' + apiKey, data: JSON.stringify({ findAndModify: collection, query: { pageId: $pageId }, update: {$inc: {count: ($this.hasClass('counted') ? 1 : -1)}}, upsert: true }), type: 'POST', contentType: 'application/json' }); e.preventDefault(); }); } })();
define(['jquery'], function($) { 'use strict'; function makeCheckbox($el) { var $checkbox = $('<input>', { type: 'checkbox', name: $el[0].id, value: '1', checked: $el.hasClass('active') }).hide(); $checkbox.insertAfter($el); return $checkbox; } return { /** * Creates checkboxes out of arbitrary elements * Toggles the active class on the element, * backs it up using a hidden checkbox */ toggleElement: function($el) { $el.each(function(i) { var $checkbox = makeCheckbox(i = $(this).on('click', function() { var selected = !$checkbox.prop('checked'); $checkbox.prop('checked', selected).change(); i.toggleClass('active', selected); })); }); } }; });
(function() { "use strict"; const app = window.app; function moveableRules(parent, handleSelector) { const placeholder = document.createElement("div"); const handles = Array.prototype.slice.call(parent.querySelectorAll(handleSelector)); let children; let mouseDown = false; let currentMovingEl; let offsetY; let currentIndex; let grid; let onMove = function() {}; placeholder.className = "sortable-placeholder"; const regetChildren = function() { children = Array.prototype.slice.call(parent.children); }; regetChildren(); const setBorders = function() { children.forEach(function(el) { el.style.background = "transparent"; }); }; const getElFullHeight = function(el) { const innerHeight = el.getBoundingClientRect().height; const compStyle = window.getComputedStyle(el); return innerHeight + parseInt(compStyle["margin-top"]); }; const getChildIndex = function(el) { const children = parent.children; let idx = children.length; while (idx-- > 0) { if (children[idx] === el) { return idx; } } return null; }; const getQualifiedChild = function(el) { let lastEl; while (el && el !== parent) { lastEl = el; el = el.parentElement; } return lastEl; }; const after = function(parent, newEl, targetEl) { const nextSib = targetEl.nextElementSibling; if (!nextSib) { parent.appendChild(newEl); } else { parent.insertBefore(newEl, nextSib); } }; const remove = function(el) { el.parentElement.removeChild(el); }; const makeGrid = function() { grid = []; regetChildren(); let currentOffset = 0; children.forEach(function(el) { if (el !== currentMovingEl) { currentOffset += getElFullHeight(el); grid.push({ el: el, offset: currentOffset }); } }); }; const getElFromGridWithY = function(y) { if (y < 0) { return null; } for (let x = 0, len = grid.length; x < len; ++x) { if (y < grid[x].offset) { return grid[x].el; } } return null; }; let lastDropTarget; document.addEventListener("mousemove", function(e) { if (mouseDown) { e.preventDefault(); currentMovingEl.style.top = e.pageY - offsetY + "px"; const mouseParentY = e.clientY - parent.getBoundingClientRect().top; const dropTarget = getElFromGridWithY(mouseParentY); if (dropTarget !== lastDropTarget) { setBorders(); if (dropTarget) { dropTarget.style.background = "#dddddd"; } lastDropTarget = dropTarget; } } }); document.addEventListener("mouseup", function(e) { mouseDown = false; if (currentMovingEl) { const mouseParentY = e.clientY - parent.getBoundingClientRect().top; const dropTarget = getElFromGridWithY(mouseParentY) || placeholder; const dropIndex = getChildIndex(dropTarget); if (dropIndex > currentIndex) { after(parent, currentMovingEl, dropTarget); } else { parent.insertBefore(currentMovingEl, dropTarget); } // this prevents a reflow from changing scroll position. setTimeout(function() { remove(placeholder); }, 1); currentMovingEl.style.position = ""; currentMovingEl.style.width = ""; currentMovingEl.style.height = ""; currentMovingEl.style.opacity = ""; currentMovingEl = null; setBorders(); onMove(); } }); const assignHandleListener = function(handle) { const el = getQualifiedChild(handle); const compStyle = window.getComputedStyle(el); handle.addEventListener("mousedown", function(e) { const boundingRect = el.getBoundingClientRect(); mouseDown = true; currentMovingEl = el; currentIndex = getChildIndex(el); offsetY = e.offsetY + parseInt(compStyle["margin-top"]); el.style.position = "absolute"; el.parentElement.insertBefore(placeholder, el); el.style.width = boundingRect.width + "px"; el.style.height = boundingRect.height + "px"; el.style.top = e.pageY - offsetY + "px"; el.style.opacity = 0.5; makeGrid(); }); }; handles.forEach(assignHandleListener); return { assignHandleListener: assignHandleListener, onMove: function(fn) { onMove = fn; } }; } app.moveableRules = moveableRules; })();
/* * @fileOverview * @author: Mike Grabowski (@grabbou) */ 'use strict'; var Blueprint = require('../lib/models/blueprint'); var expect = require('chai').expect; describe('Blueprint#getArguments', function() { var blueprint = Blueprint.load('page'); var args = [{ arg: 'arg1' }]; it('should return name argument by default', function() { var blueprintArgs = blueprint.getArguments(); expect(blueprintArgs).to.be.instanceOf(Array); expect(blueprintArgs.length).to.equals(1); expect(blueprintArgs[0]).to.have.property('name'); expect(blueprintArgs[0]).to.have.property('property'); expect(blueprintArgs[0]).to.have.property('required'); }); it('should return custom arguments', function() { blueprint.args = args; var blueprintFlags = blueprint.getArguments(); expect(blueprintFlags.length).to.equals(2); expect(blueprintFlags[1]).to.have.property('arg'); }); });
/* * Dropdown menus. * * This script customizes the Twitter Bootstrap drop-downs. * * Require: * - bootstrap/dropdown */ +function ($) { "use strict"; $(document).on('shown.bs.dropdown', '.dropdown', function(event, relatedTarget) { $(document.body).addClass('dropdown-open') var dropdown = $(relatedTarget.relatedTarget).siblings('.dropdown-menu'), dropdownContainer = $(this).data('dropdown-container') // The dropdown menu should be a sibling of the triggering element (above) // otherwise, look for any dropdown menu within this context. if (dropdown.length === 0){ dropdown = $('.dropdown-menu', this) } if ($('.dropdown-container', dropdown).length == 0) { var title = $('[data-toggle=dropdown]', this).text(), titleAttr = dropdown.data('dropdown-title'), timer = null if (titleAttr !== undefined) title = titleAttr $('li:first-child', dropdown).addClass('first-item') $('li:last-child', dropdown).addClass('last-item') dropdown.prepend($('<li />').addClass('dropdown-title').text(title)) var container = $('<li />').addClass('dropdown-container'), ul = $('<ul />') container.prepend(ul) ul.prepend(dropdown.children()) dropdown.prepend(container) dropdown.on('touchstart', function(){ window.setTimeout(function(){ dropdown.addClass('scroll') }, 200) }) dropdown.on('touchend', function(){ window.setTimeout(function(){ dropdown.removeClass('scroll') }, 200) }) dropdown.on('click', 'a', function(){ if (dropdown.hasClass('scroll')) return false }) } if (dropdownContainer !== undefined && dropdownContainer == 'body') { $(this).data('oc.dropdown', dropdown) $(document.body).append(dropdown) dropdown.css({ 'visibility': 'hidden', 'left': 0, 'top' : 0, 'display': 'block' }) var targetOffset = $(this).offset(), targetHeight = $(this).height(), targetWidth = $(this).width(), position = { x: targetOffset.left, y: targetOffset.top + targetHeight }, leftOffset = targetWidth < 30 ? -16 : 0, documentHeight = $(document).height(), dropdownHeight = dropdown.height() if ((dropdownHeight + position.y) > $(document).height()) { position.y = targetOffset.top - dropdownHeight - 12 dropdown.addClass('top') } else { dropdown.removeClass('top') } dropdown.css({ 'left': position.x + leftOffset, 'top': position.y, 'visibility': 'visible' }) } if ($('.dropdown-overlay', document.body).length == 0) { $(document.body).prepend($('<div/>').addClass('dropdown-overlay')); } }) $(document).on('hidden.bs.dropdown', '.dropdown', function() { var dropdown = $(this).data('oc.dropdown') if (dropdown !== undefined) { dropdown.css('display', 'none') $(this).append(dropdown) } $(document.body).removeClass('dropdown-open'); }) /* * Fixed positioned dropdowns * - Useful for dropdowns inside hidden overflow containers */ var $dropdown, $container, $target function fixDropdownPosition() { var position = $container.offset() $dropdown.css({ position: 'fixed', top: position.top - 1 - $(window).scrollTop() + $target.outerHeight(), left: position.left }) } $(document).on('shown.bs.dropdown', '.dropdown.dropdown-fixed', function(event, eventData) { $container = $(this) $dropdown = $('.dropdown-menu', $container) $target = $(eventData.relatedTarget) fixDropdownPosition() $(window).on('scroll.oc.dropdown, resize.oc.dropdown', fixDropdownPosition) }) $(document).on('hidden.bs.dropdown', '.dropdown.dropdown-fixed', function() { $(window).off('scroll.oc.dropdown, resize.oc.dropdown', fixDropdownPosition) }) }(window.jQuery);
(function () { 'use strict'; angular.module('ServerApp') .controller('adminCountdownReEnableController', adminCountdownReEnableController); function adminCountdownReEnableController(changeConfigFactory, $scope, hotkeys, connectFactory) { var self = this; self.reEnable = false; changeConfigFactory.onChangeConfigAdmin(onChangeConfigAdmin); connectFactory.onHelloAck(addHotkey); $scope.$watch('reEnableCtrl.reEnable', onChangeReEnable); function addHotkey(){ hotkeys.add({ combo: 'o', description: 'enable/disable auto enabling of buzzers after end of countdown', callback: function() { self.reEnable = !self.reEnable; } }); } function onChangeConfigAdmin(data) { self.reEnable = data.buzzersAutoEnable; } function onChangeReEnable(newValue, oldValue) { if(newValue == undefined){ return } if (newValue != oldValue) { changeConfigFactory.changeBuzzReEnable(newValue); } } } })();
var heroku = require('../../lib/services/heroku') describe('Heroku CI Provider', function() { it('can detect heroku', function() { process.env.HEROKU_TEST_RUN_ID = '454f5dc9-afa4-433f-bb28-84678a00fd98' expect(heroku.detect()).toBe(true) }) it('can get wercker env info', function() { process.env.HEROKU_TEST_RUN_ID = '454f5dc9-afa4-433f-bb28-84678a00fd98' process.env.HEROKU_TEST_RUN_COMMIT_VERSION = '743b04806ea677403aa2ff26c6bdeb85005de658' process.env.HEROKU_TEST_RUN_BRANCH = 'master' expect(heroku.configuration()).toEqual({ service: 'heroku', commit: '743b04806ea677403aa2ff26c6bdeb85005de658', build: '454f5dc9-afa4-433f-bb28-84678a00fd98', branch: 'master', }) }) })
'use strict'; //Categories service used to communicate Categories REST endpoints angular.module('categories').factory('Categories', ['$resource', function($resource) { return $resource('categories/:categoryId', { categoryId: '@_id', searchData: '@_searchData' }, { update: { method: 'PUT' }, search: { method: 'GET', isArray: true, url: 'categories/search/:searchData' } }); } ]);
var Tecnotek = Tecnotek || {}; Tecnotek.Visits = { visitId: 0, currentList: null, init : function() { $( "#date" ).datepicker({ defaultDate: "0d", changeMonth: true, dateFormat: "dd/mm/yy", showButtonPanel: true, currentText: "Hoy", numberOfMonths: 1, onClose: function( selectedDate ) { //$( "#to" ).datepicker( "option", "minDate", selectedDate ); } }); $('.cancelButton').click(function(event){ $.fancybox.close(); }); $("#newVisit").click(function(e){ if (!Tecnotek.UI.vars['opening-edit']) { Tecnotek.Visits.visitId = 0; $("#date").val(""); $("#comments").val(""); $("#people").val(""); $("#observations").val(""); $("#modalTitle").html(Tecnotek.UI.translates['creating-visit']); Tecnotek.Visits.enableForm(); } Tecnotek.UI.vars['opening-edit'] = false; }); $('#createVisitForm').submit(function(event){ event.preventDefault(); Tecnotek.Visits.save(); }); $('#searchText').keyup(function(event){ Tecnotek.UI.vars["page"] = 1; Tecnotek.Students.searchVisits(); }); $('#btnSearch').unbind().click(function(event){ Tecnotek.Students.searchVisits(); }); $(".sort_header").click(function() { Tecnotek.UI.vars["sortBy"] = $(this).attr("field-name"); Tecnotek.UI.vars["order"] = $(this).attr("order"); console.debug("Order by " + Tecnotek.UI.vars["sortBy"] + " " + Tecnotek.UI.vars["order"]); $(this).attr("order", Tecnotek.UI.vars["order"] == "asc"? "desc":"asc"); $(".header-title").removeClass("asc").removeClass("desc").addClass("sortable"); $(this).children().addClass(Tecnotek.UI.vars["order"]); Tecnotek.Visits.searchVisits(); }); Tecnotek.UI.vars["order"] = "asc"; Tecnotek.UI.vars["sortBy"] = "v.date"; Tecnotek.UI.vars["page"] = 1; Tecnotek.Visits.searchVisits(); }, searchVisits: function() { $("#visits-container").html(""); $("#pagination-container").html(""); Tecnotek.showWaiting(); Tecnotek.uniqueAjaxCall(Tecnotek.UI.urls["search"], { text: ""/*$("#searchText").val()*/, sortBy: Tecnotek.UI.vars["sortBy"], order: Tecnotek.UI.vars["order"], page: Tecnotek.UI.vars["page"], studentId: Tecnotek.UI.vars["student-id"] }, function(data){ if(data.error === true) { Tecnotek.hideWaiting(); Tecnotek.showErrorMessage(data.message,true, "", false); } else { var baseHtml = $("#visitRowTemplate").html(); var editButtonHtml = $("#editButtonTemplate").html(); var visits = new Array(); for (i=0; i<data.visits.length; i++) { visits[data.visits[i].id] = data.visits[i]; var row = '<div class="row userRow ROW_CLASS" rel="VISIT_ID">' + baseHtml; var creatorId = data.visits[i]['user_id']; if (Tecnotek.UI.vars["user-id"] == creatorId) { row += editButtonHtml; } row += '</div>'; row = row.replaceAll('ROW_CLASS', (i % 2 == 0? 'tableRowOdd':'tableRow')); row = row.replaceAll('VISIT_ID', data.visits[i].id); row = row.replaceAll('VISIT_DATE', data.visits[i].date); row = row.replaceAll('VISIT_CREATOR', data.visits[i].creator); row = row.replaceAll('VISIT_PEOPLE', data.visits[i].people); row = row.replaceAll('VISIT_COMMENTS', data.visits[i].comments); $("#visits-container").append(row); } Tecnotek.Visits.currentList = visits; Tecnotek.Visits.initButtons(); Tecnotek.UI.printPagination(data.total, data.filtered, Tecnotek.UI.vars["page"], 10, "pagination-container"); $(".paginationButton").unbind().click(function() { Tecnotek.UI.vars["page"] = $(this).attr("page"); Tecnotek.Visits.searchVisits(); }); Tecnotek.hideWaiting(); } }, function(jqXHR, textStatus){ if (textStatus != "abort") { Tecnotek.hideWaiting(); console.debug("Error getting data: " + textStatus); } }, true, 'searchStudents'); }, initButtons: function () { $(".viewButton").unbind().click(function (e) { Tecnotek.UI.vars['opening-edit'] = true; var visitId = $(this).attr("rel"); Tecnotek.Visits.putValuesInForm(visitId); Tecnotek.Visits.disableForm(); $("#modalTitle").html(Tecnotek.UI.translates['viewing-visit']); $("#newVisit").click(); }); $(".editButton").unbind().click(function (e) { Tecnotek.UI.vars['opening-edit'] = true; var visitId = $(this).attr("rel"); Tecnotek.Visits.putValuesInForm(visitId); Tecnotek.Visits.enableForm(); $("#modalTitle").html(Tecnotek.UI.translates['editing-visit']); $("#newVisit").click(); }); }, putValuesInForm: function(visitId) { var visit = Tecnotek.Visits.currentList[visitId]; Tecnotek.Visits.visitId = visitId; $("#date").val(visit.date); $("#comments").val(visit.comments); $("#people").val(visit.people); $("#observations").val(visit.observations); }, enableForm: function() { $("#date").removeAttr("disabled"); $("#comments").removeAttr("disabled"); $("#people").removeAttr("disabled"); $("#observations").removeAttr("disabled"); $("#saveVisitBtn").show(); $("#cancelBtn").show(); $("#closeBtn").hide(); }, disableForm: function(){ $("#date").attr("disabled", "disabled"); $("#comments").attr("disabled", "disabled"); $("#people").attr("disabled", "disabled"); $("#observations").attr("disabled", "disabled"); $("#saveVisitBtn").hide(); $("#cancelBtn").hide(); $("#closeBtn").show(); }, save : function(){ /*if(Tecnotek.UI.vars["currentPeriod"] == 0){ Tecnotek.showErrorMessage("Es necesario definir un periodo como actual antes de guardar.",true, "", false); return; } var $studentId = $("#studentId").val(); var $type = $("#typeId").val();*/ var $date = $("#date").val(); var $comments = $("#comments").val(); var $people = $("#people").val(); var $observations = $("#observations").val(); if ($comments === "") { Tecnotek.showErrorMessage("Debe incluir un comentario.", true, "", false); } else if ($people === ""){ Tecnotek.showErrorMessage("Debe incluir las personas presentes.", true, "", false); } else if ($date === ""){ Tecnotek.showErrorMessage("Debe incluir la fecha.", true, "", false); } else { Tecnotek.ajaxCall(Tecnotek.UI.urls["saveVisit"], { studentId: Tecnotek.UI.vars["student-id"], date: $date, visitId: Tecnotek.Visits.visitId, comments: $comments, people: $people, observations: $observations }, function(data){ if(data.error === true) { Tecnotek.showErrorMessage(data.message,true, "", false); } else { $.fancybox.close(); Tecnotek.showInfoMessage("La visita se ha ingresado correctamente.", true, "", false); Tecnotek.Visits.searchVisits(); } }, function(jqXHR, textStatus){ Tecnotek.showErrorMessage("Error saving visita: " + textStatus + ".", true, "", false); }, true); } } };
// HTTP module. var http = require('http'); // HTTP proxy module. var httpProxy = require('http-proxy'); // Authentication module. var auth = require('../gensrc/http-auth'); var basic = auth.basic({ realm: "Simon Area.", file: __dirname + "/../data/users.htpasswd" // gevorg:gpass, Sarah:testpass }); // Create your proxy server. httpProxy.createServer(basic, { target: 'http://localhost:1338' }).listen(1337); // Create your target server. http.createServer(function (req, res) { res.end("Request successfully proxied!"); }).listen(1338, function () { // Log URL. console.log("Server running at http://127.0.0.1:1337/"); }); // You can test proxy authentication using curl. // $ curl -x 127.0.0.1:1337 127.0.0.1:1337 -U gevorg
'use strict'; /** * Module dependencies. */ var _ = require('lodash'); var EventEmitter = require('events').EventEmitter; var Command = require('./command'); var CommandInstance = require('./command-instance'); var VorpalUtil = require('./util'); var ui = require('./ui'); var Session = require('./session'); var intercept = require('./intercept'); var minimist = require('minimist'); var commons = require('./vorpal-commons'); var chalk = require('chalk'); var os = require('os'); var History = require('./history'); require('native-promise-only'); /** * Initialize a new `Vorpal` instance. * * @return {Vorpal} * @api public */ function Vorpal() { if (!(this instanceof Vorpal)) { return new Vorpal(); } // Program version // Exposed through vorpal.version(str); this._version = ''; // Command line history instance this.cmdHistory = new this.CmdHistoryExtension(); // Registered `vorpal.command` commands and // their options. this.commands = []; // Queue of IP requests, executed async, in sync. this._queue = []; // Current command being executed. this._command = undefined; // Expose UI. this.ui = ui; // Expose chalk as a convenience. this.chalk = chalk; // Expose lodash as a convenience. this.lodash = _; // Exposed through vorpal.delimiter(str). this._delimiter = 'local@' + String(os.hostname()).split('.')[0] + '~$ '; ui.setDelimiter(this._delimiter); // Placeholder for vantage server. If vantage // is used, this will be over-written. this.server = { sessions: [] }; // Whether all stdout is being hooked through a function. this._hooked = false; // Expose common utilities, like padding. this.util = VorpalUtil; this.Session = Session; // Active vorpal server session. this.session = new this.Session({ local: true, user: 'local', parent: this, delimiter: this._delimiter }); this._init(); return this; } /** * Extend Vorpal prototype as an event emitter. */ Vorpal.prototype = Object.create(EventEmitter.prototype); /** * Vorpal prototype. */ var vorpal = Vorpal.prototype; /** * Expose `Vorpal`. */ exports = module.exports = Vorpal; /** * Extension to `constructor`. * @api private */ Vorpal.prototype._init = function () { var self = this; ui.on('vorpal_ui_keypress', function (data) { self.emit('keypress', data); self._onKeypress(data.key, data.value); }); self.use(commons); }; /** * Parses `process.argv` and executes * a Vorpal command based on it. * @api public */ Vorpal.prototype.parse = function (argv, options) { options = options || {}; var args = argv; var result = this; var catchExists = !(_.findWhere(this.commands, {_catch: true}) === undefined); args.shift(); args.shift(); if (args.length > 0 || catchExists) { if (options.use === 'minimist') { result = minimist(args); } else { this.exec(args.join(' '), function (err) { if (err !== undefined) { throw new Error(err); } }); } } return result; }; /** * Sets version of your application's API. * * @param {String} version * @return {Vorpal} * @api public */ vorpal.version = function (version) { this._version = version; return this; }; /** * Sets the permanent delimiter for this * Vorpal server instance. * * @param {String} str * @return {Vorpal} * @api public */ vorpal.delimiter = function (str) { this._delimiter = str; if (this.session.isLocal() && !this.session.client) { this.session.delimiter(str); } return this; }; /** * Imports a library of Vorpal API commands * from another Node module as an extension * of Vorpal. * * @param {Array} commands * @return {Vorpal} * @api public */ vorpal.use = function (commands, options) { if (!commands) { return this; } if (_.isFunction(commands)) { commands.call(this, this, options); } else if (_.isString(commands)) { return this.use(require(commands), options); } else { commands = _.isArray(commands) ? commands : [commands]; for (var i = 0; i < commands.length; ++i) { var cmd = commands[i]; if (cmd.command) { var command = this.command(cmd.command); if (cmd.description) { command.description(cmd.description); } if (cmd.options) { cmd.options = _.isArray(cmd.options) ? cmd.options : [cmd.options]; for (var j = 0; j < cmd.options.length; ++j) { command.option(cmd.options[j][0], cmd.options[j][1]); } } if (cmd.action) { command.action(cmd.action); } } } } return this; }; /** * Registers a new command in the vorpal API. * * @param {String} name * @param {String} desc * @param {Object} opts * @return {Command} * @api public */ vorpal.command = function (name, desc, opts) { opts = opts || {}; name = String(name); var argsRegExp = /(\[[^\]]*\]|\<[^\>]*\>)/g; var args = []; var arg; while ((arg = argsRegExp.exec(name)) !== null) { args.push(arg[1]); } var cmdNameRegExp = /^([^\[\<]*)/; var cmdName = cmdNameRegExp.exec(name)[0].trim(); var cmd = new Command(cmdName, this); if (desc) { cmd.description(desc); this.executables = true; } cmd._noHelp = Boolean(opts.noHelp); cmd._mode = opts.mode || false; cmd._catch = opts.catch || false; cmd._parseExpectedArgs(args); cmd.parent = this; var exists = false; for (var i = 0; i < this.commands.length; ++i) { exists = (this.commands[i]._name === cmd._name) ? true : exists; if (exists) { this.commands[i] = cmd; break; } } if (!exists) { this.commands.push(cmd); } else { console.warn(chalk.yellow('Warning: command named "' + name + '" was registered more than once.\nIf you intend to override a command, you should explicitly remove the first command with command.remove().')); } this.emit('command_registered', {command: cmd, name: name}); return cmd; }; /** * Registers a new 'mode' command in the vorpal API. * * @param {String} name * @param {String} desc * @param {Object} opts * @return {Command} * @api public */ vorpal.mode = function (name, desc, opts) { return this.command(name, desc, _.extend((opts || {}), {mode: true})); }; /** * Registers a 'catch' command in the vorpal API. * This is executed when no command matches are found. * * @param {String} name * @param {String} desc * @param {Object} opts * @return {Command} * @api public */ vorpal.catch = function (name, desc, opts) { return this.command(name, desc, _.extend((opts || {}), {catch: true})); }; /** * An alias to the `catch` command. * * @param {String} name * @param {String} desc * @param {Object} opts * @return {Command} * @api public */ vorpal.default = function (name, desc, opts) { return this.command(name, desc, _.extend((opts || {}), {catch: true})); }; /** * Delegates to ui.log. * * @param {String} log * @return {Vorpal} * @api public */ vorpal.log = function () { this.ui.log.apply(this.ui, arguments); return this; }; /** * Intercepts all logging through `vorpal.log` * and runs it through the function declared by * `vorpal.pipe()`. * * @param {Function} fn * @return {Vorpal} * @api public */ vorpal.pipe = function (fn) { if (this.ui) { this.ui._pipeFn = fn; } return this; }; /** * If Vorpal is the local terminal, * hook all stdout, through a fn. * * @return {Vorpal} * @api private */ vorpal.hook = function (fn) { if (fn !== undefined) { this._hook(fn); } else { this._unhook(); } return this; }; /** * Unhooks stdout capture. * * @return {Vorpal} * @api public */ vorpal._unhook = function () { if (this._hooked && this._unhook !== undefined) { this._unhook(); this._hooked = false; } return this; }; /** * Hooks all stdout through a given function. * * @param {Function} fn * @return {Vorpal} * @api public */ vorpal._hook = function (fn) { if (this._hooked && this._unhook !== undefined) { this._unhook(); } this._unhook = intercept(fn); this._hooked = true; return this; }; /** * History module used to get command history */ vorpal.CmdHistoryExtension = History; /** * Set id for command line history * @param id * @return {Vorpal} * @api public */ vorpal.history = function (id) { this.cmdHistory.setId(id); return this; }; /** * Set the path to where command line history is persisted. * Must be called before vorpal.history * @param path * @return {Vorpal} * @api public */ vorpal.historyStoragePath = function (path) { this.cmdHistory.setStoragePath(path); return this; }; /** * Hook the tty prompt to this given instance * of vorpal. * * @return {Vorpal} * @api public */ vorpal.show = function () { ui.attach(this); return this; }; /** * Disables the vorpal prompt on the * local terminal. * * @return {Vorpal} * @api public */ vorpal.hide = function () { ui.detach(this); return this; }; /** * Listener for a UI keypress. Either * handles the keypress locally or sends * it upstream. * * @param {String} key * @param {String} value * @api private */ vorpal._onKeypress = function (key, value) { var self = this; if (this.session.isLocal() && !this.session.client && !this._command) { this.session.getKeypressResult(key, value, function (err, result) { if (!err && result !== undefined) { if (_.isArray(result)) { var formatted = VorpalUtil.prettifyArray(result); self.ui.imprint(); self.session.log(formatted); } else { self.ui.input(result); } } }); } else { this._send('vantage-keypress-upstream', 'upstream', { key: key, value: value, sessionId: this.session.id }); } }; /** * For use in vorpal API commands, sends * a prompt command downstream to the local * terminal. Executes a prompt and returns * the response upstream to the API command. * * @param {Object} options * @param {Function} cb * @return {Vorpal} * @api public */ vorpal.prompt = function (options, cb) { var self = this; var prompt; options = options || {}; var ssn = self.getSessionById(options.sessionId); if (!ssn) { throw new Error('Vorpal.prompt was called without a passed Session ID.'); } function handler(data) { var response = data.value; self.removeListener('vantage-prompt-upstream', handler); cb(response); } if (ssn.isLocal()) { ui.setDelimiter(options.message || ssn.delimiter); prompt = ui.prompt(options, function (result) { ui.setDelimiter(ssn.delimiter); cb(result); }); } else { self.on('vantage-prompt-upstream', handler); self._send('vantage-prompt-downstream', 'downstream', {options: options, value: undefined, sessionId: ssn.id}); } return prompt; }; /** * Renders the CLI prompt or sends the * request to do so downstream. * * @param {Object} data * @return {Vorpal} * @api private */ vorpal._prompt = function (data) { var self = this; var prompt; data = data || {}; if (!data.sessionId) { data.sessionId = self.session.id; } var ssn = self.getSessionById(data.sessionId); // If we somehow got to _prompt and aren't the // local client, send the command downstream. if (!ssn.isLocal()) { this._send('vantage-resume-downstream', 'downstream', {sessionId: data.sessionId}); return self; } if (ui.midPrompt()) { return self; } prompt = ui.prompt({ type: 'input', name: 'command', message: ssn.fullDelimiter() }, function (result) { if (self.ui._cancelled === true) { self.ui._cancelled = false; return; } var str = String(result.command).trim(); self.emit('client_prompt_submit', str); if (str === '' || str === 'undefined') { self._prompt(data); return; } self.exec(str, function () { self._prompt(data); }); }); return prompt; }; /** * Executes a vorpal API command and * returns the response either through a * callback or Promise in the absence * of a callback. * * A little black magic here - because * we sometimes have to send commands 10 * miles upstream through 80 other instances * of vorpal and we aren't going to send * the callback / promise with us on that * trip, we store the command, callback, * resolve and reject objects (as they apply) * in a local vorpal._command variable. * * When the command eventually comes back * downstream, we dig up the callbacks and * finally resolve or reject the promise, etc. * * Lastly, to add some more complexity, we throw * command and callbacks into a queue that will * be unearthed and sent in due time. * * @param {String} cmd * @param {Function} cb * @return {Promise or Vorpal} * @api public */ vorpal.exec = function (cmd, args, cb) { var self = this; var ssn = self.session; cb = (_.isFunction(args)) ? args : cb; args = args || {}; if (args.sessionId) { ssn = self.getSessionById(args.sessionId); } var command = { command: cmd, args: args, callback: cb, session: ssn }; if (cb !== undefined) { self._queue.push(command); self._queueHandler(); return self; } return new Promise(function (resolve, reject) { command.resolve = resolve; command.reject = reject; self._queue.push(command); self._queueHandler(); }); }; /** * Commands issued to Vorpal server * are executed in sequence. Called once * when a command is inserted or completes, * shifts the next command in the queue * and sends it to `vorpal._execQueueItem`. * * @api private */ vorpal._queueHandler = function () { if (this._queue.length > 0 && this._command === undefined) { var item = this._queue.shift(); this._execQueueItem(item); } }; /** * Fires off execution of a command - either * calling upstream or executing locally. * * @param {Object} cmd * @api private */ vorpal._execQueueItem = function (cmd) { var self = this; self._command = cmd; if (cmd.session.isLocal() && !cmd.session.client) { this._exec(cmd); } else { self._send('vantage-command-upstream', 'upstream', { command: cmd.command, args: cmd.args, completed: false, sessionId: cmd.session.id }); } }; /** * Executes a vorpal API command. * Warning: Dragons lie beyond this point. * * @param {String} item * @api private */ vorpal._exec = function (item) { var self = this; item = item || {}; item.command = item.command || ''; var modeCommand = item.command; item.command = (item.session._mode) ? item.session._mode : item.command; var promptCancelled = false; if (this.ui._midPrompt) { promptCancelled = true; this.ui.cancel(); } if (!item.session) { throw new Error('Fatal Error: No session was passed into command for execution: ' + item); } if (String(item.command).indexOf('undefine') > -1) { throw new Error('vorpal._exec was called with an undefined command.'); } // History for our 'up' and 'down' arrows. item.session.history((item.session._mode ? modeCommand : item.command)); var commandData = this.util.parseCommand(item.command, this.commands); item.command = commandData.command; item.pipes = commandData.pipes; var match = commandData.match; var matchArgs = commandData.matchArgs; function throwHelp(cmd, msg, alternativeMatch) { if (msg) { cmd.session.log(msg); } var pickedMatch = alternativeMatch || match; cmd.session.log(pickedMatch.helpInformation()); } function callback(cmd, err, msg, argus) { // Resume the prompt if we had to cancel // an active prompt, due to programmatic // execution. if (promptCancelled) { self._prompt(); } if (cmd.callback) { if (argus) { cmd.callback.apply(self, argus); } else { cmd.callback.call(self, err, msg); } } else if (!err && cmd.resolve) { cmd.resolve(msg); } else if (err && cmd.reject) { cmd.reject(msg); } delete self._command; self._queueHandler(); } if (match) { item.fn = match._fn; item._cancel = match._cancel; item.validate = match._validate; item.commandObject = match; var init = match._init || function (arrgs, cb) { cb(); }; var delimiter = match._delimiter || String(item.command).toLowerCase() + ':'; item.args = self.util.buildCommandArgs(matchArgs, match, item); // If we get a string back, it's a validation error. // Show help and return. if (_.isString(item.args) || !_.isObject(item.args)) { throwHelp(item, item.args); callback(item, undefined, item.args); return; } // Build the piped commands. var allValid = true; for (var j = 0; j < item.pipes.length; ++j) { var commandParts = self.util.matchCommand(item.pipes[j], self.commands); if (!commandParts.command) { item.session.log(self._commandHelp(item.pipes[j])); allValid = false; break; } commandParts.args = self.util.buildCommandArgs(commandParts.args, commandParts.command); if (_.isString(commandParts.args) || !_.isObject(commandParts.args)) { throwHelp(item, commandParts.args, commandParts.command); allValid = false; break; } item.pipes[j] = commandParts; } // If invalid piped commands, return. if (!allValid) { callback(item); return; } // If `--help` or `/?` is passed, do help. if (item.args.options.help && _.isFunction(match._help)) { // If the command has a custom help function, run it // as the actual "command". In this way it can go through // the whole cycle and expect a callback. item.fn = match._help; delete item.validate; delete item._cancel; } else if (item.args.options.help) { // Otherwise, throw the standard help. throwHelp(item, ''); callback(item); return; } // If this command throws us into a 'mode', // prepare for it. if (match._mode === true && !item.session._mode) { // Assign vorpal to be in a 'mode'. item.session._mode = item.command; // Execute the mode's `init` function // instead of the `action` function. item.fn = init; delete item.validate; self.cmdHistory.enterMode(); item.session.modeDelimiter(delimiter); } else if (item.session._mode) { if (String(modeCommand).trim() === 'exit') { self._exitMode({sessionId: item.session.id}); callback(item); return; } // This executes when actually in a 'mode' // session. We now pass in the raw text of what // is typed into the first param of `action` // instead of arguments. item.args = modeCommand; } // Builds commandInstance objects for every // command and piped command included in the // execution string. // Build the instances for each pipe. item.pipes = item.pipes.map(function (pipe) { return new CommandInstance({ commandWrapper: item, command: pipe.command._name, commandObject: pipe.command, args: pipe.args }); }); // Reverse through the pipes and assign the // `downstream` object of each parent to its // child command. for (var k = item.pipes.length - 1; k > -1; --k) { var downstream = item.pipes[k + 1]; item.pipes[k].downstream = downstream; } item.session.execCommandSet(item, function (wrapper, err, data, argus) { callback(wrapper, err, data, argus); }); } else { // If no command match, just return. item.session.log(this._commandHelp(item.command)); callback(item, undefined, 'Invalid command.'); } }; /** * Exits out of a give 'mode' one is in. * Reverts history and delimiter back to * regular vorpal usage. * * @api private */ vorpal._exitMode = function (options) { var ssn = this.getSessionById(options.sessionId); ssn._mode = false; this.cmdHistory.exitMode(); ssn.modeDelimiter(false); }; /** * Registers a custom handler for SIGINT. * Vorpal exits with 0 by default * on a sigint. * * @param {Function} fn * @return {Vorpal} * @api public */ vorpal.sigint = function (fn) { if (_.isFunction(fn)) { ui.sigint(fn); } else { throw new Error('vorpal.sigint must be passed in a valid function.'); } return this; }; /** * Returns the instance of given command. * * @param {String} cmd * @return {Command} * @api public */ vorpal.find = function (name) { return _.findWhere(this.commands, {_name: name}); }; /** * Returns help string for a given command. * * @param {String} command * @api private */ vorpal._commandHelp = function (command) { if (!this.commands.length) { return ''; } var matches = []; var singleMatches = []; command = (command) ? String(command).trim().toLowerCase() : undefined; for (var i = 0; i < this.commands.length; ++i) { var parts = String(this.commands[i]._name).split(' '); if (parts.length === 1 && parts[0] === command && !this.commands[i]._hidden && !this.commands[i]._catch) { singleMatches.push(command); } var str = ''; for (var j = 0; j < parts.length; ++j) { str = String(str + ' ' + parts[j]).trim(); if (str === command && !this.commands[i]._hidden && !this.commands[i]._catch) { matches.push(this.commands[i]); break; } } } var invalidString = (command && matches.length === 0 && singleMatches.length === 0) ? ['', ' Invalid Command. Showing Help:', ''].join('\n') : ''; var commandMatch = (matches.length > 0); var commandMatchLength = (commandMatch) ? String(command).trim().split(' ').length + 1 : 1; matches = (matches.length === 0) ? this.commands : matches; var commands = matches.filter(function (cmd) { return !cmd._noHelp; }).filter(function (cmd) { return !cmd._catch; }).filter(function (cmd) { return !cmd._hidden; }).filter(function (cmd) { return (String(cmd._name).trim().split(' ').length <= commandMatchLength); }).map(function (cmd) { var args = cmd._args.map(function (arg) { return VorpalUtil.humanReadableArgName(arg); }).join(' '); return [ cmd._name + (cmd._alias ? '|' + cmd._alias : '') + (cmd.options.length ? ' [options]' : '') + ' ' + args, cmd.description() ]; }); var width = commands.reduce(function (max, commandX) { return Math.max(max, commandX[0].length); }, 0); var counts = {}; var groups = _.uniq(matches.filter(function (cmd) { return (String(cmd._name).trim().split(' ').length > commandMatchLength); }).map(function (cmd) { return String(cmd._name).split(' ').slice(0, commandMatchLength).join(' '); }).map(function (cmd) { counts[cmd] = counts[cmd] || 0; counts[cmd]++; return cmd; })).map(function (cmd) { return ' ' + VorpalUtil.pad(cmd + ' *', width) + ' ' + counts[cmd] + ' sub-command' + ((counts[cmd] === 1) ? '' : 's') + '.'; }); var commandsString = (commands.length < 1) ? '' : '\n Commands:' + '\n\n' + commands .map(function (cmd) { return VorpalUtil.pad(cmd[0], width) + ' ' + cmd[1]; }) .join('\n') .replace(/^/gm, ' ') + '\n\n'; var groupsString = (groups.length < 1) ? '' : ' Command Groups:\n\n' + groups.join('\n') + '\n'; var results = String(invalidString + commandsString + '\n' + groupsString).replace(/\n\n\n/g, '\n\n'); return results; }; /** * Abstracts the logic for sending and * receiving sockets upstream and downstream. * * To do: Has the start of logic for vorpal sessions, * which I haven't fully confronted yet. * * @param {String} str * @param {String} direction * @param {String} data * @param {Object} options * @api private */ vorpal._send = function (str, direction, data, options) { options = options || {}; data = data || {}; var ssn = this.getSessionById(data.sessionId); if (!ssn) { throw new Error('No Sessions logged for ID ' + data.sessionId + ' in vorpal._send.'); } if (direction === 'upstream') { if (ssn.client) { ssn.client.emit(str, data); } } else if (direction === 'downstream') { if (ssn.server) { ssn.server.emit(str, data); } } }; /** * Handles the 'middleman' in a 3+-way vagrant session. * If a vagrant instance is a 'client' and 'server', it is * now considered a 'proxy' and its sole purpose is to proxy * information through, upstream or downstream. * * If vorpal is not a proxy, it resolves a promise for further * code that assumes one is now an end user. If it ends up * piping the traffic through, it never resolves the promise. * * @param {String} str * @param {String} direction * @param {String} data * @param {Object} options * @api private */ vorpal._proxy = function (str, direction, data, options) { var self = this; return new Promise(function (resolve) { var ssn = self.getSessionById(data.sessionId); if (ssn && (!ssn.isLocal() && ssn.client)) { self._send(str, direction, data, options); } else { resolve(); } }); }; /** * Returns session by id. * * @param {Integer} id * @return {Session} * @api public */ vorpal.getSessionById = function (id) { if (_.isObject(id)) { throw new Error('vorpal.getSessionById: id ' + JSON.stringify(id) + ' should not be an object.'); } var ssn = _.findWhere(this.server.sessions, {id: id}); ssn = (this.session.id === id) ? this.session : ssn; if (!id) { throw new Error('vorpal.getSessionById was called with no ID passed.'); } if (!ssn) { var sessions = { local: this.session.id, server: _.pluck(this.server.sessions, 'id') }; throw new Error('No session found for id ' + id + ' in vorpal.getSessionById. Sessions: ' + JSON.stringify(sessions)); } return ssn; }; /** * Kills a remote vorpal session. If user * is running on a direct terminal, will kill * node instance after confirmation. * * @param {Object} options * @param {Function} cb * @api private */ vorpal.exit = function (options) { var self = this; var ssn = this.getSessionById(options.sessionId); if (ssn.isLocal()) { if (options.force) { process.exit(1); } else { this.prompt({ type: 'confirm', name: 'continue', default: false, message: 'This will actually kill this node process. Continue?', sessionId: ssn.id }, function (result) { if (result.continue) { process.exit(1); } else { self._prompt({sessionId: ssn.id}); } }); } } else { ssn.server.emit('vantage-close-downstream', {sessionId: ssn.id}); } }; Object.defineProperty(vorpal, 'activeCommand', { get: function () { var result = (this._command) ? this._command.commandInstance : undefined; return result; } });
/** * Run with: * $ node server.js */ var http = require('http'), url = require('url'), fs = require('fs'), path = require('path'), mime = require('mime'); function serveStaticFile(filename, response) { if (fs.statSync(filename).isDirectory()) filename += 'index.html'; fs.readFile(filename, 'binary', function (err, file) { if (err) { response.writeHead(500, { 'Content-Type': 'text/plain' }); response.write(err + "\n"); response.end(); return; } response.writeHead(200, { 'Content-Type': mime.lookup(filename) }); response.write(file, 'binary'); response.end(); }); } http.createServer(function (request, response) { var filename = path.join(__dirname, url.parse(request.url).pathname); fs.exists(filename, function (exists) { if (!exists) { response.writeHead(404, { 'Content-Type': 'text/plain' }); response.write("404 Not Found\n"); response.end(); return; } serveStaticFile(filename, response); }); }).listen(8080); console.info('------------------------------------------'); console.info('Server listening at http://localhost:8080/'); console.info('------------------------------------------');
var vImage = Aspectize.CreateView("Image", aas.Controls.ImageControl, aas.Zones.SideBarContent.ZoneContent); vImage.OnActivated.BindCommand(aas.Services.Browser.BootStrapClientService.ActiveLiElement(aas.ViewName.Image)); vImage.ImageProduct.OnNeedImage.BindCommand(aas.Services.Server.LoadDataService.LoadImage(vImage.SelectProduct.CurrentValue)); vImage.SelectProduct.BindList(aas.Data.AdventureWorksData.Product, "ProductID", "Name", "Name ASC"); vImage.SelectProduct.CurrentSyncDisabled.BindData(false);
/* * Copyright (c) 2014 airbug inc. http://airbug.com * * bugpack may be freely distributed under the MIT license. */ //------------------------------------------------------------------------------- // Context //------------------------------------------------------------------------------- require('./BugPackFix').fix(module, "./BugPackSourceProcessor", function(module) { //------------------------------------------------------------------------------- // Declare Class //------------------------------------------------------------------------------- /** * @constructor * @param {BugPackSource} bugPackSource * @param {BugPackContext} bugPackContext */ var BugPackSourceProcessor = function(bugPackSource, bugPackContext) { //------------------------------------------------------------------------------- // Private Properties //------------------------------------------------------------------------------- /** * @private * @type {BugPackSource} */ this.bugPackSource = bugPackSource; /** * @private * @type {BugPackContext} */ this.bugPackContext = bugPackContext; /** * @private * @type boolean} */ this.processed = false; /** * @private * @type {Array} */ this.processedCallbacks = []; /** * @private * @type {boolean} */ this.processingStarted = false; }; //------------------------------------------------------------------------------- // Getters and Setters //------------------------------------------------------------------------------- /** * @return {BugPackSource} */ BugPackSourceProcessor.prototype.getBugPackSource = function() { return this.bugPackSource; }; //------------------------------------------------------------------------------- // Public Methods //------------------------------------------------------------------------------- /** * @param {function(Error=)} callback */ BugPackSourceProcessor.prototype.addProcessedCallback = function(callback) { this.processedCallbacks.push(callback); }; /** * @return {boolean} */ BugPackSourceProcessor.prototype.hasProcessed = function() { return this.processed; }; /** * @return {boolean} */ BugPackSourceProcessor.prototype.hasProcessingStarted = function() { return this.processingStarted; }; /** * */ BugPackSourceProcessor.prototype.process = function() { if (!this.processed && !this.processingStarted) { this.processingStarted = true; this.processSource(); } }; /** * */ BugPackSourceProcessor.prototype.processSync = function() { if (!this.processed) { this.processingStarted = true; this.processSourceSync(); } }; //------------------------------------------------------------------------------- // Private Methods //------------------------------------------------------------------------------- //TODO BRN: This class is super tightly coupled with BugPackContext and really ugly. Figure out how to cleanly break this apart. /** * @private */ BugPackSourceProcessor.prototype.loadBugPackSource = function() { var _this = this; if (!this.bugPackSource.hasLoaded()) { this.bugPackSource.addLoadCallback(function(error) { _this.processingComplete(error); }); if (!this.bugPackSource.hasLoadStarted()) { this.bugPackContext.getBugPackApi().setCurrentContext(this.bugPackContext); this.bugPackSource.load(); } } else { this.processingComplete(); } }; /** * @private */ BugPackSourceProcessor.prototype.loadBugPackSourceSync = function() { if (!this.bugPackSource.hasLoaded()) { if (!this.bugPackSource.hasLoadStarted()) { this.bugPackContext.getBugPackApi().setCurrentContext(this.bugPackContext); this.bugPackSource.loadSync(); } } }; /** * @private * @param {Error=} error */ BugPackSourceProcessor.prototype.processingComplete = function(error) { if (!this.processed) { this.processed = true; this.processedCallbacks.forEach(function (processedCallback) { processedCallback(error); }); this.processedCallbacks = []; } }; /** * @private */ BugPackSourceProcessor.prototype.processSource = function() { var _this = this; var registryEntry = this.bugPackContext.getRegistry().getEntryBySourceFilePath(this.bugPackSource.getSourceFilePath()); var requiredExports = registryEntry.getRequires(); if (requiredExports.length > 0) { var loadedExportsCount = 0; requiredExports.forEach(function(requiredExport) { _this.bugPackContext.processExport(requiredExport, function(error) { if (!error) { loadedExportsCount++; if (loadedExportsCount === requiredExports.length) { _this.loadBugPackSource(); } } else { _this.processingComplete(error); } }); }); } else { this.loadBugPackSource(); } }; /** * @private */ BugPackSourceProcessor.prototype.processSourceSync = function() { var _this = this; var registryEntry = this.bugPackContext.getRegistry().getEntryBySourceFilePath(this.bugPackSource.getSourceFilePath()); var requiredExports = registryEntry.getRequires(); requiredExports.forEach(function(requiredExport) { _this.bugPackContext.processExportSync(requiredExport); }); this.loadBugPackSourceSync(); }; //------------------------------------------------------------------------------- // Exports //------------------------------------------------------------------------------- module.exports = BugPackSourceProcessor; });
'use strict'; (function() { // General item outward entries Controller Spec describe('General item outward entries Controller Tests', function() { // Initialize global variables var GeneralItemOutwardEntriesController, scope, $httpBackend, $stateParams, $location; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function() { jasmine.addMatchers({ toEqualData: function(util, customEqualityTesters) { return { compare: function(actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { // Set a new global scope scope = $rootScope.$new(); // Point global variables to injected services $stateParams = _$stateParams_; $httpBackend = _$httpBackend_; $location = _$location_; // Initialize the General item outward entries controller. GeneralItemOutwardEntriesController = $controller('GeneralItemOutwardEntriesController', { $scope: scope }); })); it('$scope.find() should create an array with at least one General item outward entry object fetched from XHR', inject(function(GeneralItemOutwardEntries) { // Create sample General item outward entry using the General item outward entries service var sampleGeneralItemOutwardEntry = new GeneralItemOutwardEntries({ name: 'New General item outward entry' }); // Create a sample General item outward entries array that includes the new General item outward entry var sampleGeneralItemOutwardEntries = [sampleGeneralItemOutwardEntry]; // Set GET response $httpBackend.expectGET('general-item-outward-entries').respond(sampleGeneralItemOutwardEntries); // Run controller functionality scope.find(); $httpBackend.flush(); // Test scope value expect(scope.generalItemOutwardEntries).toEqualData(sampleGeneralItemOutwardEntries); })); it('$scope.findOne() should create an array with one General item outward entry object fetched from XHR using a generalItemOutwardEntryId URL parameter', inject(function(GeneralItemOutwardEntries) { // Define a sample General item outward entry object var sampleGeneralItemOutwardEntry = new GeneralItemOutwardEntries({ name: 'New General item outward entry' }); // Set the URL parameter $stateParams.generalItemOutwardEntryId = '525a8422f6d0f87f0e407a33'; // Set GET response $httpBackend.expectGET(/general-item-outward-entries\/([0-9a-fA-F]{24})$/).respond(sampleGeneralItemOutwardEntry); // Run controller functionality scope.findOne(); $httpBackend.flush(); // Test scope value expect(scope.generalItemOutwardEntry).toEqualData(sampleGeneralItemOutwardEntry); })); it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(GeneralItemOutwardEntries) { // Create a sample General item outward entry object var sampleGeneralItemOutwardEntryPostData = new GeneralItemOutwardEntries({ name: 'New General item outward entry' }); // Create a sample General item outward entry response var sampleGeneralItemOutwardEntryResponse = new GeneralItemOutwardEntries({ _id: '525cf20451979dea2c000001', name: 'New General item outward entry' }); // Fixture mock form input values scope.name = 'New General item outward entry'; // Set POST response $httpBackend.expectPOST('general-item-outward-entries', sampleGeneralItemOutwardEntryPostData).respond(sampleGeneralItemOutwardEntryResponse); // Run controller functionality scope.create(); $httpBackend.flush(); // Test form inputs are reset expect(scope.name).toEqual(''); // Test URL redirection after the General item outward entry was created expect($location.path()).toBe('/general-item-outward-entries/' + sampleGeneralItemOutwardEntryResponse._id); })); it('$scope.update() should update a valid General item outward entry', inject(function(GeneralItemOutwardEntries) { // Define a sample General item outward entry put data var sampleGeneralItemOutwardEntryPutData = new GeneralItemOutwardEntries({ _id: '525cf20451979dea2c000001', name: 'New General item outward entry' }); // Mock General item outward entry in scope scope.generalItemOutwardEntry = sampleGeneralItemOutwardEntryPutData; // Set PUT response $httpBackend.expectPUT(/general-item-outward-entries\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality scope.update(); $httpBackend.flush(); // Test URL location to new object expect($location.path()).toBe('/general-item-outward-entries/' + sampleGeneralItemOutwardEntryPutData._id); })); it('$scope.remove() should send a DELETE request with a valid generalItemOutwardEntryId and remove the General item outward entry from the scope', inject(function(GeneralItemOutwardEntries) { // Create new General item outward entry object var sampleGeneralItemOutwardEntry = new GeneralItemOutwardEntries({ _id: '525a8422f6d0f87f0e407a33' }); // Create new General item outward entries array and include the General item outward entry scope.generalItemOutwardEntries = [sampleGeneralItemOutwardEntry]; // Set expected DELETE response $httpBackend.expectDELETE(/general-item-outward-entries\/([0-9a-fA-F]{24})$/).respond(204); // Run controller functionality scope.remove(sampleGeneralItemOutwardEntry); $httpBackend.flush(); // Test array after successful delete expect(scope.generalItemOutwardEntries.length).toBe(0); })); }); }());
'use strict'; /** * Module dependencies. */ var should = require('should'), mongoose = require('mongoose'), User = mongoose.model('User'), WritingBlock = mongoose.model('WritingBlock'); /** * Globals */ var user, writingBlock; /** * Unit tests */ describe('Writing block Model Unit Tests:', function() { beforeEach(function(done) { user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: 'username', password: 'password' }); user.save(function() { writingBlock = new WritingBlock({ name: 'Writing block Name', user: user }); done(); }); }); describe('Method Save', function() { it('should be able to save without problems', function(done) { return writingBlock.save(function(err) { should.not.exist(err); done(); }); }); it('should be able to show an error when try to save without name', function(done) { writingBlock.name = ''; return writingBlock.save(function(err) { should.exist(err); done(); }); }); }); afterEach(function(done) { WritingBlock.remove().exec(); User.remove().exec(); done(); }); });
"use strict"; const isKeyframeSelector = require("../../utils/isKeyframeSelector"); const isStandardSyntaxRule = require("../../utils/isStandardSyntaxRule"); const isStandardSyntaxSelector = require("../../utils/isStandardSyntaxSelector"); const isStandardSyntaxTypeSelector = require("../../utils/isStandardSyntaxTypeSelector"); const parseSelector = require("../../utils/parseSelector"); const report = require("../../utils/report"); const ruleMessages = require("../../utils/ruleMessages"); const validateOptions = require("../../utils/validateOptions"); const ruleName = "selector-type-case"; const messages = ruleMessages(ruleName, { expected: (actual, expected) => `Expected "${actual}" to be "${expected}"` }); const rule = function(expectation) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual: expectation, possible: ["lower", "upper"] }); if (!validOptions) { return; } root.walkRules(rule => { const selector = rule.selector; const selectors = rule.selectors; if (!isStandardSyntaxRule(rule)) { return; } if (!isStandardSyntaxSelector(selector)) { return; } if (selectors.some(s => isKeyframeSelector(s))) { return; } parseSelector(selector, result, rule, selectorAST => { selectorAST.walkTags(tag => { if (!isStandardSyntaxTypeSelector(tag)) { return; } const sourceIndex = tag.sourceIndex; const value = tag.value; const expectedValue = expectation === "lower" ? value.toLowerCase() : value.toUpperCase(); if (value === expectedValue) { return; } report({ message: messages.expected(value, expectedValue), node: rule, index: sourceIndex, ruleName, result }); }); }); }); }; }; rule.ruleName = ruleName; rule.messages = messages; module.exports = rule;
/* * The MIT License (MIT) * * Copyright (c) 2016-2017 The Regents of the University of California * * 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. * */ /** * @author Jim Robinson */ var hic = (function (hic) { hic.NormalizationVector = function (type, chrIdx, unit, resolution, data, idx) { this.type = type; this.chrIdx = chrIdx; this.unit = unit; this.resolution = resolution; this.data = data; this.idx = idx; } hic.getNormalizationVectorKey = function (type, chrIdx, unit, resolution) { return type + "_" + chrIdx + "_" + unit + "_" + resolution; } hic.NormalizationVector.prototype.getKey = function () { return NormalizationVector.getKey(this.type, this.chrIdx, this.unit, this.resolution); } return hic; }) (hic || {});
window.onload = init; window.onkeydown = key.press; function init() { try { stb = gSTB; stb.ExecAction("graphicres " + graphicres_mode); stb.EnableServiceButton(true); } catch (e) { } try { modes.emulate = false; stb = gSTB; } catch (e) { modes.emulate = true; stb = egSTB; } VKBlock = true; win = {"width":screen.width, "height":screen.height}; gs.layers.game = document.getElementById('game').getContext('2d'); if (!gs.layers.game || !gs.layers.game.drawImage) { return; } var loc = new String(window.location); if (loc.indexOf('?') >= 0) { var parts = loc.substr(loc.indexOf('?') + 1).split('&'), _GET = new Object(); for (var key = 0; key < parts.length; key++) { var part = parts[key]; _GET[part.substr(0, part.indexOf('='))] = part.substr(part.indexOf('=') + 1); } pages.referrer = decodeURIComponent(_GET['referrer']); } else { pages.referrer = document.referrer; } switch (win.height) { case 480: cvDraw.mode = gs.actualSize = 480; graphicres_mode = "720"; break; case 576: cvDraw.mode = gs.actualSize = 576; graphicres_mode = "720"; break; case 720: cvDraw.mode = gs.actualSize = 720; graphicres_mode = "1280"; break; case 1080: cvDraw.mode = gs.actualSize = 1080; graphicres_mode = "1920"; break; } byID('game').width = gs.size[gs.actualSize].scr.w; byID('game').height = gs.size[gs.actualSize].scr.h; window.resizeTo(win.width, win.height); window.moveTo(0, 0); cvDraw.vars.model = stb.RDir("Model"); log('\'' + cvDraw.vars.model + '\''); var fileref = document.createElement("link"); fileref.setAttribute("rel", "stylesheet"); fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", 'css/screen_' + win.height + '.css'); document.getElementsByTagName("head")[0].appendChild(fileref); log('CSS file imported: "css/screen_' + win.height + '.css"'); gs.items = new Array(); for (var y = 0; y < gs.iItems.y; y++) { gs.items[y] = new Array(); for (var x = 0; x < gs.iItems.x; x++) { gs.items[y][x] = null; } } for (var i = 0, j = 0; i < gs.imgs.length; i++, j = j + 2) { gs.imgs[i].img.src = 'img/' + cvDraw.mode + '/' + gs.imgs[i].url; gs.arr[j] = gs.imgs[i].num; gs.arr[j + 1] = gs.imgs[i].num; } gs.arr = gs.arr.shuffle(); cvDraw.bg = new Image(); cvDraw.bg.src = 'img/' + cvDraw.mode + '/back.png'; cvDraw.bg.onload = function () { cvDraw.dBg(); } } var cvDraw = {"vars":{"model":"MAG200", "started":false, "selected":false, "selectedObj":{"x":0, "y":0, "num":0}, "gameTime":0, "timer":null, "openOne":false, "counterSteps":0, "counterGoodSteps":0}, "mode":null, "bg":new Object(), "dBg":function () { for (var y = 0; y < gs.iItems.y; y++) { for (var x = 0; x < gs.iItems.x; x++) { gs.layers.game.clearRect(gs.size[gs.actualSize].cll.w * x, gs.size[gs.actualSize].cll.h * y, gs.size[gs.actualSize].cll.w, gs.size[gs.actualSize].cll.h); gs.layers.game.drawImage(this.bg, gs.size[gs.actualSize].cll.w * x, gs.size[gs.actualSize].cll.h * y, gs.size[gs.actualSize].cll.w, gs.size[gs.actualSize].cll.h); } } }, "start":function () { var cnr = 0; for (var y = 0; y < gs.iItems.y; y++) { for (var x = 0; x < gs.iItems.x; x++) { var self = this; gs.items[y][x] = {"x":x, "y":y, "status":"free", "selected":false, "img":gs.arr[cnr++], "timer":{"obj":null, "interval":50, "_scale":1, "cond":"stop", "func":function (x, y, back) { var img; if (!back) { if (this.cond == "from") { img = gs.imgs[gs.items[y][x].img].img; } if (this.cond == "to") { img = self.bg; } } else { if (this.cond == "from") { img = self.bg; } if (this.cond == "to") { img = gs.imgs[gs.items[y][x].img].img; } } if (this.cond == "from") { this._scale = this._scale - 0.2; if (this._scale <= 0.2) { this.cond = "to"; } } if (this.cond == "to") { if (this._scale < 0.2) { this._scale = 0.2; } else { this._scale = this._scale + 0.2; if (this._scale >= 0.8) { this._scale = 1; clearInterval(this.obj); this.obj = null; this.cond = "stop"; } } } gs.layers.game.clearRect(gs.size[gs.actualSize].cll.w * x, gs.size[gs.actualSize].cll.h * y, gs.size[gs.actualSize].cll.w, gs.size[gs.actualSize].cll.h); gs.layers.game.drawImage(img, gs.size[gs.actualSize].cll.w * x + (1 - this._scale) * gs.size[gs.actualSize].cll.w / 2, gs.size[gs.actualSize].cll.h * y, gs.size[gs.actualSize].cll.w * this._scale, gs.size[gs.actualSize].cll.h); }}}; gs.layers.game.clearRect(gs.size[gs.actualSize].cll.w * x, gs.size[gs.actualSize].cll.h * y, gs.size[gs.actualSize].cll.w, gs.size[gs.actualSize].cll.h); gs.layers.game.drawImage(gs.imgs[gs.arr[cnr - 1]].img, gs.size[gs.actualSize].cll.w * x, gs.size[gs.actualSize].cll.h * y, gs.size[gs.actualSize].cll.w, gs.size[gs.actualSize].cll.h); } } var self = this; setTimeout(function () { self.dBg(); self.item(); log('\n\n\n\n\n\n*******************START\n\n\n\n\n\n'); self.vars.started = true; VKBlock = false; if (self.vars.timer != null) { clearInterval(self.vars.timer); } self.vars.timer = null; self.vars.timer = setInterval(function () { self.vars.gameTime++; var mins = Math.floor(self.vars.gameTime / 60), secs = (self.vars.gameTime - mins * 60); byID('counter_time').getElementsByClassName('cover')[0].innerHTML = (mins < 10 ? '0' + mins : mins) + ' ' + (secs < 10 ? '0' + secs : secs); if (self.vars.gameTime > 60 * 60) { byID('errorFinish').style.display = 'block'; if (self.vars.timer != null) { clearInterval(self.vars.timer); } self.vars.timer = null; VKBlock = true; self.vars.started = false; } }, 999); }, 5000); }, "item":function () { byID('cursor').style.display = 'block'; byID('cursor').style.marginLeft = gs.position.current.x * gs.size[gs.actualSize].cll.w + 'px'; byID('cursor').style.marginTop = gs.position.current.y * gs.size[gs.actualSize].cll.h + 'px'; }, "rotateCell":function (x, y, back) { if (!(cvDraw.vars.model == "MAG200" && win.width == 1920)) { if (gs.items[y][x].timer.cond == 'stop') { gs.items[y][x].timer.cond = "from"; if (!back) { gs.items[y][x].timer.obj = setInterval(function () { gs.items[y][x].timer.func(x, y, true); }, gs.items[y][x].timer.interval); } else { gs.items[y][x].timer.obj = setInterval(function () { gs.items[y][x].timer.func(x, y); }, gs.items[y][x].timer.interval); } } } else { log('MAG200&&1920'); gs.layers.game.clearRect(gs.size[gs.actualSize].cll.w * x, gs.size[gs.actualSize].cll.h * y, gs.size[gs.actualSize].cll.w, gs.size[gs.actualSize].cll.h); if (!back) { gs.layers.game.drawImage(gs.imgs[gs.items[y][x].img].img, gs.size[gs.actualSize].cll.w * x, gs.size[gs.actualSize].cll.h * y, gs.size[gs.actualSize].cll.w, gs.size[gs.actualSize].cll.h); } else { gs.layers.game.drawImage(this.bg, gs.size[gs.actualSize].cll.w * x, gs.size[gs.actualSize].cll.h * y, gs.size[gs.actualSize].cll.w, gs.size[gs.actualSize].cll.h); } } }, "PressOK":function () { if (this.vars.started == false && byID('errorFinish').style.display == 'block') { window.location.reload(true); return; } if (this.vars.started == false) { byID('errorFinish').style.display = 'none'; byID('Begin').style.display = 'none'; this.start(); } else { if (gs.items[gs.position.current.y][gs.position.current.x].status == "ready") { return; } this.vars.counter++; this.vars.counterSteps++; byID('counter_steps').getElementsByClassName('cover')[0].innerHTML = this.vars.counterSteps < 100 ? (this.vars.counterSteps < 10) ? '00' + this.vars.counterSteps : '0' + this.vars.counterSteps : this.vars.counterSteps; if (this.vars.selected == false) { this.vars.selectedObj.x = gs.position.current.x; this.vars.selectedObj.y = gs.position.current.y; this.vars.selectedObj.num = gs.items[gs.position.current.y][gs.position.current.x].img; this.rotateCell(gs.position.current.x, gs.position.current.y); this.vars.selected = true; } else { if (this.vars.selectedObj.x == gs.position.current.x && this.vars.selectedObj.y == gs.position.current.y) { return; } this.rotateCell(gs.position.current.x, gs.position.current.y); if (this.vars.selectedObj.num == gs.items[gs.position.current.y][gs.position.current.x].img) { gs.items[gs.position.current.y][gs.position.current.x].status = "ready"; gs.items[this.vars.selectedObj.y][this.vars.selectedObj.x].status = "ready"; this.vars.counterGoodSteps++; } else { var self = this, coords = {"x1":gs.position.current.x, "y1":gs.position.current.y, "x2":this.vars.selectedObj.x, "y2":this.vars.selectedObj.y}; this.rotateCell(coords.x1, coords.y1); setTimeout(function () { log('rotate back'); self.rotateCell(coords.x1, coords.y1, true); self.rotateCell(coords.x2, coords.y2, true); }, 1000); } this.vars.selected = false; if (this.vars.counterGoodSteps >= gs.iItems.x * gs.iItems.y / 2) { byID('errorFinish').style.display = 'block'; if (this.vars.timer != null) { clearInterval(this.vars.timer); } this.vars.timer = null; VKBlock = true; this.vars.started = false; } } } }};
/** * Welcome to your gulpfile! * this file will contain the build task that will responsible for minifying js & compile sass */ 'use strict'; var gulp = require('gulp'); var del = require('del'); var filter = require('gulp-filter'); var sourcemaps = require('gulp-sourcemaps'); var uglify = require('gulp-uglify'); var sass = require('gulp-sass'); var gutil = require('gulp-util'); var autoprefixer = require('gulp-autoprefixer'); var rename = require('gulp-rename'); var runSequence = require('run-sequence'); var minifyHtml = require('gulp-minify-html'); var angularTemplatecache = require('gulp-angular-templatecache'); var concat = require('gulp-concat'); var errorHandler = function (title) { 'use strict'; return function (err) { gutil.log(gutil.colors.red('[' + title + ']'), err.toString()); this.emit('end'); }; }; /** * Clean task for cleaning build folder before */ gulp.task('clean', function () { return del('dist/', { force: true }); }); gulp.task('partials', function () { return gulp.src('src/**/*.html') .pipe(minifyHtml({ empty: true, spare: true, quotes: true })) .pipe(angularTemplatecache('templateCacheHtml.js', { module: 'angular-css-spinners', root: 'src' })) .pipe(gulp.dest('temp')); }); gulp.task('minifyJs', function () { return gulp.src(['src/*.js', 'temp/*.js']) .pipe(concat('angular-css-spinners.js')) .pipe(uglify()).on('error', errorHandler('Uglify')) .pipe(rename(function (path) { path.basename += ".min"; path.extname = ".js" })) .pipe(gulp.dest('dist')); }); gulp.task('compileSass', function () { var sassOptions = { style: 'expanded' }; return gulp.src('src/*.scss') .pipe(sass(sassOptions)).on('error', errorHandler('Sass')) .pipe(autoprefixer()).on('error', errorHandler('Autoprefixer')) .pipe(gulp.dest('dist')) }); gulp.task('cleanTemp', function () { del('temp', { force: true }) }) /** * Default task clean temporaries directories and launch the * main optimization build task */ gulp.task('build', function () { runSequence('clean', 'partials', 'minifyJs','compileSass','cleanTemp') })
/* * grunt-yaml-to-swagger * * * Copyright (c) 2014 Cyril GIACOPINO * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ // Configuration to be run (and then tested). yaml_to_swagger: { all: { options: { route_path: './../../api/routes', models_path: './../../api/models/definitions', output_docs_path: './../../api/api_docs' } } } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'yaml_to_swagger']); // By default, lint and run all tests. grunt.registerTask('default', ['yaml_to_swagger']); };