code
stringlengths
2
1.05M
var path = require('path') var fs = require('fs') var [ packageJSON, ...scripts ] = process.argv.slice(2) var packageJSONPath = path.join(process.cwd(), packageJSON) var pJSON = require(packageJSONPath) var scriptKeys = scripts.filter((s, i) => i % 2 === 0) var scriptValues = scripts.filter((s, i) => i % 2) pJSON.scripts = scriptKeys.reduce((prev, curr, index) => { return Object.assign({}, prev, { [curr]: scriptValues[index] }) }, {}) fs.writeFileSync(packageJSONPath, JSON.stringify(pJSON, null, 2))
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-rc.5-master-3a0f323 */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.menu-bar */ angular.module('material.components.menuBar', [ 'material.core', 'material.components.menu' ]); angular .module('material.components.menuBar') .controller('MenuBarController', MenuBarController); var BOUND_MENU_METHODS = ['handleKeyDown', 'handleMenuHover', 'scheduleOpenHoveredMenu', 'cancelScheduledOpen']; /** * ngInject */ function MenuBarController($scope, $rootScope, $element, $attrs, $mdConstant, $document, $mdUtil, $timeout) { this.$element = $element; this.$attrs = $attrs; this.$mdConstant = $mdConstant; this.$mdUtil = $mdUtil; this.$document = $document; this.$scope = $scope; this.$rootScope = $rootScope; this.$timeout = $timeout; var self = this; angular.forEach(BOUND_MENU_METHODS, function(methodName) { self[methodName] = angular.bind(self, self[methodName]); }); } MenuBarController.$inject = ["$scope", "$rootScope", "$element", "$attrs", "$mdConstant", "$document", "$mdUtil", "$timeout"]; MenuBarController.prototype.init = function() { var $element = this.$element; var $mdUtil = this.$mdUtil; var $scope = this.$scope; var self = this; var deregisterFns = []; $element.on('keydown', this.handleKeyDown); this.parentToolbar = $mdUtil.getClosest($element, 'MD-TOOLBAR'); deregisterFns.push(this.$rootScope.$on('$mdMenuOpen', function(event, el) { if (self.getMenus().indexOf(el[0]) != -1) { $element[0].classList.add('md-open'); el[0].classList.add('md-open'); self.currentlyOpenMenu = el.controller('mdMenu'); self.currentlyOpenMenu.registerContainerProxy(self.handleKeyDown); self.enableOpenOnHover(); } })); deregisterFns.push(this.$rootScope.$on('$mdMenuClose', function(event, el, opts) { var rootMenus = self.getMenus(); if (rootMenus.indexOf(el[0]) != -1) { $element[0].classList.remove('md-open'); el[0].classList.remove('md-open'); } if ($element[0].contains(el[0])) { var parentMenu = el[0]; while (parentMenu && rootMenus.indexOf(parentMenu) == -1) { parentMenu = $mdUtil.getClosest(parentMenu, 'MD-MENU', true); } if (parentMenu) { if (!opts.skipFocus) parentMenu.querySelector('button:not([disabled])').focus(); self.currentlyOpenMenu = undefined; self.disableOpenOnHover(); self.setKeyboardMode(true); } } })); $scope.$on('$destroy', function() { while (deregisterFns.length) { deregisterFns.shift()(); } }); this.setKeyboardMode(true); }; MenuBarController.prototype.setKeyboardMode = function(enabled) { if (enabled) this.$element[0].classList.add('md-keyboard-mode'); else this.$element[0].classList.remove('md-keyboard-mode'); }; MenuBarController.prototype.enableOpenOnHover = function() { if (this.openOnHoverEnabled) return; this.openOnHoverEnabled = true; var parentToolbar; if (parentToolbar = this.parentToolbar) { parentToolbar.dataset.mdRestoreStyle = parentToolbar.getAttribute('style'); parentToolbar.style.position = 'relative'; parentToolbar.style.zIndex = 100; } angular .element(this.getMenus()) .on('mouseenter', this.handleMenuHover); }; MenuBarController.prototype.handleMenuHover = function(e) { this.setKeyboardMode(false); if (this.openOnHoverEnabled) { this.scheduleOpenHoveredMenu(e); } }; MenuBarController.prototype.disableOpenOnHover = function() { if (!this.openOnHoverEnabled) return; this.openOnHoverEnabled = false; var parentToolbar; if (parentToolbar = this.parentToolbar) { parentToolbar.style.cssText = parentToolbar.dataset.mdRestoreStyle || ''; } angular .element(this.getMenus()) .off('mouseenter', this.handleMenuHover); }; MenuBarController.prototype.scheduleOpenHoveredMenu = function(e) { var menuEl = angular.element(e.currentTarget); var menuCtrl = menuEl.controller('mdMenu'); this.setKeyboardMode(false); this.scheduleOpenMenu(menuCtrl); }; MenuBarController.prototype.scheduleOpenMenu = function(menuCtrl) { var self = this; var $timeout = this.$timeout; if (menuCtrl != self.currentlyOpenMenu) { $timeout.cancel(self.pendingMenuOpen); self.pendingMenuOpen = $timeout(function() { self.pendingMenuOpen = undefined; if (self.currentlyOpenMenu) { self.currentlyOpenMenu.close(true, { closeAll: true }); } menuCtrl.open(); }, 200, false); } }; MenuBarController.prototype.handleKeyDown = function(e) { var keyCodes = this.$mdConstant.KEY_CODE; var currentMenu = this.currentlyOpenMenu; var wasOpen = currentMenu && currentMenu.isOpen; this.setKeyboardMode(true); var handled, newMenu, newMenuCtrl; switch (e.keyCode) { case keyCodes.DOWN_ARROW: if (currentMenu) { currentMenu.focusMenuContainer(); } else { this.openFocusedMenu(); } handled = true; break; case keyCodes.UP_ARROW: currentMenu && currentMenu.close(); handled = true; break; case keyCodes.LEFT_ARROW: newMenu = this.focusMenu(-1); if (wasOpen) { newMenuCtrl = angular.element(newMenu).controller('mdMenu'); this.scheduleOpenMenu(newMenuCtrl); } handled = true; break; case keyCodes.RIGHT_ARROW: newMenu = this.focusMenu(+1); if (wasOpen) { newMenuCtrl = angular.element(newMenu).controller('mdMenu'); this.scheduleOpenMenu(newMenuCtrl); } handled = true; break; } if (handled) { e && e.preventDefault && e.preventDefault(); e && e.stopImmediatePropagation && e.stopImmediatePropagation(); } }; MenuBarController.prototype.focusMenu = function(direction) { var menus = this.getMenus(); var focusedIndex = this.getFocusedMenuIndex(); if (focusedIndex == -1) { focusedIndex = this.getOpenMenuIndex(); } var changed = false; if (focusedIndex == -1) { focusedIndex = 0; changed = true; } else if ( direction < 0 && focusedIndex > 0 || direction > 0 && focusedIndex < menus.length - direction ) { focusedIndex += direction; changed = true; } if (changed) { menus[focusedIndex].querySelector('button').focus(); return menus[focusedIndex]; } }; MenuBarController.prototype.openFocusedMenu = function() { var menu = this.getFocusedMenu(); menu && angular.element(menu).controller('mdMenu').open(); }; MenuBarController.prototype.getMenus = function() { var $element = this.$element; return this.$mdUtil.nodesToArray($element[0].children) .filter(function(el) { return el.nodeName == 'MD-MENU'; }); }; MenuBarController.prototype.getFocusedMenu = function() { return this.getMenus()[this.getFocusedMenuIndex()]; }; MenuBarController.prototype.getFocusedMenuIndex = function() { var $mdUtil = this.$mdUtil; var focusedEl = $mdUtil.getClosest( this.$document[0].activeElement, 'MD-MENU' ); if (!focusedEl) return -1; var focusedIndex = this.getMenus().indexOf(focusedEl); return focusedIndex; }; MenuBarController.prototype.getOpenMenuIndex = function() { var menus = this.getMenus(); for (var i = 0; i < menus.length; ++i) { if (menus[i].classList.contains('md-open')) return i; } return -1; }; /** * @ngdoc directive * @name mdMenuBar * @module material.components.menu-bar * @restrict E * @description * * Menu bars are containers that hold multiple menus. They change the behavior and appearence * of the `md-menu` directive to behave similar to an operating system provided menu. * * @usage * <hljs lang="html"> * <md-menu-bar> * <md-menu> * <button ng-click="$mdOpenMenu()"> * File * </button> * <md-menu-content> * <md-menu-item> * <md-button ng-click="ctrl.sampleAction('share', $event)"> * Share... * </md-button> * </md-menu-item> * <md-menu-divider></md-menu-divider> * <md-menu-item> * <md-menu-item> * <md-menu> * <md-button ng-click="$mdOpenMenu()">New</md-button> * <md-menu-content> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Document', $event)">Document</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Spreadsheet', $event)">Spreadsheet</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Presentation', $event)">Presentation</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Form', $event)">Form</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Drawing', $event)">Drawing</md-button></md-menu-item> * </md-menu-content> * </md-menu> * </md-menu-item> * </md-menu-content> * </md-menu> * </md-menu-bar> * </hljs> * * ## Menu Bar Controls * * You may place `md-menu-items` that function as controls within menu bars. * There are two modes that are exposed via the `type` attribute of the `md-menu-item`. * `type="checkbox"` will function as a boolean control for the `ng-model` attribute of the * `md-menu-item`. `type="radio"` will function like a radio button, setting the `ngModel` * to the `string` value of the `value` attribute. If you need non-string values, you can use * `ng-value` to provide an expression (this is similar to how angular's native `input[type=radio]` works. * * <hljs lang="html"> * <md-menu-bar> * <md-menu> * <button ng-click="$mdOpenMenu()"> * Sample Menu * </button> * <md-menu-content> * <md-menu-item type="checkbox" ng-model="settings.allowChanges">Allow changes</md-menu-item> * <md-menu-divider></md-menu-divider> * <md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 1</md-menu-item> * <md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 2</md-menu-item> * <md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 3</md-menu-item> * </md-menu-content> * </md-menu> * </md-menu-bar> * </hljs> * * * ### Nesting Menus * * Menus may be nested within menu bars. This is commonly called cascading menus. * To nest a menu place the nested menu inside the content of the `md-menu-item`. * <hljs lang="html"> * <md-menu-item> * <md-menu> * <button ng-click="$mdOpenMenu()">New</md-button> * <md-menu-content> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Document', $event)">Document</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Spreadsheet', $event)">Spreadsheet</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Presentation', $event)">Presentation</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Form', $event)">Form</md-button></md-menu-item> * <md-menu-item><md-button ng-click="ctrl.sampleAction('New Drawing', $event)">Drawing</md-button></md-menu-item> * </md-menu-content> * </md-menu> * </md-menu-item> * </hljs> * */ angular .module('material.components.menuBar') .directive('mdMenuBar', MenuBarDirective); /* ngInject */ function MenuBarDirective($mdUtil, $mdTheming) { return { restrict: 'E', require: 'mdMenuBar', controller: 'MenuBarController', compile: function compile(templateEl, templateAttrs) { if (!templateAttrs.ariaRole) { templateEl[0].setAttribute('role', 'menubar'); } angular.forEach(templateEl[0].children, function(menuEl) { if (menuEl.nodeName == 'MD-MENU') { if (!menuEl.hasAttribute('md-position-mode')) { menuEl.setAttribute('md-position-mode', 'left bottom'); // Since we're in the compile function and actual `md-buttons` are not compiled yet, // we need to query for possible `md-buttons` as well. menuEl.querySelector('button, a, md-button').setAttribute('role', 'menuitem'); } var contentEls = $mdUtil.nodesToArray(menuEl.querySelectorAll('md-menu-content')); angular.forEach(contentEls, function(contentEl) { contentEl.classList.add('md-menu-bar-menu'); contentEl.classList.add('md-dense'); if (!contentEl.hasAttribute('width')) { contentEl.setAttribute('width', 5); } }); } }); // Mark the child menu items that they're inside a menu bar. This is necessary, // because mnMenuItem has special behaviour during compilation, depending on // whether it is inside a mdMenuBar. We can usually figure this out via the DOM, // however if a directive that uses documentFragment is applied to the child (e.g. ngRepeat), // the element won't have a parent and won't compile properly. templateEl.find('md-menu-item').addClass('md-in-menu-bar'); return function postLink(scope, el, attr, ctrl) { el.addClass('_md'); // private md component indicator for styling $mdTheming(scope, el); ctrl.init(); }; } }; } MenuBarDirective.$inject = ["$mdUtil", "$mdTheming"]; angular .module('material.components.menuBar') .directive('mdMenuDivider', MenuDividerDirective); function MenuDividerDirective() { return { restrict: 'E', compile: function(templateEl, templateAttrs) { if (!templateAttrs.role) { templateEl[0].setAttribute('role', 'separator'); } } }; } angular .module('material.components.menuBar') .controller('MenuItemController', MenuItemController); /** * ngInject */ function MenuItemController($scope, $element, $attrs) { this.$element = $element; this.$attrs = $attrs; this.$scope = $scope; } MenuItemController.$inject = ["$scope", "$element", "$attrs"]; MenuItemController.prototype.init = function(ngModel) { var $element = this.$element; var $attrs = this.$attrs; this.ngModel = ngModel; if ($attrs.type == 'checkbox' || $attrs.type == 'radio') { this.mode = $attrs.type; this.iconEl = $element[0].children[0]; this.buttonEl = $element[0].children[1]; if (ngModel) { // Clear ngAria set attributes this.initClickListeners(); } } }; // ngAria auto sets attributes on a menu-item with a ngModel. // We don't want this because our content (buttons) get the focus // and set their own aria attributes appropritately. Having both // breaks NVDA / JAWS. This undeoes ngAria's attrs. MenuItemController.prototype.clearNgAria = function() { var el = this.$element[0]; var clearAttrs = ['role', 'tabindex', 'aria-invalid', 'aria-checked']; angular.forEach(clearAttrs, function(attr) { el.removeAttribute(attr); }); }; MenuItemController.prototype.initClickListeners = function() { var self = this; var ngModel = this.ngModel; var $scope = this.$scope; var $attrs = this.$attrs; var $element = this.$element; var mode = this.mode; this.handleClick = angular.bind(this, this.handleClick); var icon = this.iconEl; var button = angular.element(this.buttonEl); var handleClick = this.handleClick; $attrs.$observe('disabled', setDisabled); setDisabled($attrs.disabled); ngModel.$render = function render() { self.clearNgAria(); if (isSelected()) { icon.style.display = ''; button.attr('aria-checked', 'true'); } else { icon.style.display = 'none'; button.attr('aria-checked', 'false'); } }; $scope.$$postDigest(ngModel.$render); function isSelected() { if (mode == 'radio') { var val = $attrs.ngValue ? $scope.$eval($attrs.ngValue) : $attrs.value; return ngModel.$modelValue == val; } else { return ngModel.$modelValue; } } function setDisabled(disabled) { if (disabled) { button.off('click', handleClick); } else { button.on('click', handleClick); } } }; MenuItemController.prototype.handleClick = function(e) { var mode = this.mode; var ngModel = this.ngModel; var $attrs = this.$attrs; var newVal; if (mode == 'checkbox') { newVal = !ngModel.$modelValue; } else if (mode == 'radio') { newVal = $attrs.ngValue ? this.$scope.$eval($attrs.ngValue) : $attrs.value; } ngModel.$setViewValue(newVal); ngModel.$render(); }; angular .module('material.components.menuBar') .directive('mdMenuItem', MenuItemDirective); /* ngInject */ function MenuItemDirective($mdUtil) { return { controller: 'MenuItemController', require: ['mdMenuItem', '?ngModel'], priority: 210, // ensure that our post link runs after ngAria compile: function(templateEl, templateAttrs) { var type = templateAttrs.type; var inMenuBarClass = 'md-in-menu-bar'; // Note: This allows us to show the `check` icon for the md-menu-bar items. // The `md-in-menu-bar` class is set by the mdMenuBar directive. if ((type == 'checkbox' || type == 'radio') && templateEl.hasClass(inMenuBarClass)) { var text = templateEl[0].textContent; var buttonEl = angular.element('<md-button type="button"></md-button>'); buttonEl.html(text); buttonEl.attr('tabindex', '0'); templateEl.html(''); templateEl.append(angular.element('<md-icon md-svg-icon="check"></md-icon>')); templateEl.append(buttonEl); templateEl.addClass('md-indent').removeClass(inMenuBarClass); setDefault('role', type == 'checkbox' ? 'menuitemcheckbox' : 'menuitemradio', buttonEl); moveAttrToButton('ng-disabled'); } else { setDefault('role', 'menuitem', templateEl[0].querySelector('md-button, button, a')); } return function(scope, el, attrs, ctrls) { var ctrl = ctrls[0]; var ngModel = ctrls[1]; ctrl.init(ngModel); }; function setDefault(attr, val, el) { el = el || templateEl; if (el instanceof angular.element) { el = el[0]; } if (!el.hasAttribute(attr)) { el.setAttribute(attr, val); } } function moveAttrToButton(attribute) { var attributes = $mdUtil.prefixer(attribute); angular.forEach(attributes, function(attr) { if (templateEl[0].hasAttribute(attr)) { var val = templateEl[0].getAttribute(attr); buttonEl[0].setAttribute(attr, val); templateEl[0].removeAttribute(attr); } }); } } }; } MenuItemDirective.$inject = ["$mdUtil"]; })(window, window.angular);
/*global describe, beforeEach, it*/ 'use strict'; var assert = require('assert'); describe('gulptimate generator', function () { it('can be imported without blowing up', function () { var app = require('../app'); assert(app !== undefined); }); });
if (!error && response.statusCode === 200) { console.log(body); jsonContent = JSON.stringify(body); } console.log(response.statusCode); console.log('NYAMPE'); // empty 200 OK response for now res.writeHead(200, "OK", { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin' : '*' }); console.log(jsonContent); res.end(''+jsonContent); console.log('SENT'); // -------------- // ONCLICK console.log(dataParam); $.post('http://localhost:8080/', dataParam, function(data, status) { document.write(data); console.log(data); data = JSON.parse(data); for(id in data) { console.log(data[id]); } });
count=0; function add () { if(!(((document.getElementById('qt1').checked) || (document.getElementById('qt2').checked) || (document.getElementById('qt3').checked)) && ((document.getElementById('at1').checked) || (document.getElementById('at2').checked) ) ) ){ return; } count++; if (count>1) {location.reload(true);} var ans = document.main.atype.value; if ( ans =="multiple") { var newdiv = document.createElement('div'); newdiv.innerHTML = "<h4>Number of choices</h4><div class='form-group'><input type='number' id='num'name='choice'><br></div><input type='button' name='step2' onclick='option();' class='btn btn-primary'value='Proceed'>"; document.getElementById('cho').appendChild(newdiv); } else { option(); } } function option () { var ans = document.main.atype.value; var que = document.main.qtype.value; if (ans=='multiple') { if ((document.getElementById('num').value)== '' ){ return;} } if(que==1) {var newdiv = document.createElement('div'); newdiv.innerHTML = "<h4>Enter the question</h4><div class='form-group'><textarea rows='25' cols='50' name='quest' required></textarea></div> "; document.getElementById('cho').appendChild(newdiv); } else if (que==2) { var newdiv = document.createElement('div'); newdiv.innerHTML = "<h4>Select the image for question </h4> <div class='form-group'><input type='file' name='quesi' required></div> "; document.getElementById('cho').appendChild(newdiv); } else if (que==3) { var newdiv = document.createElement('div'); newdiv.innerHTML = "<h4>Enter the question</h4><div class='form-group'> <textarea rows='25' cols='50' name='quest'required></textarea></div> "; document.getElementById('cho').appendChild(newdiv); var newdiv = document.createElement('div'); newdiv.innerHTML = "<h4>Select the image for question </h4><div class='form-group'> <input type='file' name='quesi' required> </div>"; document.getElementById('cho').appendChild(newdiv); } if( ans =="multiple") { var num = document.main.choice.value; var i=1; while (i<=num) { var newdiv = document.createElement('div'); newdiv.innerHTML = "<h4>Option " + i + " </h4><div class='form-group'><input type='text' name='opt" + i + "' required></div>"; document.getElementById('cho').appendChild(newdiv); i++; } var newdiv = document.createElement('div'); newdiv.innerHTML = "<div class='form-group'><br></div><input name='submit'type='submit'class='btn btn-success' value='Submit'>"; document.getElementById('cho').appendChild(newdiv); } else { var newdiv = document.createElement('div'); newdiv.innerHTML = "<div class='form-group'><br></div><input type='submit' class='btn btn-success' value='Submit'>"; document.getElementById('cho').appendChild(newdiv); } }
"use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(require("./seller-list/sellers.list.component")); var seller_thumbnail_component_1 = require("./seller-thumbnail/seller.thumbnail.component"); exports.SellerThumbnail = seller_thumbnail_component_1.SellerThumbnail; __export(require("./seller-details/seller.details.component")); __export(require("./seller-profile/seller.profile.component")); var seller_add_product_component_1 = require("./seller-add-product/seller.add.product.component"); exports.SellerAddComponent = seller_add_product_component_1.SellerAddComponent; __export(require("./seller-profile-edit/seller.profile.edit.component")); var seller_products_filter_component_1 = require("./seller-products-filter/seller.products.filter.component"); exports.SellerProductsFilter = seller_products_filter_component_1.SellerProductsFilter; __export(require("./seller.routes")); //# sourceMappingURL=index.js.map
import React from 'react'; export default class Home extends React.Component { render() { return ( <h1>Hey, I am Home!</h1> ); } }
var gulp = require('gulp'); var sass = require('gulp-sass'); var minifyCss = require('gulp-minify-css'); var rename = require('gulp-rename'); var paths = { sass: ['./client/scss/**/*.scss'] }; gulp.task('default', ['sass', 'watch']); gulp.task('sass', function(done) { gulp.src('./client/scss/farol.scss') .pipe(sass()) .pipe(rename({basename: 'style'})) .pipe(gulp.dest('./client/public/css/')) .pipe(minifyCss({ keepSpecialComments: 0 })) .pipe(rename({extname: '.min.css' })) .pipe(gulp.dest('./client/public/css/')) .on('end', done); }); gulp.task('watch', function() { gulp.watch(paths.sass, ['sass']); });
var _ = require('underscore'); function Issue(id, description, creator) { this.id = id; this.description = description; this.creator = creator; this.critical = false; // TODO: last updated date this.assignee = Issue.UNASSIGNED; this.createdDate = new Date(); this.closed = false; this.closer = Issue.UNASSIGNED; this.closedDate = null; this.tags = []; } Issue.UNASSIGNED = 'nobody'; Issue.applyDefaults = function (issues) { _.each(issues, function (issue) { _.defaults(issue, { critical: false, closer: Issue.UNASSIGNED, closedDate: null, tags: [] }); }); return issues; }; module.exports = Issue;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const monadic_react_1 = require("../../../src/monadic_react"); exports.promise_sample = monadic_react_1.repeat(`input number`)(n => monadic_react_1.label("Insert an even number: ", true)(n => monadic_react_1.number("edit", "number")(n))(n))(0).then(`input number bind`, n => monadic_react_1.button(`Send ${n.toString()} further`, false, "button_key")(n).then("key", (n) => monadic_react_1.lift_promise(getResponse, // "never", { kind: "retry then show failure", times: 3, on_failure: monadic_react_1.string("view")("99999").map(a => undefined) }, "new promise", undefined)(n) .then("response_offer", (r) => { console.log("then in response"); return monadic_react_1.unit((n + 5) * 5); })) .map(n => `Your selection is ${n.toString()}`) .then(`button to string`, s => monadic_react_1.string("view")(s).ignore())); const getResponse = (request) => { console.log("getResponse"); return new Promise((resolve, reject) => { setTimeout(function () { console.log('Request'); //resolve(); reject(); }, 1000); }); }; //# sourceMappingURL=promise_sample.js.map
var Validators = require('../../').validators; var PostcodeData = require('../helpers/postcodes'); var isCoverageTest = require.cache[require.resolve('istanbul')]; var describeUnlessCoverage = isCoverageTest ? describe.skip : describe; describe('Postcode validation', function () { it('correctly validates empty string', function () { Validators.postcode('').should.be.ok; }); it('correctly rejects invalid postcodes', function () { Validators.postcode('A11AA A11AA').should.not.be.ok; Validators.postcode('N443 6DFG').should.not.be.ok; Validators.postcode('ABCD1234').should.not.be.ok; }); describeUnlessCoverage('Full postcode test - loads full UK postcode database, may take some time', function () { var testData; var test = function (pc) { try { Validators.postcode(pc).should.be.ok; } catch (e) { // echo out the failing postcode global.console.error('Failed postcode:', pc); throw e; } }; before(function (done) { PostcodeData.load(function (err, data) { testData = data; done(err); }); }); it('correctly validates uk postcodes with a single space', function () { testData.forEach(function (testPostcode) { var pc = testPostcode.replace(/ \s+/, ' '); test(pc); }); }); it('correctly validates uk postcodes with no spaces', function () { testData.forEach(function (testPostcode) { var pc = testPostcode.replace(/\s+/g, ''); test(pc); }); }); }); });
/* */ "format cjs"; foo = 1/a/2 foo = 1/a/ 2 foo = 1/a/(b+1) foo = 1/a/~bar.indexOf(baz) foo = 1/a/+str foo = 1/a/-1 foo = 1/a/-bar foo = 1/a/--bar foo = 1/a/ --bar foo = 1/a/ ++bar foo = 1/a/g+1 foo = 1/a/g - 1 foo = 1/a/g*1 foo = 1/a/g/1 foo = 1/a/g /1 if (1/a/g && foo) {} if (1/a/g && foo) {} if (1/a/g || foo) {} if (1/a/g === 3) {} foo = 1/a/g ? true : false nan = 1/a/'' nan = 1/a/ "" foo = 1/a/goo foo = 1/a/iff foo = 1/a/igor foo = 1/a/moo foo = 1/a/yüm foo = 1/a/imgyp
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { facebookLogin, googleLogin, loginUser } from '../App/AppActions'; import { getUserName } from '../App/AppReducer'; import styles from '../../main.css'; import grid from '../../grid.css'; class DangNhapPages extends Component { constructor(props) { super(props); this.state = { emailSDT: '', matKhau: '', remember: false, error: '' }; } componentWillMount() { if (this.props.userName !== '') { this.context.router.push('/'); } } componentWillReceiveProps(nextProps) { if (nextProps && nextProps.userName !== '') { this.context.router.push('/'); } } onSignIn = () => { const user = { userName: this.state.emailSDT, password: this.state.matKhau, }; this.props.dispatch(loginUser(user, this.state.remember)).then((res) => { if (res.user !== 'unknown' && res.user !== 'missing') { this.setState({ error: 'error' }); } else { this.setState({ error: '' }); } }); }; handleEmailChanged = (eventKey) => { this.setState({ emailSDT: eventKey.target.value }); }; handleMatKhauChanged = (eventKey) => { this.setState({ matKhau: eventKey.target.value }); }; signInByFacebook =() => { this.props.dispatch(facebookLogin(this.state.remember)); }; signInByGoogle =() => { this.props.dispatch(googleLogin(this.state.remember)); }; turnToSignUp = () => { this.context.router.push('/signup'); }; handleRemember = () => { this.setState({ remember: !this.state.remember }); }; render() { return ( <div> <div className={`panel panel-default col-sm-8 col-sm-offset-2 col-md-5 ${grid.loginLogoutPage}`}> <div style={{ padding: '20px' }}> <p className={styles.signInTitle}>ĐĂNG NHẬP</p> <div style={{ paddingTo: '10px' }}> <button onClick={this.signInByFacebook} className={styles.signInWithFacebook}> <i style={{ position: 'absolute' }} className="fa fa-facebook" aria-hidden="true" /> <span style={{fontSize: '11pt' }}> Đăng nhập bằng Facebook</span> </button> </div> <div style={{ marginBottom: '30px' }}> <button onClick={this.signInByGoogle} className={styles.signInWithGoogle}> <i style={{ position: 'absolute' }} className="fa fa-google-plus" aria-hidden="true" /> <span style={{fontSize: '11pt' }}>Đăng nhập bằng Google</span> </button> </div> <div className="text-center"> <hr className="hr-over" /> <span className={styles.spanOverHr}> <span className="ng-scope" style={{fontSize: '11pt' }}>Hoặc đăng nhập bằng Email/Số điện thoại</span> </span> </div> <div className="form-horizontal"> <div className={styles.inputGroup} style={{ marginTop: '-10px' }}> <input type="text" className="form-control" placeholder="Email/ Số điện thoại" style={{fontSize: '10pt' }} value={this.state.emailSDT} onChange={this.handleEmailChanged} onKeyDown={this.onSignIn} /> </div> <div className={styles.inputGroup} > <input type="password" className="form-control" placeholder="Mật khẩu" style={{ fontSize: '10pt' }} value={this.state.matKhau} onChange={this.handleMatKhauChanged} onKeyDown={this.onSignIn} /> </div> <div className={`row form-group ${styles.inputGroup}`} > <div className="col-md-6" > <label className="clearfix"> <input type="checkbox" checked={this.state.remember} onChange={this.handleRemember} style={{ marginRight: '10px', fontSize: '10pt' }} /> Ghi nhớ mật khẩu </label> </div> <div className="col-md-6"> <a href="#" className={`form-control ${styles.checkboxSignIn}`} style={{ fontSize: '10pt' }}>Bạn quên mật khẩu?</a> </div> </div> <div className="text-center" > <button onClick={this.onSignIn} className={styles.inputSignInButton}> ĐĂNG NHẬP </button> </div> <div className={`${styles.inputGroup} text-center`}> <p> <span style={{ fontSize: '10pt' }}>Bạn đã có tài khoản? </span> <span style={{ fontSize: '10pt' }}><a onClick={this.turnToSignUp} className={styles.registerNowSpan}>Đăng ký ngay</a></span> </p> </div> </div> </div> </div> </div> ); } } // Retrieve data from store as props function mapStateToProps(state) { return { userName: getUserName(state), }; } DangNhapPages.propTypes = { dispatch: PropTypes.func.isRequired, userName: PropTypes.string.isRequired, }; DangNhapPages.contextTypes = { router: PropTypes.object, }; export default connect(mapStateToProps)(DangNhapPages);
const assert = require('assert'); const mongo = require('mongodb').MongoClient; const BasicCollection = require('./lib/basic-collection'); const TypedCollection = require('./lib/typed-collection'); const constants = require('./lib/constants'); const EdgeCollection = require('./lib/edge-collection'); const builder = require('./lib/schema-builder'); const DbContext = require('./lib/db-context'); const QueryBuilder = require('./lib/query-builder/builder'); const edgeState = require('./bin/edge-state'); const PathBuilder = require('./lib/query-builder/path-builder'); const EdgePathCollection = require('./lib/edge-path-collection'); class Db { constructor(configuration){ this.configuration = configuration; this.collectionMap = new Map(); this.parameterMap = new Map(); this.constants = constants; } async connect(schema) { this.db = await mongo.connect(this.configuration.mongo.serverUrl); for(let collectionSchema of schema.collections) { let collection = new TypedCollection(this, collectionSchema); this.collectionMap.set(collectionSchema.name, collection); this.parameterMap.set(collectionSchema.parameterName, collection); this[collectionSchema.name] = collection; await collection.connect(); } for(let name in schema.basicCollections) { this[name] = new BasicCollection(this, {name}); await this[name].connect(); } this.edges = new EdgeCollection(this, schema); await this.edges.connect(); return this.openContext(); } openContext() { const ctx = new DbContext(); for(let [name, collection] of this.collectionMap) { collection.openContext(ctx); } this.edges.openContext(ctx); return ctx; } isNew(object) { return object._descriptor.state === constants.state.NEW; } data(object, expression, state) { return this.edges.data(object, expression, state); } expand(objects) { for(let object of objects) { assert(object._descriptor, 'routing queries start from loaded objects'); } return new QueryBuilder(async (builder) => { builder.starts = objects.map(o => o._descriptor); let paths = await this.edges.runSelect(builder); return paths; }, objects[0]._descriptor.collection.schema); } async _clearAll() { for(let [name, collection] of this.collectionMap) { await collection.clear(); } await this.edges.clear(); return this.openContext(); } //we need this to take advantage of ONE MERGE approach with edges!!! async merge(collections) { } async commit(ctx) { let promises = []; for(let [name, collection] of this.collectionMap) { promises.push(collection.commit(ctx)); } //do this later promises.push(this.edges.commit(ctx)); await Promise.all(promises); } sync() { for(let [name, collection] of this.collectionMap) { collection.sync(); } this.edges.sync(); } async scan(expression) { const builder = new PathBuilder(this.schema); const query = builder.build(expression); let paths = await this.edges.matrix.pathQuery(query); if (paths && paths.find(p=>p.length > 0)) { return new EdgePathCollection(paths, this); } return null; } disconnect(){ this.db.close(); } } module.exports = { Db, constants, builder, edgeState };
/* TERMS OF USE - EASING EQUATIONS Open source under the BSD License. Copyright © 2001 Robert Penner All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ function Behaviours() { this.elastic = function() { this.elastic = function(argOb) { try { this.elementRef = argOb[0]; this.elementStyle = this.elementRef.style; this.condition = argOb[1] || function() { return(true) } this.tension = (argOb[2]) ? (argOb[2] < 1) ? argOb[2] : .04 : .04; this.currentX = 0; this.currentY = 0; this.ddx=0; this.ddy=0; this.PX=0; this.PY=0; // determine target x,y switch(typeof(argOb[3])) { case 'object': this.master = argOb[3].style; this.targetX = function() { return(parseInt(this.master.left)); } this.targetY = function() { return(parseInt(this.master.top)); } break; case 'string': this.targetX = function() { return(System.Document.cursorX()); } this.targetY = function() { return(System.Document.cursorY()); } break; case 'number': this.tX = argOb[3]; this.tY = argOb[4]; this.targetX = function() { return(this.tX); } this.targetY = function() { return(this.tY); } break; default: break; } } catch(e) { System.handleException(e,arguments); } } this.main = function() { this.elementStyle.left = this.currentX = Math.round(this.PX+=(this.ddx+=((this.targetX()-this.PX-this.ddx))*this.tension)); this.elementStyle.top = this.currentY = Math.round(this.PY+=(this.ddy+=((this.targetY()-this.PY-this.ddy))*this.tension)); return(this.condition()); } } this.moveTo = function() { this.moveTo = function(argOb) { try { this.elementRef = argOb[0]; this.elementStyle = argOb[0].style; this.condition = argOb[1] || function() { if(this.time>this.duration) { return false; } return true; } this.time = 0; this.type = argOb[2]; this.xStart = parseInt(this.elementStyle.left); this.yStart = parseInt(this.elementStyle.top); this.xFinish = argOb[3]; this.yFinish = argOb[4]; this.duration = argOb[5]; this.xChange = this.xFinish - this.xStart; this.yChange = this.yFinish - this.yStart; this.currentX = 0; this.currentY = 0; this.setEasing(this.type); } catch(e) { System.handleException(e,arguments); } } this.setEasing = function(ease) { this.type = ease; switch(this.type.toLowerCase()) { /* * Cubic easing */ case "incubic": this.step = function() { this.currentX = this.xChange*Math.pow(this.time/this.duration,3)+this.xStart; this.currentY = this.yChange*Math.pow(this.time/this.duration,3)+this.yStart; } break; case "outcubic": this.step = function() { this.currentX = this.xChange*(Math.pow(this.time/this.duration-1,3)+1)+this.xStart; this.currentY = this.yChange*(Math.pow(this.time/this.duration-1,3)+1)+this.yStart; } break; case "inoutcubic": this.step = function() { time = this.time; this.currentX = ((time/=this.duration/2)<1) ? this.xChange/2 * Math.pow(time,3) + this.xStart : this.xChange/2 * (Math.pow(time-2,3)+2) + this.xStart; time = this.time; this.currentY = ((time/=this.duration/2)<1) ? this.yChange/2 * Math.pow(time,3) + this.yStart : this.yChange/2 * (Math.pow(time-2,3)+2) + this.yStart; } break; /* * Quadratic easing */ case "inquadratic": this.step = function() { time = this.time; this.currentX = this.xChange*(time/=this.duration)*time + this.xStart; time = this.time; this.currentY = this.yChange*(time/=this.duration)*time + this.yStart; } break; case "outquadratic": this.step = function() { time = this.time; this.currentX = -this.xChange*(time/=this.duration)*(time-2) + this.xStart; time = this.time; this.currentY = -this.yChange*(time/=this.duration)*(time-2) + this.yStart; } break; case "inoutquadratic": this.step = function() { time = this.time; this.currentX = ((time/=this.duration/2)<1) ? this.xChange/2*time*time + this.xStart : -this.xChange/2*((--time)*(time-2)-1) + this.xStart; time = this.time; this.currentY = ((time/=this.duration/2)<1) ? this.yChange/2*time*time + this.yStart : -this.yChange/2*((--time)*(time-2)-1) + this.yStart; } break; /* * Circular easing */ case "incircular": this.step = function() { time = this.time; this.currentX = this.xChange*(1-Math.sqrt(1-(time/=this.duration)*time)) + this.xStart; time = this.time; this.currentY = this.yChange*(1-Math.sqrt(1-(time/=this.duration)*time)) + this.yStart; } break; case "outcircular": this.step = function() { time = this.time; this.currentX = this.xChange*Math.sqrt(1-(time=time/this.duration-1)*time) + this.xStart; time = this.time; this.currentY = this.yChange*Math.sqrt(1-(time=time/this.duration-1)*time) + this.yStart; } break; case "inoutcircular": this.step = function() { time = this.time; this.currentX = ((time/=this.duration/2)<1) ? this.xChange/2*(1-Math.sqrt(1-time*time)) + this.xStart : this.xChange/2*(Math.sqrt(1-(time-=2)*time)+1) + this.xStart; time = this.time; this.currentY = ((time/=this.duration/2)<1) ? this.yChange/2*(1-Math.sqrt(1-time*time)) + this.yStart : this.yChange/2*(Math.sqrt(1-(time-=2)*time)+1) + this.yStart; } break; default: break; } } this.main = function() { this.step(); this.elementStyle.left = Math.round(this.currentX); this.elementStyle.top = Math.round(this.currentY); ++this.time; return(this.condition()); } } }
/** * Created by paulius on 03/08/16. */ import { Router } from 'express'; import * as StadiumController from '../controllers/stadium.controller'; const router = new Router(); // Get stadium by id router.route('/stadiums/:id').get(StadiumController.getStadiumById); router.route('/stadiums').get(StadiumController.getAllStadiums); export default router;
WY3D.Face3 = (function(){ function Face3(a, b, c, normal, color, materialIndex) { this.a = a; this.b = b; this.c = c; this.normal = normal instanceof WY3D.Vector3 ? normal : new WY3D.Vector3(); this.vertexNormals = normal instanceof Array ? normal : []; this.color = color === undefined ? 0xFFFFFFFF : color; this.vertexColors = color instanceof Array ? color : []; this.vertexTangents = []; this.centroid = new WY3D.Vector3(); } Face3.prototype = { constructor: WY3D.Face3, clone: function(){ var face = new WY3D.Face3(this.a, this.b, this.c); face.normal.copy(this.normal); face.color.copy(this.color); face.centroid.copy(this.centroid); var i, il; for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) { face.vertexNormals[ i ] = this.vertexNormals[ i ].clone(); } for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) { face.vertexColors[ i ] = this.vertexColors[ i ].clone(); } for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) { face.vertexTangents[ i ] = this.vertexTangents[ i ].clone(); } return face; } }; return Face3; })();
import test from "tape"; /** * isPrime detects if input is prime * @param {number} num The number to check * @returns {boolean} * * Assumptions * 1. 1, decimals, and negatives are not prime */ const isPrime = num => { if (typeof num !== "number") { throw TypeError( "Expected type number but received: " + Object.prototype.toString.call(num) ); } // remove simple cases: NaN, negatives and 1, and decimals if (Number.isNaN(num) || num < 2 || num % 1 !== 0) return false; if (num === 2) return true; let divisor = 2; // numbers divided by more than their half will return decimal while (divisor < num / 2) { if (num % divisor === 0) return false; divisor += 1; } return true; }; test("num is a number", t => { t.throws(() => isPrime("boot")); t.throws(() => isPrime({ bob: "hello" })); t.throws(() => isPrime(["hello"])); t.end(); }); test("num is not negative, decimal, or NaN", t => { t.notOk(isPrime(-34)); t.notOk(isPrime(0.34)); t.notOk(isPrime(NaN)); t.end(); }); test("isPrime detects prime successfully", t => { t.ok(isPrime(997), "997 is prime"); t.ok(isPrime(2), "2 is prime"); t.ok(isPrime(3), "3 is prime"); t.end(); }); test("isPrime returns false for non primes", t => { t.notOk(isPrime(6)); t.notOk(isPrime(1)); t.notOk(isPrime(15)); t.end(); }); /** * Factorial returns the factorial of a given number * @param {number} num * @returns {number} The factorial * Assumptions * num must be a postive integer */ const factorial = num => { if (typeof num !== "number") throw TypeError( `expected type number but received ${Object.prototype.toString.call(num)}` ); if (num < 0 || Number.isNaN(num) || num % 1 !== 0) throw Error("num must be a positive integer"); if (num === 0) return 1; let i = 1, fac = num; while (i < num) { fac *= num - i; i += 1; } return fac; }; test("factorial correctly calculates factorial", t => { t.equals(factorial(0), 1); t.equals(factorial(1), 1); t.equals(factorial(2), 2); t.equals(factorial(5), 120); t.end(); }); test("factorial rejects invalid input", t => { t.throws(() => factorial([])); t.throws(() => factorial({})); t.throws(() => factorial("hello")); t.throws(() => factorial(NaN)); t.throws(() => factorial(-34)); t.throws(() => factorial(3.9)); t.end(); }); Array.prototype.reverse = function reverse() { let reversed = []; this.forEach(x => reversed.unshift(x)); return reversed; }; test("reverse correctly reverses an array", t => { t.deepEqual([1, 2, 3, 4, 5].reverse(), [5, 4, 3, 2, 1]); t.deepEqual(["hello", "goodbye", "shmello"].reverse(), [ "shmello", "goodbye", "hello" ]); t.deepEqual(["hello"].reverse(), ["hello"]); t.deepEqual([].reverse(), []); t.end(); }); Array.prototype.indexOf = function indexOf(x) { for (let i = 0; i < this.length; i++) { if (x === this[i]) return i; } return -1; }; test("indexOf indentifies the correct index", t => { const obj = { name: 2 }; const arr = [obj, 1, 4, "hello", NaN]; t.equal(arr.indexOf(1), 1); t.equal(arr.indexOf("hello"), 3); t.equal(arr.indexOf(NaN), -1); t.equal(arr.indexOf(34), -1); t.equal(arr.indexOf(obj), 0); t.end(); }); /** * Find the missing number in sequence * Assumptions * 1. no repeats * 2. no spaces * 3. sequence starts at 1 */ const missing = arr => { for (let i = 0; i < arr.length; i++) { arr.sort(); if (i + 1 !== arr[i]) return i + 1; } return undefined; }; test("missing correctly identifies the missing value in sequence", t => { t.equals(missing([]), undefined); t.equals(missing([1, 4, 3]), 2); t.equals(missing([2, 3, 4]), 1); t.equals(missing([5, 1, 4, 2]), 3); t.equals(missing([1, 2, 3, 4]), undefined); t.end(); }); const missingFancy = arr => { const sum = arr.reduce((a, b) => a + b, 0); const sumSequence = len => len / 2 * (len + 1); if (sumSequence(arr.length) === sum) return undefined; return sumSequence(arr.length + 1) - sum; }; test("missing Fancy correctly identifies the missing value in sequence", t => { t.equals(missingFancy([]), undefined); t.equals(missingFancy([1, 4, 3]), 2); t.equals(missingFancy([2, 3, 4]), 1); t.equals(missingFancy([5, 1, 4, 2]), 3); t.equals(missingFancy([1, 2, 3, 4]), undefined); t.end(); }); const isBalanced = str => { if (typeof str !== "string") throw TypeError( `expected string but received ${Object.prototype.toString.call(str)}` ); let removed = str.replace(/[^{}]/g, ""); let reversed = removed .replace(/{|}/g, match => (match === "{" ? "}" : "{")) .split("") .reverse() .join(""); return removed === reversed && removed[0] !== "}"; }; test("isbalanced correctly identifies balanced strings", t => { t.notOk(isBalanced("}{")); t.notOk(isBalanced("{{}")); t.notOk(isBalanced("{{{}")); t.ok(isBalanced("{}{}")); t.ok(isBalanced("foo { bar { baz } boo }")); t.notOk(isBalanced("foo { bar { baz }")); t.notOk(isBalanced("foo { bar } }")); t.end(); });
const gulp = require('gulp'); const del = require('del'); const babel = require('gulp-babel'); const terser = require('gulp-terser'); const rename = require('gulp-rename'); const rollup = require('rollup').rollup; const rollupBabel = require('rollup-plugin-babel'); const babelConfig = { presets: [ ['@babel/preset-env', { loose: true, modules: false }] ], plugins: [ '@babel/plugin-proposal-export-default-from', '@babel/plugin-proposal-export-namespace-from' ] }; gulp.task('clean', () => del([ './es', './lib' ])); gulp.task('build', () => gulp.src('./src/**/*.js') .pipe(babel(babelConfig)) .pipe(gulp.dest('./es')) .pipe(babel({ plugins: ['@babel/plugin-transform-modules-commonjs'], })) .pipe(gulp.dest('./lib')) ); gulp.task('rollup', () => rollup({ input: './src/index.js', plugins: [ rollupBabel(babelConfig), ], external: ['underscore'], }).then(bundle => bundle.write({ file: './lib/browser.js', format: 'amd', name: 'plug-modules', })) ); const minify = () => gulp.src('./lib/browser.js') .pipe(terser()) .pipe(rename('plug-modules.js')) .pipe(gulp.dest('./')); gulp.task('rollup:min', gulp.series('rollup', minify)); gulp.task('default', gulp.parallel('build', 'rollup:min'));
/********************************************* * app-src/js/ycalendar.js * YeAPF 0.8.62-100 built on 2019-05-09 19:34 (-3 DST) * Copyright (C) 2004-2019 Esteban Daniel Dortta - dortta@yahoo.com * 2018-05-30 11:21:04 (-3 DST) * First Version (C) August 2013 - esteban daniel dortta - dortta@yahoo.com **********************************************/ //# sourceURL=app-src/js/ycalendar.js /* * cfg elements * view: 0 || 1 || 2 * orientation: 0 (landscape) || 1 (portrait) * date: Date() * dateScope { first: YYMMDDhhmmss, last: YYMMDDhhmmss} * dayEntryDivision: 20 (minutes) * cellSize { width: integer(px), height: integer (px) } * divContainerName: string */ var yCalendar = function (cfg) { var that = { }; that.cfg = cfg || { }; /* 0-month 1-week 2-day */ that.cfg.view = +(that.cfg.view || 0); /* * 0 - landscape * 1 - portrait */ that.cfg.orientation = +(that.cfg.orientation || 0); /* * highlight date (or today as default) */ that.cfg.date = (that.cfg.date || new Date()); /* * common division for day visualization (minutes) */ that.cfg.dayEntryDivision = that.cfg.dayEntryDivision || 20; /* * cell size in pixels */ if (that.cfg.cellSize) { that.cfg.cellSize.width = that.cfg.cellSize.width || null; that.cfg.cellSize.height = that.cfg.cellSize.height || null; } else that.cfg.cellSize = { width: null , height: null}; /* * div container where to place the calendar */ that.cfg.divContainerName = that.cfg.divContainerName || ''; /* * callback function to be called on different moments */ that.cfg.callback = that.cfg.callback || null; that.context = { }; that.context.dateScope = { first: '', last: '' }; that.context.nCols = 0; that.context.nRows = 0; /* * configuration functions */ /* * set the container (div) to place the calendar */ that.setDivContainerName = function(aDivName) { that.cfg.divContainerName = aDivName; return that; } /* * set cell size (width x height) in pixels */ that.setCellSize = function(aCellWidth, aCellHeight) { that.cfg.cellSize.width = that.cfg.cellSize.width || aCellWidth; that.cfg.cellSize.height = that.cfg.cellSize.height || aCellHeight; return that; } that.setView = function(aView) { that.cfg.view = +(aView) % 3; return that; } that.setCallback = function(aCallback) { that.cfg.callback = aCallback; return that; } that.setDate = function(aDate) { that.cfg.date = aDate || that.cfg.date; return that; } that.getDate = function() { return that.cfg.date; } /* * set calendar orientation (0-landscape 1-portrait) */ that.setOrientation = function(aOrientation) { that.cfg.orientation = (+(aOrientation) % 2); return that; } /* style that will be used calBand, calDayLCell, calWeekLCell, calMonthLCell calDayPCell, calWeekPCell, calMonthPCell calEmptyDayCel, calEmptyWeekCell, calEmptyMonthCell */ that.draw = function(aCaller) { var orientationTag = ['L', 'P']; var theDiv = y$(that.cfg.divContainerName); if (theDiv) { try { /* status = 0. DOM BEING CREATED */ that.cfg.status = 0; if (that.cfg.callback != null) that.cfg.callback(that, 'DOMLocked', theDiv); var aTag = null, aCellID = null, aTagClass = null, aCellContent = null, aAuxTag = null, aDiv = null, aSpan = null, aText = null; /* month ans week views increments in day chunks */ if (that.cfg.view<2) var inc = 24 * 60 * 60 * 1000; else var inc = that.cfg.dayEntryDivision * 60 * 1000; var colNumber = 0, rowNumber=0; /* * create a class base name to be used with all the elements * that is: calDay followed by L(landscape) or P (portrait) */ var classBaseName = 'calDay'+orientationTag[that.cfg.view % 2]; /* remove all children nodes */ while (theDiv.hasChildNodes()) { theDiv.removeChild(theDiv.lastChild); } /* create the calendar table */ that.context.oCalTable = document.createElement('table'); that.context.oCalTable.cellPadding=0; that.context.oCalTable.cellSpacing=0; var oTR = that.context.oCalTable.insertRow(-1); var oTD = oTR.insertCell(); oTD.className = 'calBand'; var openRow = true; var emptyCellCount = 0; var extraStyle = { }; if (that.cfg.cellSize.height != null) extraStyle.height = parseInt(that.cfg.cellSize.height) + 'px'; if (that.cfg.cellSize.width != null) extraStyle.width = parseInt(that.cfg.cellSize.width) + 'px'; var d1 = that.context.dateScope.first; var d2 = that.context.dateScope.last; d1.setHours(12); d2.setHours(12); var createEmptyCell = function() { /* create an unique ID for the empty day */ aCellID = that.cfg.divContainerName+"_empty_"+emptyCellCount; /* create an empty day */ var aDiv = document.createElement('div'); mergeObject(extraStyle, aDiv.style); aDiv.id = aCellID; aDiv.className = classBaseName+"Cell "+classBaseName+"EmptyCell"; oTD.appendChild(aDiv); if (that.cfg.orientation==0) colNumber++; emptyCellCount++; /* call callback function */ if (that.cfg.callback!= null) that.cfg.callback(that, 'getEmptyDayContent', aDiv); } var createFilledCell = function (aTagType) { if (aTagType==0) { aCellID = that.cfg.divContainerName+'_day_'+d.toUDate().substring(0,8); aTag = d.getDate(); } else { aTag = d.getHours()+':'+d.getMinutes(); aCellID = that.cfg.divContainerName+'_day_'+d.toUDate().substring(0, 12); } } var d = new Date(d1); var interactions = (d2 - d) / inc + 1; if (that.cfg.view === 0) { if (that.cfg.orientation==0) { for(n = 0; n < d1.getDay(); n++) { createEmptyCell(); } } else { d.setDate( d.getDate() - d1.getDay() ); var dOffset = []; var dAux = new Date(d); for(n = 0; n < that.context.nRows; n++) { dOffset[n] = new Date(dAux); dAux.setDate(dAux.getDate()+1); } } } while (interactions>0) { if (!openRow) { oTR = that.context.oCalTable.insertRow(-1); oTD = oTR.insertCell(); oTD.className = 'calBand'; openRow = true; } aTag = ''; if (that.cfg.orientation==1) { if ((d<d1) || (d>d2)) createEmptyCell(); else { if ((that.cfg.view === 0) || (that.cfg.view === 1)) { createFilledCell(0); } else if (that.cfg.view === 2){ createFilledCell(1); } else _dumpy(8,1,"Not implemented"); } } else if (that.cfg.orientation==0) { if ((that.cfg.view === 0) || (that.cfg.view === 1)) { createFilledCell(0); } else if (that.cfg.view === 2) { createFilledCell(1); } else _dumpy(8,1,"Not implemented"); } if (aTag>'') { aTagClass = classBaseName+'Cell'; if (d.getDay() === 0) aTagClass += ' '+classBaseName+'FreeCell'; if (d.getDate()==that.cfg.date.getDate()) aTagClass += ' '+classBaseName+'Highlight'; /* create a day container */ aDiv = document.createElement('div'); mergeObject(extraStyle, aDiv.style); aDiv.id = aCellID; aDiv.className = aTagClass; mergeObject(extraStyle, aDiv.style); aDiv.date = d; /* create a day tag */ aSpan = document.createElement('span'); aSpan.id = aCellID+"_tag"; aSpan.className = 'calTag'; if (that.cfg.callback!= null) { aAuxTag = that.cfg.callback(that, 'getTagContent', aSpan) || ''; if (aAuxTag>'') aTag = aAuxTag; } aSpan.innerHTML = aTag; aDiv.appendChild(aSpan); if (that.cfg.callback!= null) { aText = that.cfg.callback(that, 'getCellContent', aDiv) || ''; if (aText>'') { aDiv.innerHTML += aText; } } oTD.appendChild(aDiv); } if (that.cfg.orientation==1) { d.setTime(d.getTime()+inc * that.context.nRows); } else d.setTime(d.getTime()+inc); colNumber++; if(colNumber>=that.context.nCols) { colNumber = 0; rowNumber++; openRow = false; if (that.cfg.orientation==1) d=dOffset[rowNumber]; } interactions--; } if (openRow) { while (colNumber<that.context.nCols) { createEmptyCell(); } colNumber = 0; openRow = false; } theDiv.appendChild(that.context.oCalTable); } catch(err) { _dumpy(8,1,'ERROR: '+err.message); } // status = 1. DOM READY that.cfg.status = 1; if (that.cfg.callback!= null) that.cfg.callback(that, 'DOMReleased', theDiv); } return that; } that.build = function(aDate, aView, aOrientation) { that.cfg.orientation = aOrientation || that.cfg.orientation; that.cfg.view = aView || that.cfg.view; that.cfg.date = aDate || that.cfg.date; var theDiv = y$(that.cfg.divContainerName); if (theDiv) { var d1 = new Date(that.cfg.date), d2 = null, secondsPerDay = 24 * 60 * 60 * 1000, nCols = 0, nRows = 0; switch (that.cfg.view) { case 0: // month view. nCols = 7; nRows = 5; // Recalculate dateScope d1.setDate(1); var d2 = new Date(d1); d2.setDate(d1.daysInMonth()); break; case 1: // week view. nCols = 1; nRows = 7; // Recalculate dateScope var d1 = new Date(that.cfg.date); while (d1.getDay()>0) d1.setTime(d1.getTime()-secondsPerDay) var d2 = new Date(d1); d2.setTime(d1.getTime()+secondsPerDay * 6); break; case 2: // day view nCols = 1; nRows = Math.round(24 * 60 / that.cfg.dayEntryDivision); // Recalculate dateScope d1.setHours(6); // <--- Need more config there d1.setMinutes(0); // <--- Need more config there var d2 = new Date(d1); d2.setHours(21); // <--- Need more config there d2.setMinutes(60-that.cfg.dayEntryDivision); break; default: _dumpy(8,1,"Not implemented"); } that.context.dateScope.first = d1; that.context.dateScope.last = d2; if (that.cfg.orientation === 1) { that.context.nCols = nRows; that.context.nRows = nCols; } else { that.context.nCols = nCols; that.context.nRows = nRows; } that.draw(that); _dumpy(8,1,"Build calendar on "+that.cfg.date.toUDate()+" View: "+that.cfg.view+" Orientation: "+that.cfg.orientation+" cols: "+nCols+" rows: "+nRows); } else _dumpy(8,1,"ERROR: "+that.cfg.divContainerName+" not found on that page"); return that; } that.each = function(aFunction) { if (typeof aFunction == 'function') { if (that.context.oCalTable) { var idSeed = that.cfg.divContainerName+"_day_"; var processElement = function (aTagSpec) { var elements = that.context.oCalTable.getElementsByTagName(aTagSpec); for (var i=0; i<elements.length; i++) if (elements[i].id.substr(0,idSeed.length)==idSeed) aFunction(elements[i]); } processElement('div'); processElement('span'); } } return that; }; return that; };
// ============================================================================= // // Copyright (c) 2014 Brannon Dorsey <http://brannondorsey.com> // // 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. // // ============================================================================= /* Assumes that the following are globally pre-defined: - jquery.js - ace.js - helper.js - underscore.js */ function SketchEditor(callback) { var _self = this; var _settings = new EditorSettings(); var _tabs = []; var _project = undefined; var _isRunning = false; var _isCompiling = false; var _disabled = false; var _projectFileTemplate; var _classTemplate; var _autosaveTimeout; ace.require("ace/ext/language_tools"); var _editor = ace.edit('editor'); var _currentRunTaskId = undefined; var _applySettings = function(editorSettings) { _editor.getSession().setMode(_settings.getData().setMode); _editor.setTheme(_settings.getData().setTheme); _editor.setBehavioursEnabled(_settings.getData().setBehavioursEnabled); _editor.setDisplayIndentGuides(_settings.getData().setDisplayIndentGuides); _editor.setDragDelay(_settings.getData().setDragDelay); _editor.setFadeFoldWidgets(_settings.getData().setFadeFoldWidgets); _editor.setFontSize(_settings.getData().setFontSize); _editor.setHighlightActiveLine(_settings.getData().setHighlightActiveLine); _editor.setHighlightGutterLine(_settings.getData().setHighlightGutterLine); _editor.setHighlightSelectedWord(_settings.getData().setHighlightSelectedWord); _editor.getSession().setNewLineMode(_settings.getData().setNewLineMode); _editor.setOverwrite(_settings.getData().setOverwrite); _editor.setPrintMarginColumn(_settings.getData().setPrintMarginColumn); _editor.setReadOnly(_settings.getData().setReadOnly); _editor.setScrollSpeed(_settings.getData().setScrollSpeed); _editor.setShowFoldWidgets(_settings.getData().setShowFoldWidgets); _editor.setShowInvisibles(_settings.getData().setShowInvisibles); _editor.setShowPrintMargin(_settings.getData().setShowPrintMargin); _editor.getSession().setTabSize(_settings.getData().setTabSize); _editor.getSession().setUseSoftTabs(_settings.getData().setUseSoftTabs); _editor.setWrapBehavioursEnabled(_settings.getData().setWrapBehavioursEnabled); _editor.getSession().setWrapLimit(_settings.getData().setWrapLimit); _editor.getSession().setUseWrapMode(_settings.getData().setUseWrapMode); _editor.setOptions({ enableBasicAutocompletion: true, enableSnippets: true }); } var _registerEvents = function() { // autocomplete trigger _editor.commands.on("afterExec", function(e){ if (e.command.name == "insertstring"&&/^[\w.]$/.test(e.args)) { _editor.execCommand("startAutocomplete"); } }); //keyboard overrides _editor.commands.addCommand({ name: 'Ctrl-sOverride', bindKey: {win: 'Ctrl-R'}, exec: function(editor) { run(); //WARNING: this is a global variable } }); _editor.commands.addCommand({ name: 'Ctrl-oOverride', bindKey: {mac: 'Ctrl-O'}, exec: function(editor) { openProject(); //WARNING: this is a global variable } }); _editor.commands.addCommand({ name: 'Show Editor Settings', bindKey: {mac: 'Command-,', win: 'Ctrl-,'}, exec: function(editor) { if (!_self.isDisabled()) _self.showSettingsMenu(); } }); // autosave _editor.on('change', function(){ clearTimeout(_autosaveTimeout); _autosaveTimeout = setTimeout(function(){ if (_self.projectLoaded() && !_project.isTemplate() && _project.needsSave()) { _self.saveProject(function(){ console.log('Project Autosaved'); }, function(){}); } }, 1000 * 20); // Autosave every 20 seconds }); } var _registerTabEvent = function(tabElement) { $(tabElement).on('click', function(){ _self.selectTab($(this).find('.tab-name').text()); }); } var _initTabs = function() { _tabs = []; var projectFile = _project.getProjectFile(); _addTab(getPrettyFileName(projectFile.fileName), projectFile.fileName, true, new ace.createEditSession(_project.getProjectFile().fileContents, _settings.getData().setMode)); var classes = _project.getClasses(); _.each(classes, function(c){ _addTab(getPrettyFileName(c.fileName), c.fileName, false, new ace.createEditSession(c.fileContents, _settings.getData().setMode)); }); _resizeTabs(true); _self.selectTab(_project.getName()); } var _addTab = function(name, fileName, isProjectFile, editSession) { var tabElement = $('<li class="file-tab"><a href="#" onclick="return false;"><span class="tab-name">' + name + '</span> <span class="badge alert-danger"></span></a></li>'); editSession.on('change', function(){ tabElement.addClass('unsaved'); _project.setNeedsSave(true); }); var tab = { name: name, fileName: fileName, isProjectFile: isProjectFile, isSelected: false, editSession: editSession, tabElement: tabElement } _tabs.push(tab); _registerTabEvent(tabElement); if (tab.isProjectFile) tabElement.addClass('active'); $('#tab-bar li:last').prev().prev().after(tabElement); } var _renderTab = function(name) { var tab = _getTab(name); if (tab) { _editor.setSession(tab.editSession); } return tab; } var _renameTab = function(name, newName) { // TODO: come back and change this to use _.without _.each(_tabs, function(tab, i) { if (tab.name == name) { _tabs[i].name = newName; _tabs[i].fileName = newName + ".sketch"; _tabs[i].tabElement.find('.tab-name').text(newName); } }); } var _getTab = function(tabName) { return _.find(_tabs, function(tab){ return tab.name == tabName; }); } var _updateProject = function() { var projectData = _project.getData(); projectTab = _.find(_tabs, function(tab){ return tab.isProjectFile }); projectData.projectFile.fileName = projectTab.fileName; projectData.projectFile.fileContents = projectTab.editSession.getValue(); var classTabs = _.filter(_tabs, function(tab){ return !tab.isProjectFile }); var classFiles = projectData.classes; _.each(classFiles, function(classFile, i) { var tab = _.findWhere(classTabs, { fileName: classFile.fileName }); if (!_.isUndefined(tab)) { classFiles[i].fileContents = tab.editSession.getValue(); } }); } var _resizeTabs = function(noResizeEvent) { var tab; // the tab to move var debounce = 5; var containerWidth = $('#tab-bar').width(); var combinedTabWidth = 0; var lastTabWidth = 0; $('#tab-bar').children() .each(function(){ combinedTabWidth += $(this).width(); lastTabWidth = $(this).width(); }); if (combinedTabWidth + debounce >= containerWidth) { tab = $('.file-tab:not(#tab-dropdown .file-tab):last'); tab.prependTo('#tab-dropdown'); if (noResizeEvent && combinedTabWidth - lastTabWidth + debounce >= containerWidth) { _resizeTabs(noResizeEvent); } } else { tab = $('#tab-dropdown .file-tab:first'); $('#tab-bar li:last').prev().prev().after(tab); combinedTabWidth += tab.width(); if (combinedTabWidth >= containerWidth) { _resizeTabs(); } } if ($('#tab-dropdown').is(':empty')) $('#tab-dropdown-button').hide(); else $('#tab-dropdown-button').show(); } var _getEditorSettings = function() { // Omitted as of now: // "setVScrollBarAlwaysVisible": "", // "setHScrollBarAlwaysVisible": "", // "setOptions": "", // "setUseWorker": "" // "setShowGutter": _editor.getShowGutter(), // "setKeyboardHandler": _editor.getKeyboardHandler(), return { setMode: _editor.getSession().getMode().$id, setTheme: _editor.getTheme(), setBehavioursEnabled: _editor.getBehavioursEnabled(), setDisplayIndentGuides: _editor.getDisplayIndentGuides(), setDragDelay: _editor.getDragDelay(), setFadeFoldWidgets: _editor.getFadeFoldWidgets(), setFontSize: _editor.getFontSize(), setHighlightActiveLine: _editor.getHighlightActiveLine(), setHighlightGutterLine: _editor.getHighlightGutterLine(), setHighlightSelectedWord: _editor.getHighlightSelectedWord(), setNewLineMode: _editor.getSession().getNewLineMode(), setOverwrite: _editor.getOverwrite(), setPrintMarginColumn: _editor.getPrintMarginColumn(), setReadOnly: _editor.getReadOnly(), setScrollSpeed: _editor.getScrollSpeed(), setShowFoldWidgets: _editor.getShowFoldWidgets(), setShowInvisibles: _editor.getShowInvisibles(), setShowPrintMargin: _editor.getShowPrintMargin(), setTabSize: _editor.getSession().getTabSize(), setUseSoftTabs: _editor.getSession().getUseSoftTabs(), setWrapBehavioursEnabled: _editor.getWrapBehavioursEnabled(), setWrapLimit: _editor.getSession().getWrapLimit(), setUseWrapMode: _editor.getSession().getUseWrapMode() }; } this.loadProject = function(projectName, onSuccess, onError) { _project = new Project(projectName, function(result) { _initTabs(); onSuccess(result); }, onError); } this.loadTemplateProject = function(onSuccess, onError) { _project = new Project('', function(result) { _initTabs(); onSuccess(result); }, onError, true); // signifies isTemplate } this.saveProject = function(onSuccess, onError) { _updateProject(); _project.save(function(){ _.each(_tabs, function(tab){ tab.tabElement.removeClass('unsaved'); }); onSuccess(); }, onError); } this.createProject = function(projectName, onSuccess, onError) { var oldName = _project.getName(); _project.assignName(projectName); _renameTab(oldName, projectName); _updateProject(); _project.create(onSuccess, onError); } this.deleteProject = function(onSuccess, onError) { JSONRPCClient.call('delete-project', { projectName: _project.getName(), clientUUID: CLIENT_UUID }, onSuccess, onError); } this.renameProject = function(newProjectName, onSuccess, onError) { var oldProjectName = _project.getName(); _project.rename(newProjectName, function(result){ console.log("renaming tab"); _renameTab(oldProjectName, newProjectName); onSuccess(result); }, onError); } this.exportProject = function(platform, onSuccess, onError) { JSONRPCClient.call('export-project', { projectName: _project.getName(), platform: platform}, onSuccess, onError); } this.getProject = function() { return _project; } this.projectLoaded = function() { return !_.isUndefined(_project); } this.compile = function(onSuccess, onError) { JSONRPCClient.call('compile-project', { projectName: _project.getName() }, function(result) { _currentRunTaskId = result; _self.setCompiling(true); onSuccess(result); }, function(error) { onError(error); }); } this.run = function(onSuccess, onError) { JSONRPCClient.call('run-project', { projectName: _project.getName() }, function(result) { _currentRunTaskId = result; _self.setRunning(true); onSuccess(result); }, function(error) { onError(error); }); } // commands a running project to stop this.stop = function(onSuccess, onError) { if (_currentRunTaskId != undefined) { JSONRPCClient.call('stop', { taskId: _currentRunTaskId }, function(result) { onSuccess(result); _currentRunTaskId = undefined; _self.setCompiling(false); _self.setRunning(false); }, function(error) { onError(error); }); } } // notifies that a running project has stopped this.notifyProjectStopped = function() { _currentRunTaskId = undefined; _self.setRunning(false) } this.createClass = function(className, onSuccess, onError) { _project.createClass(className, function(classFile) { console.log('creating class'); _addTab(classFile.name, classFile.fileName, false, new ace.createEditSession(classFile.fileContents, _settings.getData().setMode)); _resizeTabs(true); onSuccess(); // should I pass result object? }, onError); } this.deleteClass = function(className, onSuccess, onError) { _project.deleteClass(className, function(result){ var tab = _.findWhere(_tabs, { name: className }); tab.tabElement.remove(); _tabs = _.without(_tabs, tab); _resizeTabs(true); onSuccess(result); }, onError); } this.renameClass = function(className, newClassName, onSuccess, onError) { _project.renameClass(className, newClassName, function(result){ _renameTab(className, newClassName); onSuccess(result); }, onError); } this.selectTab = function(name) { $('.file-tab').each(function(){ $(this).removeClass('active'); if ($(this).find('.tab-name').text() == name) { $(this).addClass('active'); _renderTab($(this).find('.tab-name').text()); } }); } this.getSelectedTabName = function() { return $('.file-tab.active .tab-name').text(); } this.getProjectList = function(onSuccess, onError) { JSONRPCClient.call('get-project-list', {}, function(result) { onSuccess(result); }, function(error) { onError(error); }); } this.getAddonList = function(onSuccess, onError) { JSONRPCClient.call('get-addon-list', {}, function(result) { onSuccess(result); }, function(error) { onError(error); }); } this.isRunning = function() { return _isRunning; } this.setRunning = function(bool) { _isRunning = bool; } this.isCompiling = function() { return _isCompiling; } this.setCompiling = function(bool) { _isCompiling = bool; } this.getCurrentRunTaskId = function() { return _currentRunTaskId; } this.resize = function() { _editor.resize(); _resizeTabs(); } this.showSettingsMenu = function() { _editor.execCommand('showSettingsMenu'); onSettingsMenuShow(function(){ // hide select inputs $('[contains="setMode"').hide(); $('[contains="setNewLineMode"').hide(); $('[contains="setTabSize"]').hide(); $('[contains="setUseSoftTabs"]').hide(); $('[contains="setWrapLimit"]').hide(); $('[contains="setOptions"]').hide(); $('[contains="setBehavioursEnabled"]').hide(); $('[contains="setKeyboardHandler"]').hide(); $('[contains="setVScrollBarAlwaysVisible"]').hide(); $('[contains="setHScrollBarAlwaysVisible"]').hide(); $('[contains="setUseWorker"]').hide(); $('[contains="setWrapBehavioursEnabled"]').hide(); $('[contains="setUseWrapMode"]').hide(); $('[contains="setReadOnly"]').hide(); $('#setFontSize').on('change', function(){ _editor.setFontSize(parseInt($(this).val())); }); $('#ace_settingsmenu input, #ace_settingsmenu select').on('change', function(){ _settings.update(_getEditorSettings()); _settings.save(function(){ console.log('success!'); }, function(err){ // console.log(err); }); }); }); // recursively check if the menu has loaded function onSettingsMenuShow(callback) { setTimeout(function(){ if ($('#ace_settingsmenu').size() > 0) callback(); else onSettingsMenuShow(callback); }, 50); } } this.updateSettings = function(data) { _settings.update(data); _applySettings(); } this.notifyProjectClosed = function(onSuccess, onError) { if (!_project.isTemplate()) { JSONRPCClient.call('notify-project-closed', { projectName: _project.getName() }, onSuccess, onError); } } this.requestProjectClosed = function(onSuccess, onError) { JSONRPCClient.call('request-project-closed', { projectName: _project.getName(), clientUUID: CLIENT_UUID }, onSuccess, onError); } this.requestAppQuit = function(onSuccess, onError) { JSONRPCClient.call('request-app-quit', { clientUUID: CLIENT_UUID }, onSuccess, onError); } this.annotate = function(compileError) { var tab = _getTab(compileError.tabName); if (tab) { // for some reason ACE sets annotations // at the wrong row compileError.annotation.row--; var annotations = tab.editSession.getAnnotations(); var newAnnotations = []; var numAnnotationBadges = 0; // loop through all current annotations for this EditSession if (annotations.length > 0) { for (var i = 0; i < annotations.length; i++) { var annotation = annotations[i]; if (annotation.row <= tab.editSession.getLength()) { newAnnotations.push(annotation); if (annotation.type == 'error') { numAnnotationBadges++; } } } } // now add this compileError if (compileError.annotation.row <= tab.editSession.getLength()) { // hack for #includes if (compileError.annotation.text.indexOf('file not found') != -1) { compileError.annotation.row = 0; compileError.annotation.column = 1; } newAnnotations.push(compileError.annotation); if (compileError.annotation.type == 'error') { numAnnotationBadges++; } _self.selectTab(compileError.tabName); } tab.editSession.setAnnotations(newAnnotations); if (numAnnotationBadges > 0) { tab.tabElement.find('.badge').text(numAnnotationBadges) } } } this.clearAnnotations = function() { _.each(_tabs, function(tab){ tab.editSession.clearAnnotations(); tab.tabElement.find('.badge').text(''); }); } this.setDisabled = function(bool) { _disabled = bool } this.isDisabled = function() { return _disabled; } _settings.load(function(data){ _applySettings(); _registerEvents(); callback(); }, function(){ console.log('error loading editor settings'); }); }
/* ======================================== @preserve 03. Isotope used and distributed under Commercial License Isotope PACKAGED v3.0.0 Licensed GPLv3 for open source use or Isotope Commercial License for commercial use http://isotope.metafizzy.co Copyright 2016 Metafizzy Bridget makes jQuery widgets v2.0.0 MIT license ======================================== */ (function(window, factory) { 'use strict'; /* globals define: false, module: false, require: false */ if (typeof define == 'function' && define.amd) { // AMD define('jquery-bridget/jquery-bridget', ['jquery'], function(jQuery) { factory(window, jQuery); }); } else if (typeof module == 'object' && module.exports) { // CommonJS module.exports = factory(window, require('jquery')); } else { // browser global window.jQueryBridget = factory(window, window.jQuery); } }(window, function factory(window, jQuery) { 'use strict'; // ----- utils ----- // var arraySlice = Array.prototype.slice; // helper function for logging errors // $.error breaks jQuery chaining var console = window.console; var logError = typeof console == 'undefined' ? function() {} : function(message) { console.error(message); }; // ----- jQueryBridget ----- // function jQueryBridget(namespace, PluginClass, $) { $ = $ || jQuery || window.jQuery; if (!$) { return; } // add option method -> $().plugin('option', {...}) if (!PluginClass.prototype.option) { // option setter PluginClass.prototype.option = function(opts) { // bail out if not an object if (!$.isPlainObject(opts)) { return; } this.options = $.extend(true, this.options, opts); }; } // make jQuery plugin $.fn[namespace] = function(arg0) { if (typeof arg0 == 'string') { // method call $().plugin( 'methodName', { options } ) // shift arguments by 1 var args = arraySlice.call(arguments, 1); return methodCall(this, arg0, args); } // just $().plugin({ options }) plainCall(this, arg0); return this; }; // $().plugin('methodName') function methodCall($elems, methodName, args) { var returnValue; var pluginMethodStr = '$().' + namespace + '("' + methodName + '")'; $elems.each(function(i, elem) { // get instance var instance = $.data(elem, namespace); if (!instance) { logError(namespace + ' not initialized. Cannot call methods, i.e. ' + pluginMethodStr); return; } var method = instance[methodName]; if (!method || methodName.charAt(0) == '_') { logError(pluginMethodStr + ' is not a valid method'); return; } // apply method, get return value var value = method.apply(instance, args); // set return value if value is returned, use only first value returnValue = returnValue === undefined ? value : returnValue; }); return returnValue !== undefined ? returnValue : $elems; } function plainCall($elems, options) { $elems.each(function(i, elem) { var instance = $.data(elem, namespace); if (instance) { // set options & init instance.option(options); instance._init(); } else { // initialize new instance instance = new PluginClass(elem, options); $.data(elem, namespace, instance); } }); } updateJQuery($); } // ----- updateJQuery ----- // // set $.bridget for v1 backwards compatibility function updateJQuery($) { if (!$ || $ && $.bridget) { return; } $.bridget = jQueryBridget; } updateJQuery(jQuery || window.jQuery); // ----- ----- // return jQueryBridget; })); /** * EvEmitter v1.0.3 * Lil' event emitter * MIT License */ /* jshint unused: true, undef: true, strict: true */ (function(global, factory) { // universal module definition /* jshint strict: false */ /* globals define, module, window */ if (typeof define == 'function' && define.amd) { // AMD - RequireJS define('ev-emitter/ev-emitter', factory); } else if (typeof module == 'object' && module.exports) { // CommonJS - Browserify, Webpack module.exports = factory(); } else { // Browser globals global.EvEmitter = factory(); } }(typeof window != 'undefined' ? window : this, function() { function EvEmitter() {} var proto = EvEmitter.prototype; proto.on = function(eventName, listener) { if (!eventName || !listener) { return; } // set events hash var events = this._events = this._events || {}; // set listeners array var listeners = events[eventName] = events[eventName] || []; // only add once if (listeners.indexOf(listener) == -1) { listeners.push(listener); } return this; }; proto.once = function(eventName, listener) { if (!eventName || !listener) { return; } // add event this.on(eventName, listener); // set once flag // set onceEvents hash var onceEvents = this._onceEvents = this._onceEvents || {}; // set onceListeners object var onceListeners = onceEvents[eventName] = onceEvents[eventName] || {}; // set flag onceListeners[listener] = true; return this; }; proto.off = function(eventName, listener) { var listeners = this._events && this._events[eventName]; if (!listeners || !listeners.length) { return; } var index = listeners.indexOf(listener); if (index != -1) { listeners.splice(index, 1); } return this; }; proto.emitEvent = function(eventName, args) { var listeners = this._events && this._events[eventName]; if (!listeners || !listeners.length) { return; } var i = 0; var listener = listeners[i]; args = args || []; // once stuff var onceListeners = this._onceEvents && this._onceEvents[eventName]; while (listener) { var isOnce = onceListeners && onceListeners[listener]; if (isOnce) { // remove listener // remove before trigger to prevent recursion this.off(eventName, listener); // unset once flag delete onceListeners[listener]; } // trigger listener listener.apply(this, args); // get next listener i += isOnce ? 0 : 1; listener = listeners[i]; } return this; }; return EvEmitter; })); /*! * getSize v2.0.2 * measure size of elements * MIT license */ /*jshint browser: true, strict: true, undef: true, unused: true */ /*global define: false, module: false, console: false */ (function(window, factory) { 'use strict'; if (typeof define == 'function' && define.amd) { // AMD define('get-size/get-size', [], function() { return factory(); }); } else if (typeof module == 'object' && module.exports) { // CommonJS module.exports = factory(); } else { // browser global window.getSize = factory(); } }(window, function factory() { 'use strict'; // -------------------------- helpers -------------------------- // // get a number from a string, not a percentage function getStyleSize(value) { var num = parseFloat(value); // not a percent like '100%', and a number var isValid = value.indexOf('%') == -1 && !isNaN(num); return isValid && num; } function noop() {} var logError = typeof console == 'undefined' ? noop : function(message) { console.error(message); }; // -------------------------- measurements -------------------------- // var measurements = [ 'paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom', 'marginLeft', 'marginRight', 'marginTop', 'marginBottom', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth', 'borderBottomWidth' ]; var measurementsLength = measurements.length; function getZeroSize() { var size = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 }; for (var i = 0; i < measurementsLength; i++) { var measurement = measurements[i]; size[measurement] = 0; } return size; } // -------------------------- getStyle -------------------------- // /** * getStyle, get style of element, check for Firefox bug * https://bugzilla.mozilla.org/show_bug.cgi?id=548397 */ function getStyle(elem) { var style = getComputedStyle(elem); if (!style) { logError('Style returned ' + style + '. Are you running this code in a hidden iframe on Firefox? ' + 'See http://bit.ly/getsizebug1'); } return style; } // -------------------------- setup -------------------------- // var isSetup = false; var isBoxSizeOuter; /** * setup * check isBoxSizerOuter * do on first getSize() rather than on page load for Firefox bug */ function setup() { // setup once if (isSetup) { return; } isSetup = true; // -------------------------- box sizing -------------------------- // /** * WebKit measures the outer-width on style.width on border-box elems * IE & Firefox<29 measures the inner-width */ var div = document.createElement('div'); div.style.width = '200px'; div.style.padding = '1px 2px 3px 4px'; div.style.borderStyle = 'solid'; div.style.borderWidth = '1px 2px 3px 4px'; div.style.boxSizing = 'border-box'; var body = document.body || document.documentElement; body.appendChild(div); var style = getStyle(div); getSize.isBoxSizeOuter = isBoxSizeOuter = getStyleSize(style.width) == 200; body.removeChild(div); } // -------------------------- getSize -------------------------- // function getSize(elem) { setup(); // use querySeletor if elem is string if (typeof elem == 'string') { elem = document.querySelector(elem); } // do not proceed on non-objects if (!elem || typeof elem != 'object' || !elem.nodeType) { return; } var style = getStyle(elem); // if hidden, everything is 0 if (style.display == 'none') { return getZeroSize(); } var size = {}; size.width = elem.offsetWidth; size.height = elem.offsetHeight; var isBorderBox = size.isBorderBox = style.boxSizing == 'border-box'; // get all measurements for (var i = 0; i < measurementsLength; i++) { var measurement = measurements[i]; var value = style[measurement]; var num = parseFloat(value); // any 'auto', 'medium' value will be 0 size[measurement] = !isNaN(num) ? num : 0; } var paddingWidth = size.paddingLeft + size.paddingRight; var paddingHeight = size.paddingTop + size.paddingBottom; var marginWidth = size.marginLeft + size.marginRight; var marginHeight = size.marginTop + size.marginBottom; var borderWidth = size.borderLeftWidth + size.borderRightWidth; var borderHeight = size.borderTopWidth + size.borderBottomWidth; var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter; // overwrite width and height if we can get it from style var styleWidth = getStyleSize(style.width); if (styleWidth !== false) { size.width = styleWidth + (isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth); } var styleHeight = getStyleSize(style.height); if (styleHeight !== false) { size.height = styleHeight + (isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight); } size.innerWidth = size.width - (paddingWidth + borderWidth); size.innerHeight = size.height - (paddingHeight + borderHeight); size.outerWidth = size.width + marginWidth; size.outerHeight = size.height + marginHeight; return size; } return getSize; })); /** * matchesSelector v2.0.1 * matchesSelector( element, '.selector' ) * MIT license */ /*jshint browser: true, strict: true, undef: true, unused: true */ (function(window, factory) { /*global define: false, module: false */ 'use strict'; // universal module definition if (typeof define == 'function' && define.amd) { // AMD define('desandro-matches-selector/matches-selector', factory); } else if (typeof module == 'object' && module.exports) { // CommonJS module.exports = factory(); } else { // browser global window.matchesSelector = factory(); } }(window, function factory() { 'use strict'; var matchesMethod = function() { var ElemProto = Element.prototype; // check for the standard method name first if (ElemProto.matches) { return 'matches'; } // check un-prefixed if (ElemProto.matchesSelector) { return 'matchesSelector'; } // check vendor prefixes var prefixes = [ 'webkit', 'moz', 'ms', 'o' ]; for (var i = 0; i < prefixes.length; i++) { var prefix = prefixes[i]; var method = prefix + 'MatchesSelector'; if (ElemProto[method]) { return method; } } }(); return function matchesSelector(elem, selector) { return elem[matchesMethod](selector); }; })); /** * Fizzy UI utils v2.0.2 * MIT license */ /*jshint browser: true, undef: true, unused: true, strict: true */ (function(window, factory) { // universal module definition /*jshint strict: false */ /*globals define, module, require */ if (typeof define == 'function' && define.amd) { // AMD define('fizzy-ui-utils/utils', ['desandro-matches-selector/matches-selector'], function(matchesSelector) { return factory(window, matchesSelector); }); } else if (typeof module == 'object' && module.exports) { // CommonJS module.exports = factory(window, require('desandro-matches-selector')); } else { // browser global window.fizzyUIUtils = factory(window, window.matchesSelector); } }(window, function factory(window, matchesSelector) { var utils = {}; // ----- extend ----- // // extends objects utils.extend = function(a, b) { for (var prop in b) { a[prop] = b[prop]; } return a; }; // ----- modulo ----- // utils.modulo = function(num, div) { return (num % div + div) % div; }; // ----- makeArray ----- // // turn element or nodeList into an array utils.makeArray = function(obj) { var ary = []; if (Array.isArray(obj)) { // use object if already an array ary = obj; } else if (obj && typeof obj.length == 'number') { // convert nodeList to array for (var i = 0; i < obj.length; i++) { ary.push(obj[i]); } } else { // array of single index ary.push(obj); } return ary; }; // ----- removeFrom ----- // utils.removeFrom = function(ary, obj) { var index = ary.indexOf(obj); if (index != -1) { ary.splice(index, 1); } }; // ----- getParent ----- // utils.getParent = function(elem, selector) { while (elem != document.body) { elem = elem.parentNode; if (matchesSelector(elem, selector)) { return elem; } } }; // ----- getQueryElement ----- // // use element as selector string utils.getQueryElement = function(elem) { if (typeof elem == 'string') { return document.querySelector(elem); } return elem; }; // ----- handleEvent ----- // // enable .ontype to trigger from .addEventListener( elem, 'type' ) utils.handleEvent = function(event) { var method = 'on' + event.type; if (this[method]) { this[method](event); } }; // ----- filterFindElements ----- // utils.filterFindElements = function(elems, selector) { // make array of elems elems = utils.makeArray(elems); var ffElems = []; elems.forEach(function(elem) { // check that elem is an actual element if (!(elem instanceof HTMLElement)) { return; } // add elem if no selector if (!selector) { ffElems.push(elem); return; } // filter & find items if we have a selector // filter if (matchesSelector(elem, selector)) { ffElems.push(elem); } // find children var childElems = elem.querySelectorAll(selector); // concat childElems to filterFound array for (var i = 0; i < childElems.length; i++) { ffElems.push(childElems[i]); } }); return ffElems; }; // ----- debounceMethod ----- // utils.debounceMethod = function(_class, methodName, threshold) { // original method var method = _class.prototype[methodName]; var timeoutName = methodName + 'Timeout'; _class.prototype[methodName] = function() { var timeout = this[timeoutName]; if (timeout) { clearTimeout(timeout); } var args = arguments; var _this = this; this[timeoutName] = setTimeout(function() { method.apply(_this, args); delete _this[timeoutName]; }, threshold || 100); }; }; // ----- docReady ----- // utils.docReady = function(callback) { var readyState = document.readyState; if (readyState == 'complete' || readyState == 'interactive') { callback(); } else { document.addEventListener('DOMContentLoaded', callback); } }; // ----- htmlInit ----- // // http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/ utils.toDashed = function(str) { return str.replace(/(.)([A-Z])/g, function(match, $1, $2) { return $1 + '-' + $2; }).toLowerCase(); }; var console = window.console; /** * allow user to initialize classes via [data-namespace] or .js-namespace class * htmlInit( Widget, 'widgetName' ) * options are parsed from data-namespace-options */ utils.htmlInit = function(WidgetClass, namespace) { utils.docReady(function() { var dashedNamespace = utils.toDashed(namespace); var dataAttr = 'data-' + dashedNamespace; var dataAttrElems = document.querySelectorAll('[' + dataAttr + ']'); var jsDashElems = document.querySelectorAll('.js-' + dashedNamespace); var elems = utils.makeArray(dataAttrElems).concat(utils.makeArray(jsDashElems)); var dataOptionsAttr = dataAttr + '-options'; var jQuery = window.jQuery; elems.forEach(function(elem) { var attr = elem.getAttribute(dataAttr) || elem.getAttribute(dataOptionsAttr); var options; try { options = attr && JSON.parse(attr); } catch (error) { // log error, do not initialize if (console) { console.error('Error parsing ' + dataAttr + ' on ' + elem.className + ': ' + error); } return; } // initialize var instance = new WidgetClass(elem, options); // make available via $().data('layoutname') if (jQuery) { jQuery.data(elem, namespace, instance); } }); }); }; // ----- ----- // return utils; })); /** * Outlayer Item */ (function(window, factory) { // universal module definition /* jshint strict: false */ /* globals define, module, require */ if (typeof define == 'function' && define.amd) { // AMD - RequireJS define('outlayer/item', [ 'ev-emitter/ev-emitter', 'get-size/get-size' ], factory); } else if (typeof module == 'object' && module.exports) { // CommonJS - Browserify, Webpack module.exports = factory(require('ev-emitter'), require('get-size')); } else { // browser global window.Outlayer = {}; window.Outlayer.Item = factory(window.EvEmitter, window.getSize); } }(window, function factory(EvEmitter, getSize) { 'use strict'; // ----- helpers ----- // function isEmptyObj(obj) { for (var prop in obj) { return false; } prop = null; return true; } // -------------------------- CSS3 support -------------------------- // var docElemStyle = document.documentElement.style; var transitionProperty = typeof docElemStyle.transition == 'string' ? 'transition' : 'WebkitTransition'; var transformProperty = typeof docElemStyle.transform == 'string' ? 'transform' : 'WebkitTransform'; var transitionEndEvent = { WebkitTransition: 'webkitTransitionEnd', transition: 'transitionend' }[transitionProperty]; // cache all vendor properties that could have vendor prefix var vendorProperties = { transform: transformProperty, transition: transitionProperty, transitionDuration: transitionProperty + 'Duration', transitionProperty: transitionProperty + 'Property', transitionDelay: transitionProperty + 'Delay' }; // -------------------------- Item -------------------------- // function Item(element, layout) { if (!element) { return; } this.element = element; // parent layout class, i.e. Masonry, Isotope, or Packery this.layout = layout; this.position = { x: 0, y: 0 }; this._create(); } // inherit EvEmitter var proto = Item.prototype = Object.create(EvEmitter.prototype); proto.constructor = Item; proto._create = function() { // transition objects this._transn = { ingProperties: {}, clean: {}, onEnd: {} }; this.css({ position: 'absolute' }); }; // trigger specified handler for event type proto.handleEvent = function(event) { var method = 'on' + event.type; if (this[method]) { this[method](event); } }; proto.getSize = function() { this.size = getSize(this.element); }; /** * apply CSS styles to element * @param {Object} style */ proto.css = function(style) { var elemStyle = this.element.style; for (var prop in style) { // use vendor property if available var supportedProp = vendorProperties[prop] || prop; elemStyle[supportedProp] = style[prop]; } }; // measure position, and sets it proto.getPosition = function() { var style = getComputedStyle(this.element); var isOriginLeft = this.layout._getOption('originLeft'); var isOriginTop = this.layout._getOption('originTop'); var xValue = style[isOriginLeft ? 'left' : 'right']; var yValue = style[isOriginTop ? 'top' : 'bottom']; // convert percent to pixels var layoutSize = this.layout.size; var x = xValue.indexOf('%') != -1 ? parseFloat(xValue) / 100 * layoutSize.width : parseInt(xValue, 10); var y = yValue.indexOf('%') != -1 ? parseFloat(yValue) / 100 * layoutSize.height : parseInt(yValue, 10); // clean up 'auto' or other non-integer values x = isNaN(x) ? 0 : x; y = isNaN(y) ? 0 : y; // remove padding from measurement x -= isOriginLeft ? layoutSize.paddingLeft : layoutSize.paddingRight; y -= isOriginTop ? layoutSize.paddingTop : layoutSize.paddingBottom; this.position.x = x; this.position.y = y; }; // set settled position, apply padding proto.layoutPosition = function() { var layoutSize = this.layout.size; var style = {}; var isOriginLeft = this.layout._getOption('originLeft'); var isOriginTop = this.layout._getOption('originTop'); // x var xPadding = isOriginLeft ? 'paddingLeft' : 'paddingRight'; var xProperty = isOriginLeft ? 'left' : 'right'; var xResetProperty = isOriginLeft ? 'right' : 'left'; var x = this.position.x + layoutSize[xPadding]; // set in percentage or pixels style[xProperty] = this.getXValue(x); // reset other property style[xResetProperty] = ''; // y var yPadding = isOriginTop ? 'paddingTop' : 'paddingBottom'; var yProperty = isOriginTop ? 'top' : 'bottom'; var yResetProperty = isOriginTop ? 'bottom' : 'top'; var y = this.position.y + layoutSize[yPadding]; // set in percentage or pixels style[yProperty] = this.getYValue(y); // reset other property style[yResetProperty] = ''; this.css(style); this.emitEvent('layout', [this]); }; proto.getXValue = function(x) { var isHorizontal = this.layout._getOption('horizontal'); return this.layout.options.percentPosition && !isHorizontal ? x / this.layout.size.width * 100 + '%' : x + 'px'; }; proto.getYValue = function(y) { var isHorizontal = this.layout._getOption('horizontal'); return this.layout.options.percentPosition && isHorizontal ? y / this.layout.size.height * 100 + '%' : y + 'px'; }; proto._transitionTo = function(x, y) { this.getPosition(); // get current x & y from top/left var curX = this.position.x; var curY = this.position.y; var compareX = parseInt(x, 10); var compareY = parseInt(y, 10); var didNotMove = compareX === this.position.x && compareY === this.position.y; // save end position this.setPosition(x, y); // if did not move and not transitioning, just go to layout if (didNotMove && !this.isTransitioning) { this.layoutPosition(); return; } var transX = x - curX; var transY = y - curY; var transitionStyle = {}; transitionStyle.transform = this.getTranslate(transX, transY); this.transition({ to: transitionStyle, onTransitionEnd: { transform: this.layoutPosition }, isCleaning: true }); }; proto.getTranslate = function(x, y) { // flip cooridinates if origin on right or bottom var isOriginLeft = this.layout._getOption('originLeft'); var isOriginTop = this.layout._getOption('originTop'); x = isOriginLeft ? x : -x; y = isOriginTop ? y : -y; return 'translate3d(' + x + 'px, ' + y + 'px, 0)'; }; // non transition + transform support proto.goTo = function(x, y) { this.setPosition(x, y); this.layoutPosition(); }; proto.moveTo = proto._transitionTo; proto.setPosition = function(x, y) { this.position.x = parseInt(x, 10); this.position.y = parseInt(y, 10); }; // ----- transition ----- // /** * @param {Object} style - CSS * @param {Function} onTransitionEnd */ // non transition, just trigger callback proto._nonTransition = function(args) { this.css(args.to); if (args.isCleaning) { this._removeStyles(args.to); } for (var prop in args.onTransitionEnd) { args.onTransitionEnd[prop].call(this); } }; /** * proper transition * @param {Object} args - arguments * @param {Object} to - style to transition to * @param {Object} from - style to start transition from * @param {Boolean} isCleaning - removes transition styles after transition * @param {Function} onTransitionEnd - callback */ proto.transition = function(args) { // redirect to nonTransition if no transition duration if (!parseFloat(this.layout.options.transitionDuration)) { this._nonTransition(args); return; } var _transition = this._transn; // keep track of onTransitionEnd callback by css property for (var prop in args.onTransitionEnd) { _transition.onEnd[prop] = args.onTransitionEnd[prop]; } // keep track of properties that are transitioning for (prop in args.to) { _transition.ingProperties[prop] = true; // keep track of properties to clean up when transition is done if (args.isCleaning) { _transition.clean[prop] = true; } } // set from styles if (args.from) { this.css(args.from); // force redraw. http://blog.alexmaccaw.com/css-transitions var h = this.element.offsetHeight; // hack for JSHint to hush about unused var h = null; } // enable transition this.enableTransition(args.to); // set styles that are transitioning this.css(args.to); this.isTransitioning = true; }; // dash before all cap letters, including first for // WebkitTransform => -webkit-transform function toDashedAll(str) { return str.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); }); } var transitionProps = 'opacity,' + toDashedAll(transformProperty); proto.enableTransition = function() { // HACK changing transitionProperty during a transition // will cause transition to jump if (this.isTransitioning) { return; } // make `transition: foo, bar, baz` from style object // HACK un-comment this when enableTransition can work // while a transition is happening // var transitionValues = []; // for ( var prop in style ) { // // dash-ify camelCased properties like WebkitTransition // prop = vendorProperties[ prop ] || prop; // transitionValues.push( toDashedAll( prop ) ); // } // munge number to millisecond, to match stagger var duration = this.layout.options.transitionDuration; duration = typeof duration == 'number' ? duration + 'ms' : duration; // enable transition styles this.css({ transitionProperty: transitionProps, transitionDuration: duration, transitionDelay: this.staggerDelay || 0 }); // listen for transition end event this.element.addEventListener(transitionEndEvent, this, false); }; // ----- events ----- // proto.onwebkitTransitionEnd = function(event) { this.ontransitionend(event); }; proto.onotransitionend = function(event) { this.ontransitionend(event); }; // properties that I munge to make my life easier var dashedVendorProperties = { '-webkit-transform': 'transform' }; proto.ontransitionend = function(event) { // disregard bubbled events from children if (event.target !== this.element) { return; } var _transition = this._transn; // get property name of transitioned property, convert to prefix-free var propertyName = dashedVendorProperties[event.propertyName] || event.propertyName; // remove property that has completed transitioning delete _transition.ingProperties[propertyName]; // check if any properties are still transitioning if (isEmptyObj(_transition.ingProperties)) { // all properties have completed transitioning this.disableTransition(); } // clean style if (propertyName in _transition.clean) { // clean up style this.element.style[event.propertyName] = ''; delete _transition.clean[propertyName]; } // trigger onTransitionEnd callback if (propertyName in _transition.onEnd) { var onTransitionEnd = _transition.onEnd[propertyName]; onTransitionEnd.call(this); delete _transition.onEnd[propertyName]; } this.emitEvent('transitionEnd', [this]); }; proto.disableTransition = function() { this.removeTransitionStyles(); this.element.removeEventListener(transitionEndEvent, this, false); this.isTransitioning = false; }; /** * removes style property from element * @param {Object} style **/ proto._removeStyles = function(style) { // clean up transition styles var cleanStyle = {}; for (var prop in style) { cleanStyle[prop] = ''; } this.css(cleanStyle); }; var cleanTransitionStyle = { transitionProperty: '', transitionDuration: '', transitionDelay: '' }; proto.removeTransitionStyles = function() { // remove transition this.css(cleanTransitionStyle); }; // ----- stagger ----- // proto.stagger = function(delay) { delay = isNaN(delay) ? 0 : delay; this.staggerDelay = delay + 'ms'; }; // ----- show/hide/remove ----- // // remove element from DOM proto.removeElem = function() { this.element.parentNode.removeChild(this.element); // remove display: none this.css({ display: '' }); this.emitEvent('remove', [this]); }; proto.remove = function() { // just remove element if no transition support or no transition if (!transitionProperty || !parseFloat(this.layout.options.transitionDuration)) { this.removeElem(); return; } // start transition this.once('transitionEnd', function() { this.removeElem(); }); this.hide(); }; proto.reveal = function() { delete this.isHidden; // remove display: none this.css({ display: '' }); var options = this.layout.options; var onTransitionEnd = {}; var transitionEndProperty = this.getHideRevealTransitionEndProperty('visibleStyle'); onTransitionEnd[transitionEndProperty] = this.onRevealTransitionEnd; this.transition({ from: options.hiddenStyle, to: options.visibleStyle, isCleaning: true, onTransitionEnd: onTransitionEnd }); }; proto.onRevealTransitionEnd = function() { // check if still visible // during transition, item may have been hidden if (!this.isHidden) { this.emitEvent('reveal'); } }; /** * get style property use for hide/reveal transition end * @param {String} styleProperty - hiddenStyle/visibleStyle * @returns {String} */ proto.getHideRevealTransitionEndProperty = function(styleProperty) { var optionStyle = this.layout.options[styleProperty]; // use opacity if (optionStyle.opacity) { return 'opacity'; } // get first property for (var prop in optionStyle) { return prop; } }; proto.hide = function() { // set flag this.isHidden = true; // remove display: none this.css({ display: '' }); var options = this.layout.options; var onTransitionEnd = {}; var transitionEndProperty = this.getHideRevealTransitionEndProperty('hiddenStyle'); onTransitionEnd[transitionEndProperty] = this.onHideTransitionEnd; this.transition({ from: options.visibleStyle, to: options.hiddenStyle, // keep hidden stuff hidden isCleaning: true, onTransitionEnd: onTransitionEnd }); }; proto.onHideTransitionEnd = function() { // check if still hidden // during transition, item may have been un-hidden if (this.isHidden) { this.css({ display: 'none' }); this.emitEvent('hide'); } }; proto.destroy = function() { this.css({ position: '', left: '', right: '', top: '', bottom: '', transition: '', transform: '' }); }; return Item; })); /*! * Outlayer v2.1.0 * the brains and guts of a layout library * MIT license */ (function(window, factory) { 'use strict'; // universal module definition /* jshint strict: false */ /* globals define, module, require */ if (typeof define == 'function' && define.amd) { // AMD - RequireJS define('outlayer/outlayer', [ 'ev-emitter/ev-emitter', 'get-size/get-size', 'fizzy-ui-utils/utils', './item' ], function(EvEmitter, getSize, utils, Item) { return factory(window, EvEmitter, getSize, utils, Item); }); } else if (typeof module == 'object' && module.exports) { // CommonJS - Browserify, Webpack module.exports = factory(window, require('ev-emitter'), require('get-size'), require('fizzy-ui-utils'), require('./item')); } else { // browser global window.Outlayer = factory(window, window.EvEmitter, window.getSize, window.fizzyUIUtils, window.Outlayer.Item); } }(window, function factory(window, EvEmitter, getSize, utils, Item) { 'use strict'; // ----- vars ----- // var console = window.console; var jQuery = window.jQuery; var noop = function() {}; // -------------------------- Outlayer -------------------------- // // globally unique identifiers var GUID = 0; // internal store of all Outlayer intances var instances = {}; /** * @param {Element, String} element * @param {Object} options * @constructor */ function Outlayer(element, options) { var queryElement = utils.getQueryElement(element); if (!queryElement) { if (console) { console.error('Bad element for ' + this.constructor.namespace + ': ' + (queryElement || element)); } return; } this.element = queryElement; // add jQuery if (jQuery) { this.$element = jQuery(this.element); } // options this.options = utils.extend({}, this.constructor.defaults); this.option(options); // add id for Outlayer.getFromElement var id = ++GUID; this.element.outlayerGUID = id; // expando instances[id] = this; // associate via id // kick it off this._create(); var isInitLayout = this._getOption('initLayout'); if (isInitLayout) { this.layout(); } } // settings are for internal use only Outlayer.namespace = 'outlayer'; Outlayer.Item = Item; // default options Outlayer.defaults = { containerStyle: { position: 'relative' }, initLayout: true, originLeft: true, originTop: true, resize: true, resizeContainer: true, // item options transitionDuration: '0.4s', hiddenStyle: { opacity: 0, transform: 'scale(0.001)' }, visibleStyle: { opacity: 1, transform: 'scale(1)' } }; var proto = Outlayer.prototype; // inherit EvEmitter utils.extend(proto, EvEmitter.prototype); /** * set options * @param {Object} opts */ proto.option = function(opts) { utils.extend(this.options, opts); }; /** * get backwards compatible option value, check old name */ proto._getOption = function(option) { var oldOption = this.constructor.compatOptions[option]; return oldOption && this.options[oldOption] !== undefined ? this.options[oldOption] : this.options[option]; }; Outlayer.compatOptions = { // currentName: oldName initLayout: 'isInitLayout', horizontal: 'isHorizontal', layoutInstant: 'isLayoutInstant', originLeft: 'isOriginLeft', originTop: 'isOriginTop', resize: 'isResizeBound', resizeContainer: 'isResizingContainer' }; proto._create = function() { // get items from children this.reloadItems(); // elements that affect layout, but are not laid out this.stamps = []; this.stamp(this.options.stamp); // set container style utils.extend(this.element.style, this.options.containerStyle); // bind resize method var canBindResize = this._getOption('resize'); if (canBindResize) { this.bindResize(); } }; // goes through all children again and gets bricks in proper order proto.reloadItems = function() { // collection of item elements this.items = this._itemize(this.element.children); }; /** * turn elements into Outlayer.Items to be used in layout * @param {Array or NodeList or HTMLElement} elems * @returns {Array} items - collection of new Outlayer Items */ proto._itemize = function(elems) { var itemElems = this._filterFindItemElements(elems); var Item = this.constructor.Item; // create new Outlayer Items for collection var items = []; for (var i = 0; i < itemElems.length; i++) { var elem = itemElems[i]; var item = new Item(elem, this); items.push(item); } return items; }; /** * get item elements to be used in layout * @param {Array or NodeList or HTMLElement} elems * @returns {Array} items - item elements */ proto._filterFindItemElements = function(elems) { return utils.filterFindElements(elems, this.options.itemSelector); }; /** * getter method for getting item elements * @returns {Array} elems - collection of item elements */ proto.getItemElements = function() { return this.items.map(function(item) { return item.element; }); }; // ----- init & layout ----- // /** * lays out all items */ proto.layout = function() { this._resetLayout(); this._manageStamps(); // don't animate first layout var layoutInstant = this._getOption('layoutInstant'); var isInstant = layoutInstant !== undefined ? layoutInstant : !this._isLayoutInited; this.layoutItems(this.items, isInstant); // flag for initalized this._isLayoutInited = true; }; // _init is alias for layout proto._init = proto.layout; /** * logic before any new layout */ proto._resetLayout = function() { this.getSize(); }; proto.getSize = function() { this.size = getSize(this.element); }; /** * get measurement from option, for columnWidth, rowHeight, gutter * if option is String -> get element from selector string, & get size of element * if option is Element -> get size of element * else use option as a number * * @param {String} measurement * @param {String} size - width or height * @private */ proto._getMeasurement = function(measurement, size) { var option = this.options[measurement]; var elem; if (!option) { // default to 0 this[measurement] = 0; } else { // use option as an element if (typeof option == 'string') { elem = this.element.querySelector(option); } else if (option instanceof HTMLElement) { elem = option; } // use size of element, if element this[measurement] = elem ? getSize(elem)[size] : option; } }; /** * layout a collection of item elements * @api public */ proto.layoutItems = function(items, isInstant) { items = this._getItemsForLayout(items); this._layoutItems(items, isInstant); this._postLayout(); }; /** * get the items to be laid out * you may want to skip over some items * @param {Array} items * @returns {Array} items */ proto._getItemsForLayout = function(items) { return items.filter(function(item) { return !item.isIgnored; }); }; /** * layout items * @param {Array} items * @param {Boolean} isInstant */ proto._layoutItems = function(items, isInstant) { this._emitCompleteOnItems('layout', items); if (!items || !items.length) { // no items, emit event with empty array return; } var queue = []; items.forEach(function(item) { // get x/y object from method var position = this._getItemLayoutPosition(item); // enqueue position.item = item; position.isInstant = isInstant || item.isLayoutInstant; queue.push(position); }, this); this._processLayoutQueue(queue); }; /** * get item layout position * @param {Outlayer.Item} item * @returns {Object} x and y position */ proto._getItemLayoutPosition = function() { return { x: 0, y: 0 }; }; /** * iterate over array and position each item * Reason being - separating this logic prevents 'layout invalidation' * thx @paul_irish * @param {Array} queue */ proto._processLayoutQueue = function(queue) { this.updateStagger(); queue.forEach(function(obj, i) { this._positionItem(obj.item, obj.x, obj.y, obj.isInstant, i); }, this); }; // set stagger from option in milliseconds number proto.updateStagger = function() { var stagger = this.options.stagger; if (stagger === null || stagger === undefined) { this.stagger = 0; return; } this.stagger = getMilliseconds(stagger); return this.stagger; }; /** * Sets position of item in DOM * @param {Outlayer.Item} item * @param {Number} x - horizontal position * @param {Number} y - vertical position * @param {Boolean} isInstant - disables transitions */ proto._positionItem = function(item, x, y, isInstant, i) { if (isInstant) { // if not transition, just set CSS item.goTo(x, y); } else { item.stagger(i * this.stagger); item.moveTo(x, y); } }; /** * Any logic you want to do after each layout, * i.e. size the container */ proto._postLayout = function() { this.resizeContainer(); }; proto.resizeContainer = function() { var isResizingContainer = this._getOption('resizeContainer'); if (!isResizingContainer) { return; } var size = this._getContainerSize(); if (size) { this._setContainerMeasure(size.width, true); this._setContainerMeasure(size.height, false); } }; /** * Sets width or height of container if returned * @returns {Object} size * @param {Number} width * @param {Number} height */ proto._getContainerSize = noop; /** * @param {Number} measure - size of width or height * @param {Boolean} isWidth */ proto._setContainerMeasure = function(measure, isWidth) { if (measure === undefined) { return; } var elemSize = this.size; // add padding and border width if border box if (elemSize.isBorderBox) { measure += isWidth ? elemSize.paddingLeft + elemSize.paddingRight + elemSize.borderLeftWidth + elemSize.borderRightWidth : elemSize.paddingBottom + elemSize.paddingTop + elemSize.borderTopWidth + elemSize.borderBottomWidth; } measure = Math.max(measure, 0); this.element.style[isWidth ? 'width' : 'height'] = measure + 'px'; }; /** * emit eventComplete on a collection of items events * @param {String} eventName * @param {Array} items - Outlayer.Items */ proto._emitCompleteOnItems = function(eventName, items) { var _this = this; function onComplete() { _this.dispatchEvent(eventName + 'Complete', null, [items]); } var count = items.length; if (!items || !count) { onComplete(); return; } var doneCount = 0; function tick() { doneCount++; if (doneCount == count) { onComplete(); } } // bind callback items.forEach(function(item) { item.once(eventName, tick); }); }; /** * emits events via EvEmitter and jQuery events * @param {String} type - name of event * @param {Event} event - original event * @param {Array} args - extra arguments */ proto.dispatchEvent = function(type, event, args) { // add original event to arguments var emitArgs = event ? [event].concat(args) : args; this.emitEvent(type, emitArgs); if (jQuery) { // set this.$element this.$element = this.$element || jQuery(this.element); if (event) { // create jQuery event var $event = jQuery.Event(event); $event.type = type; this.$element.trigger($event, args); } else { // just trigger with type if no event available this.$element.trigger(type, args); } } }; // -------------------------- ignore & stamps -------------------------- // /** * keep item in collection, but do not lay it out * ignored items do not get skipped in layout * @param {Element} elem */ proto.ignore = function(elem) { var item = this.getItem(elem); if (item) { item.isIgnored = true; } }; /** * return item to layout collection * @param {Element} elem */ proto.unignore = function(elem) { var item = this.getItem(elem); if (item) { delete item.isIgnored; } }; /** * adds elements to stamps * @param {NodeList, Array, Element, or String} elems */ proto.stamp = function(elems) { elems = this._find(elems); if (!elems) { return; } this.stamps = this.stamps.concat(elems); // ignore elems.forEach(this.ignore, this); }; /** * removes elements to stamps * @param {NodeList, Array, or Element} elems */ proto.unstamp = function(elems) { elems = this._find(elems); if (!elems) { return; } elems.forEach(function(elem) { // filter out removed stamp elements utils.removeFrom(this.stamps, elem); this.unignore(elem); }, this); }; /** * finds child elements * @param {NodeList, Array, Element, or String} elems * @returns {Array} elems */ proto._find = function(elems) { if (!elems) { return; } // if string, use argument as selector string if (typeof elems == 'string') { elems = this.element.querySelectorAll(elems); } elems = utils.makeArray(elems); return elems; }; proto._manageStamps = function() { if (!this.stamps || !this.stamps.length) { return; } this._getBoundingRect(); this.stamps.forEach(this._manageStamp, this); }; // update boundingLeft / Top proto._getBoundingRect = function() { // get bounding rect for container element var boundingRect = this.element.getBoundingClientRect(); var size = this.size; this._boundingRect = { left: boundingRect.left + size.paddingLeft + size.borderLeftWidth, top: boundingRect.top + size.paddingTop + size.borderTopWidth, right: boundingRect.right - (size.paddingRight + size.borderRightWidth), bottom: boundingRect.bottom - (size.paddingBottom + size.borderBottomWidth) }; }; /** * @param {Element} stamp **/ proto._manageStamp = noop; /** * get x/y position of element relative to container element * @param {Element} elem * @returns {Object} offset - has left, top, right, bottom */ proto._getElementOffset = function(elem) { var boundingRect = elem.getBoundingClientRect(); var thisRect = this._boundingRect; var size = getSize(elem); var offset = { left: boundingRect.left - thisRect.left - size.marginLeft, top: boundingRect.top - thisRect.top - size.marginTop, right: thisRect.right - boundingRect.right - size.marginRight, bottom: thisRect.bottom - boundingRect.bottom - size.marginBottom }; return offset; }; // -------------------------- resize -------------------------- // // enable event handlers for listeners // i.e. resize -> onresize proto.handleEvent = utils.handleEvent; /** * Bind layout to window resizing */ proto.bindResize = function() { window.addEventListener('resize', this); this.isResizeBound = true; }; /** * Unbind layout to window resizing */ proto.unbindResize = function() { window.removeEventListener('resize', this); this.isResizeBound = false; }; proto.onresize = function() { this.resize(); }; utils.debounceMethod(Outlayer, 'onresize', 100); proto.resize = function() { // don't trigger if size did not change // or if resize was unbound. See #9 if (!this.isResizeBound || !this.needsResizeLayout()) { return; } this.layout(); }; /** * check if layout is needed post layout * @returns Boolean */ proto.needsResizeLayout = function() { var size = getSize(this.element); // check that this.size and size are there // IE8 triggers resize on body size change, so they might not be var hasSizes = this.size && size; return hasSizes && size.innerWidth !== this.size.innerWidth; }; // -------------------------- methods -------------------------- // /** * add items to Outlayer instance * @param {Array or NodeList or Element} elems * @returns {Array} items - Outlayer.Items **/ proto.addItems = function(elems) { var items = this._itemize(elems); // add items to collection if (items.length) { this.items = this.items.concat(items); } return items; }; /** * Layout newly-appended item elements * @param {Array or NodeList or Element} elems */ proto.appended = function(elems) { var items = this.addItems(elems); if (!items.length) { return; } // layout and reveal just the new items this.layoutItems(items, true); this.reveal(items); }; /** * Layout prepended elements * @param {Array or NodeList or Element} elems */ proto.prepended = function(elems) { var items = this._itemize(elems); if (!items.length) { return; } // add items to beginning of collection var previousItems = this.items.slice(0); this.items = items.concat(previousItems); // start new layout this._resetLayout(); this._manageStamps(); // layout new stuff without transition this.layoutItems(items, true); this.reveal(items); // layout previous items this.layoutItems(previousItems); }; /** * reveal a collection of items * @param {Array of Outlayer.Items} items */ proto.reveal = function(items) { this._emitCompleteOnItems('reveal', items); if (!items || !items.length) { return; } var stagger = this.updateStagger(); items.forEach(function(item, i) { item.stagger(i * stagger); item.reveal(); }); }; /** * hide a collection of items * @param {Array of Outlayer.Items} items */ proto.hide = function(items) { this._emitCompleteOnItems('hide', items); if (!items || !items.length) { return; } var stagger = this.updateStagger(); items.forEach(function(item, i) { item.stagger(i * stagger); item.hide(); }); }; /** * reveal item elements * @param {Array}, {Element}, {NodeList} items */ proto.revealItemElements = function(elems) { var items = this.getItems(elems); this.reveal(items); }; /** * hide item elements * @param {Array}, {Element}, {NodeList} items */ proto.hideItemElements = function(elems) { var items = this.getItems(elems); this.hide(items); }; /** * get Outlayer.Item, given an Element * @param {Element} elem * @param {Function} callback * @returns {Outlayer.Item} item */ proto.getItem = function(elem) { // loop through items to get the one that matches for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; if (item.element == elem) { // return item return item; } } }; /** * get collection of Outlayer.Items, given Elements * @param {Array} elems * @returns {Array} items - Outlayer.Items */ proto.getItems = function(elems) { elems = utils.makeArray(elems); var items = []; elems.forEach(function(elem) { var item = this.getItem(elem); if (item) { items.push(item); } }, this); return items; }; /** * remove element(s) from instance and DOM * @param {Array or NodeList or Element} elems */ proto.remove = function(elems) { var removeItems = this.getItems(elems); this._emitCompleteOnItems('remove', removeItems); // bail if no items to remove if (!removeItems || !removeItems.length) { return; } removeItems.forEach(function(item) { item.remove(); // remove item from collection utils.removeFrom(this.items, item); }, this); }; // ----- destroy ----- // // remove and disable Outlayer instance proto.destroy = function() { // clean up dynamic styles var style = this.element.style; style.height = ''; style.position = ''; style.width = ''; // destroy items this.items.forEach(function(item) { item.destroy(); }); this.unbindResize(); var id = this.element.outlayerGUID; delete instances[id]; // remove reference to instance by id delete this.element.outlayerGUID; // remove data for jQuery if (jQuery) { jQuery.removeData(this.element, this.constructor.namespace); } }; // -------------------------- data -------------------------- // /** * get Outlayer instance from element * @param {Element} elem * @returns {Outlayer} */ Outlayer.data = function(elem) { elem = utils.getQueryElement(elem); var id = elem && elem.outlayerGUID; return id && instances[id]; }; // -------------------------- create Outlayer class -------------------------- // /** * create a layout class * @param {String} namespace */ Outlayer.create = function(namespace, options) { // sub-class Outlayer var Layout = subclass(Outlayer); // apply new options and compatOptions Layout.defaults = utils.extend({}, Outlayer.defaults); utils.extend(Layout.defaults, options); Layout.compatOptions = utils.extend({}, Outlayer.compatOptions); Layout.namespace = namespace; Layout.data = Outlayer.data; // sub-class Item Layout.Item = subclass(Item); // -------------------------- declarative -------------------------- // utils.htmlInit(Layout, namespace); // -------------------------- jQuery bridge -------------------------- // // make into jQuery plugin if (jQuery && jQuery.bridget) { jQuery.bridget(namespace, Layout); } return Layout; }; function subclass(Parent) { function SubClass() { Parent.apply(this, arguments); } SubClass.prototype = Object.create(Parent.prototype); SubClass.prototype.constructor = SubClass; return SubClass; } // ----- helpers ----- // // how many milliseconds are in each unit var msUnits = { ms: 1, s: 1000 }; // munge time-like parameter into millisecond number // '0.4s' -> 40 function getMilliseconds(time) { if (typeof time == 'number') { return time; } var matches = time.match(/(^\d*\.?\d*)(\w*)/); var num = matches && matches[1]; var unit = matches && matches[2]; if (!num.length) { return 0; } num = parseFloat(num); var mult = msUnits[unit] || 1; return num * mult; } // ----- fin ----- // // back in global Outlayer.Item = Item; return Outlayer; })); /** * Isotope Item **/ (function(window, factory) { // universal module definition /* jshint strict: false */ /*globals define, module, require */ if (typeof define == 'function' && define.amd) { // AMD define('isotope/js/item', ['outlayer/outlayer'], factory); } else if (typeof module == 'object' && module.exports) { // CommonJS module.exports = factory(require('outlayer')); } else { // browser global window.Isotope = window.Isotope || {}; window.Isotope.Item = factory(window.Outlayer); } }(window, function factory(Outlayer) { 'use strict'; // -------------------------- Item -------------------------- // // sub-class Outlayer Item function Item() { Outlayer.Item.apply(this, arguments); } var proto = Item.prototype = Object.create(Outlayer.Item.prototype); var _create = proto._create; proto._create = function() { // assign id, used for original-order sorting this.id = this.layout.itemGUID++; _create.call(this); this.sortData = {}; }; proto.updateSortData = function() { if (this.isIgnored) { return; } // default sorters this.sortData.id = this.id; // for backward compatibility this.sortData['original-order'] = this.id; this.sortData.random = Math.random(); // go thru getSortData obj and apply the sorters var getSortData = this.layout.options.getSortData; var sorters = this.layout._sorters; for (var key in getSortData) { var sorter = sorters[key]; this.sortData[key] = sorter(this.element, this); } }; var _destroy = proto.destroy; proto.destroy = function() { // call super _destroy.apply(this, arguments); // reset display, #741 this.css({ display: '' }); }; return Item; })); /** * Isotope LayoutMode */ (function(window, factory) { // universal module definition /* jshint strict: false */ /*globals define, module, require */ if (typeof define == 'function' && define.amd) { // AMD define('isotope/js/layout-mode', [ 'get-size/get-size', 'outlayer/outlayer' ], factory); } else if (typeof module == 'object' && module.exports) { // CommonJS module.exports = factory(require('get-size'), require('outlayer')); } else { // browser global window.Isotope = window.Isotope || {}; window.Isotope.LayoutMode = factory(window.getSize, window.Outlayer); } }(window, function factory(getSize, Outlayer) { 'use strict'; // layout mode class function LayoutMode(isotope) { this.isotope = isotope; // link properties if (isotope) { this.options = isotope.options[this.namespace]; this.element = isotope.element; this.items = isotope.filteredItems; this.size = isotope.size; } } var proto = LayoutMode.prototype; /** * some methods should just defer to default Outlayer method * and reference the Isotope instance as `this` **/ var facadeMethods = [ '_resetLayout', '_getItemLayoutPosition', '_manageStamp', '_getContainerSize', '_getElementOffset', 'needsResizeLayout', '_getOption' ]; facadeMethods.forEach(function(methodName) { proto[methodName] = function() { return Outlayer.prototype[methodName].apply(this.isotope, arguments); }; }); // ----- ----- // // for horizontal layout modes, check vertical size proto.needsVerticalResizeLayout = function() { // don't trigger if size did not change var size = getSize(this.isotope.element); // check that this.size and size are there // IE8 triggers resize on body size change, so they might not be var hasSizes = this.isotope.size && size; return hasSizes && size.innerHeight != this.isotope.size.innerHeight; }; // ----- measurements ----- // proto._getMeasurement = function() { this.isotope._getMeasurement.apply(this, arguments); }; proto.getColumnWidth = function() { this.getSegmentSize('column', 'Width'); }; proto.getRowHeight = function() { this.getSegmentSize('row', 'Height'); }; /** * get columnWidth or rowHeight * segment: 'column' or 'row' * size 'Width' or 'Height' **/ proto.getSegmentSize = function(segment, size) { var segmentName = segment + size; var outerSize = 'outer' + size; // columnWidth / outerWidth // rowHeight / outerHeight this._getMeasurement(segmentName, outerSize); // got rowHeight or columnWidth, we can chill if (this[segmentName]) { return; } // fall back to item of first element var firstItemSize = this.getFirstItemSize(); this[segmentName] = firstItemSize && firstItemSize[outerSize] || // or size of container this.isotope.size['inner' + size]; }; proto.getFirstItemSize = function() { var firstItem = this.isotope.filteredItems[0]; return firstItem && firstItem.element && getSize(firstItem.element); }; // ----- methods that should reference isotope ----- // proto.layout = function() { this.isotope.layout.apply(this.isotope, arguments); }; proto.getSize = function() { this.isotope.getSize(); this.size = this.isotope.size; }; // -------------------------- create -------------------------- // LayoutMode.modes = {}; LayoutMode.create = function(namespace, options) { function Mode() { LayoutMode.apply(this, arguments); } Mode.prototype = Object.create(proto); Mode.prototype.constructor = Mode; // default options if (options) { Mode.options = options; } Mode.prototype.namespace = namespace; // register in Isotope LayoutMode.modes[namespace] = Mode; return Mode; }; return LayoutMode; })); /*! * Masonry v4.1.0 * Cascading grid layout library * http://masonry.desandro.com * MIT License * by David DeSandro */ (function(window, factory) { // universal module definition /* jshint strict: false */ /*globals define, module, require */ if (typeof define == 'function' && define.amd) { // AMD define('masonry/masonry', [ 'outlayer/outlayer', 'get-size/get-size' ], factory); } else if (typeof module == 'object' && module.exports) { // CommonJS module.exports = factory(require('outlayer'), require('get-size')); } else { // browser global window.Masonry = factory(window.Outlayer, window.getSize); } }(window, function factory(Outlayer, getSize) { // -------------------------- masonryDefinition -------------------------- // // create an Outlayer layout class var Masonry = Outlayer.create('masonry'); // isFitWidth -> fitWidth Masonry.compatOptions.fitWidth = 'isFitWidth'; Masonry.prototype._resetLayout = function() { this.getSize(); this._getMeasurement('columnWidth', 'outerWidth'); this._getMeasurement('gutter', 'outerWidth'); this.measureColumns(); // reset column Y this.colYs = []; for (var i = 0; i < this.cols; i++) { this.colYs.push(0); } this.maxY = 0; }; Masonry.prototype.measureColumns = function() { this.getContainerWidth(); // if columnWidth is 0, default to outerWidth of first item if (!this.columnWidth) { var firstItem = this.items[0]; var firstItemElem = firstItem && firstItem.element; // columnWidth fall back to item of first element this.columnWidth = firstItemElem && getSize(firstItemElem).outerWidth || // if first elem has no width, default to size of container this.containerWidth; } var columnWidth = this.columnWidth += this.gutter; // calculate columns var containerWidth = this.containerWidth + this.gutter; var cols = containerWidth / columnWidth; // fix rounding errors, typically with gutters var excess = columnWidth - containerWidth % columnWidth; // if overshoot is less than a pixel, round up, otherwise floor it var mathMethod = excess && excess < 1 ? 'round' : 'floor'; cols = Math[mathMethod](cols); this.cols = Math.max(cols, 1); }; Masonry.prototype.getContainerWidth = function() { // container is parent if fit width var isFitWidth = this._getOption('fitWidth'); var container = isFitWidth ? this.element.parentNode : this.element; // check that this.size and size are there // IE8 triggers resize on body size change, so they might not be var size = getSize(container); this.containerWidth = size && size.innerWidth; }; Masonry.prototype._getItemLayoutPosition = function(item) { item.getSize(); // how many columns does this brick span var remainder = item.size.outerWidth % this.columnWidth; var mathMethod = remainder && remainder < 1 ? 'round' : 'ceil'; // round if off by 1 pixel, otherwise use ceil var colSpan = Math[mathMethod](item.size.outerWidth / this.columnWidth); colSpan = Math.min(colSpan, this.cols); var colGroup = this._getColGroup(colSpan); // get the minimum Y value from the columns var minimumY = Math.min.apply(Math, colGroup); var shortColIndex = colGroup.indexOf(minimumY); // position the brick var position = { x: this.columnWidth * shortColIndex, y: minimumY }; // apply setHeight to necessary columns var setHeight = minimumY + item.size.outerHeight; var setSpan = this.cols + 1 - colGroup.length; for (var i = 0; i < setSpan; i++) { this.colYs[shortColIndex + i] = setHeight; } return position; }; /** * @param {Number} colSpan - number of columns the element spans * @returns {Array} colGroup */ Masonry.prototype._getColGroup = function(colSpan) { if (colSpan < 2) { // if brick spans only one column, use all the column Ys return this.colYs; } var colGroup = []; // how many different places could this brick fit horizontally var groupCount = this.cols + 1 - colSpan; // for each group potential horizontal position for (var i = 0; i < groupCount; i++) { // make an array of colY values for that one group var groupColYs = this.colYs.slice(i, i + colSpan); // and get the max value of the array colGroup[i] = Math.max.apply(Math, groupColYs); } return colGroup; }; Masonry.prototype._manageStamp = function(stamp) { var stampSize = getSize(stamp); var offset = this._getElementOffset(stamp); // get the columns that this stamp affects var isOriginLeft = this._getOption('originLeft'); var firstX = isOriginLeft ? offset.left : offset.right; var lastX = firstX + stampSize.outerWidth; var firstCol = Math.floor(firstX / this.columnWidth); firstCol = Math.max(0, firstCol); var lastCol = Math.floor(lastX / this.columnWidth); // lastCol should not go over if multiple of columnWidth #425 lastCol -= lastX % this.columnWidth ? 0 : 1; lastCol = Math.min(this.cols - 1, lastCol); // set colYs to bottom of the stamp var isOriginTop = this._getOption('originTop'); var stampMaxY = (isOriginTop ? offset.top : offset.bottom) + stampSize.outerHeight; for (var i = firstCol; i <= lastCol; i++) { this.colYs[i] = Math.max(stampMaxY, this.colYs[i]); } }; Masonry.prototype._getContainerSize = function() { this.maxY = Math.max.apply(Math, this.colYs); var size = { height: this.maxY }; if (this._getOption('fitWidth')) { size.width = this._getContainerFitWidth(); } return size; }; Masonry.prototype._getContainerFitWidth = function() { var unusedCols = 0; // count unused columns var i = this.cols; while (--i) { if (this.colYs[i] !== 0) { break; } unusedCols++; } // fit container to columns that have been used return (this.cols - unusedCols) * this.columnWidth - this.gutter; }; Masonry.prototype.needsResizeLayout = function() { var previousWidth = this.containerWidth; this.getContainerWidth(); return previousWidth != this.containerWidth; }; return Masonry; })); /*! * Masonry layout mode * sub-classes Masonry * http://masonry.desandro.com */ (function(window, factory) { // universal module definition /* jshint strict: false */ /*globals define, module, require */ if (typeof define == 'function' && define.amd) { // AMD define('isotope/js/layout-modes/masonry', [ '../layout-mode', 'masonry/masonry' ], factory); } else if (typeof module == 'object' && module.exports) { // CommonJS module.exports = factory(require('../layout-mode'), require('masonry-layout')); } else { // browser global factory(window.Isotope.LayoutMode, window.Masonry); } }(window, function factory(LayoutMode, Masonry) { 'use strict'; // -------------------------- masonryDefinition -------------------------- // // create an Outlayer layout class var MasonryMode = LayoutMode.create('masonry'); var proto = MasonryMode.prototype; var keepModeMethods = { _getElementOffset: true, layout: true, _getMeasurement: true }; // inherit Masonry prototype for (var method in Masonry.prototype) { // do not inherit mode methods if (!keepModeMethods[method]) { proto[method] = Masonry.prototype[method]; } } var measureColumns = proto.measureColumns; proto.measureColumns = function() { // set items, used if measuring first item this.items = this.isotope.filteredItems; measureColumns.call(this); }; // point to mode options for fitWidth var _getOption = proto._getOption; proto._getOption = function(option) { if (option == 'fitWidth') { return this.options.isFitWidth !== undefined ? this.options.isFitWidth : this.options.fitWidth; } return _getOption.apply(this.isotope, arguments); }; return MasonryMode; })); /** * fitRows layout mode */ (function(window, factory) { // universal module definition /* jshint strict: false */ /*globals define, module, require */ if (typeof define == 'function' && define.amd) { // AMD define('isotope/js/layout-modes/fit-rows', ['../layout-mode'], factory); } else if (typeof exports == 'object') { // CommonJS module.exports = factory(require('../layout-mode')); } else { // browser global factory(window.Isotope.LayoutMode); } }(window, function factory(LayoutMode) { 'use strict'; var FitRows = LayoutMode.create('fitRows'); var proto = FitRows.prototype; proto._resetLayout = function() { this.x = 0; this.y = 0; this.maxY = 0; this._getMeasurement('gutter', 'outerWidth'); }; proto._getItemLayoutPosition = function(item) { item.getSize(); var itemWidth = item.size.outerWidth + this.gutter; // if this element cannot fit in the current row var containerWidth = this.isotope.size.innerWidth + this.gutter; if (this.x !== 0 && itemWidth + this.x > containerWidth) { this.x = 0; this.y = this.maxY; } var position = { x: this.x, y: this.y }; this.maxY = Math.max(this.maxY, this.y + item.size.outerHeight); this.x += itemWidth; return position; }; proto._getContainerSize = function() { return { height: this.maxY }; }; return FitRows; })); /** * vertical layout mode */ (function(window, factory) { // universal module definition /* jshint strict: false */ /*globals define, module, require */ if (typeof define == 'function' && define.amd) { // AMD define('isotope/js/layout-modes/vertical', ['../layout-mode'], factory); } else if (typeof module == 'object' && module.exports) { // CommonJS module.exports = factory(require('../layout-mode')); } else { // browser global factory(window.Isotope.LayoutMode); } }(window, function factory(LayoutMode) { 'use strict'; var Vertical = LayoutMode.create('vertical', { horizontalAlignment: 0 }); var proto = Vertical.prototype; proto._resetLayout = function() { this.y = 0; }; proto._getItemLayoutPosition = function(item) { item.getSize(); var x = (this.isotope.size.innerWidth - item.size.outerWidth) * this.options.horizontalAlignment; var y = this.y; this.y += item.size.outerHeight; return { x: x, y: y }; }; proto._getContainerSize = function() { return { height: this.y }; }; return Vertical; })); /*! * Isotope v3.0.1 * * Licensed GPLv3 for open source use * or Isotope Commercial License for commercial use * * http://isotope.metafizzy.co * Copyright 2016 Metafizzy */ (function(window, factory) { // universal module definition /* jshint strict: false */ /*globals define, module, require */ if (typeof define == 'function' && define.amd) { // AMD define([ 'outlayer/outlayer', 'get-size/get-size', 'desandro-matches-selector/matches-selector', 'fizzy-ui-utils/utils', 'isotope/js/item', 'isotope/js/layout-mode', // include default layout modes 'isotope/js/layout-modes/masonry', 'isotope/js/layout-modes/fit-rows', 'isotope/js/layout-modes/vertical' ], function(Outlayer, getSize, matchesSelector, utils, Item, LayoutMode) { return factory(window, Outlayer, getSize, matchesSelector, utils, Item, LayoutMode); }); } else if (typeof module == 'object' && module.exports) { // CommonJS module.exports = factory(window, require('outlayer'), require('get-size'), require('desandro-matches-selector'), require('fizzy-ui-utils'), require('isotope/js/item'), require('isotope/js/layout-mode'), // include default layout modes require('isotope/js/layout-modes/masonry'), require('isotope/js/layout-modes/fit-rows'), require('isotope/js/layout-modes/vertical')); } else { // browser global window.Isotope = factory(window, window.Outlayer, window.getSize, window.matchesSelector, window.fizzyUIUtils, window.Isotope.Item, window.Isotope.LayoutMode); } }(window, function factory(window, Outlayer, getSize, matchesSelector, utils, Item, LayoutMode) { // -------------------------- vars -------------------------- // var jQuery = window.jQuery; // -------------------------- helpers -------------------------- // var trim = String.prototype.trim ? function(str) { return str.trim(); } : function(str) { return str.replace(/^\s+|\s+$/g, ''); }; // -------------------------- isotopeDefinition -------------------------- // // create an Outlayer layout class var Isotope = Outlayer.create('isotope', { layoutMode: 'masonry', isJQueryFiltering: true, sortAscending: true }); Isotope.Item = Item; Isotope.LayoutMode = LayoutMode; var proto = Isotope.prototype; proto._create = function() { this.itemGUID = 0; // functions that sort items this._sorters = {}; this._getSorters(); // call super Outlayer.prototype._create.call(this); // create layout modes this.modes = {}; // start filteredItems with all items this.filteredItems = this.items; // keep of track of sortBys this.sortHistory = ['original-order']; // create from registered layout modes for (var name in LayoutMode.modes) { this._initLayoutMode(name); } }; proto.reloadItems = function() { // reset item ID counter this.itemGUID = 0; // call super Outlayer.prototype.reloadItems.call(this); }; proto._itemize = function() { var items = Outlayer.prototype._itemize.apply(this, arguments); // assign ID for original-order for (var i = 0; i < items.length; i++) { var item = items[i]; item.id = this.itemGUID++; } this._updateItemsSortData(items); return items; }; // -------------------------- layout -------------------------- // proto._initLayoutMode = function(name) { var Mode = LayoutMode.modes[name]; // set mode options // HACK extend initial options, back-fill in default options var initialOpts = this.options[name] || {}; this.options[name] = Mode.options ? utils.extend(Mode.options, initialOpts) : initialOpts; // init layout mode instance this.modes[name] = new Mode(this); }; proto.layout = function() { // if first time doing layout, do all magic if (!this._isLayoutInited && this._getOption('initLayout')) { this.arrange(); return; } this._layout(); }; // private method to be used in layout() & magic() proto._layout = function() { // don't animate first layout var isInstant = this._getIsInstant(); // layout flow this._resetLayout(); this._manageStamps(); this.layoutItems(this.filteredItems, isInstant); // flag for initalized this._isLayoutInited = true; }; // filter + sort + layout proto.arrange = function(opts) { // set any options pass this.option(opts); this._getIsInstant(); // filter, sort, and layout // filter var filtered = this._filter(this.items); this.filteredItems = filtered.matches; this._bindArrangeComplete(); if (this._isInstant) { this._noTransition(this._hideReveal, [filtered]); } else { this._hideReveal(filtered); } this._sort(); this._layout(); }; // alias to _init for main plugin method proto._init = proto.arrange; proto._hideReveal = function(filtered) { this.reveal(filtered.needReveal); this.hide(filtered.needHide); }; // HACK // Don't animate/transition first layout // Or don't animate/transition other layouts proto._getIsInstant = function() { var isLayoutInstant = this._getOption('layoutInstant'); var isInstant = isLayoutInstant !== undefined ? isLayoutInstant : !this._isLayoutInited; this._isInstant = isInstant; return isInstant; }; // listen for layoutComplete, hideComplete and revealComplete // to trigger arrangeComplete proto._bindArrangeComplete = function() { // listen for 3 events to trigger arrangeComplete var isLayoutComplete, isHideComplete, isRevealComplete; var _this = this; function arrangeParallelCallback() { if (isLayoutComplete && isHideComplete && isRevealComplete) { _this.dispatchEvent('arrangeComplete', null, [_this.filteredItems]); } } this.once('layoutComplete', function() { isLayoutComplete = true; arrangeParallelCallback(); }); this.once('hideComplete', function() { isHideComplete = true; arrangeParallelCallback(); }); this.once('revealComplete', function() { isRevealComplete = true; arrangeParallelCallback(); }); }; // -------------------------- filter -------------------------- // proto._filter = function(items) { var filter = this.options.filter; filter = filter || '*'; var matches = []; var hiddenMatched = []; var visibleUnmatched = []; var test = this._getFilterTest(filter); // test each item for (var i = 0; i < items.length; i++) { var item = items[i]; if (item.isIgnored) { continue; } // add item to either matched or unmatched group var isMatched = test(item); // item.isFilterMatched = isMatched; // add to matches if its a match if (isMatched) { matches.push(item); } // add to additional group if item needs to be hidden or revealed if (isMatched && item.isHidden) { hiddenMatched.push(item); } else if (!isMatched && !item.isHidden) { visibleUnmatched.push(item); } } // return collections of items to be manipulated return { matches: matches, needReveal: hiddenMatched, needHide: visibleUnmatched }; }; // get a jQuery, function, or a matchesSelector test given the filter proto._getFilterTest = function(filter) { if (jQuery && this.options.isJQueryFiltering) { // use jQuery return function(item) { return jQuery(item.element).is(filter); }; } if (typeof filter == 'function') { // use filter as function return function(item) { return filter(item.element); }; } // default, use filter as selector string return function(item) { return matchesSelector(item.element, filter); }; }; // -------------------------- sorting -------------------------- // /** * @params {Array} elems * @public */ proto.updateSortData = function(elems) { // get items var items; if (elems) { elems = utils.makeArray(elems); items = this.getItems(elems); } else { // update all items if no elems provided items = this.items; } this._getSorters(); this._updateItemsSortData(items); }; proto._getSorters = function() { var getSortData = this.options.getSortData; for (var key in getSortData) { var sorter = getSortData[key]; this._sorters[key] = mungeSorter(sorter); } }; /** * @params {Array} items - of Isotope.Items * @private */ proto._updateItemsSortData = function(items) { // do not update if no items var len = items && items.length; for (var i = 0; len && i < len; i++) { var item = items[i]; item.updateSortData(); } }; // ----- munge sorter ----- // // encapsulate this, as we just need mungeSorter // other functions in here are just for munging var mungeSorter = function() { // add a magic layer to sorters for convienent shorthands // `.foo-bar` will use the text of .foo-bar querySelector // `[foo-bar]` will use attribute // you can also add parser // `.foo-bar parseInt` will parse that as a number function mungeSorter(sorter) { // if not a string, return function or whatever it is if (typeof sorter != 'string') { return sorter; } // parse the sorter string var args = trim(sorter).split(' '); var query = args[0]; // check if query looks like [an-attribute] var attrMatch = query.match(/^\[(.+)\]$/); var attr = attrMatch && attrMatch[1]; var getValue = getValueGetter(attr, query); // use second argument as a parser var parser = Isotope.sortDataParsers[args[1]]; // parse the value, if there was a parser sorter = parser ? function(elem) { return elem && parser(getValue(elem)); } : // otherwise just return value function(elem) { return elem && getValue(elem); }; return sorter; } // get an attribute getter, or get text of the querySelector function getValueGetter(attr, query) { // if query looks like [foo-bar], get attribute if (attr) { return function getAttribute(elem) { return elem.getAttribute(attr); }; } // otherwise, assume its a querySelector, and get its text return function getChildText(elem) { var child = elem.querySelector(query); return child && child.textContent; }; } return mungeSorter; }(); // parsers used in getSortData shortcut strings Isotope.sortDataParsers = { 'parseInt': function(val) { return parseInt(val, 10); }, 'parseFloat': function(val) { return parseFloat(val); } }; // ----- sort method ----- // // sort filteredItem order proto._sort = function() { var sortByOpt = this.options.sortBy; if (!sortByOpt) { return; } // concat all sortBy and sortHistory var sortBys = [].concat.apply(sortByOpt, this.sortHistory); // sort magic var itemSorter = getItemSorter(sortBys, this.options.sortAscending); this.filteredItems.sort(itemSorter); // keep track of sortBy History if (sortByOpt != this.sortHistory[0]) { // add to front, oldest goes in last this.sortHistory.unshift(sortByOpt); } }; // returns a function used for sorting function getItemSorter(sortBys, sortAsc) { return function sorter(itemA, itemB) { // cycle through all sortKeys for (var i = 0; i < sortBys.length; i++) { var sortBy = sortBys[i]; var a = itemA.sortData[sortBy]; var b = itemB.sortData[sortBy]; if (a > b || a < b) { // if sortAsc is an object, use the value given the sortBy key var isAscending = sortAsc[sortBy] !== undefined ? sortAsc[sortBy] : sortAsc; var direction = isAscending ? 1 : -1; return (a > b ? 1 : -1) * direction; } } return 0; }; } // -------------------------- methods -------------------------- // // get layout mode proto._mode = function() { var layoutMode = this.options.layoutMode; var mode = this.modes[layoutMode]; if (!mode) { // TODO console.error throw new Error('No layout mode: ' + layoutMode); } // HACK sync mode's options // any options set after init for layout mode need to be synced mode.options = this.options[layoutMode]; return mode; }; proto._resetLayout = function() { // trigger original reset layout Outlayer.prototype._resetLayout.call(this); this._mode()._resetLayout(); }; proto._getItemLayoutPosition = function(item) { return this._mode()._getItemLayoutPosition(item); }; proto._manageStamp = function(stamp) { this._mode()._manageStamp(stamp); }; proto._getContainerSize = function() { return this._mode()._getContainerSize(); }; proto.needsResizeLayout = function() { return this._mode().needsResizeLayout(); }; // -------------------------- adding & removing -------------------------- // // HEADS UP overwrites default Outlayer appended proto.appended = function(elems) { var items = this.addItems(elems); if (!items.length) { return; } // filter, layout, reveal new items var filteredItems = this._filterRevealAdded(items); // add to filteredItems this.filteredItems = this.filteredItems.concat(filteredItems); }; // HEADS UP overwrites default Outlayer prepended proto.prepended = function(elems) { var items = this._itemize(elems); if (!items.length) { return; } // start new layout this._resetLayout(); this._manageStamps(); // filter, layout, reveal new items var filteredItems = this._filterRevealAdded(items); // layout previous items this.layoutItems(this.filteredItems); // add to items and filteredItems this.filteredItems = filteredItems.concat(this.filteredItems); this.items = items.concat(this.items); }; proto._filterRevealAdded = function(items) { var filtered = this._filter(items); this.hide(filtered.needHide); // reveal all new items this.reveal(filtered.matches); // layout new items, no transition this.layoutItems(filtered.matches, true); return filtered.matches; }; /** * Filter, sort, and layout newly-appended item elements * @param {Array or NodeList or Element} elems */ proto.insert = function(elems) { var items = this.addItems(elems); if (!items.length) { return; } // append item elements var i, item; var len = items.length; for (i = 0; i < len; i++) { item = items[i]; this.element.appendChild(item.element); } // filter new stuff var filteredInsertItems = this._filter(items).matches; // set flag for (i = 0; i < len; i++) { items[i].isLayoutInstant = true; } this.arrange(); // reset flag for (i = 0; i < len; i++) { delete items[i].isLayoutInstant; } this.reveal(filteredInsertItems); }; var _remove = proto.remove; proto.remove = function(elems) { elems = utils.makeArray(elems); var removeItems = this.getItems(elems); // do regular thing _remove.call(this, elems); // bail if no items to remove var len = removeItems && removeItems.length; // remove elems from filteredItems for (var i = 0; len && i < len; i++) { var item = removeItems[i]; // remove item from collection utils.removeFrom(this.filteredItems, item); } }; proto.shuffle = function() { // update random sortData for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; item.sortData.random = Math.random(); } this.options.sortBy = 'random'; this._sort(); this._layout(); }; /** * trigger fn without transition * kind of hacky to have this in the first place * @param {Function} fn * @param {Array} args * @returns ret * @private */ proto._noTransition = function(fn, args) { // save transitionDuration before disabling var transitionDuration = this.options.transitionDuration; // disable transition this.options.transitionDuration = 0; // do it var returnValue = fn.apply(this, args); // re-enable transition for reveal this.options.transitionDuration = transitionDuration; return returnValue; }; // ----- helper methods ----- // /** * getter method for getting filtered item elements * @returns {Array} elems - collection of item elements */ proto.getFilteredItemElements = function() { return this.filteredItems.map(function(item) { return item.element; }); }; // ----- ----- // return Isotope; }));
import { redirect } from 'redux-first-router' import { isAllowed, isServer } from './utils' export default { onBeforeChange: (dispatch, getState, action) => { const allowed = isAllowed(action.type, getState()) if (!allowed) { const action = redirect({ type: 'LOGIN' }) dispatch(action) } }, onAfterChange: (dispatch, getState) => { const { type } = getState().location if (type === 'LOGIN' && !isServer) { setTimeout(() => { alert(alertMessage) }, 1500) } }, } const alertMessage = "NICE, You're adventurous! Try changing the jwToken cookie from 'fake' to 'real' in server/index.js (and manually refresh) to access the Admin Panel. Then 'onBeforeChange' will let you in."
import { moduleFor, test } from 'ember-qunit'; moduleFor('route:public', 'Unit | Route | public', { // Specify the other units that are required for this test. // needs: ['controller:foo'] }); test('it exists', function(assert) { let route = this.subject(); assert.ok(route); });
import React, { PropTypes } from 'react'; import RedirectButton from '../RedirectButton/index'; import baseStyle from '../../common/Style/baseStyle.css'; import styles from './styles.css'; const contactSection = (({ content, buttonLabel }) => <div className={styles.wrapper}> <h1 className={baseStyle.display1}>{content}</h1> <RedirectButton label={buttonLabel} path="/contact" /> </div> ); contactSection.propTypes = { content: PropTypes.string.isRequired, buttonLabel: PropTypes.string.isRequired, }; export default contactSection;
version https://git-lfs.github.com/spec/v1 oid sha256:93b82a8c6d0935f5a8f9547f3b437883b40629314e0c6504e9433ad634f2081b size 9088
var support__feedback__blink_8h = [ [ "feedback_blink_mode_t", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5c", [ [ "KG_BLINK_MODE_OFF", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5ca57c3cbe256191010d4c7c0ef1733a7d0", null ], [ "KG_BLINK_MODE_SOLID", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5ca4664365f520eb10ce1ae18a088bd5bac", null ], [ "KG_BLINK_MODE_B200_100", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5ca09c065099e9d70d94445d7adc5d9b046", null ], [ "KG_BLINK_MODE_B200_50", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5cab0691b0318cec2e13a3453942402ed1e", null ], [ "KG_BLINK_MODE_B1000_500", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5ca2e7c27dfe2be5465f5b688b200ccd2f8", null ], [ "KG_BLINK_MODE_B1000_100", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5caf1edf429be740e8ad492e18e3883d202", null ], [ "KG_BLINK_MODE_B1000_100_2X", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5cacfe607ff63ae1d0e0f2d64c36decdeaa", null ], [ "KG_BLINK_MODE_B1000_100_3X", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5ca7ad3acda2b3f0ac8c046a7b5c4eacc4e", null ], [ "KG_BLINK_MODE_B3000_1000", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5ca6142d36517e6627c810be65c25c4e4a4", null ], [ "KG_BLINK_MODE_B3000_100", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5cad840a8a2f954972fc104bf95236d3351", null ], [ "KG_BLINK_MODE_B3000_100_2X", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5caaa55115d7ff5a9c00b1fea37df4ef6b4", null ], [ "KG_BLINK_MODE_B3000_100_3X", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5ca32ca431a096eb92333c34d9f7a65b30e", null ], [ "KG_BLINK_MODE_MAX", "support__feedback__blink_8h.html#a35189fed6614ac24f7c917460b8c8b5ca4a2b5e305cd1122a339993097fb1c8e1", null ] ] ], [ "feedback_set_blink_logic", "support__feedback__blink_8h.html#a607d8d9801c63e22c38caee5510960c2", null ], [ "feedback_set_blink_mode", "support__feedback__blink_8h.html#a5b89b785ba997eacd97b1efe3d25c7a2", null ], [ "kg_cmd_feedback_get_blink_mode", "support__feedback__blink_8h.html#a9cea3dfe23aa8c27b7bb35eb1eb46be7", null ], [ "kg_cmd_feedback_set_blink_mode", "support__feedback__blink_8h.html#a8d1bb83d1d7b0f03e0f1b164e7e8c477", null ], [ "setup_feedback_blink", "support__feedback__blink_8h.html#ab9034b1c524658a092853b85cdfd5da3", null ], [ "update_feedback_blink", "support__feedback__blink_8h.html#a1e07c51a0bd376696315ac0146586ecb", null ] ];
/** * Copyright 2017 Google Inc. * * 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. */ /** * @fileoverview Firebase Auth API. * Version: ${JSCORE_VERSION} * * Copyright 2017 Google Inc. All Rights Reserved. * * 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. * * @externs */ /** * Gets the {@link firebase.auth.Auth `Auth`} service for the default app or a * given app. * * `firebase.auth()` can be called with no arguments to access the default app's * {@link firebase.auth.Auth `Auth`} service or as `firebase.auth(app)` to * access the {@link firebase.auth.Auth `Auth`} service associated with a * specific app. * * @example * // Get the Auth service for the default app * var defaultAuth = firebase.auth(); * * @example * // Get the Auth service for a given app * var otherAuth = firebase.auth(otherApp); * * @namespace * @param {!firebase.app.App=} app * * @return {!firebase.auth.Auth} */ firebase.auth = function(app) {}; /** * Interface that represents the credentials returned by an auth provider. * Implementations specify the details about each auth provider's credential * requirements. * * @interface */ firebase.auth.AuthCredential = function() {}; /** * The authentication provider ID for the credential. * For example, 'facebook.com', or 'google.com'. * * @type {string} */ firebase.auth.AuthCredential.prototype.providerId; /** * Interface that represents the OAuth credentials returned by an OAuth * provider. Implementations specify the details about each auth provider's * credential requirements. * * @interface * @extends {firebase.auth.AuthCredential} */ firebase.auth.OAuthCredential = function() {}; /** * The OAuth ID token associated with the credential if it belongs to an * OIDC provider, such as `google.com`. * * @type {?string|undefined} */ firebase.auth.OAuthCredential.prototype.idToken; /** * The OAuth access token associated with the credential if it belongs to an * OAuth provider, such as `facebook.com`, `twitter.com`, etc. * * @type {?string|undefined} */ firebase.auth.OAuthCredential.prototype.accessToken; /** * The OAuth access token secret associated with the credential if it belongs * to an OAuth 1.0 provider, such as `twitter.com`. * * @type {?string|undefined} */ firebase.auth.OAuthCredential.prototype.secret; /** * Gets the {@link firebase.auth.Auth `Auth`} service for the current app. * * @example * var auth = app.auth(); * // The above is shorthand for: * // var auth = firebase.auth(app); * * @return {!firebase.auth.Auth} */ firebase.app.App.prototype.auth = function() {}; /** * Interface representing a user's metadata. * * @interface */ firebase.auth.UserMetadata = function() {}; /** * The date the user last signed in, formatted as a UTC string. * For example, 'Fri, 22 Sep 2017 01:49:58 GMT'. * * @type {?string} */ firebase.auth.UserMetadata.prototype.lastSignInTime; /** * The date the user was created, formatted as a UTC string. * For example, 'Fri, 22 Sep 2017 01:49:58 GMT'. * * @type {?string} */ firebase.auth.UserMetadata.prototype.creationTime; /** * User profile information, visible only to the Firebase project's * apps. * * @interface */ firebase.UserInfo = function() {}; /** * The user's unique ID. * * @type {string} */ firebase.UserInfo.prototype.uid; /** * The authentication provider ID for the current user. * For example, 'facebook.com', or 'google.com'. * * @type {string} */ firebase.UserInfo.prototype.providerId; /** * The user's email address (if available). * @type {?string} */ firebase.UserInfo.prototype.email; /** * The user's display name (if available). * * @type {?string} */ firebase.UserInfo.prototype.displayName; /** * The URL of the user's profile picture (if available). * * @type {?string} */ firebase.UserInfo.prototype.photoURL; /** * The user's E.164 formatted phone number (if available). * * @type {?string} */ firebase.UserInfo.prototype.phoneNumber; /** * A user account. * * @interface * @extends {firebase.UserInfo} */ firebase.User = function() {}; /** * The phone number normalized based on the E.164 standard (e.g. +16505550101) * for the current user. This is null if the user has no phone credential linked * to the account. * @type {?string} */ firebase.User.prototype.phoneNumber; /** @type {boolean} */ firebase.User.prototype.isAnonymous; /** * True if the user's email address has been verified. * @type {boolean} */ firebase.User.prototype.emailVerified; /** * Additional metadata about the user. * @type {!firebase.auth.UserMetadata} */ firebase.User.prototype.metadata; /** * Additional provider-specific information about the user. * @type {!Array<firebase.UserInfo>} */ firebase.User.prototype.providerData; /** * A refresh token for the user account. Use only for advanced scenarios that * require explicitly refreshing tokens. * @type {string} */ firebase.User.prototype.refreshToken; /** * Returns a JWT token used to identify the user to a Firebase service. * * Returns the current token if it has not expired, otherwise this will * refresh the token and return a new one. * * This property is deprecated. Use {@link firebase.User#getIdToken} instead. * * @param {boolean=} forceRefresh Force refresh regardless of token * expiration. * @return {!firebase.Promise<string>} * @deprecated */ firebase.User.prototype.getToken = function(forceRefresh) {}; /** * Returns a JWT token used to identify the user to a Firebase service. * * Returns the current token if it has not expired, otherwise this will * refresh the token and return a new one. * * @param {boolean=} forceRefresh Force refresh regardless of token * expiration. * @return {!firebase.Promise<string>} */ firebase.User.prototype.getIdToken = function(forceRefresh) {}; /** * Refreshes the current user, if signed in. * * @return {!firebase.Promise<void>} */ firebase.User.prototype.reload = function() {}; /** * Sends a verification email to a user. * * The verification process is completed by calling * {@link firebase.auth.Auth#applyActionCode} * * <h4>Error Codes</h4> * <dl> * <dt>auth/missing-android-pkg-name</dt> * <dd>An Android package name must be provided if the Android app is required * to be installed.</dd> * <dt>auth/missing-continue-uri</dt> * <dd>A continue URL must be provided in the request.</dd> * <dt>auth/missing-ios-bundle-id</dt> * <dd>An iOS bundle ID must be provided if an App Store ID is provided.</dd> * <dt>auth/invalid-continue-uri</dt> * <dd>The continue URL provided in the request is invalid.</dd> * <dt>auth/unauthorized-continue-uri</dt> * <dd>The domain of the continue URL is not whitelisted. Whitelist * the domain in the Firebase console.</dd> * </dl> * * @example * var actionCodeSettings = { * url: 'https://www.example.com/cart?email=user@example.com&cartId=123', * iOS: { * bundleId: 'com.example.ios' * }, * android: { * packageName: 'com.example.android', * installApp: true, * minimumVersion: '12' * }, * handleCodeInApp: true * }; * firebase.auth().currentUser.sendEmailVerification(actionCodeSettings) * .then(function() { * // Verification email sent. * }) * .catch(function(error) { * // Error occurred. Inspect error.code. * }); * * @param {?firebase.auth.ActionCodeSettings=} actionCodeSettings The action * code settings. If specified, the state/continue URL will be set as the * "continueUrl" parameter in the email verification link. The default email * verification landing page will use this to display a link to go back to * the app if it is installed. * If the actionCodeSettings is not specified, no URL is appended to the * action URL. * The state URL provided must belong to a domain that is whitelisted by the * developer in the console. Otherwise an error will be thrown. * Mobile app redirects will only be applicable if the developer configures * and accepts the Firebase Dynamic Links terms of condition. * The Android package name and iOS bundle ID will be respected only if they * are configured in the same Firebase Auth project used. * @return {!firebase.Promise<void>} */ firebase.User.prototype.sendEmailVerification = function(actionCodeSettings) {}; /** * Links the user account with the given credentials. * * <h4>Error Codes</h4> * <dl> * <dt>auth/provider-already-linked</dt> * <dd>Thrown if the provider has already been linked to the user. This error is * thrown even if this is not the same provider's account that is currently * linked to the user.</dd> * <dt>auth/invalid-credential</dt> * <dd>Thrown if the provider's credential is not valid. This can happen if it * has already expired when calling link, or if it used invalid token(s). * See the Firebase documentation for your provider, and make sure you pass * in the correct parameters to the credential method.</dd> * <dt>auth/credential-already-in-use</dt> * <dd>Thrown if the account corresponding to the credential already exists * among your users, or is already linked to a Firebase User. * For example, this error could be thrown if you are upgrading an anonymous * user to a Google user by linking a Google credential to it and the Google * credential used is already associated with an existing Firebase Google * user. * The fields <code>error.email</code>, <code>error.phoneNumber</code>, and * <code>error.credential</code> ({@link firebase.auth.AuthCredential}) * may be provided, depending on the type of credential. You can recover * from this error by signing in with <code>error.credential</code> directly * via {@link firebase.auth.Auth#signInWithCredential}.</dd> * <dt>auth/email-already-in-use</dt> * <dd>Thrown if the email corresponding to the credential already exists * among your users. When thrown while linking a credential to an existing * user, an <code>error.email</code> and <code>error.credential</code> * ({@link firebase.auth.AuthCredential}) fields are also provided. * You have to link the credential to the existing user with that email if * you wish to continue signing in with that credential. To do so, call * {@link firebase.auth.Auth#fetchProvidersForEmail}, sign in to * <code>error.email</code> via one of the providers returned and then * {@link firebase.User#linkWithCredential} the original credential to that * newly signed in user.</dd> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if you have not enabled the provider in the Firebase Console. Go * to the Firebase Console for your project, in the Auth section and the * <strong>Sign in Method</strong> tab and configure the provider.</dd> * <dt>auth/invalid-email</dt> * <dd>Thrown if the email used in a * {@link firebase.auth.EmailAuthProvider#credential} is invalid.</dd> * <dt>auth/wrong-password</dt> * <dd>Thrown if the password used in a * {@link firebase.auth.EmailAuthProvider#credential} is not correct or * when the user associated with the email does not have a password.</dd> * <dt>auth/invalid-verification-code</dt> * <dd>Thrown if the credential is a * {@link firebase.auth.PhoneAuthProvider#credential} and the verification * code of the credential is not valid.</dd> * <dt>auth/invalid-verification-id</dt> * <dd>Thrown if the credential is a * {@link firebase.auth.PhoneAuthProvider#credential} and the verification * ID of the credential is not valid.</dd> * </dl> * * @param {!firebase.auth.AuthCredential} credential The auth credential. * @return {!firebase.Promise<!firebase.User>} */ firebase.User.prototype.linkWithCredential = function(credential) {}; /** * Links the user account with the given credentials, and returns any available * additional user information, such as user name. * * <h4>Error Codes</h4> * <dl> * <dt>auth/provider-already-linked</dt> * <dd>Thrown if the provider has already been linked to the user. This error is * thrown even if this is not the same provider's account that is currently * linked to the user.</dd> * <dt>auth/invalid-credential</dt> * <dd>Thrown if the provider's credential is not valid. This can happen if it * has already expired when calling link, or if it used invalid token(s). * See the Firebase documentation for your provider, and make sure you pass * in the correct parameters to the credential method.</dd> * <dt>auth/credential-already-in-use</dt> * <dd>Thrown if the account corresponding to the credential already exists * among your users, or is already linked to a Firebase User. * For example, this error could be thrown if you are upgrading an anonymous * user to a Google user by linking a Google credential to it and the Google * credential used is already associated with an existing Firebase Google * user. * The fields <code>error.email</code>, <code>error.phoneNumber</code>, and * <code>error.credential</code> ({@link firebase.auth.AuthCredential}) * may be provided, depending on the type of credential. You can recover * from this error by signing in with <code>error.credential</code> directly * via {@link firebase.auth.Auth#signInWithCredential}.</dd> * <dt>auth/email-already-in-use</dt> * <dd>Thrown if the email corresponding to the credential already exists * among your users. When thrown while linking a credential to an existing * user, an <code>error.email</code> and <code>error.credential</code> * ({@link firebase.auth.AuthCredential}) fields are also provided. * You have to link the credential to the existing user with that email if * you wish to continue signing in with that credential. To do so, call * {@link firebase.auth.Auth#fetchProvidersForEmail}, sign in to * <code>error.email</code> via one of the providers returned and then * {@link firebase.User#linkWithCredential} the original credential to that * newly signed in user.</dd> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if you have not enabled the provider in the Firebase Console. Go * to the Firebase Console for your project, in the Auth section and the * <strong>Sign in Method</strong> tab and configure the provider.</dd> * <dt>auth/invalid-email</dt> * <dd>Thrown if the email used in a * {@link firebase.auth.EmailAuthProvider#credential} is invalid.</dd> * <dt>auth/wrong-password</dt> * <dd>Thrown if the password used in a * {@link firebase.auth.EmailAuthProvider#credential} is not correct or * when the user associated with the email does not have a password.</dd> * <dt>auth/invalid-verification-code</dt> * <dd>Thrown if the credential is a * {@link firebase.auth.PhoneAuthProvider#credential} and the verification * code of the credential is not valid.</dd> * <dt>auth/invalid-verification-id</dt> * <dd>Thrown if the credential is a * {@link firebase.auth.PhoneAuthProvider#credential} and the verification * ID of the credential is not valid.</dd> * </dl> * * @param {!firebase.auth.AuthCredential} credential The auth credential. * @return {!firebase.Promise<!firebase.auth.UserCredential>} */ firebase.User.prototype.linkAndRetrieveDataWithCredential = function( credential ) {}; /** * Links the user account with the given phone number. * * <h4>Error Codes</h4> * <dl> * <dt>auth/provider-already-linked</dt> * <dd>Thrown if the provider has already been linked to the user. This error is * thrown even if this is not the same provider's account that is currently * linked to the user.</dd> * <dt>auth/captcha-check-failed</dt> * <dd>Thrown if the reCAPTCHA response token was invalid, expired, or if * this method was called from a non-whitelisted domain.</dd> * <dt>auth/invalid-phone-number</dt> * <dd>Thrown if the phone number has an invalid format.</dd> * <dt>auth/missing-phone-number</dt> * <dd>Thrown if the phone number is missing.</dd> * <dt>auth/quota-exceeded</dt> * <dd>Thrown if the SMS quota for the Firebase project has been exceeded.</dd> * <dt>auth/user-disabled</dt> * <dd>Thrown if the user corresponding to the given phone number has been * disabled.</dd> * <dt>auth/credential-already-in-use</dt> * <dd>Thrown if the account corresponding to the phone number already exists * among your users, or is already linked to a Firebase User. * The fields <code>error.phoneNumber</code> and * <code>error.credential</code> ({@link firebase.auth.AuthCredential}) * are provided in this case. You can recover from this error by signing in * with that credential directly via * {@link firebase.auth.Auth#signInWithCredential}.</dd> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if you have not enabled the phone authentication provider in the * Firebase Console. Go to the Firebase Console for your project, in the * Auth section and the <strong>Sign in Method</strong> tab and configure * the provider.</dd> * </dl> * * @param {string} phoneNumber The user's phone number in E.164 format (e.g. * +16505550101). * @param {!firebase.auth.ApplicationVerifier} applicationVerifier * @return {!firebase.Promise<!firebase.auth.ConfirmationResult>} */ firebase.User.prototype.linkWithPhoneNumber = function( phoneNumber, applicationVerifier ) {}; /** * Unlinks a provider from a user account. * * <h4>Error Codes</h4> * <dl> * <dt>auth/no-such-provider</dt> * <dd>Thrown if the user does not have this provider linked or when the * provider ID given does not exist.</dd> * </dt> * * @param {string} providerId * @return {!firebase.Promise<!firebase.User>} */ firebase.User.prototype.unlink = function(providerId) {}; /** * Re-authenticates a user using a fresh credential. Use before operations * such as {@link firebase.User#updatePassword} that require tokens from recent * sign-in attempts. * * <h4>Error Codes</h4> * <dl> * <dt>auth/user-mismatch</dt> * <dd>Thrown if the credential given does not correspond to the user.</dd> * <dt>auth/user-not-found</dt> * <dd>Thrown if the credential given does not correspond to any existing user. * </dd> * <dt>auth/invalid-credential</dt> * <dd>Thrown if the provider's credential is not valid. This can happen if it * has already expired when calling link, or if it used invalid token(s). * See the Firebase documentation for your provider, and make sure you pass * in the correct parameters to the credential method.</dd> * <dt>auth/invalid-email</dt> * <dd>Thrown if the email used in a * {@link firebase.auth.EmailAuthProvider#credential} is invalid.</dd> * <dt>auth/wrong-password</dt> * <dd>Thrown if the password used in a * {@link firebase.auth.EmailAuthProvider#credential} is not correct or when * the user associated with the email does not have a password.</dd> * <dt>auth/invalid-verification-code</dt> * <dd>Thrown if the credential is a * {@link firebase.auth.PhoneAuthProvider#credential} and the verification * code of the credential is not valid.</dd> * <dt>auth/invalid-verification-id</dt> * <dd>Thrown if the credential is a * {@link firebase.auth.PhoneAuthProvider#credential} and the verification * ID of the credential is not valid.</dd> * </dl> * * @param {!firebase.auth.AuthCredential} credential * @return {!firebase.Promise<void>} */ firebase.User.prototype.reauthenticateWithCredential = function(credential) {}; /** * Re-authenticates a user using a fresh credential, and returns any available * additional user information, such as user name. Use before operations * such as {@link firebase.User#updatePassword} that require tokens from recent * sign-in attempts. * * <h4>Error Codes</h4> * <dl> * <dt>auth/user-mismatch</dt> * <dd>Thrown if the credential given does not correspond to the user.</dd> * <dt>auth/user-not-found</dt> * <dd>Thrown if the credential given does not correspond to any existing user. * </dd> * <dt>auth/invalid-credential</dt> * <dd>Thrown if the provider's credential is not valid. This can happen if it * has already expired when calling link, or if it used invalid token(s). * See the Firebase documentation for your provider, and make sure you pass * in the correct parameters to the credential method.</dd> * <dt>auth/invalid-email</dt> * <dd>Thrown if the email used in a * {@link firebase.auth.EmailAuthProvider#credential} is invalid.</dd> * <dt>auth/wrong-password</dt> * <dd>Thrown if the password used in a * {@link firebase.auth.EmailAuthProvider#credential} is not correct or when * the user associated with the email does not have a password.</dd> * <dt>auth/invalid-verification-code</dt> * <dd>Thrown if the credential is a * {@link firebase.auth.PhoneAuthProvider#credential} and the verification * code of the credential is not valid.</dd> * <dt>auth/invalid-verification-id</dt> * <dd>Thrown if the credential is a * {@link firebase.auth.PhoneAuthProvider#credential} and the verification * ID of the credential is not valid.</dd> * </dl> * * @param {!firebase.auth.AuthCredential} credential * @return {!firebase.Promise<!firebase.auth.UserCredential>} */ firebase.User.prototype.reauthenticateAndRetrieveDataWithCredential = function( credential ) {}; /** * Re-authenticates a user using a fresh credential. Use before operations * such as {@link firebase.User#updatePassword} that require tokens from recent * sign-in attempts. * * <h4>Error Codes</h4> * <dl> * <dt>auth/user-mismatch</dt> * <dd>Thrown if the credential given does not correspond to the user.</dd> * <dt>auth/user-not-found</dt> * <dd>Thrown if the credential given does not correspond to any existing user. * </dd> * <dt>auth/captcha-check-failed</dt> * <dd>Thrown if the reCAPTCHA response token was invalid, expired, or if * this method was called from a non-whitelisted domain.</dd> * <dt>auth/invalid-phone-number</dt> * <dd>Thrown if the phone number has an invalid format.</dd> * <dt>auth/missing-phone-number</dt> * <dd>Thrown if the phone number is missing.</dd> * <dt>auth/quota-exceeded</dt> * <dd>Thrown if the SMS quota for the Firebase project has been exceeded.</dd> * </dl> * * @param {string} phoneNumber The user's phone number in E.164 format (e.g. * +16505550101). * @param {!firebase.auth.ApplicationVerifier} applicationVerifier * @return {!firebase.Promise<!firebase.auth.ConfirmationResult>} */ firebase.User.prototype.reauthenticateWithPhoneNumber = function( phoneNumber, applicationVerifier ) {}; /** * Updates the user's email address. * * An email will be sent to the original email address (if it was set) that * allows to revoke the email address change, in order to protect them from * account hijacking. * * <b>Important:</b> this is a security sensitive operation that requires the * user to have recently signed in. If this requirement isn't met, ask the user * to authenticate again and then call * {@link firebase.User#reauthenticateWithCredential}. * * <h4>Error Codes</h4> * <dl> * <dt>auth/invalid-email</dt> * <dd>Thrown if the email used is invalid.</dd> * <dt>auth/email-already-in-use</dt> * <dd>Thrown if the email is already used by another user.</dd> * <dt>auth/requires-recent-login</dt> * <dd>Thrown if the user's last sign-in time does not meet the security * threshold. Use {@link firebase.User#reauthenticateWithCredential} to * resolve. This does not apply if the user is anonymous.</dd> * </dl> * * @param {string} newEmail The new email address. * @return {!firebase.Promise<void>} */ firebase.User.prototype.updateEmail = function(newEmail) {}; /** * Updates the user's password. * * <b>Important:</b> this is a security sensitive operation that requires the * user to have recently signed in. If this requirement isn't met, ask the user * to authenticate again and then call * {@link firebase.User#reauthenticateWithCredential}. * * <h4>Error Codes</h4> * <dl> * <dt>auth/weak-password</dt> * <dd>Thrown if the password is not strong enough.</dd> * <dt>auth/requires-recent-login</dt> * <dd>Thrown if the user's last sign-in time does not meet the security * threshold. Use {@link firebase.User#reauthenticateWithCredential} to * resolve. This does not apply if the user is anonymous.</dd> * </dl> * * @param {string} newPassword * @return {!firebase.Promise<void>} */ firebase.User.prototype.updatePassword = function(newPassword) {}; /** * Updates the user's phone number. * * <h4>Error Codes</h4> * <dl> * <dt>auth/invalid-verification-code</dt> * <dd>Thrown if the verification code of the credential is not valid.</dd> * <dt>auth/invalid-verification-id</dt> * <dd>Thrown if the verification ID of the credential is not valid.</dd> * </dl> * * @param {!firebase.auth.AuthCredential} phoneCredential * @return {!firebase.Promise<void>} */ firebase.User.prototype.updatePhoneNumber = function(phoneCredential) {}; /** * Updates a user's profile data. * * @example * // Updates the user attributes: * user.updateProfile({ * displayName: "Jane Q. User", * photoURL: "https://example.com/jane-q-user/profile.jpg" * }).then(function() { * // Profile updated successfully! * // "Jane Q. User" * var displayName = user.displayName; * // "https://example.com/jane-q-user/profile.jpg" * var photoURL = user.photoURL; * }, function(error) { * // An error happened. * }); * * // Passing a null value will delete the current attribute's value, but not * // passing a property won't change the current attribute's value: * // Let's say we're using the same user than before, after the update. * user.updateProfile({photoURL: null}).then(function() { * // Profile updated successfully! * // "Jane Q. User", hasn't changed. * var displayName = user.displayName; * // Now, this is null. * var photoURL = user.photoURL; * }, function(error) { * // An error happened. * }); * * @param {!{displayName: ?string, photoURL: ?string}} profile The profile's * displayName and photoURL to update. * @return {!firebase.Promise<void>} */ firebase.User.prototype.updateProfile = function(profile) {}; /** * Deletes and signs out the user. * * <b>Important:</b> this is a security sensitive operation that requires the * user to have recently signed in. If this requirement isn't met, ask the user * to authenticate again and then call * {@link firebase.User#reauthenticateWithCredential}. * * <h4>Error Codes</h4> * <dl> * <dt>auth/requires-recent-login</dt> * <dd>Thrown if the user's last sign-in time does not meet the security * threshold. Use {@link firebase.User#reauthenticateWithCredential} to * resolve. This does not apply if the user is anonymous.</dd> * </dl> * * @return {!firebase.Promise<void>} */ firebase.User.prototype.delete = function() {}; /** * Returns a JSON-serializable representation of this object. * * @return {!Object} A JSON-serializable representation of this object. */ firebase.User.prototype.toJSON = function() {}; /** * The Firebase Auth service interface. * * Do not call this constructor directly. Instead, use * {@link firebase.auth `firebase.auth()`}. * * See * {@link https://firebase.google.com/docs/auth/ Firebase Authentication} * for a full guide on how to use the Firebase Auth service. * * @interface */ firebase.auth.Auth = function() {}; /** * Checks a password reset code sent to the user by email or other out-of-band * mechanism. * * Returns the user's email address if valid. * * <h4>Error Codes</h4> * <dl> * <dt>auth/expired-action-code</dt> * <dd>Thrown if the password reset code has expired.</dd> * <dt>auth/invalid-action-code</dt> * <dd>Thrown if the password reset code is invalid. This can happen if the code * is malformed or has already been used.</dd> * <dt>auth/user-disabled</dt> * <dd>Thrown if the user corresponding to the given password reset code has * been disabled.</dd> * <dt>auth/user-not-found</dt> * <dd>Thrown if there is no user corresponding to the password reset code. This * may have happened if the user was deleted between when the code was * issued and when this method was called.</dd> * </dl> * * @param {string} code A verification code sent to the user. * @return {!firebase.Promise<string>} */ firebase.auth.Auth.prototype.verifyPasswordResetCode = function(code) {}; /** * A response from {@link firebase.auth.Auth#checkActionCode}. * * @interface */ firebase.auth.ActionCodeInfo = function() {}; /** * The data associated with the action code. * * For the PASSWORD_RESET, VERIFY_EMAIL, and RECOVER_EMAIL actions, this object * contains an `email` field with the address the email was sent to. * * For the RECOVER_EMAIL action, which allows a user to undo an email address * change, this object also contains a `fromEmail` field with the user account's * new email address. After the action completes, the user's email address will * revert to the value in the `email` field from the value in `fromEmail` field. * * @typedef {{ * email: (?string|undefined), * fromEmail: (?string|undefined) * }} */ firebase.auth.ActionCodeInfo.prototype.data; /** * The type of operation that generated the action code. This could be: * <ul> * <li>`PASSWORD_RESET`: password reset code generated via * {@link firebase.auth.Auth#sendPasswordResetEmail}.</li> * <li>`VERIFY_EMAIL`: email verification code generated via * {@link firebase.User#sendEmailVerification}.</li> * <li>`RECOVER_EMAIL`: email change revocation code generated via * {@link firebase.User#updateEmail}.</li> * </ul> * * @type {string} */ firebase.auth.ActionCodeInfo.prototype.operation; /** * This is the interface that defines the required continue/state URL with * optional Android and iOS bundle identifiers. * The action code setting fields are: * <ul> * <li><p>url: Sets the link continue/state URL, which has different meanings * in different contexts:</p> * <ul> * <li>When the link is handled in the web action widgets, this is the deep * link in the continueUrl query parameter.</li> * <li>When the link is handled in the app directly, this is the continueUrl * query parameter in the deep link of the Dynamic Link.</li> * </ul> * </li> * <li>iOS: Sets the iOS bundle ID. This will try to open the link in an iOS app * if it is installed.</li> * <li>android: Sets the Android package name. This will try to open the link in * an android app if it is installed. If installApp is passed, it specifies * whether to install the Android app if the device supports it and the app * is not already installed. If this field is provided without a * packageName, an error is thrown explaining that the packageName must be * provided in conjunction with this field. * If minimumVersion is specified, and an older version of the app is * installed, the user is taken to the Play Store to upgrade the app.</li> * <li>handleCodeInApp: The default is false. When set to true, the action code * link will be be sent as a Universal Link or Android App Link and will be * opened by the app if installed. In the false case, the code will be sent * to the web widget first and then on continue will redirect to the app if * installed.</li> * </ul> * * @typedef {{ * url: string, * iOS: ({bundleId: string}|undefined), * android: ({packageName: string, installApp: (boolean|undefined), * minimumVersion: (string|undefined)}|undefined), * handleCodeInApp: (boolean|undefined) * }} */ firebase.auth.ActionCodeSettings; /** * Checks a verification code sent to the user by email or other out-of-band * mechanism. * * Returns metadata about the code. * * <h4>Error Codes</h4> * <dl> * <dt>auth/expired-action-code</dt> * <dd>Thrown if the action code has expired.</dd> * <dt>auth/invalid-action-code</dt> * <dd>Thrown if the action code is invalid. This can happen if the code is * malformed or has already been used.</dd> * <dt>auth/user-disabled</dt> * <dd>Thrown if the user corresponding to the given action code has been * disabled.</dd> * <dt>auth/user-not-found</dt> * <dd>Thrown if there is no user corresponding to the action code. This may * have happened if the user was deleted between when the action code was * issued and when this method was called.</dd> * </dl> * * @param {string} code A verification code sent to the user. * @return {!firebase.Promise<!firebase.auth.ActionCodeInfo>} */ firebase.auth.Auth.prototype.checkActionCode = function(code) {}; /** * Applies a verification code sent to the user by email or other out-of-band * mechanism. * * <h4>Error Codes</h4> * <dl> * <dt>auth/expired-action-code</dt> * <dd>Thrown if the action code has expired.</dd> * <dt>auth/invalid-action-code</dt> * <dd>Thrown if the action code is invalid. This can happen if the code is * malformed or has already been used.</dd> * <dt>auth/user-disabled</dt> * <dd>Thrown if the user corresponding to the given action code has been * disabled.</dd> * <dt>auth/user-not-found</dt> * <dd>Thrown if there is no user corresponding to the action code. This may * have happened if the user was deleted between when the action code was * issued and when this method was called.</dd> * </dl> * * @param {string} code A verification code sent to the user. * @return {!firebase.Promise<void>} */ firebase.auth.Auth.prototype.applyActionCode = function(code) {}; /** * The {@link firebase.app.App app} associated with the `Auth` service * instance. * * @example * var app = auth.app; * * @type {!firebase.app.App} */ firebase.auth.Auth.prototype.app; /** * The currently signed-in user (or null). * * @type {firebase.User|null} */ firebase.auth.Auth.prototype.currentUser; /** * @enum {string} * An enumeration of the possible persistence mechanism types. */ firebase.auth.Auth.Persistence = { /** * Indicates that the state will be persisted even when the browser window is * closed or the activity is destroyed in react-native. */ LOCAL: 'local', /** * Indicates that the state will only be stored in memory and will be cleared * when the window or activity is refreshed. */ NONE: 'none', /** * Indicates that the state will only persist in current session/tab, relevant * to web only, and will be cleared when the tab is closed. */ SESSION: 'session' }; /** * Changes the current type of persistence on the current Auth instance for the * currently saved Auth session and applies this type of persistence for * future sign-in requests, including sign-in with redirect requests. This will * return a promise that will resolve once the state finishes copying from one * type of storage to the other. * Calling a sign-in method after changing persistence will wait for that * persistence change to complete before applying it on the new Auth state. * * This makes it easy for a user signing in to specify whether their session * should be remembered or not. It also makes it easier to never persist the * Auth state for applications that are shared by other users or have sensitive * data. * * The default for web browser apps and React Native apps is 'local' (provided * the browser supports this mechanism) whereas it is 'none' for Node.js backend * apps. * * <h4>Error Codes (thrown synchronously)</h4> * <dl> * <dt>auth/invalid-persistence-type</dt> * <dd>Thrown if the specified persistence type is invalid.</dd> * <dt>auth/unsupported-persistence-type</dt> * <dd>Thrown if the current environment does not support the specified * persistence type.</dd> * </dl> * * @example * firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION) * .then(function() { * // Existing and future Auth states are now persisted in the current * // session only. Closing the window would clear any existing state even if * // a user forgets to sign out. * }); * * @param {!firebase.auth.Auth.Persistence} persistence The auth state * persistence mechanism. * @return {!firebase.Promise<void>} */ firebase.auth.Auth.prototype.setPersistence = function(persistence) {}; /** * The current Auth instance's language code. This is a readable/writable * property. When set to null, the default Firebase Console language setting * is applied. The language code will propagate to email action templates * (password reset, email verification and email change revocation), SMS * templates for phone authentication, reCAPTCHA verifier and OAuth * popup/redirect operations provided the specified providers support * localization with the language code specified. * * @type {string|null} */ firebase.auth.Auth.prototype.languageCode; /** * Sets the current language to the default device/browser preference. */ firebase.auth.Auth.prototype.useDeviceLanguage = function() {}; /** * Creates a new user account associated with the specified email address and * password and returns any additional user info data or credentials. * * This method will be renamed to `createUserWithEmailAndPassword` replacing * the existing method with the same name in the next major version change. * * On successful creation of the user account, this user will also be * signed in to your application. * * User account creation can fail if the account already exists or the password * is invalid. * * Note: The email address acts as a unique identifier for the user and * enables an email-based password reset. This function will create * a new user account and set the initial user password. * * <h4>Error Codes</h4> * <dl> * <dt>auth/email-already-in-use</dt> * <dd>Thrown if there already exists an account with the given email * address.</dd> * <dt>auth/invalid-email</dt> * <dd>Thrown if the email address is not valid.</dd> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if email/password accounts are not enabled. Enable email/password * accounts in the Firebase Console, under the Auth tab.</dd> * <dt>auth/weak-password</dt> * <dd>Thrown if the password is not strong enough.</dd> * </dl> * * @example * firebase.auth().createUserAndRetrieveDataWithEmailAndPassword(email, password) * .catch(function(error) { * // Handle Errors here. * var errorCode = error.code; * var errorMessage = error.message; * if (errorCode == 'auth/weak-password') { * alert('The password is too weak.'); * } else { * alert(errorMessage); * } * console.log(error); * }); * * @param {string} email The user's email address. * @param {string} password The user's chosen password. * @return {!firebase.Promise<!firebase.auth.UserCredential>} */ firebase.auth.Auth.prototype.createUserAndRetrieveDataWithEmailAndPassword = function( email, password ) {}; /** * Creates a new user account associated with the specified email address and * password. * * This method will be deprecated and will be updated to resolve with a * `firebase.auth.UserCredential` as is returned in * {@link firebase.auth.Auth#createUserAndRetrieveDataWithEmailAndPassword}. * * On successful creation of the user account, this user will also be * signed in to your application. * * User account creation can fail if the account already exists or the password * is invalid. * * Note: The email address acts as a unique identifier for the user and * enables an email-based password reset. This function will create * a new user account and set the initial user password. * * <h4>Error Codes</h4> * <dl> * <dt>auth/email-already-in-use</dt> * <dd>Thrown if there already exists an account with the given email * address.</dd> * <dt>auth/invalid-email</dt> * <dd>Thrown if the email address is not valid.</dd> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if email/password accounts are not enabled. Enable email/password * accounts in the Firebase Console, under the Auth tab.</dd> * <dt>auth/weak-password</dt> * <dd>Thrown if the password is not strong enough.</dd> * </dl> * * @example * firebase.auth().createUserWithEmailAndPassword(email, password) * .catch(function(error) { * // Handle Errors here. * var errorCode = error.code; * var errorMessage = error.message; * if (errorCode == 'auth/weak-password') { * alert('The password is too weak.'); * } else { * alert(errorMessage); * } * console.log(error); * }); * * @param {string} email The user's email address. * @param {string} password The user's chosen password. * @return {!firebase.Promise<!firebase.User>} */ firebase.auth.Auth.prototype.createUserWithEmailAndPassword = function( email, password ) {}; /** * Gets the list of provider IDs that can be used to sign in for the given email * address. Useful for an "identifier-first" sign-in flow. * * <h4>Error Codes</h4> * <dl> * <dt>auth/invalid-email</dt> * <dd>Thrown if the email address is not valid.</dd> * </dl> * * @param {string} email An email address. * @return {!firebase.Promise<!Array<string>>} */ firebase.auth.Auth.prototype.fetchProvidersForEmail = function(email) {}; /** * Adds an observer for changes to the user's sign-in state. * * Prior to 4.0.0, this triggered the observer when users were signed in, * signed out, or when the user's ID token changed in situations such as token * expiry or password change. After 4.0.0, the observer is only triggered * on sign-in or sign-out. * * To keep the old behavior, see {@link firebase.auth.Auth#onIdTokenChanged}. * * @example * firebase.auth().onAuthStateChanged(function(user) { * if (user) { * // User is signed in. * } * }); * * @param {!firebase.Observer<firebase.User, firebase.auth.Error>|function(?firebase.User)} * nextOrObserver An observer object or a function triggered on change. * @param {function(!firebase.auth.Error)=} error Optional A function * triggered on auth error. * @param {firebase.CompleteFn=} completed Optional A function triggered when the * observer is removed. * @return {!firebase.Unsubscribe} The unsubscribe function for the observer. */ firebase.auth.Auth.prototype.onAuthStateChanged = function( nextOrObserver, error, completed ) {}; /** * Adds an observer for changes to the signed-in user's ID token, which includes * sign-in, sign-out, and token refresh events. This method has the same * behavior as {@link firebase.auth.Auth#onAuthStateChanged} had prior to 4.0.0. * * @example * firebase.auth().onIdTokenChanged(function(user) { * if (user) { * // User is signed in or token was refreshed. * } * }); * * @param {!firebase.Observer<firebase.User, firebase.auth.Error>|function(?firebase.User)} * nextOrObserver An observer object or a function triggered on change. * @param {function(!firebase.auth.Error)=} error Optional A function * triggered on auth error. * @param {firebase.CompleteFn=} completed Optional A function triggered when the * observer is removed. * @return {!firebase.Unsubscribe} The unsubscribe function for the observer. */ firebase.auth.Auth.prototype.onIdTokenChanged = function( nextOrObserver, error, completed ) {}; /** * Sends a password reset email to the given email address. * * To complete the password reset, call * {@link firebase.auth.Auth#confirmPasswordReset} with the code supplied in the * email sent to the user, along with the new password specified by the user. * * <h4>Error Codes</h4> * <dl> * <dt>auth/invalid-email</dt> * <dd>Thrown if the email address is not valid.</dd> * <dt>auth/missing-android-pkg-name</dt> * <dd>An Android package name must be provided if the Android app is required * to be installed.</dd> * <dt>auth/missing-continue-uri</dt> * <dd>A continue URL must be provided in the request.</dd> * <dt>auth/missing-ios-bundle-id</dt> * <dd>An iOS Bundle ID must be provided if an App Store ID is provided.</dd> * <dt>auth/invalid-continue-uri</dt> * <dd>The continue URL provided in the request is invalid.</dd> * <dt>auth/unauthorized-continue-uri</dt> * <dd>The domain of the continue URL is not whitelisted. Whitelist * the domain in the Firebase console.</dd> * <dt>auth/user-not-found</dt> * <dd>Thrown if there is no user corresponding to the email address.</dd> * </dl> * * @example * var actionCodeSettings = { * url: 'https://www.example.com/?email=user@example.com', * iOS: { * bundleId: 'com.example.ios' * }, * android: { * packageName: 'com.example.android', * installApp: true, * minimumVersion: '12' * }, * handleCodeInApp: true * }; * firebase.auth().sendPasswordResetEmail( * 'user@example.com', actionCodeSettings) * .then(function() { * // Password reset email sent. * }) * .catch(function(error) { * // Error occurred. Inspect error.code. * }); * * @param {string} email The email address with the password to be reset. * @param {?firebase.auth.ActionCodeSettings=} actionCodeSettings The action * code settings. If specified, the state/continue URL will be set as the * "continueUrl" parameter in the password reset link. The default password * reset landing page will use this to display a link to go back to the app * if it is installed. * If the actionCodeSettings is not specified, no URL is appended to the * action URL. * The state URL provided must belong to a domain that is whitelisted by the * developer in the console. Otherwise an error will be thrown. * Mobile app redirects will only be applicable if the developer configures * and accepts the Firebase Dynamic Links terms of condition. * The Android package name and iOS bundle ID will be respected only if they * are configured in the same Firebase Auth project used. * @return {!firebase.Promise<void>} */ firebase.auth.Auth.prototype.sendPasswordResetEmail = function( email, actionCodeSettings ) {}; /** * Completes the password reset process, given a confirmation code and new * password. * * <h4>Error Codes</h4> * <dl> * <dt>auth/expired-action-code</dt> * <dd>Thrown if the password reset code has expired.</dd> * <dt>auth/invalid-action-code</dt> * <dd>Thrown if the password reset code is invalid. This can happen if the * code is malformed or has already been used.</dd> * <dt>auth/user-disabled</dt> * <dd>Thrown if the user corresponding to the given password reset code has * been disabled.</dd> * <dt>auth/user-not-found</dt> * <dd>Thrown if there is no user corresponding to the password reset code. This * may have happened if the user was deleted between when the code was * issued and when this method was called.</dd> * <dt>auth/weak-password</dt> * <dd>Thrown if the new password is not strong enough.</dd> * </dl> * * @param {string} code The confirmation code send via email to the user. * @param {string} newPassword The new password. * @return {!firebase.Promise<void>} */ firebase.auth.Auth.prototype.confirmPasswordReset = function( code, newPassword ) {}; /** * Asynchronously signs in with the given credentials. * * <h4>Error Codes</h4> * <dl> * <dt>auth/account-exists-with-different-credential</dt> * <dd>Thrown if there already exists an account with the email address * asserted by the credential. Resolve this by calling * {@link firebase.auth.Auth#fetchProvidersForEmail} and then asking the * user to sign in using one of the returned providers. Once the user is * signed in, the original credential can be linked to the user with * {@link firebase.User#linkWithCredential}.</dd> * <dt>auth/invalid-credential</dt> * <dd>Thrown if the credential is malformed or has expired.</dd> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if the type of account corresponding to the credential * is not enabled. Enable the account type in the Firebase Console, under * the Auth tab.</dd> * <dt>auth/user-disabled</dt> * <dd>Thrown if the user corresponding to the given credential has been * disabled.</dd> * <dt>auth/user-not-found</dt> * <dd>Thrown if signing in with a credential from * {@link firebase.auth.EmailAuthProvider#credential} and there is no user * corresponding to the given email. </dd> * <dt>auth/wrong-password</dt> * <dd>Thrown if signing in with a credential from * {@link firebase.auth.EmailAuthProvider#credential} and the password is * invalid for the given email, or if the account corresponding to the email * does not have a password set.</dd> * <dt>auth/invalid-verification-code</dt> * <dd>Thrown if the credential is a * {@link firebase.auth.PhoneAuthProvider#credential} and the verification * code of the credential is not valid.</dd> * <dt>auth/invalid-verification-id</dt> * <dd>Thrown if the credential is a * {@link firebase.auth.PhoneAuthProvider#credential} and the verification * ID of the credential is not valid.</dd> * </dl> * * @example * firebase.auth().signInWithCredential(credential).catch(function(error) { * // Handle Errors here. * var errorCode = error.code; * var errorMessage = error.message; * // The email of the user's account used. * var email = error.email; * // The firebase.auth.AuthCredential type that was used. * var credential = error.credential; * if (errorCode === 'auth/account-exists-with-different-credential') { * alert('Email already associated with another account.'); * // Handle account linking here, if using. * } else { * console.error(error); * } * }); * * @param {!firebase.auth.AuthCredential} credential The auth credential. * @return {!firebase.Promise<!firebase.User>} */ firebase.auth.Auth.prototype.signInWithCredential = function(credential) {}; /** * Asynchronously signs in with the given credentials, and returns any available * additional user information, such as user name. * * <h4>Error Codes</h4> * <dl> * <dt>auth/account-exists-with-different-credential</dt> * <dd>Thrown if there already exists an account with the email address * asserted by the credential. Resolve this by calling * {@link firebase.auth.Auth#fetchProvidersForEmail} and then asking the * user to sign in using one of the returned providers. Once the user is * signed in, the original credential can be linked to the user with * {@link firebase.User#linkWithCredential}.</dd> * <dt>auth/invalid-credential</dt> * <dd>Thrown if the credential is malformed or has expired.</dd> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if the type of account corresponding to the credential * is not enabled. Enable the account type in the Firebase Console, under * the Auth tab.</dd> * <dt>auth/user-disabled</dt> * <dd>Thrown if the user corresponding to the given credential has been * disabled.</dd> * <dt>auth/user-not-found</dt> * <dd>Thrown if signing in with a credential from * {@link firebase.auth.EmailAuthProvider#credential} and there is no user * corresponding to the given email. </dd> * <dt>auth/wrong-password</dt> * <dd>Thrown if signing in with a credential from * {@link firebase.auth.EmailAuthProvider#credential} and the password is * invalid for the given email, or if the account corresponding to the email * does not have a password set.</dd> * <dt>auth/invalid-verification-code</dt> * <dd>Thrown if the credential is a * {@link firebase.auth.PhoneAuthProvider#credential} and the verification * code of the credential is not valid.</dd> * <dt>auth/invalid-verification-id</dt> * <dd>Thrown if the credential is a * {@link firebase.auth.PhoneAuthProvider#credential} and the verification * ID of the credential is not valid.</dd> * </dl> * * @example * firebase.auth().signInAndRetrieveDataWithCredential(credential) * .then(function(userCredential) { * console.log(userCredential.additionalUserInfo.username); * }); * * @param {!firebase.auth.AuthCredential} credential The auth credential. * @return {!firebase.Promise<!firebase.auth.UserCredential>} */ firebase.auth.Auth.prototype.signInAndRetrieveDataWithCredential = function( credential ) {}; /** * Signs in a user asynchronously using a custom token and returns any * additional user info data or credentials. * * This method will be renamed to `signInWithCustomToken` replacing * the existing method with the same name in the next major version change. * * Custom tokens are used to integrate Firebase Auth with existing auth systems, * and must be generated by the auth backend. * * Fails with an error if the token is invalid, expired, or not accepted by the * Firebase Auth service. * * <h4>Error Codes</h4> * <dl> * <dt>auth/custom-token-mismatch</dt> * <dd>Thrown if the custom token is for a different Firebase App.</dd> * <dt>auth/invalid-custom-token</dt> * <dd>Thrown if the custom token format is incorrect.</dd> * </dl> * * @example * firebase.auth().signInAndRetrieveDataWithCustomToken(token) * .catch(function(error) { * // Handle Errors here. * var errorCode = error.code; * var errorMessage = error.message; * if (errorCode === 'auth/invalid-custom-token') { * alert('The token you provided is not valid.'); * } else { * console.error(error); * } * }); * * @param {string} token The custom token to sign in with. * @return {!firebase.Promise<!firebase.auth.UserCredential>} */ firebase.auth.Auth.prototype.signInAndRetrieveDataWithCustomToken = function( token ) {}; /** * Asynchronously signs in using a custom token. * * This method will be deprecated and will be updated to resolve with a * `firebase.auth.UserCredential` as is returned in * {@link firebase.auth.Auth#signInAndRetrieveDataWithCustomToken}. * * Custom tokens are used to integrate Firebase Auth with existing auth systems, * and must be generated by the auth backend. * * Fails with an error if the token is invalid, expired, or not accepted by the * Firebase Auth service. * * <h4>Error Codes</h4> * <dl> * <dt>auth/custom-token-mismatch</dt> * <dd>Thrown if the custom token is for a different Firebase App.</dd> * <dt>auth/invalid-custom-token</dt> * <dd>Thrown if the custom token format is incorrect.</dd> * </dl> * * @example * firebase.auth().signInWithCustomToken(token).catch(function(error) { * // Handle Errors here. * var errorCode = error.code; * var errorMessage = error.message; * if (errorCode === 'auth/invalid-custom-token') { * alert('The token you provided is not valid.'); * } else { * console.error(error); * } * }); * * @param {string} token The custom token to sign in with. * @return {!firebase.Promise<!firebase.User>} */ firebase.auth.Auth.prototype.signInWithCustomToken = function(token) {}; /** * Asynchronously signs in using an email and password and returns any additional * user info data or credentials. * * This method will be renamed to `signInWithEmailAndPassword` replacing * the existing method with the same name in the next major version change. * * Fails with an error if the email address and password do not match. * * Note: The user's password is NOT the password used to access the user's email * account. The email address serves as a unique identifier for the user, and * the password is used to access the user's account in your Firebase project. * * See also: * {@link firebase.auth.Auth#createUserAndRetrieveDataWithEmailAndPassword}. * * <h4>Error Codes</h4> * <dl> * <dt>auth/invalid-email</dt> * <dd>Thrown if the email address is not valid.</dd> * <dt>auth/user-disabled</dt> * <dd>Thrown if the user corresponding to the given email has been * disabled.</dd> * <dt>auth/user-not-found</dt> * <dd>Thrown if there is no user corresponding to the given email.</dd> * <dt>auth/wrong-password</dt> * <dd>Thrown if the password is invalid for the given email, or the account * corresponding to the email does not have a password set.</dd> * </dl> * * @example * firebase.auth().signInAndRetrieveDataWithEmailAndPassword(email, password) * .catch(function(error) { * // Handle Errors here. * var errorCode = error.code; * var errorMessage = error.message; * if (errorCode === 'auth/wrong-password') { * alert('Wrong password.'); * } else { * alert(errorMessage); * } * console.log(error); * }); * * @param {string} email The users email address. * @param {string} password The users password. * @return {!firebase.Promise<!firebase.auth.UserCredential>} */ firebase.auth.Auth.prototype.signInAndRetrieveDataWithEmailAndPassword = function( email, password ) {}; /** * Asynchronously signs in using an email and password. * * This method will be deprecated and will be updated to resolve with a * `firebase.auth.UserCredential` as is returned in * {@link firebase.auth.Auth#signInAndRetrieveDataWithEmailAndPassword}. * * Fails with an error if the email address and password do not match. * * Note: The user's password is NOT the password used to access the user's email * account. The email address serves as a unique identifier for the user, and * the password is used to access the user's account in your Firebase project. * * See also: {@link firebase.auth.Auth#createUserWithEmailAndPassword}. * * <h4>Error Codes</h4> * <dl> * <dt>auth/invalid-email</dt> * <dd>Thrown if the email address is not valid.</dd> * <dt>auth/user-disabled</dt> * <dd>Thrown if the user corresponding to the given email has been * disabled.</dd> * <dt>auth/user-not-found</dt> * <dd>Thrown if there is no user corresponding to the given email.</dd> * <dt>auth/wrong-password</dt> * <dd>Thrown if the password is invalid for the given email, or the account * corresponding to the email does not have a password set.</dd> * </dl> * * @example * firebase.auth().signInWithEmailAndPassword(email, password) * .catch(function(error) { * // Handle Errors here. * var errorCode = error.code; * var errorMessage = error.message; * if (errorCode === 'auth/wrong-password') { * alert('Wrong password.'); * } else { * alert(errorMessage); * } * console.log(error); * }); * * @param {string} email The users email address. * @param {string} password The users password. * @return {!firebase.Promise<!firebase.User>} */ firebase.auth.Auth.prototype.signInWithEmailAndPassword = function( email, password ) {}; /** * Asynchronously signs in using a phone number. This method sends a code via * SMS to the given phone number, and returns a * {@link firebase.auth.ConfirmationResult}. After the user provides the code * sent to their phone, call {@link firebase.auth.ConfirmationResult#confirm} * with the code to sign the user in. * * For abuse prevention, this method also requires a * {@link firebase.auth.ApplicationVerifier}. The Firebase Auth SDK includes * a reCAPTCHA-based implementation, {@link firebase.auth.RecaptchaVerifier}. * * <h4>Error Codes</h4> * <dl> * <dt>auth/captcha-check-failed</dt> * <dd>Thrown if the reCAPTCHA response token was invalid, expired, or if * this method was called from a non-whitelisted domain.</dd> * <dt>auth/invalid-phone-number</dt> * <dd>Thrown if the phone number has an invalid format.</dd> * <dt>auth/missing-phone-number</dt> * <dd>Thrown if the phone number is missing.</dd> * <dt>auth/quota-exceeded</dt> * <dd>Thrown if the SMS quota for the Firebase project has been exceeded.</dd> * <dt>auth/user-disabled</dt> * <dd>Thrown if the user corresponding to the given phone number has been * disabled.</dd> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if you have not enabled the provider in the Firebase Console. Go * to the Firebase Console for your project, in the Auth section and the * <strong>Sign in Method</strong> tab and configure the provider.</dd> * </dl> * * @example * // 'recaptcha-container' is the ID of an element in the DOM. * var applicationVerifier = new firebase.auth.RecaptchaVerifier( * 'recaptcha-container'); * firebase.auth().signInWithPhoneNumber(phoneNumber, applicationVerifier) * .then(function(confirmationResult) { * var verificationCode = window.prompt('Please enter the verification ' + * 'code that was sent to your mobile device.'); * return confirmationResult.confirm(verificationCode); * }) * .catch(function(error) { * // Handle Errors here. * }); * * @param {string} phoneNumber The user's phone number in E.164 format (e.g. * +16505550101). * @param {!firebase.auth.ApplicationVerifier} applicationVerifier * @return {!firebase.Promise<!firebase.auth.ConfirmationResult>} */ firebase.auth.Auth.prototype.signInWithPhoneNumber = function( phoneNumber, applicationVerifier ) {}; /** * A result from a phone number sign-in, link, or reauthenticate call. * @interface */ firebase.auth.ConfirmationResult = function() {}; /** * The phone number authentication operation's verification ID. This can be used * along with the verification code to initialize a phone auth credential. * * @type {string} */ firebase.auth.ConfirmationResult.prototype.verificationId; /** * Finishes a phone number sign-in, link, or reauthentication, given the code * that was sent to the user's mobile device. * * <h4>Error Codes</h4> * <dl> * <dt>auth/invalid-verification-code</dt> * <dd>Thrown if the verification code is not valid.</dd> * <dt>auth/missing-verification-code</dt> * <dd>Thrown if the verification code is missing.</dd> * </dl> * @param {string} verificationCode * @return {!firebase.Promise<!firebase.auth.UserCredential>} */ firebase.auth.ConfirmationResult.prototype.confirm = function( verificationCode ) {}; /** * Signs in a user anonymously and returns any additional user info data or * credentials. * * This method will be renamed to `signInAnonymously` replacing the existing * method with the same name in the next major version change. * * If there is already an anonymous user signed in, that user with * additional date will be returned; otherwise, a new anonymous user * identity will be created and returned. * * <h4>Error Codes</h4> * <dl> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if anonymous accounts are not enabled. Enable anonymous accounts * in the Firebase Console, under the Auth tab.</dd> * </dl> * * @example * firebase.auth().signInAnonymouslyAndRetrieveData().catch(function(error) { * // Handle Errors here. * var errorCode = error.code; * var errorMessage = error.message; * * if (errorCode === 'auth/operation-not-allowed') { * alert('You must enable Anonymous auth in the Firebase Console.'); * } else { * console.error(error); * } * }); * * @return {!firebase.Promise<!firebase.auth.UserCredential>} */ firebase.auth.Auth.prototype.signInAnonymouslyAndRetrieveData = function() {}; /** * Asynchronously signs in as an anonymous user. * * This method will be deprecated and will be updated to resolve with a * `firebase.auth.UserCredential` as is returned in * {@link firebase.auth.Auth#signInAnonymouslyAndRetrieveData}. * * If there is already an anonymous user signed in, that user will be returned; * otherwise, a new anonymous user identity will be created and returned. * * <h4>Error Codes</h4> * <dl> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if anonymous accounts are not enabled. Enable anonymous accounts * in the Firebase Console, under the Auth tab.</dd> * </dl> * * @example * firebase.auth().signInAnonymously().catch(function(error) { * // Handle Errors here. * var errorCode = error.code; * var errorMessage = error.message; * * if (errorCode === 'auth/operation-not-allowed') { * alert('You must enable Anonymous auth in the Firebase Console.'); * } else { * console.error(error); * } * }); * * @return {!firebase.Promise<!firebase.User>} */ firebase.auth.Auth.prototype.signInAnonymously = function() {}; /** * A structure containing a User, an AuthCredential, the operationType, and * any additional user information that was returned from the identity provider. * operationType could be 'signIn' for a sign-in operation, 'link' for a linking * operation and 'reauthenticate' for a reauthentication operation. * * @typedef {{ * user: ?firebase.User, * credential: ?firebase.auth.AuthCredential, * operationType: (?string|undefined), * additionalUserInfo: (?firebase.auth.AdditionalUserInfo|undefined) * }} */ firebase.auth.UserCredential; /** * A structure containing additional user information from a federated identity * provider. * @typedef {{ * providerId: string, * profile: ?Object, * username: (?string|undefined), * isNewUser: boolean * }} */ firebase.auth.AdditionalUserInfo; /** * Signs out the current user. * * @return {!firebase.Promise<void>} */ firebase.auth.Auth.prototype.signOut = function() {}; /** * An authentication error. * For method-specific error codes, refer to the specific methods in the * documentation. For common error codes, check the reference below. Use {@link * firebase.auth.Error#code} to get the specific error code. For a detailed * message, use {@link firebase.auth.Error#message}. * Errors with the code <strong>auth/account-exists-with-different-credential * </strong> will have the additional fields <strong>email</strong> and <strong> * credential</strong> which are needed to provide a way to resolve these * specific errors. Refer to {@link firebase.auth.Auth#signInWithPopup} for more * information. * * <h4>Common Error Codes</h4> * <dl> * <dt>auth/app-deleted</dt> * <dd>Thrown if the instance of FirebaseApp has been deleted.</dd> * <dt>auth/app-not-authorized</dt> * <dd>Thrown if the app identified by the domain where it's hosted, is not * authorized to use Firebase Authentication with the provided API key. * Review your key configuration in the Google API console.</dd> * <dt>auth/argument-error</dt> * <dd>Thrown if a method is called with incorrect arguments.</dd> * <dt>auth/invalid-api-key</dt> * <dd>Thrown if the provided API key is invalid. Please check that you have * copied it correctly from the Firebase Console.</dd> * <dt>auth/invalid-user-token</dt> * <dd>Thrown if the user's credential is no longer valid. The user must sign in * again.</dd> * <dt>auth/network-request-failed</dt> * <dd>Thrown if a network error (such as timeout, interrupted connection or * unreachable host) has occurred.</dd> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if you have not enabled the provider in the Firebase Console. Go * to the Firebase Console for your project, in the Auth section and the * <strong>Sign in Method</strong> tab and configure the provider.</dd> * <dt>auth/requires-recent-login</dt> * <dd>Thrown if the user's last sign-in time does not meet the security * threshold. Use {@link firebase.User#reauthenticateWithCredential} to * resolve. This does not apply if the user is anonymous.</dd> * <dt>auth/too-many-requests</dt> * <dd>Thrown if requests are blocked from a device due to unusual activity. * Trying again after some delay would unblock.</dd> * <dt>auth/unauthorized-domain</dt> * <dd>Thrown if the app domain is not authorized for OAuth operations for your * Firebase project. Edit the list of authorized domains from the Firebase * console.</dd> * <dt>auth/user-disabled</dt> * <dd>Thrown if the user account has been disabled by an administrator. * Accounts can be enabled or disabled in the Firebase Console, the Auth * section and Users subsection.</dd> * <dt>auth/user-token-expired</dt> * <dd>Thrown if the user's credential has expired. This could also be thrown if * a user has been deleted. Prompting the user to sign in again should * resolve this for either case.</dd> * <dt>auth/web-storage-unsupported</dt> * <dd>Thrown if the browser does not support web storage or if the user * disables them.</dd> * </dl> * * @interface */ firebase.auth.Error = function() {}; /** * Unique error code. * * @type {string} */ firebase.auth.Error.prototype.code; /** * Complete error message. * * @type {string} */ firebase.auth.Error.prototype.message; // // List of Auth Providers. // /** * Interface that represents an auth provider. * * @interface */ firebase.auth.AuthProvider = function() {}; /** @type {string} */ firebase.auth.AuthProvider.prototype.providerId; /** * Generic OAuth provider. * * @example * // Using a redirect. * firebase.auth().getRedirectResult().then(function(result) { * if (result.credential) { * // This gives you the OAuth Access Token for that provider. * var token = result.credential.accessToken; * } * var user = result.user; * }); * * // Start a sign in process for an unauthenticated user. * var provider = new firebase.auth.OAuthProvider('google.com'); * provider.addScope('profile'); * provider.addScope('email'); * firebase.auth().signInWithRedirect(provider); * * @example * // Using a popup. * var provider = new firebase.auth.OAuthProvider('google.com'); * provider.addScope('profile'); * provider.addScope('email'); * firebase.auth().signInWithPopup(provider).then(function(result) { * // This gives you the OAuth Access Token for that provider. * var token = result.credential.accessToken; * // The signed-in user info. * var user = result.user; * }); * * @see {@link firebase.auth.Auth#onAuthStateChanged} to receive sign in state * changes. * @param {string} providerId The associated provider ID, such as `github.com`. * @constructor * @implements {firebase.auth.AuthProvider} */ firebase.auth.OAuthProvider = function(providerId) {}; /** * Creates a Firebase credential from a generic OAuth provider's access token or * ID token. * * @example * // `googleUser` from the onsuccess Google Sign In callback. * // Initialize a generate OAuth provider with a `google.com` providerId. * var provider = new firebase.auth.OAuthProvider('google.com'); * var credential = provider.credential( * googleUser.getAuthResponse().id_token); * firebase.auth().signInWithCredential(credential) * * @param {?string=} idToken The OAuth ID token if OIDC compliant. * @param {?string=} accessToken The OAuth access token. * @return {!firebase.auth.OAuthCredential} The auth provider credential. */ firebase.auth.OAuthProvider.prototype.credential = function( idToken, accessToken ) {}; /** @type {string} */ firebase.auth.OAuthProvider.prototype.providerId; /** * @param {string} scope Provider OAuth scope to add. * @return {!firebase.auth.OAuthProvider} The provider instance. */ firebase.auth.OAuthProvider.prototype.addScope = function(scope) {}; /** * Sets the OAuth custom parameters to pass in an OAuth request for popup * and redirect sign-in operations. * For a detailed list, check the * reserved required OAuth 2.0 parameters such as `client_id`, `redirect_uri`, * `scope`, `response_type` and `state` are not allowed and will be ignored. * @param {!Object} customOAuthParameters The custom OAuth parameters to pass * in the OAuth request. * @return {!firebase.auth.OAuthProvider} The provider instance. */ firebase.auth.OAuthProvider.prototype.setCustomParameters = function( customOAuthParameters ) {}; /** * Facebook auth provider. * * @example * // Sign in using a redirect. * firebase.auth().getRedirectResult().then(function(result) { * if (result.credential) { * // This gives you a Google Access Token. * var token = result.credential.accessToken; * } * var user = result.user; * }) * // Start a sign in process for an unauthenticated user. * var provider = new firebase.auth.FacebookAuthProvider(); * provider.addScope('user_birthday'); * firebase.auth().signInWithRedirect(provider); * * @example * // Sign in using a popup. * var provider = new firebase.auth.FacebookAuthProvider(); * provider.addScope('user_birthday'); * firebase.auth().signInWithPopup(provider).then(function(result) { * // This gives you a Facebook Access Token. * var token = result.credential.accessToken; * // The signed-in user info. * var user = result.user; * }); * * @see {@link firebase.auth.Auth#onAuthStateChanged} to receive sign in state * changes. * @constructor * @implements {firebase.auth.AuthProvider} */ firebase.auth.FacebookAuthProvider = function() {}; /** @type {string} */ firebase.auth.FacebookAuthProvider.PROVIDER_ID; /** * @example * var cred = firebase.auth.FacebookAuthProvider.credential( * // `event` from the Facebook auth.authResponseChange callback. * event.authResponse.accessToken * ); * * @param {string} token Facebook access token. * @return {!firebase.auth.OAuthCredential} The auth provider credential. */ firebase.auth.FacebookAuthProvider.credential = function(token) {}; /** @type {string} */ firebase.auth.FacebookAuthProvider.prototype.providerId; /** * @param {string} scope Facebook OAuth scope. * @return {!firebase.auth.AuthProvider} The provider instance itself. */ firebase.auth.FacebookAuthProvider.prototype.addScope = function(scope) {}; /** * Sets the OAuth custom parameters to pass in a Facebook OAuth request for * popup and redirect sign-in operations. * Valid parameters include 'auth_type', 'display' and 'locale'. * For a detailed list, check the * {@link https://goo.gl/pve4fo Facebook} * documentation. * Reserved required OAuth 2.0 parameters such as 'client_id', 'redirect_uri', * 'scope', 'response_type' and 'state' are not allowed and will be ignored. * @param {!Object} customOAuthParameters The custom OAuth parameters to pass * in the OAuth request. * @return {!firebase.auth.AuthProvider} The provider instance itself. */ firebase.auth.FacebookAuthProvider.prototype.setCustomParameters = function( customOAuthParameters ) {}; /** * Github auth provider. * * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect * directly, or use the signInWithPopup handler: * * @example * // Using a redirect. * firebase.auth().getRedirectResult().then(function(result) { * if (result.credential) { * // This gives you a GitHub Access Token. * var token = result.credential.accessToken; * } * var user = result.user; * }).catch(function(error) { * // Handle Errors here. * var errorCode = error.code; * var errorMessage = error.message; * // The email of the user's account used. * var email = error.email; * // The firebase.auth.AuthCredential type that was used. * var credential = error.credential; * if (errorCode === 'auth/account-exists-with-different-credential') { * alert('You have signed up with a different provider for that email.'); * // Handle linking here if your app allows it. * } else { * console.error(error); * } * }); * * // Start a sign in process for an unauthenticated user. * var provider = new firebase.auth.GithubAuthProvider(); * provider.addScope('repo'); * firebase.auth().signInWithRedirect(provider); * * @example * // With popup. * var provider = new firebase.auth.GithubAuthProvider(); * provider.addScope('repo'); * firebase.auth().signInWithPopup(provider).then(function(result) { * // This gives you a GitHub Access Token. * var token = result.credential.accessToken; * // The signed-in user info. * var user = result.user; * }).catch(function(error) { * // Handle Errors here. * var errorCode = error.code; * var errorMessage = error.message; * // The email of the user's account used. * var email = error.email; * // The firebase.auth.AuthCredential type that was used. * var credential = error.credential; * if (errorCode === 'auth/account-exists-with-different-credential') { * alert('You have signed up with a different provider for that email.'); * // Handle linking here if your app allows it. * } else { * console.error(error); * } * }); * * @see {@link firebase.auth.Auth#onAuthStateChanged} to receive sign in state * changes. * @constructor * @implements {firebase.auth.AuthProvider} */ firebase.auth.GithubAuthProvider = function() {}; /** @type {string} */ firebase.auth.GithubAuthProvider.PROVIDER_ID; /** * @example * var cred = firebase.auth.FacebookAuthProvider.credential( * // `event` from the Facebook auth.authResponseChange callback. * event.authResponse.accessToken * ); * * @param {string} token Github access token. * @return {!firebase.auth.OAuthCredential} The auth provider credential. */ firebase.auth.GithubAuthProvider.credential = function(token) {}; /** @type {string} */ firebase.auth.GithubAuthProvider.prototype.providerId; /** * @param {string} scope Github OAuth scope. * @return {!firebase.auth.AuthProvider} The provider instance itself. */ firebase.auth.GithubAuthProvider.prototype.addScope = function(scope) {}; /** * Sets the OAuth custom parameters to pass in a GitHub OAuth request for popup * and redirect sign-in operations. * Valid parameters include 'allow_signup'. * For a detailed list, check the * {@link https://developer.github.com/v3/oauth/ GitHub} documentation. * Reserved required OAuth 2.0 parameters such as 'client_id', 'redirect_uri', * 'scope', 'response_type' and 'state' are not allowed and will be ignored. * @param {!Object} customOAuthParameters The custom OAuth parameters to pass * in the OAuth request. * @return {!firebase.auth.AuthProvider} The provider instance itself. */ firebase.auth.GithubAuthProvider.prototype.setCustomParameters = function( customOAuthParameters ) {}; /** * Google auth provider. * * @example * // Using a redirect. * firebase.auth().getRedirectResult().then(function(result) { * if (result.credential) { * // This gives you a Google Access Token. * var token = result.credential.accessToken; * } * var user = result.user; * }); * * // Start a sign in process for an unauthenticated user. * var provider = new firebase.auth.GoogleAuthProvider(); * provider.addScope('profile'); * provider.addScope('email'); * firebase.auth().signInWithRedirect(provider); * * @example * // Using a popup. * var provider = new firebase.auth.GoogleAuthProvider(); * provider.addScope('profile'); * provider.addScope('email'); * firebase.auth().signInWithPopup(provider).then(function(result) { * // This gives you a Google Access Token. * var token = result.credential.accessToken; * // The signed-in user info. * var user = result.user; * }); * * @see {@link firebase.auth.Auth#onAuthStateChanged} to receive sign in state * changes. * @constructor * @implements {firebase.auth.AuthProvider} */ firebase.auth.GoogleAuthProvider = function() {}; /** @type {string} */ firebase.auth.GoogleAuthProvider.PROVIDER_ID; /** * Creates a credential for Google. At least one of ID token and access token * is required. * * @example * // `googleUser` from the onsuccess Google Sign In callback. * var credential = firebase.auth.GoogleAuthProvider.credential( googleUser.getAuthResponse().id_token); * firebase.auth().signInWithCredential(credential) * * @param {?string=} idToken Google ID token. * @param {?string=} accessToken Google access token. * @return {!firebase.auth.OAuthCredential} The auth provider credential. */ firebase.auth.GoogleAuthProvider.credential = function(idToken, accessToken) {}; /** @type {string} */ firebase.auth.GoogleAuthProvider.prototype.providerId; /** * @param {string} scope Google OAuth scope. * @return {!firebase.auth.AuthProvider} The provider instance itself. */ firebase.auth.GoogleAuthProvider.prototype.addScope = function(scope) {}; /** * Sets the OAuth custom parameters to pass in a Google OAuth request for popup * and redirect sign-in operations. * Valid parameters include 'hd', 'hl', 'include_granted_scopes', 'login_hint' * and 'prompt'. * For a detailed list, check the * {@link https://goo.gl/Xo01Jm Google} * documentation. * Reserved required OAuth 2.0 parameters such as 'client_id', 'redirect_uri', * 'scope', 'response_type' and 'state' are not allowed and will be ignored. * @param {!Object} customOAuthParameters The custom OAuth parameters to pass * in the OAuth request. * @return {!firebase.auth.AuthProvider} The provider instance itself. */ firebase.auth.GoogleAuthProvider.prototype.setCustomParameters = function( customOAuthParameters ) {}; /** * Twitter auth provider. * * @example * // Using a redirect. * firebase.auth().getRedirectResult().then(function(result) { * if (result.credential) { * // For accessing the Twitter API. * var token = result.credential.accessToken; * var secret = result.credential.secret; * } * var user = result.user; * }); * * // Start a sign in process for an unauthenticated user. * var provider = new firebase.auth.TwitterAuthProvider(); * firebase.auth().signInWithRedirect(provider); * * @example * // Using a popup. * var provider = new firebase.auth.TwitterAuthProvider(); * firebase.auth().signInWithPopup(provider).then(function(result) { * // For accessing the Twitter API. * var token = result.credential.accessToken; * var secret = result.credential.secret; * // The signed-in user info. * var user = result.user; * }); * * @see {@link firebase.auth.Auth#onAuthStateChanged} to receive sign in state * changes. * @constructor * @implements {firebase.auth.AuthProvider} */ firebase.auth.TwitterAuthProvider = function() {}; /** @type {string} */ firebase.auth.TwitterAuthProvider.PROVIDER_ID; /** * @param {string} token Twitter access token. * @param {string} secret Twitter secret. * @return {!firebase.auth.OAuthCredential} The auth provider credential. */ firebase.auth.TwitterAuthProvider.credential = function(token, secret) {}; /** @type {string} */ firebase.auth.TwitterAuthProvider.prototype.providerId; /** * Sets the OAuth custom parameters to pass in a Twitter OAuth request for popup * and redirect sign-in operations. * Valid parameters include 'lang'. * Reserved required OAuth 1.0 parameters such as 'oauth_consumer_key', * 'oauth_token', 'oauth_signature', etc are not allowed and will be ignored. * @param {!Object} customOAuthParameters The custom OAuth parameters to pass * in the OAuth request. * @return {!firebase.auth.AuthProvider} The provider instance itself. */ firebase.auth.TwitterAuthProvider.prototype.setCustomParameters = function( customOAuthParameters ) {}; /** * Email and password auth provider implementation. * * To authenticate: {@link firebase.auth.Auth#createUserWithEmailAndPassword} * and {@link firebase.auth.Auth#signInWithEmailAndPassword}. * * @constructor * @implements {firebase.auth.AuthProvider} */ firebase.auth.EmailAuthProvider = function() {}; /** @type {string} */ firebase.auth.EmailAuthProvider.PROVIDER_ID; /** * @example * var cred = firebase.auth.EmailAuthProvider.credential( * email, * password * ); * * @param {string} email Email address. * @param {string} password User account password. * @return {!firebase.auth.AuthCredential} The auth provider credential. */ firebase.auth.EmailAuthProvider.credential = function(email, password) {}; /** @type {string} */ firebase.auth.EmailAuthProvider.prototype.providerId; /** * Phone number auth provider. * * @example * // 'recaptcha-container' is the ID of an element in the DOM. * var applicationVerifier = new firebase.auth.RecaptchaVerifier( * 'recaptcha-container'); * var provider = new firebase.auth.PhoneAuthProvider(); * provider.verifyPhoneNumber('+16505550101', applicationVerifier) * .then(function(verificationId) { * var verificationCode = window.prompt('Please enter the verification ' + * 'code that was sent to your mobile device.'); * return firebase.auth.PhoneAuthProvider.credential(verificationId, * verificationCode); * }) * .then(function(phoneCredential) { * return firebase.auth().signInWithCredential(phoneCredential); * }); * * @constructor * @param {?firebase.auth.Auth=} auth The Firebase Auth instance in which * sign-ins should occur. Uses the default Auth instance if unspecified. * @implements {firebase.auth.AuthProvider} */ firebase.auth.PhoneAuthProvider = function(auth) {}; /** @type {string} */ firebase.auth.PhoneAuthProvider.PROVIDER_ID; /** * Creates a phone auth credential, given the verification ID from * {@link firebase.auth.PhoneAuthProvider#verifyPhoneNumber} and the code * that was sent to the user's mobile device. * * <h4>Error Codes</h4> * <dl> * <dt>auth/missing-verification-code</dt> * <dd>Thrown if the verification code is missing.</dd> * <dt>auth/missing-verification-id</dt> * <dd>Thrown if the verification ID is missing.</dd> * </dl> * * @param {string} verificationId The verification ID returned from * {@link firebase.auth.PhoneAuthProvider#verifyPhoneNumber}. * @param {string} verificationCode The verification code sent to the user's * mobile device. * @return {!firebase.auth.AuthCredential} The auth provider credential. */ firebase.auth.PhoneAuthProvider.credential = function( verificationId, verificationCode ) {}; /** @type {string} */ firebase.auth.PhoneAuthProvider.prototype.providerId; /** * Starts a phone number authentication flow by sending a verification code to * the given phone number. Returns an ID that can be passed to * {@link firebase.auth.PhoneAuthProvider#credential} to identify this flow. * * For abuse prevention, this method also requires a * {@link firebase.auth.ApplicationVerifier}. The Firebase Auth SDK includes * a reCAPTCHA-based implementation, {@link firebase.auth.RecaptchaVerifier}. * * <h4>Error Codes</h4> * <dl> * <dt>auth/captcha-check-failed</dt> * <dd>Thrown if the reCAPTCHA response token was invalid, expired, or if * this method was called from a non-whitelisted domain.</dd> * <dt>auth/invalid-phone-number</dt> * <dd>Thrown if the phone number has an invalid format.</dd> * <dt>auth/missing-phone-number</dt> * <dd>Thrown if the phone number is missing.</dd> * <dt>auth/quota-exceeded</dt> * <dd>Thrown if the SMS quota for the Firebase project has been exceeded.</dd> * <dt>auth/user-disabled</dt> * <dd>Thrown if the user corresponding to the given phone number has been * disabled.</dd> * </dl> * * @param {string} phoneNumber The user's phone number in E.164 format (e.g. * +16505550101). * @param {!firebase.auth.ApplicationVerifier} applicationVerifier * @return {!firebase.Promise<string>} A Promise for the verification ID. */ firebase.auth.PhoneAuthProvider.prototype.verifyPhoneNumber = function( phoneNumber, applicationVerifier ) {}; /** * A verifier for domain verification and abuse prevention. Currently, the * only implementation is {@link firebase.auth.RecaptchaVerifier}. * @interface */ firebase.auth.ApplicationVerifier = function() {}; /** * Identifies the type of application verifier (e.g. "recaptcha"). * @type {string} */ firebase.auth.ApplicationVerifier.prototype.type; /** * Executes the verification process. * @return {!firebase.Promise<string>} A Promise for a token that can be used to * assert the validity of a request. */ firebase.auth.ApplicationVerifier.prototype.verify = function() {};
module.exports = function (n) { return n * 11 }
'use strict'; // Setting up route angular.module('core').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { // Redirect to home view when route not found $urlRouterProvider.otherwise('/'); // Home state routing $stateProvider. state('comment', { url: '/comment', templateUrl: 'modules/core/views/comment.client.view.html' }). state('search', { url: '/search', templateUrl: 'modules/core/views/search.client.view.html' }). state('home', { url: '/', templateUrl: 'modules/core/views/home.client.view.html' }); } ]);
/*! backgrid 0.3.5 http://github.com/wyuenho/backgrid Copyright (c) 2015 Jimmy Yuen Ho Wong and contributors <wyuenho@gmail.com> Licensed under the MIT license. */ (function (root, factory) { if (typeof define === "function" && define.amd) { // AMD (+ global for extensions) define(["underscore", "backbone"], function (_, Backbone) { return (root.Backgrid = factory(_, Backbone)); }); } else if (typeof exports === "object") { // CommonJS var Backbone = require("backbone"); Backbone.$ = Backbone.$ || require("jquery"); module.exports = factory(require("underscore"), Backbone); } else { // Browser root.Backgrid = factory(root._, root.Backbone); }}(this, function (_, Backbone) { "use strict"; /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT license. */ // Copyright 2009, 2010 Kristopher Michael Kowal // https://github.com/kriskowal/es5-shim // ES5 15.5.4.20 // http://es5.github.com/#x15.5.4.20 var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { if (this === undefined || this === null) { throw new TypeError("can't convert " + this + " to object"); } return String(this) .replace(trimBeginRegexp, "") .replace(trimEndRegexp, ""); }; } function lpad(str, length, padstr) { var paddingLen = length - (str + '').length; paddingLen = paddingLen < 0 ? 0 : paddingLen; var padding = ''; for (var i = 0; i < paddingLen; i++) { padding = padding + padstr; } return padding + str; } var $ = Backbone.$; var Backgrid = { Extension: {}, resolveNameToClass: function (name, suffix) { if (_.isString(name)) { var key = _.map(name.split('-'), function (e) { return e.slice(0, 1).toUpperCase() + e.slice(1); }).join('') + suffix; var klass = Backgrid[key] || Backgrid.Extension[key]; if (_.isUndefined(klass)) { throw new ReferenceError("Class '" + key + "' not found"); } return klass; } return name; }, callByNeed: function () { var value = arguments[0]; if (!_.isFunction(value)) return value; var context = arguments[1]; var args = [].slice.call(arguments, 2); return value.apply(context, !!(args + '') ? args : []); } }; _.extend(Backgrid, Backbone.Events); /** Command translates a DOM Event into commands that Backgrid recognizes. Interested parties can listen on selected Backgrid events that come with an instance of this class and act on the commands. It is also possible to globally rebind the keyboard shortcuts by replacing the methods in this class' prototype. @class Backgrid.Command @constructor */ var Command = Backgrid.Command = function (evt) { _.extend(this, { altKey: !!evt.altKey, "char": evt["char"], charCode: evt.charCode, ctrlKey: !!evt.ctrlKey, key: evt.key, keyCode: evt.keyCode, locale: evt.locale, location: evt.location, metaKey: !!evt.metaKey, repeat: !!evt.repeat, shiftKey: !!evt.shiftKey, which: evt.which }); }; _.extend(Command.prototype, { /** Up Arrow @member Backgrid.Command */ moveUp: function () { return this.keyCode == 38; }, /** Down Arrow @member Backgrid.Command */ moveDown: function () { return this.keyCode === 40; }, /** Shift Tab @member Backgrid.Command */ moveLeft: function () { return this.shiftKey && this.keyCode === 9; }, /** Tab @member Backgrid.Command */ moveRight: function () { return !this.shiftKey && this.keyCode === 9; }, /** Enter @member Backgrid.Command */ save: function () { return this.keyCode === 13; }, /** Esc @member Backgrid.Command */ cancel: function () { return this.keyCode === 27; }, /** None of the above. @member Backgrid.Command */ passThru: function () { return !(this.moveUp() || this.moveDown() || this.moveLeft() || this.moveRight() || this.save() || this.cancel()); } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT license. */ /** Just a convenient class for interested parties to subclass. The default Cell classes don't require the formatter to be a subclass of Formatter as long as the fromRaw(rawData) and toRaw(formattedData) methods are defined. @abstract @class Backgrid.CellFormatter @constructor */ var CellFormatter = Backgrid.CellFormatter = function () {}; _.extend(CellFormatter.prototype, { /** Takes a raw value from a model and returns an optionally formatted string for display. The default implementation simply returns the supplied value as is without any type conversion. @member Backgrid.CellFormatter @param {*} rawData @param {Backbone.Model} model Used for more complicated formatting @return {*} */ fromRaw: function (rawData, model) { return rawData; }, /** Takes a formatted string, usually from user input, and returns a appropriately typed value for persistence in the model. If the user input is invalid or unable to be converted to a raw value suitable for persistence in the model, toRaw must return `undefined`. @member Backgrid.CellFormatter @param {string} formattedData @param {Backbone.Model} model Used for more complicated formatting @return {*|undefined} */ toRaw: function (formattedData, model) { return formattedData; } }); /** A floating point number formatter. Doesn't understand scientific notation at the moment. @class Backgrid.NumberFormatter @extends Backgrid.CellFormatter @constructor @throws {RangeError} If decimals < 0 or > 20. */ var NumberFormatter = Backgrid.NumberFormatter = function (options) { _.extend(this, this.defaults, options || {}); if (this.decimals < 0 || this.decimals > 20) { throw new RangeError("decimals must be between 0 and 20"); } }; NumberFormatter.prototype = new CellFormatter(); _.extend(NumberFormatter.prototype, { /** @member Backgrid.NumberFormatter @cfg {Object} options @cfg {number} [options.decimals=2] Number of decimals to display. Must be an integer. @cfg {string} [options.decimalSeparator='.'] The separator to use when displaying decimals. @cfg {string} [options.orderSeparator=','] The separator to use to separator thousands. May be an empty string. */ defaults: { decimals: 2, decimalSeparator: '.', orderSeparator: ',' }, HUMANIZED_NUM_RE: /(\d)(?=(?:\d{3})+$)/g, /** Takes a floating point number and convert it to a formatted string where every thousand is separated by `orderSeparator`, with a `decimal` number of decimals separated by `decimalSeparator`. The number returned is rounded the usual way. @member Backgrid.NumberFormatter @param {number} number @param {Backbone.Model} model Used for more complicated formatting @return {string} */ fromRaw: function (number, model) { if (_.isNull(number) || _.isUndefined(number)) return ''; number = number.toFixed(~~this.decimals); var parts = number.split('.'); var integerPart = parts[0]; var decimalPart = parts[1] ? (this.decimalSeparator || '.') + parts[1] : ''; return integerPart.replace(this.HUMANIZED_NUM_RE, '$1' + this.orderSeparator) + decimalPart; }, /** Takes a string, possibly formatted with `orderSeparator` and/or `decimalSeparator`, and convert it back to a number. @member Backgrid.NumberFormatter @param {string} formattedData @param {Backbone.Model} model Used for more complicated formatting @return {number|undefined} Undefined if the string cannot be converted to a number. */ toRaw: function (formattedData, model) { formattedData = formattedData.trim(); if (formattedData === '') return null; var rawData = ''; var thousands = formattedData.split(this.orderSeparator); for (var i = 0; i < thousands.length; i++) { rawData += thousands[i]; } var decimalParts = rawData.split(this.decimalSeparator); rawData = ''; for (var i = 0; i < decimalParts.length; i++) { rawData = rawData + decimalParts[i] + '.'; } if (rawData[rawData.length - 1] === '.') { rawData = rawData.slice(0, rawData.length - 1); } var result = (rawData * 1).toFixed(~~this.decimals) * 1; if (_.isNumber(result) && !_.isNaN(result)) return result; } }); /** A number formatter that converts a floating point number, optionally multiplied by a multiplier, to a percentage string and vice versa. @class Backgrid.PercentFormatter @extends Backgrid.NumberFormatter @constructor @throws {RangeError} If decimals < 0 or > 20. */ var PercentFormatter = Backgrid.PercentFormatter = function () { Backgrid.NumberFormatter.apply(this, arguments); }; PercentFormatter.prototype = new Backgrid.NumberFormatter(), _.extend(PercentFormatter.prototype, { /** @member Backgrid.PercentFormatter @cfg {Object} options @cfg {number} [options.multiplier=1] The number used to multiply the model value for display. @cfg {string} [options.symbol='%'] The symbol to append to the percentage string. */ defaults: _.extend({}, NumberFormatter.prototype.defaults, { multiplier: 1, symbol: "%" }), /** Takes a floating point number, where the number is first multiplied by `multiplier`, then converted to a formatted string like NumberFormatter#fromRaw, then finally append `symbol` to the end. @member Backgrid.PercentFormatter @param {number} rawValue @param {Backbone.Model} model Used for more complicated formatting @return {string} */ fromRaw: function (number, model) { var args = [].slice.call(arguments, 1); args.unshift(number * this.multiplier); return (NumberFormatter.prototype.fromRaw.apply(this, args) || "0") + this.symbol; }, /** Takes a string, possibly appended with `symbol` and/or `decimalSeparator`, and convert it back to a number for the model like NumberFormatter#toRaw, and then dividing it by `multiplier`. @member Backgrid.PercentFormatter @param {string} formattedData @param {Backbone.Model} model Used for more complicated formatting @return {number|undefined} Undefined if the string cannot be converted to a number. */ toRaw: function (formattedValue, model) { var tokens = formattedValue.split(this.symbol); if (tokens && tokens[0] && tokens[1] === "" || tokens[1] == null) { var rawValue = NumberFormatter.prototype.toRaw.call(this, tokens[0]); if (_.isUndefined(rawValue)) return rawValue; return rawValue / this.multiplier; } } }); /** Formatter to converts between various datetime formats. This class only understands ISO-8601 formatted datetime strings and UNIX offset (number of milliseconds since UNIX Epoch). See Backgrid.Extension.MomentFormatter if you need a much more flexible datetime formatter. @class Backgrid.DatetimeFormatter @extends Backgrid.CellFormatter @constructor @throws {Error} If both `includeDate` and `includeTime` are false. */ var DatetimeFormatter = Backgrid.DatetimeFormatter = function (options) { _.extend(this, this.defaults, options || {}); if (!this.includeDate && !this.includeTime) { throw new Error("Either includeDate or includeTime must be true"); } }; DatetimeFormatter.prototype = new CellFormatter(); _.extend(DatetimeFormatter.prototype, { /** @member Backgrid.DatetimeFormatter @cfg {Object} options @cfg {boolean} [options.includeDate=true] Whether the values include the date part. @cfg {boolean} [options.includeTime=true] Whether the values include the time part. @cfg {boolean} [options.includeMilli=false] If `includeTime` is true, whether to include the millisecond part, if it exists. */ defaults: { includeDate: true, includeTime: true, includeMilli: false }, DATE_RE: /^([+\-]?\d{4})-(\d{2})-(\d{2})$/, TIME_RE: /^(\d{2}):(\d{2}):(\d{2})(\.(\d{3}))?$/, ISO_SPLITTER_RE: /T|Z| +/, _convert: function (data, validate) { if ((data + '').trim() === '') return null; var date, time = null; if (_.isNumber(data)) { var jsDate = new Date(data); date = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0); time = lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0); } else { data = data.trim(); var parts = data.split(this.ISO_SPLITTER_RE) || []; date = this.DATE_RE.test(parts[0]) ? parts[0] : ''; time = date && parts[1] ? parts[1] : this.TIME_RE.test(parts[0]) ? parts[0] : ''; } var YYYYMMDD = this.DATE_RE.exec(date) || []; var HHmmssSSS = this.TIME_RE.exec(time) || []; if (validate) { if (this.includeDate && _.isUndefined(YYYYMMDD[0])) return; if (this.includeTime && _.isUndefined(HHmmssSSS[0])) return; if (!this.includeDate && date) return; if (!this.includeTime && time) return; } var jsDate = new Date(Date.UTC(YYYYMMDD[1] * 1 || 0, YYYYMMDD[2] * 1 - 1 || 0, YYYYMMDD[3] * 1 || 0, HHmmssSSS[1] * 1 || null, HHmmssSSS[2] * 1 || null, HHmmssSSS[3] * 1 || null, HHmmssSSS[5] * 1 || null)); var result = ''; if (this.includeDate) { result = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0); } if (this.includeTime) { result = result + (this.includeDate ? 'T' : '') + lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0); if (this.includeMilli) { result = result + '.' + lpad(jsDate.getUTCMilliseconds(), 3, 0); } } if (this.includeDate && this.includeTime) { result += "Z"; } return result; }, /** Converts an ISO-8601 formatted datetime string to a datetime string, date string or a time string. The timezone is ignored if supplied. @member Backgrid.DatetimeFormatter @param {string} rawData @param {Backbone.Model} model Used for more complicated formatting @return {string|null|undefined} ISO-8601 string in UTC. Null and undefined values are returned as is. */ fromRaw: function (rawData, model) { if (_.isNull(rawData) || _.isUndefined(rawData)) return ''; return this._convert(rawData); }, /** Converts an ISO-8601 formatted datetime string to a datetime string, date string or a time string. The timezone is ignored if supplied. This method parses the input values exactly the same way as Backgrid.Extension.MomentFormatter#fromRaw(), in addition to doing some sanity checks. @member Backgrid.DatetimeFormatter @param {string} formattedData @param {Backbone.Model} model Used for more complicated formatting @return {string|undefined} ISO-8601 string in UTC. Undefined if a date is found when `includeDate` is false, or a time is found when `includeTime` is false, or if `includeDate` is true and a date is not found, or if `includeTime` is true and a time is not found. */ toRaw: function (formattedData, model) { return this._convert(formattedData, true); } }); /** Formatter to convert any value to string. @class Backgrid.StringFormatter @extends Backgrid.CellFormatter @constructor */ var StringFormatter = Backgrid.StringFormatter = function () {}; StringFormatter.prototype = new CellFormatter(); _.extend(StringFormatter.prototype, { /** Converts any value to a string using Ecmascript's implicit type conversion. If the given value is `null` or `undefined`, an empty string is returned instead. @member Backgrid.StringFormatter @param {*} rawValue @param {Backbone.Model} model Used for more complicated formatting @return {string} */ fromRaw: function (rawValue, model) { if (_.isUndefined(rawValue) || _.isNull(rawValue)) return ''; return rawValue + ''; } }); /** Simple email validation formatter. @class Backgrid.EmailFormatter @extends Backgrid.CellFormatter @constructor */ var EmailFormatter = Backgrid.EmailFormatter = function () {}; EmailFormatter.prototype = new CellFormatter(); _.extend(EmailFormatter.prototype, { /** Return the input if it is a string that contains an '@' character and if the strings before and after '@' are non-empty. If the input does not validate, `undefined` is returned. @member Backgrid.EmailFormatter @param {*} formattedData @param {Backbone.Model} model Used for more complicated formatting @return {string|undefined} */ toRaw: function (formattedData, model) { var parts = formattedData.trim().split("@"); if (parts.length === 2 && _.all(parts)) { return formattedData; } } }); /** Formatter for SelectCell. If the type of a model value is not a string, it is expected that a subclass of this formatter is provided to the SelectCell, with #toRaw overridden to convert the string value returned from the DOM back to whatever value is expected in the model. @class Backgrid.SelectFormatter @extends Backgrid.CellFormatter @constructor */ var SelectFormatter = Backgrid.SelectFormatter = function () {}; SelectFormatter.prototype = new CellFormatter(); _.extend(SelectFormatter.prototype, { /** Normalizes raw scalar or array values to an array. @member Backgrid.SelectFormatter @param {*} rawValue @param {Backbone.Model} model Used for more complicated formatting @return {Array.<*>} */ fromRaw: function (rawValue, model) { return _.isArray(rawValue) ? rawValue : rawValue != null ? [rawValue] : []; } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT license. */ /** Generic cell editor base class. Only defines an initializer for a number of required parameters. @abstract @class Backgrid.CellEditor @extends Backbone.View */ var CellEditor = Backgrid.CellEditor = Backbone.View.extend({ /** Initializer. @param {Object} options @param {Backgrid.CellFormatter} options.formatter @param {Backgrid.Column} options.column @param {Backbone.Model} options.model @throws {TypeError} If `formatter` is not a formatter instance, or when `model` or `column` are undefined. */ initialize: function (options) { this.formatter = options.formatter; this.column = options.column; if (!(this.column instanceof Column)) { this.column = new Column(this.column); } this.listenTo(this.model, "backgrid:editing", this.postRender); }, /** Post-rendering setup and initialization. Focuses the cell editor's `el` in this default implementation. **Should** be called by Cell classes after calling Backgrid.CellEditor#render. */ postRender: function (model, column) { if (column == null || column.get("name") == this.column.get("name")) { this.$el.focus(); } return this; } }); /** InputCellEditor the cell editor type used by most core cell types. This cell editor renders a text input box as its editor. The input will render a placeholder if the value is empty on supported browsers. @class Backgrid.InputCellEditor @extends Backgrid.CellEditor */ var InputCellEditor = Backgrid.InputCellEditor = CellEditor.extend({ /** @property */ tagName: "input", /** @property */ attributes: { type: "text" }, /** @property */ events: { "blur": "saveOrCancel", "keydown": "saveOrCancel" }, /** Initializer. Removes this `el` from the DOM when a `done` event is triggered. @param {Object} options @param {Backgrid.CellFormatter} options.formatter @param {Backgrid.Column} options.column @param {Backbone.Model} options.model @param {string} [options.placeholder] */ initialize: function (options) { InputCellEditor.__super__.initialize.apply(this, arguments); if (options.placeholder) { this.$el.attr("placeholder", options.placeholder); } }, /** Renders a text input with the cell value formatted for display, if it exists. */ render: function () { var model = this.model; this.$el.val(this.formatter.fromRaw(model.get(this.column.get("name")), model)); return this; }, /** If the key pressed is `enter`, `tab`, `up`, or `down`, converts the value in the editor to a raw value for saving into the model using the formatter. If the key pressed is `esc` the changes are undone. If the editor goes out of focus (`blur`) but the value is invalid, the event is intercepted and cancelled so the cell remains in focus pending for further action. The changes are saved otherwise. Triggers a Backbone `backgrid:edited` event from the model when successful, and `backgrid:error` if the value cannot be converted. Classes listening to the `error` event, usually the Cell classes, should respond appropriately, usually by rendering some kind of error feedback. @param {Event} e */ saveOrCancel: function (e) { var formatter = this.formatter; var model = this.model; var column = this.column; var command = new Command(e); var blurred = e.type === "blur"; if (command.moveUp() || command.moveDown() || command.moveLeft() || command.moveRight() || command.save() || blurred) { e.preventDefault(); e.stopPropagation(); var val = this.$el.val(); var newValue = formatter.toRaw(val, model); if (_.isUndefined(newValue)) { model.trigger("backgrid:error", model, column, val); } else { model.set(column.get("name"), newValue); model.trigger("backgrid:edited", model, column, command); } } // esc else if (command.cancel()) { // undo e.stopPropagation(); model.trigger("backgrid:edited", model, column, command); } }, postRender: function (model, column) { if (column == null || column.get("name") == this.column.get("name")) { // move the cursor to the end on firefox if text is right aligned if (this.$el.css("text-align") === "right") { var val = this.$el.val(); this.$el.focus().val(null).val(val); } else this.$el.focus(); } return this; } }); /** The super-class for all Cell types. By default, this class renders a plain table cell with the model value converted to a string using the formatter. The table cell is clickable, upon which the cell will go into editor mode, which is rendered by a Backgrid.InputCellEditor instance by default. Upon encountering any formatting errors, this class will add an `error` CSS class to the table cell. @abstract @class Backgrid.Cell @extends Backbone.View */ var Cell = Backgrid.Cell = Backbone.View.extend({ /** @property */ tagName: "td", /** @property {Backgrid.CellFormatter|Object|string} [formatter=CellFormatter] */ formatter: CellFormatter, /** @property {Backgrid.CellEditor} [editor=Backgrid.InputCellEditor] The default editor for all cell instances of this class. This value must be a class, it will be automatically instantiated upon entering edit mode. See Backgrid.CellEditor */ editor: InputCellEditor, /** @property */ events: { "click": "enterEditMode" }, /** Initializer. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column @throws {ReferenceError} If formatter is a string but a formatter class of said name cannot be found in the Backgrid module. */ initialize: function (options) { this.column = options.column; if (!(this.column instanceof Column)) { this.column = new Column(this.column); } var column = this.column, model = this.model, $el = this.$el; var formatter = Backgrid.resolveNameToClass(column.get("formatter") || this.formatter, "Formatter"); if (!_.isFunction(formatter.fromRaw) && !_.isFunction(formatter.toRaw)) { formatter = new formatter(); } this.formatter = formatter; this.editor = Backgrid.resolveNameToClass(this.editor, "CellEditor"); this.listenTo(model, "change:" + column.get("name"), function () { if (!$el.hasClass("editor")) this.render(); }); this.listenTo(model, "backgrid:error", this.renderError); this.listenTo(column, "change:editable change:sortable change:renderable", function (column) { var changed = column.changedAttributes(); for (var key in changed) { if (changed.hasOwnProperty(key)) { $el.toggleClass(key, changed[key]); } } }); if (Backgrid.callByNeed(column.editable(), column, model)) $el.addClass("editable"); if (Backgrid.callByNeed(column.sortable(), column, model)) $el.addClass("sortable"); if (Backgrid.callByNeed(column.renderable(), column, model)) $el.addClass("renderable"); }, /** Render a text string in a table cell. The text is converted from the model's raw value for this cell's column. */ render: function () { this.$el.empty(); var model = this.model; this.$el.text(this.formatter.fromRaw(model.get(this.column.get("name")), model)); this.delegateEvents(); return this; }, /** If this column is editable, a new CellEditor instance is instantiated with its required parameters. An `editor` CSS class is added to the cell upon entering edit mode. This method triggers a Backbone `backgrid:edit` event from the model when the cell is entering edit mode and an editor instance has been constructed, but before it is rendered and inserted into the DOM. The cell and the constructed cell editor instance are sent as event parameters when this event is triggered. When this cell has finished switching to edit mode, a Backbone `backgrid:editing` event is triggered from the model. The cell and the constructed cell instance are also sent as parameters in the event. When the model triggers a `backgrid:error` event, it means the editor is unable to convert the current user input to an apprpriate value for the model's column, and an `error` CSS class is added to the cell accordingly. */ enterEditMode: function () { var model = this.model; var column = this.column; var editable = Backgrid.callByNeed(column.editable(), column, model); if (editable) { this.currentEditor = new this.editor({ column: this.column, model: this.model, formatter: this.formatter }); model.trigger("backgrid:edit", model, column, this, this.currentEditor); // Need to redundantly undelegate events for Firefox this.undelegateEvents(); this.$el.empty(); this.$el.append(this.currentEditor.$el); this.currentEditor.render(); this.$el.addClass("editor"); model.trigger("backgrid:editing", model, column, this, this.currentEditor); } }, /** Put an `error` CSS class on the table cell. */ renderError: function (model, column) { if (column == null || column.get("name") == this.column.get("name")) { this.$el.addClass("error"); } }, /** Removes the editor and re-render in display mode. */ exitEditMode: function () { this.$el.removeClass("error"); this.currentEditor.remove(); this.stopListening(this.currentEditor); delete this.currentEditor; this.$el.removeClass("editor"); this.render(); }, /** Clean up this cell. @chainable */ remove: function () { if (this.currentEditor) { this.currentEditor.remove.apply(this.currentEditor, arguments); delete this.currentEditor; } return Cell.__super__.remove.apply(this, arguments); } }); /** StringCell displays HTML escaped strings and accepts anything typed in. @class Backgrid.StringCell @extends Backgrid.Cell */ var StringCell = Backgrid.StringCell = Cell.extend({ /** @property */ className: "string-cell", formatter: StringFormatter }); /** UriCell renders an HTML `<a>` anchor for the value and accepts URIs as user input values. No type conversion or URL validation is done by the formatter of this cell. Users who need URL validation are encourage to subclass UriCell to take advantage of the parsing capabilities of the HTMLAnchorElement available on HTML5-capable browsers or using a third-party library like [URI.js](https://github.com/medialize/URI.js). @class Backgrid.UriCell @extends Backgrid.Cell */ var UriCell = Backgrid.UriCell = Cell.extend({ /** @property */ className: "uri-cell", /** @property {string} [title] The title attribute of the generated anchor. It uses the display value formatted by the `formatter.fromRaw` by default. */ title: null, /** @property {string} [target="_blank"] The target attribute of the generated anchor. */ target: "_blank", initialize: function (options) { UriCell.__super__.initialize.apply(this, arguments); this.title = options.title || this.title; this.target = options.target || this.target; }, render: function () { this.$el.empty(); var rawValue = this.model.get(this.column.get("name")); var formattedValue = this.formatter.fromRaw(rawValue, this.model); this.$el.append($("<a>", { tabIndex: -1, href: rawValue, title: this.title || formattedValue, target: this.target }).text(formattedValue)); this.delegateEvents(); return this; } }); /** Like Backgrid.UriCell, EmailCell renders an HTML `<a>` anchor for the value. The `href` in the anchor is prefixed with `mailto:`. EmailCell will complain if the user enters a string that doesn't contain the `@` sign. @class Backgrid.EmailCell @extends Backgrid.StringCell */ var EmailCell = Backgrid.EmailCell = StringCell.extend({ /** @property */ className: "email-cell", formatter: EmailFormatter, render: function () { this.$el.empty(); var model = this.model; var formattedValue = this.formatter.fromRaw(model.get(this.column.get("name")), model); this.$el.append($("<a>", { tabIndex: -1, href: "mailto:" + formattedValue, title: formattedValue }).text(formattedValue)); this.delegateEvents(); return this; } }); /** NumberCell is a generic cell that renders all numbers. Numbers are formatted using a Backgrid.NumberFormatter. @class Backgrid.NumberCell @extends Backgrid.Cell */ var NumberCell = Backgrid.NumberCell = Cell.extend({ /** @property */ className: "number-cell", /** @property {number} [decimals=2] Must be an integer. */ decimals: NumberFormatter.prototype.defaults.decimals, /** @property {string} [decimalSeparator='.'] */ decimalSeparator: NumberFormatter.prototype.defaults.decimalSeparator, /** @property {string} [orderSeparator=','] */ orderSeparator: NumberFormatter.prototype.defaults.orderSeparator, /** @property {Backgrid.CellFormatter} [formatter=Backgrid.NumberFormatter] */ formatter: NumberFormatter, /** Initializes this cell and the number formatter. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column */ initialize: function (options) { NumberCell.__super__.initialize.apply(this, arguments); var formatter = this.formatter; formatter.decimals = this.decimals; formatter.decimalSeparator = this.decimalSeparator; formatter.orderSeparator = this.orderSeparator; } }); /** An IntegerCell is just a Backgrid.NumberCell with 0 decimals. If a floating point number is supplied, the number is simply rounded the usual way when displayed. @class Backgrid.IntegerCell @extends Backgrid.NumberCell */ var IntegerCell = Backgrid.IntegerCell = NumberCell.extend({ /** @property */ className: "integer-cell", /** @property {number} decimals Must be an integer. */ decimals: 0 }); /** A PercentCell is another Backgrid.NumberCell that takes a floating number, optionally multiplied by a multiplier and display it as a percentage. @class Backgrid.PercentCell @extends Backgrid.NumberCell */ var PercentCell = Backgrid.PercentCell = NumberCell.extend({ /** @property */ className: "percent-cell", /** @property {number} [multiplier=1] */ multiplier: PercentFormatter.prototype.defaults.multiplier, /** @property {string} [symbol='%'] */ symbol: PercentFormatter.prototype.defaults.symbol, /** @property {Backgrid.CellFormatter} [formatter=Backgrid.PercentFormatter] */ formatter: PercentFormatter, /** Initializes this cell and the percent formatter. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column */ initialize: function () { PercentCell.__super__.initialize.apply(this, arguments); var formatter = this.formatter; formatter.multiplier = this.multiplier; formatter.symbol = this.symbol; } }); /** DatetimeCell is a basic cell that accepts datetime string values in RFC-2822 or W3C's subset of ISO-8601 and displays them in ISO-8601 format. For a much more sophisticated date time cell with better datetime formatting, take a look at the Backgrid.Extension.MomentCell extension. @class Backgrid.DatetimeCell @extends Backgrid.Cell See: - Backgrid.Extension.MomentCell - Backgrid.DatetimeFormatter */ var DatetimeCell = Backgrid.DatetimeCell = Cell.extend({ /** @property */ className: "datetime-cell", /** @property {boolean} [includeDate=true] */ includeDate: DatetimeFormatter.prototype.defaults.includeDate, /** @property {boolean} [includeTime=true] */ includeTime: DatetimeFormatter.prototype.defaults.includeTime, /** @property {boolean} [includeMilli=false] */ includeMilli: DatetimeFormatter.prototype.defaults.includeMilli, /** @property {Backgrid.CellFormatter} [formatter=Backgrid.DatetimeFormatter] */ formatter: DatetimeFormatter, /** Initializes this cell and the datetime formatter. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column */ initialize: function (options) { DatetimeCell.__super__.initialize.apply(this, arguments); var formatter = this.formatter; formatter.includeDate = this.includeDate; formatter.includeTime = this.includeTime; formatter.includeMilli = this.includeMilli; var placeholder = this.includeDate ? "YYYY-MM-DD" : ""; placeholder += (this.includeDate && this.includeTime) ? "T" : ""; placeholder += this.includeTime ? "HH:mm:ss" : ""; placeholder += (this.includeTime && this.includeMilli) ? ".SSS" : ""; this.editor = this.editor.extend({ attributes: _.extend({}, this.editor.prototype.attributes, this.editor.attributes, { placeholder: placeholder }) }); } }); /** DateCell is a Backgrid.DatetimeCell without the time part. @class Backgrid.DateCell @extends Backgrid.DatetimeCell */ var DateCell = Backgrid.DateCell = DatetimeCell.extend({ /** @property */ className: "date-cell", /** @property */ includeTime: false }); /** TimeCell is a Backgrid.DatetimeCell without the date part. @class Backgrid.TimeCell @extends Backgrid.DatetimeCell */ var TimeCell = Backgrid.TimeCell = DatetimeCell.extend({ /** @property */ className: "time-cell", /** @property */ includeDate: false }); /** BooleanCellEditor renders a checkbox as its editor. @class Backgrid.BooleanCellEditor @extends Backgrid.CellEditor */ var BooleanCellEditor = Backgrid.BooleanCellEditor = CellEditor.extend({ /** @property */ tagName: "input", /** @property */ attributes: { tabIndex: -1, type: "checkbox" }, /** @property */ events: { "mousedown": function () { this.mouseDown = true; }, "blur": "enterOrExitEditMode", "mouseup": function () { this.mouseDown = false; }, "change": "saveOrCancel", "keydown": "saveOrCancel" }, /** Renders a checkbox and check it if the model value of this column is true, uncheck otherwise. */ render: function () { var model = this.model; var val = this.formatter.fromRaw(model.get(this.column.get("name")), model); this.$el.prop("checked", val); return this; }, /** Event handler. Hack to deal with the case where `blur` is fired before `change` and `click` on a checkbox. */ enterOrExitEditMode: function (e) { if (!this.mouseDown) { var model = this.model; model.trigger("backgrid:edited", model, this.column, new Command(e)); } }, /** Event handler. Save the value into the model if the event is `change` or one of the keyboard navigation key presses. Exit edit mode without saving if `escape` was pressed. */ saveOrCancel: function (e) { var model = this.model; var column = this.column; var formatter = this.formatter; var command = new Command(e); // skip ahead to `change` when space is pressed if (command.passThru() && e.type != "change") return true; if (command.cancel()) { e.stopPropagation(); model.trigger("backgrid:edited", model, column, command); } var $el = this.$el; if (command.save() || command.moveLeft() || command.moveRight() || command.moveUp() || command.moveDown()) { e.preventDefault(); e.stopPropagation(); var val = formatter.toRaw($el.prop("checked"), model); model.set(column.get("name"), val); model.trigger("backgrid:edited", model, column, command); } else if (e.type == "change") { var val = formatter.toRaw($el.prop("checked"), model); model.set(column.get("name"), val); $el.focus(); } } }); /** BooleanCell renders a checkbox both during display mode and edit mode. The checkbox is checked if the model value is true, unchecked otherwise. @class Backgrid.BooleanCell @extends Backgrid.Cell */ var BooleanCell = Backgrid.BooleanCell = Cell.extend({ /** @property */ className: "boolean-cell", /** @property */ editor: BooleanCellEditor, /** @property */ events: { "click": "enterEditMode" }, /** Renders a checkbox and check it if the model value of this column is true, uncheck otherwise. */ render: function () { this.$el.empty(); var model = this.model, column = this.column; var editable = Backgrid.callByNeed(column.editable(), column, model); this.$el.append($("<input>", { tabIndex: -1, type: "checkbox", checked: this.formatter.fromRaw(model.get(column.get("name")), model), disabled: !editable })); this.delegateEvents(); return this; } }); /** SelectCellEditor renders an HTML `<select>` fragment as the editor. @class Backgrid.SelectCellEditor @extends Backgrid.CellEditor */ var SelectCellEditor = Backgrid.SelectCellEditor = CellEditor.extend({ /** @property */ tagName: "select", /** @property */ events: { "change": "save", "blur": "close", "keydown": "close" }, /** @property {function(Object, ?Object=): string} template */ template: _.template('<option value="<%- value %>" <%= selected ? \'selected="selected"\' : "" %>><%- text %></option>', null, {variable: null}), setOptionValues: function (optionValues) { this.optionValues = optionValues; this.optionValues = _.result(this, "optionValues"); }, setMultiple: function (multiple) { this.multiple = multiple; this.$el.prop("multiple", multiple); }, _renderOptions: function (nvps, selectedValues) { var options = ''; for (var i = 0; i < nvps.length; i++) { options = options + this.template({ text: nvps[i][0], value: nvps[i][1], selected: _.indexOf(selectedValues, nvps[i][1]) > -1 }); } return options; }, /** Renders the options if `optionValues` is a list of name-value pairs. The options are contained inside option groups if `optionValues` is a list of object hashes. The name is rendered at the option text and the value is the option value. If `optionValues` is a function, it is called without a parameter. */ render: function () { this.$el.empty(); var optionValues = _.result(this, "optionValues"); var model = this.model; var selectedValues = this.formatter.fromRaw(model.get(this.column.get("name")), model); if (!_.isArray(optionValues)) throw new TypeError("optionValues must be an array"); var optionValue = null; var optionText = null; var optionValue = null; var optgroupName = null; var optgroup = null; for (var i = 0; i < optionValues.length; i++) { var optionValue = optionValues[i]; if (_.isArray(optionValue)) { optionText = optionValue[0]; optionValue = optionValue[1]; this.$el.append(this.template({ text: optionText, value: optionValue, selected: _.indexOf(selectedValues, optionValue) > -1 })); } else if (_.isObject(optionValue)) { optgroupName = optionValue.name; optgroup = $("<optgroup></optgroup>", { label: optgroupName }); optgroup.append(this._renderOptions.call(this, optionValue.values, selectedValues)); this.$el.append(optgroup); } else { throw new TypeError("optionValues elements must be a name-value pair or an object hash of { name: 'optgroup label', value: [option name-value pairs] }"); } } this.delegateEvents(); return this; }, /** Saves the value of the selected option to the model attribute. */ save: function (e) { var model = this.model; var column = this.column; model.set(column.get("name"), this.formatter.toRaw(this.$el.val(), model)); }, /** Triggers a `backgrid:edited` event from the model so the body can close this editor. */ close: function (e) { var model = this.model; var column = this.column; var command = new Command(e); if (command.cancel()) { e.stopPropagation(); model.trigger("backgrid:edited", model, column, new Command(e)); } else if (command.save() || command.moveLeft() || command.moveRight() || command.moveUp() || command.moveDown() || e.type == "blur") { e.preventDefault(); e.stopPropagation(); this.save(e); model.trigger("backgrid:edited", model, column, new Command(e)); } } }); /** SelectCell is also a different kind of cell in that upon going into edit mode the cell renders a list of options to pick from, as opposed to an input box. SelectCell cannot be referenced by its string name when used in a column definition because it requires an `optionValues` class attribute to be defined. `optionValues` can either be a list of name-value pairs, to be rendered as options, or a list of object hashes which consist of a key *name* which is the option group name, and a key *values* which is a list of name-value pairs to be rendered as options under that option group. In addition, `optionValues` can also be a parameter-less function that returns one of the above. If the options are static, it is recommended the returned values to be memoized. `_.memoize()` is a good function to help with that. During display mode, the default formatter will normalize the raw model value to an array of values whether the raw model value is a scalar or an array. Each value is compared with the `optionValues` values using Ecmascript's implicit type conversion rules. When exiting edit mode, no type conversion is performed when saving into the model. This behavior is not always desirable when the value type is anything other than string. To control type conversion on the client-side, you should subclass SelectCell to provide a custom formatter or provide the formatter to your column definition. See: [$.fn.val()](http://api.jquery.com/val/) @class Backgrid.SelectCell @extends Backgrid.Cell */ var SelectCell = Backgrid.SelectCell = Cell.extend({ /** @property */ className: "select-cell", /** @property */ editor: SelectCellEditor, /** @property */ multiple: false, /** @property */ formatter: SelectFormatter, /** @property {Array.<Array>|Array.<{name: string, values: Array.<Array>}>} optionValues */ optionValues: undefined, /** @property */ delimiter: ', ', /** Initializer. @param {Object} options @param {Backbone.Model} options.model @param {Backgrid.Column} options.column @throws {TypeError} If `optionsValues` is undefined. */ initialize: function (options) { SelectCell.__super__.initialize.apply(this, arguments); this.listenTo(this.model, "backgrid:edit", function (model, column, cell, editor) { if (column.get("name") == this.column.get("name")) { editor.setOptionValues(this.optionValues); editor.setMultiple(this.multiple); } }); }, /** Renders the label using the raw value as key to look up from `optionValues`. @throws {TypeError} If `optionValues` is malformed. */ render: function () { this.$el.empty(); var optionValues = _.result(this, "optionValues"); var model = this.model; var rawData = this.formatter.fromRaw(model.get(this.column.get("name")), model); var selectedText = []; try { if (!_.isArray(optionValues) || _.isEmpty(optionValues)) throw new TypeError; for (var k = 0; k < rawData.length; k++) { var rawDatum = rawData[k]; for (var i = 0; i < optionValues.length; i++) { var optionValue = optionValues[i]; if (_.isArray(optionValue)) { var optionText = optionValue[0]; var optionValue = optionValue[1]; if (optionValue == rawDatum) selectedText.push(optionText); } else if (_.isObject(optionValue)) { var optionGroupValues = optionValue.values; for (var j = 0; j < optionGroupValues.length; j++) { var optionGroupValue = optionGroupValues[j]; if (optionGroupValue[1] == rawDatum) { selectedText.push(optionGroupValue[0]); } } } else { throw new TypeError; } } } this.$el.append(selectedText.join(this.delimiter)); } catch (ex) { if (ex instanceof TypeError) { throw new TypeError("'optionValues' must be of type {Array.<Array>|Array.<{name: string, values: Array.<Array>}>}"); } throw ex; } this.delegateEvents(); return this; } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT license. */ /** A Column is a placeholder for column metadata. You usually don't need to create an instance of this class yourself as a collection of column instances will be created for you from a list of column attributes in the Backgrid.js view class constructors. @class Backgrid.Column @extends Backbone.Model */ var Column = Backgrid.Column = Backbone.Model.extend({ /** @cfg {Object} defaults Column defaults. To override any of these default values, you can either change the prototype directly to override Column.defaults globally or extend Column and supply the custom class to Backgrid.Grid: // Override Column defaults globally Column.prototype.defaults.sortable = false; // Override Column defaults locally var MyColumn = Column.extend({ defaults: _.defaults({ editable: false }, Column.prototype.defaults) }); var grid = new Backgrid.Grid(columns: new Columns([{...}, {...}], { model: MyColumn })); @cfg {string} [defaults.name] The default name of the model attribute. @cfg {string} [defaults.label] The default label to show in the header. @cfg {string|Backgrid.Cell} [defaults.cell] The default cell type. If this is a string, the capitalized form will be used to look up a cell class in Backbone, i.e.: string => StringCell. If a Cell subclass is supplied, it is initialized with a hash of parameters. If a Cell instance is supplied, it is used directly. @cfg {string|Backgrid.HeaderCell} [defaults.headerCell] The default header cell type. @cfg {boolean|string|function(): boolean} [defaults.sortable=true] Whether this column is sortable. If the value is a string, a method will the same name will be looked up from the column instance to determine whether the column should be sortable. The method's signature must be `function (Backgrid.Column, Backbone.Model): boolean`. @cfg {boolean|string|function(): boolean} [defaults.editable=true] Whether this column is editable. If the value is a string, a method will the same name will be looked up from the column instance to determine whether the column should be editable. The method's signature must be `function (Backgrid.Column, Backbone.Model): boolean`. @cfg {boolean|string|function(): boolean} [defaults.renderable=true] Whether this column is renderable. If the value is a string, a method will the same name will be looked up from the column instance to determine whether the column should be renderable. The method's signature must be `function (Backrid.Column, Backbone.Model): boolean`. @cfg {Backgrid.CellFormatter | Object | string} [defaults.formatter] The formatter to use to convert between raw model values and user input. @cfg {"toggle"|"cycle"} [defaults.sortType="cycle"] Whether sorting will toggle between ascending and descending order, or cycle between insertion order, ascending and descending order. @cfg {(function(Backbone.Model, string): *) | string} [defaults.sortValue] The function to use to extract a value from the model for comparison during sorting. If this value is a string, a method with the same name will be looked up from the column instance. @cfg {"ascending"|"descending"|null} [defaults.direction=null] The initial sorting direction for this column. The default is ordered by Backbone.Model.cid, which usually means the collection is ordered by insertion order. */ defaults: { name: undefined, label: undefined, sortable: true, editable: true, renderable: true, formatter: undefined, sortType: "cycle", sortValue: undefined, direction: null, cell: undefined, headerCell: undefined }, /** Initializes this Column instance. @param {Object} attrs @param {string} attrs.name The model attribute this column is responsible for. @param {string|Backgrid.Cell} attrs.cell The cell type to use to render this column. @param {string} [attrs.label] @param {string|Backgrid.HeaderCell} [attrs.headerCell] @param {boolean|string|function(): boolean} [attrs.sortable=true] @param {boolean|string|function(): boolean} [attrs.editable=true] @param {boolean|string|function(): boolean} [attrs.renderable=true] @param {Backgrid.CellFormatter | Object | string} [attrs.formatter] @param {"toggle"|"cycle"} [attrs.sortType="cycle"] @param {(function(Backbone.Model, string): *) | string} [attrs.sortValue] @throws {TypeError} If attrs.cell or attrs.options are not supplied. @throws {ReferenceError} If formatter is a string but a formatter class of said name cannot be found in the Backgrid module. See: - Backgrid.Column.defaults - Backgrid.Cell - Backgrid.CellFormatter */ initialize: function () { if (!this.has("label")) { this.set({ label: this.get("name") }, { silent: true }); } var headerCell = Backgrid.resolveNameToClass(this.get("headerCell"), "HeaderCell"); var cell = Backgrid.resolveNameToClass(this.get("cell"), "Cell"); this.set({cell: cell, headerCell: headerCell}, { silent: true }); }, /** Returns an appropriate value extraction function from a model for sorting. If the column model contains an attribute `sortValue`, if it is a string, a method from the column instance identifified by the `sortValue` string is returned. If it is a function, it it returned as is. If `sortValue` isn't found from the column model's attributes, a default value extraction function is returned which will compare according to the natural order of the value's type. @return {function(Backbone.Model, string): *} */ sortValue: function () { var sortValue = this.get("sortValue"); if (_.isString(sortValue)) return this[sortValue]; else if (_.isFunction(sortValue)) return sortValue; return function (model, colName) { return model.get(colName); }; } /** @member Backgrid.Column @protected @method sortable @return {function(Backgrid.Column, Backbone.Model): boolean | boolean} */ /** @member Backgrid.Column @protected @method editable @return {function(Backgrid.Column, Backbone.Model): boolean | boolean} */ /** @member Backgrid.Column @protected @method renderable @return {function(Backgrid.Column, Backbone.Model): boolean | boolean} */ }); _.each(["sortable", "renderable", "editable"], function (key) { Column.prototype[key] = function () { var value = this.get(key); if (_.isString(value)) return this[value]; else if (_.isFunction(value)) return value; return !!value; }; }); /** A Backbone collection of Column instances. @class Backgrid.Columns @extends Backbone.Collection */ var Columns = Backgrid.Columns = Backbone.Collection.extend({ /** @property {Backgrid.Column} model */ model: Column }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT license. */ /** Row is a simple container view that takes a model instance and a list of column metadata describing how each of the model's attribute is to be rendered, and apply the appropriate cell to each attribute. @class Backgrid.Row @extends Backbone.View */ var Row = Backgrid.Row = Backbone.View.extend({ /** @property */ tagName: "tr", /** Initializes a row view instance. @param {Object} options @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Model} options.model The model instance to render. @throws {TypeError} If options.columns or options.model is undefined. */ initialize: function (options) { var columns = this.columns = options.columns; if (!(columns instanceof Backbone.Collection)) { columns = this.columns = new Columns(columns); } var cells = this.cells = []; for (var i = 0; i < columns.length; i++) { cells.push(this.makeCell(columns.at(i), options)); } this.listenTo(columns, "add", function (column, columns) { var i = columns.indexOf(column); var cell = this.makeCell(column, options); cells.splice(i, 0, cell); var $el = this.$el; if (i === 0) { $el.prepend(cell.render().$el); } else if (i === columns.length - 1) { $el.append(cell.render().$el); } else { $el.children().eq(i).before(cell.render().$el); } }); this.listenTo(columns, "remove", function (column, columns, opts) { cells[opts.index].remove(); cells.splice(opts.index, 1); }); }, /** Factory method for making a cell. Used by #initialize internally. Override this to provide an appropriate cell instance for a custom Row subclass. @protected @param {Backgrid.Column} column @param {Object} options The options passed to #initialize. @return {Backgrid.Cell} */ makeCell: function (column) { return new (column.get("cell"))({ column: column, model: this.model }); }, /** Renders a row of cells for this row's model. */ render: function () { this.$el.empty(); var fragment = document.createDocumentFragment(); for (var i = 0; i < this.cells.length; i++) { fragment.appendChild(this.cells[i].render().el); } this.el.appendChild(fragment); this.delegateEvents(); return this; }, /** Clean up this row and its cells. @chainable */ remove: function () { for (var i = 0; i < this.cells.length; i++) { var cell = this.cells[i]; cell.remove.apply(cell, arguments); } return Backbone.View.prototype.remove.apply(this, arguments); } }); /** EmptyRow is a simple container view that takes a list of column and render a row with a single column. @class Backgrid.EmptyRow @extends Backbone.View */ var EmptyRow = Backgrid.EmptyRow = Backbone.View.extend({ /** @property */ tagName: "tr", /** @property {string|function(): string} */ emptyText: null, /** Initializer. @param {Object} options @param {string|function(): string} options.emptyText @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. */ initialize: function (options) { this.emptyText = options.emptyText; this.columns = options.columns; }, /** Renders an empty row. */ render: function () { this.$el.empty(); var td = document.createElement("td"); td.setAttribute("colspan", this.columns.length); td.appendChild(document.createTextNode(_.result(this, "emptyText"))); this.el.className = "empty"; this.el.appendChild(td); return this; } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT license. */ /** HeaderCell is a special cell class that renders a column header cell. If the column is sortable, a sorter is also rendered and will trigger a table refresh after sorting. @class Backgrid.HeaderCell @extends Backbone.View */ var HeaderCell = Backgrid.HeaderCell = Backbone.View.extend({ /** @property */ tagName: "th", /** @property */ events: { "click a": "onClick" }, /** Initializer. @param {Object} options @param {Backgrid.Column|Object} options.column @throws {TypeError} If options.column or options.collection is undefined. */ initialize: function (options) { this.column = options.column; if (!(this.column instanceof Column)) { this.column = new Column(this.column); } var column = this.column, collection = this.collection, $el = this.$el; this.listenTo(column, "change:editable change:sortable change:renderable", function (column) { var changed = column.changedAttributes(); for (var key in changed) { if (changed.hasOwnProperty(key)) { $el.toggleClass(key, changed[key]); } } }); this.listenTo(column, "change:direction", this.setCellDirection); this.listenTo(column, "change:name change:label", this.render); if (Backgrid.callByNeed(column.editable(), column, collection)) $el.addClass("editable"); if (Backgrid.callByNeed(column.sortable(), column, collection)) $el.addClass("sortable"); if (Backgrid.callByNeed(column.renderable(), column, collection)) $el.addClass("renderable"); this.listenTo(collection.fullCollection || collection, "sort", this.removeCellDirection); }, /** Event handler for the collection's `sort` event. Removes all the CSS direction classes. */ removeCellDirection: function () { this.$el.removeClass("ascending").removeClass("descending"); this.column.set("direction", null); }, /** Event handler for the column's `change:direction` event. If this HeaderCell's column is being sorted on, it applies the direction given as a CSS class to the header cell. Removes all the CSS direction classes otherwise. */ setCellDirection: function (column, direction) { this.$el.removeClass("ascending").removeClass("descending"); if (column.cid == this.column.cid) this.$el.addClass(direction); }, /** Event handler for the `click` event on the cell's anchor. If the column is sortable, clicking on the anchor will cycle through 3 sorting orderings - `ascending`, `descending`, and default. */ onClick: function (e) { e.preventDefault(); var column = this.column; var collection = this.collection; var event = "backgrid:sort"; function cycleSort(header, col) { if (column.get("direction") === "ascending") collection.trigger(event, col, null); else if (column.get("direction") === "descending") collection.trigger(event, col, "ascending"); else collection.trigger(event, col, "descending"); } function toggleSort(header, col) { if (column.get("direction") === "descending") collection.trigger(event, col, "ascending"); else collection.trigger(event, col, "descending"); } var sortable = Backgrid.callByNeed(column.sortable(), column, this.collection); if (sortable) { var sortType = column.get("sortType"); if (sortType === "toggle") toggleSort(this, column); else cycleSort(this, column); } }, /** Renders a header cell with a sorter, a label, and a class name for this column. */ render: function () { this.$el.empty(); var column = this.column; var sortable = Backgrid.callByNeed(column.sortable(), column, this.collection); var label; if(sortable){ label = $("<a>").text(column.get("label")).append("<b class='sort-caret'></b>"); } else { label = document.createTextNode(column.get("label")); } this.$el.append(label); this.$el.addClass(column.get("name")); this.$el.addClass(column.get("direction")); this.delegateEvents(); return this; } }); /** HeaderRow is a controller for a row of header cells. @class Backgrid.HeaderRow @extends Backgrid.Row */ var HeaderRow = Backgrid.HeaderRow = Backgrid.Row.extend({ /** Initializer. @param {Object} options @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns @param {Backgrid.HeaderCell} [options.headerCell] Customized default HeaderCell for all the columns. Supply a HeaderCell class or instance to a the `headerCell` key in a column definition for column-specific header rendering. @throws {TypeError} If options.columns or options.collection is undefined. */ initialize: function () { Backgrid.Row.prototype.initialize.apply(this, arguments); }, makeCell: function (column, options) { var headerCell = column.get("headerCell") || options.headerCell || HeaderCell; headerCell = new headerCell({ column: column, collection: this.collection }); return headerCell; } }); /** Header is a special structural view class that renders a table head with a single row of header cells. @class Backgrid.Header @extends Backbone.View */ var Header = Backgrid.Header = Backbone.View.extend({ /** @property */ tagName: "thead", /** Initializer. Initializes this table head view to contain a single header row view. @param {Object} options @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Model} options.model The model instance to render. @throws {TypeError} If options.columns or options.model is undefined. */ initialize: function (options) { this.columns = options.columns; if (!(this.columns instanceof Backbone.Collection)) { this.columns = new Columns(this.columns); } this.row = new Backgrid.HeaderRow({ columns: this.columns, collection: this.collection }); }, /** Renders this table head with a single row of header cells. */ render: function () { this.$el.append(this.row.render().$el); this.delegateEvents(); return this; }, /** Clean up this header and its row. @chainable */ remove: function () { this.row.remove.apply(this.row, arguments); return Backbone.View.prototype.remove.apply(this, arguments); } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT license. */ /** Body is the table body which contains the rows inside a table. Body is responsible for refreshing the rows after sorting, insertion and removal. @class Backgrid.Body @extends Backbone.View */ var Body = Backgrid.Body = Backbone.View.extend({ /** @property */ tagName: "tbody", /** Initializer. @param {Object} options @param {Backbone.Collection} options.collection @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backgrid.Row} [options.row=Backgrid.Row] The Row class to use. @param {string|function(): string} [options.emptyText] The text to display in the empty row. @throws {TypeError} If options.columns or options.collection is undefined. See Backgrid.Row. */ initialize: function (options) { this.columns = options.columns; if (!(this.columns instanceof Backbone.Collection)) { this.columns = new Columns(this.columns); } this.row = options.row || Row; this.rows = this.collection.map(function (model) { var row = new this.row({ columns: this.columns, model: model }); return row; }, this); this.emptyText = options.emptyText; this._unshiftEmptyRowMayBe(); var collection = this.collection; this.listenTo(collection, "add", this.insertRow); this.listenTo(collection, "remove", this.removeRow); this.listenTo(collection, "sort", this.refresh); this.listenTo(collection, "reset", this.refresh); this.listenTo(collection, "backgrid:sort", this.sort); this.listenTo(collection, "backgrid:edited", this.moveToNextCell); }, _unshiftEmptyRowMayBe: function () { if (this.rows.length === 0 && this.emptyText != null) { this.rows.unshift(new EmptyRow({ emptyText: this.emptyText, columns: this.columns })); return true; } }, /** This method can be called either directly or as a callback to a [Backbone.Collecton#add](http://backbonejs.org/#Collection-add) event. When called directly, it accepts a model or an array of models and an option hash just like [Backbone.Collection#add](http://backbonejs.org/#Collection-add) and delegates to it. Once the model is added, a new row is inserted into the body and automatically rendered. When called as a callback of an `add` event, splices a new row into the body and renders it. @param {Backbone.Model} model The model to render as a row. @param {Backbone.Collection} collection When called directly, this parameter is actually the options to [Backbone.Collection#add](http://backbonejs.org/#Collection-add). @param {Object} options When called directly, this must be null. See: - [Backbone.Collection#add](http://backbonejs.org/#Collection-add) */ insertRow: function (model, collection, options) { if (this.rows[0] instanceof EmptyRow) this.rows.pop().remove(); // insertRow() is called directly if (!(collection instanceof Backbone.Collection) && !options) { this.collection.add(model, (options = collection)); return; } var row = new this.row({ columns: this.columns, model: model }); var index = collection.indexOf(model); this.rows.splice(index, 0, row); var $el = this.$el; var $children = $el.children(); var $rowEl = row.render().$el; if (index >= $children.length) { $el.append($rowEl); } else { $children.eq(index).before($rowEl); } return this; }, /** The method can be called either directly or as a callback to a [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove) event. When called directly, it accepts a model or an array of models and an option hash just like [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove) and delegates to it. Once the model is removed, a corresponding row is removed from the body. When called as a callback of a `remove` event, splices into the rows and removes the row responsible for rendering the model. @param {Backbone.Model} model The model to remove from the body. @param {Backbone.Collection} collection When called directly, this parameter is actually the options to [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove). @param {Object} options When called directly, this must be null. See: - [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove) */ removeRow: function (model, collection, options) { // removeRow() is called directly if (!options) { this.collection.remove(model, (options = collection)); if (this._unshiftEmptyRowMayBe()) { this.render(); } return; } if (_.isUndefined(options.render) || options.render) { this.rows[options.index].remove(); } this.rows.splice(options.index, 1); if (this._unshiftEmptyRowMayBe()) { this.render(); } return this; }, /** Reinitialize all the rows inside the body and re-render them. Triggers a Backbone `backgrid:refresh` event from the collection along with the body instance as its sole parameter when done. */ refresh: function () { for (var i = 0; i < this.rows.length; i++) { this.rows[i].remove(); } this.rows = this.collection.map(function (model) { var row = new this.row({ columns: this.columns, model: model }); return row; }, this); this._unshiftEmptyRowMayBe(); this.render(); this.collection.trigger("backgrid:refresh", this); return this; }, /** Renders all the rows inside this body. If the collection is empty and `options.emptyText` is defined and not null in the constructor, an empty row is rendered, otherwise no row is rendered. */ render: function () { this.$el.empty(); var fragment = document.createDocumentFragment(); for (var i = 0; i < this.rows.length; i++) { var row = this.rows[i]; fragment.appendChild(row.render().el); } this.el.appendChild(fragment); this.delegateEvents(); return this; }, /** Clean up this body and it's rows. @chainable */ remove: function () { for (var i = 0; i < this.rows.length; i++) { var row = this.rows[i]; row.remove.apply(row, arguments); } return Backbone.View.prototype.remove.apply(this, arguments); }, /** If the underlying collection is a Backbone.PageableCollection in server-mode or infinite-mode, a page of models is fetched after sorting is done on the server. If the underlying collection is a Backbone.PageableCollection in client-mode, or any [Backbone.Collection](http://backbonejs.org/#Collection) instance, sorting is done on the client side. If the collection is an instance of a Backbone.PageableCollection, sorting will be done globally on all the pages and the current page will then be returned. Triggers a Backbone `backgrid:sorted` event from the collection when done with the column, direction and a reference to the collection. @param {Backgrid.Column|string} column @param {null|"ascending"|"descending"} direction See [Backbone.Collection#comparator](http://backbonejs.org/#Collection-comparator) */ sort: function (column, direction) { if (!_.contains(["ascending", "descending", null], direction)) { throw new RangeError('direction must be one of "ascending", "descending" or `null`'); } if (_.isString(column)) column = this.columns.findWhere({name: column}); var collection = this.collection; var order; if (direction === "ascending") order = -1; else if (direction === "descending") order = 1; else order = null; var comparator = this.makeComparator(column.get("name"), order, order ? column.sortValue() : function (model) { return model.cid.replace('c', '') * 1; }); if (collection.pageableCollection) { collection = collection.pageableCollection; } if (Backbone.PageableCollection && collection instanceof Backbone.PageableCollection) { collection.setSorting(order && column.get("name"), order, {sortValue: column.sortValue()}); if (collection.fullCollection && collection.mode == 'client') { // If order is null, pageable will remove the comparator on both sides, // in this case the default insertion order comparator needs to be // attached to get back to the order before sorting. if (collection.fullCollection.comparator == null) { collection.fullCollection.comparator = comparator; } collection.fullCollection.sort(); collection.trigger("backgrid:sorted", column, direction, collection); } else { //fire cool event collection.trigger("backgrid:willsort", column, direction, collection); //reset the fullCollection as we start from scratch if(collection.fullCollection) { collection.fullCollection.reset(); } //start from the first page again collection.state.currentPage = collection.state.firstPage; //clear the next links cache for(var i = collection.state.firstPage + 1; collection.links[i] != undefined; i++) { collection.links[i] = undefined; } collection.fetch({reset: true, success: function () { collection.trigger("backgrid:sorted", column, direction, collection); }}); } } else { collection.comparator = comparator; collection.sort(); collection.trigger("backgrid:sorted", column, direction, collection); } column.set("direction", direction); return this; }, makeComparator: function (attr, order, func) { return function (left, right) { // extract the values from the models var l = func(left, attr), r = func(right, attr), t; // if descending order, swap left and right if (order === 1) t = l, l = r, r = t; // compare as usual if (l === r) return 0; else if (l < r) return -1; return 1; }; }, /** Moves focus to the next renderable and editable cell and return the currently editing cell to display mode. Triggers a `backgrid:next` event on the model with the indices of the row and column the user *intended* to move to, and whether the intended move was going to go out of bounds. Note that *out of bound* always means an attempt to go past the end of the last row. @param {Backbone.Model} model The originating model @param {Backgrid.Column} column The originating model column @param {Backgrid.Command} command The Command object constructed from a DOM event */ moveToNextCell: function (model, column, command) { var i = this.collection.indexOf(model); var j = this.columns.indexOf(column); var cell, renderable, editable, m, n; // return if model being edited in a different grid if (j === -1) return this; this.rows[i].cells[j].exitEditMode(); if (command.moveUp() || command.moveDown() || command.moveLeft() || command.moveRight() || command.save()) { var l = this.columns.length; var maxOffset = l * this.collection.length; if (command.moveUp() || command.moveDown()) { m = i + (command.moveUp() ? -1 : 1); var row = this.rows[m]; if (row) { cell = row.cells[j]; if (Backgrid.callByNeed(cell.column.editable(), cell.column, model)) { cell.enterEditMode(); model.trigger("backgrid:next", m, j, false); } } else model.trigger("backgrid:next", m, j, true); } else if (command.moveLeft() || command.moveRight()) { var right = command.moveRight(); for (var offset = i * l + j + (right ? 1 : -1); offset >= 0 && offset < maxOffset; right ? offset++ : offset--) { m = ~~(offset / l); n = offset - m * l; cell = this.rows[m].cells[n]; renderable = Backgrid.callByNeed(cell.column.renderable(), cell.column, cell.model); editable = Backgrid.callByNeed(cell.column.editable(), cell.column, model); if (renderable && editable) { cell.enterEditMode(); model.trigger("backgrid:next", m, n, false); break; } } if (offset == maxOffset) { model.trigger("backgrid:next", ~~(offset / l), offset - m * l, true); } } } return this; } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT license. */ /** A Footer is a generic class that only defines a default tag `tfoot` and number of required parameters in the initializer. @abstract @class Backgrid.Footer @extends Backbone.View */ var Footer = Backgrid.Footer = Backbone.View.extend({ /** @property */ tagName: "tfoot", /** Initializer. @param {Object} options @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Collection} options.collection @throws {TypeError} If options.columns or options.collection is undefined. */ initialize: function (options) { this.columns = options.columns; if (!(this.columns instanceof Backbone.Collection)) { this.columns = new Backgrid.Columns(this.columns); } } }); /* backgrid http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT license. */ /** Grid represents a data grid that has a header, body and an optional footer. By default, a Grid treats each model in a collection as a row, and each attribute in a model as a column. To render a grid you must provide a list of column metadata and a collection to the Grid constructor. Just like any Backbone.View class, the grid is rendered as a DOM node fragment when you call render(). var grid = Backgrid.Grid({ columns: [{ name: "id", label: "ID", type: "string" }, // ... ], collections: books }); $("#table-container").append(grid.render().el); Optionally, if you want to customize the rendering of the grid's header and footer, you may choose to extend Backgrid.Header and Backgrid.Footer, and then supply that class or an instance of that class to the Grid constructor. See the documentation for Header and Footer for further details. var grid = Backgrid.Grid({ columns: [{ name: "id", label: "ID", type: "string" }], collections: books, header: Backgrid.Header.extend({ //... }), footer: Backgrid.Paginator }); Finally, if you want to override how the rows are rendered in the table body, you can supply a Body subclass as the `body` attribute that uses a different Row class. @class Backgrid.Grid @extends Backbone.View See: - Backgrid.Column - Backgrid.Header - Backgrid.Body - Backgrid.Row - Backgrid.Footer */ var Grid = Backgrid.Grid = Backbone.View.extend({ /** @property */ tagName: "table", /** @property */ className: "backgrid", /** @property */ header: Header, /** @property */ body: Body, /** @property */ footer: null, /** Initializes a Grid instance. @param {Object} options @param {Backbone.Collection.<Backgrid.Columns>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata. @param {Backbone.Collection} options.collection The collection of tabular model data to display. @param {Backgrid.Header} [options.header=Backgrid.Header] An optional Header class to override the default. @param {Backgrid.Body} [options.body=Backgrid.Body] An optional Body class to override the default. @param {Backgrid.Row} [options.row=Backgrid.Row] An optional Row class to override the default. @param {Backgrid.Footer} [options.footer=Backgrid.Footer] An optional Footer class. */ initialize: function (options) { // Convert the list of column objects here first so the subviews don't have // to. if (!(options.columns instanceof Backbone.Collection)) { options.columns = new Columns(options.columns || this.columns); } this.columns = options.columns; var filteredOptions = _.omit(options, ["el", "id", "attributes", "className", "tagName", "events"]); // must construct body first so it listens to backgrid:sort first this.body = options.body || this.body; this.body = new this.body(filteredOptions); this.header = options.header || this.header; if (this.header) { this.header = new this.header(filteredOptions); } this.footer = options.footer || this.footer; if (this.footer) { this.footer = new this.footer(filteredOptions); } this.listenTo(this.columns, "reset", function () { if (this.header) { this.header = new (this.header.remove().constructor)(filteredOptions); } this.body = new (this.body.remove().constructor)(filteredOptions); if (this.footer) { this.footer = new (this.footer.remove().constructor)(filteredOptions); } this.render(); }); }, /** Delegates to Backgrid.Body#insertRow. */ insertRow: function () { this.body.insertRow.apply(this.body, arguments); return this; }, /** Delegates to Backgrid.Body#removeRow. */ removeRow: function () { this.body.removeRow.apply(this.body, arguments); return this; }, /** Delegates to Backgrid.Columns#add for adding a column. Subviews can listen to the `add` event from their internal `columns` if rerendering needs to happen. @param {Object} [options] Options for `Backgrid.Columns#add`. */ insertColumn: function () { this.columns.add.apply(this.columns, arguments); return this; }, /** Delegates to Backgrid.Columns#remove for removing a column. Subviews can listen to the `remove` event from the internal `columns` if rerendering needs to happen. @param {Object} [options] Options for `Backgrid.Columns#remove`. */ removeColumn: function () { this.columns.remove.apply(this.columns, arguments); return this; }, /** Delegates to Backgrid.Body#sort. */ sort: function () { this.body.sort.apply(this.body, arguments); return this; }, /** Renders the grid's header, then footer, then finally the body. Triggers a Backbone `backgrid:rendered` event along with a reference to the grid when the it has successfully been rendered. */ render: function () { this.$el.empty(); if (this.header) { this.$el.append(this.header.render().$el); } if (this.footer) { this.$el.append(this.footer.render().$el); } this.$el.append(this.body.render().$el); this.delegateEvents(); this.trigger("backgrid:rendered", this); return this; }, /** Clean up this grid and its subviews. @chainable */ remove: function () { this.header && this.header.remove.apply(this.header, arguments); this.body.remove.apply(this.body, arguments); this.footer && this.footer.remove.apply(this.footer, arguments); return Backbone.View.prototype.remove.apply(this, arguments); } }); return Backgrid; }));
/** * TPBC keyboard support for image navigation. */ ( function( $ ) { $( document ).on( 'keydown.tpbc', function( e ) { var url = false; // Left arrow key code. if ( 37 === e.which ) { url = $( '.nav-previous a' ).attr( 'href' ); // Right arrow key code. } else if ( 39 === e.which ) { url = $( '.nav-next a' ).attr( 'href' ); // Other key code. } else { return; } if ( url && ! $( 'textarea, input' ).is( ':focus' ) ) { window.location = url; } } ); } )( jQuery );
// The MIT License (MIT) // Copyright (c) 2016 Derek Breen, breenworks@gmail.com //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 (ext) { var Nouns = { "Fruit": ["Apples", "Bananas", "Oranges"], "Animals": ["Cat", "Dog", "Monkey"], "Countries": ["England", "Ireland", "Scotland"] }; ext.getRandomWord = function (nounList) { // Get noun list requested // return random value from array list return Nouns.nounList[Math.floor(Math.Random(Nouns.nounList.length))]; }; ext.getRandomValue = function (min, max) { return Math.floor((Math.random() * max) + min); }; // Block and block menu descriptions var descriptor = { blocks: [ ['r', 'get random noun from list %m.nouns', getRandomWord, 'Fruit'] ], menus: { nouns: ['Fruit', 'Animals', 'Countries'] }, url: 'http://derekbreen.com/scratchlinks' }; // Cleanup function when the extension is unloaded ext._shutdown = function () { }; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function () { return { status: 2, msg: 'Connected' }; }; ext.Disconnect = function (callback) { }; // Register the extension ScratchExtensions.register('Derek Extension', descriptor, ext); })({});
'use strict' const expressDeliver = require('..') const expect = require('chai').expect const express = require('express') const request = require('supertest') const ExceptionPool = expressDeliver.ExceptionPool function testApp(app,endpoint,statusCode,body,done){ let test = function(err,res){ expect(res.status).to.be.equal(statusCode) expect(res.body).to.be.deep.equal(body) done() } request(app).get(endpoint).end(test) } function getApp(routes){ let app = express() expressDeliver(app,{ exceptionPool: new ExceptionPool({ CustomFromApp:{ code:4000, message:'Message from app' } }) }) app.get('/',function*(){ return 'hi from app' }) app.get('/error-app',function*(req,res){ throw new res.exception.CustomFromApp() }) if (routes) routes(app) expressDeliver.errorHandler(app) return app } function getRouterA(){ let router = express.Router() expressDeliver(router,{ exceptionPool: new ExceptionPool({ CustomFromRouterA:{ code:4001, message:'Message from router A' } }) }) router.get('/',function*(){ return 'hi from router a' }) router.get('/error-a',function*(req,res){ throw new res.exception.CustomFromRouterA() }) router.get('/error-app',function*(req,res){ throw new res.exception.CustomFromApp() }) return router } function getRouterB(){ let router = express.Router() expressDeliver(router,{ exceptionPool: new ExceptionPool({ CustomFromRouterB:{ code:4003, message:'Message from router B' } }) }) router.get('/error-a',function*(req,res){ throw new res.exception.CustomFromRouterA() }) router.get('/error-app',function*(req,res){ throw new res.exception.CustomFromApp() }) router.get('/error-b',function*(req,res){ throw new res.exception.CustomFromRouterB() }) return router } describe('nested apps',()=>{ it('should respond from app',(done)=>{ let app = getApp() testApp(app,'/',200,{ status:true, data:'hi from app' },done) }) it('should respond from router',(done)=>{ let app = getApp(app=>{ app.use('/a',getRouterA()) }) testApp(app,'/a',200,{ status:true, data:'hi from router a' },done) }) it('should respond app-error from app',(done)=>{ let app = getApp() testApp(app,'/error-app',500,{ status:false, error:{ code:4000, message:'Message from app' } },done) }) it('should respond app-error from router',(done)=>{ let app = getApp(app=>{ app.use('/a',getRouterA()) }) testApp(app,'/a/error-app',500,{ status:false, error:{ code:4000, message:'Message from app' } },done) }) it('should respond app-error from router',(done)=>{ let app = getApp(app=>{ app.use('/a',getRouterA()) }) testApp(app,'/a/error-app',500,{ status:false, error:{ code:4000, message:'Message from app' } },done) }) it('should respond router-error from router',(done)=>{ let app = getApp(app=>{ app.use('/a',getRouterA()) }) testApp(app,'/a/error-a',500,{ status:false, error:{ code:4001, message:'Message from router A' } },done) }) it('should fail responding router-error-a from router-b',(done)=>{ let app = getApp(app=>{ app.use('/b',getRouterB()) }) testApp(app,'/b/error-a',500,{ status:false, error:{ code:1000, message:'Internal error' } },done) }) it('should respond router-error-b from nested router-b',(done)=>{ let app = getApp(app=>{ let routerA = getRouterA() routerA.use('/b',getRouterB()) app.use('/a',routerA) }) testApp(app,'/a/b/error-b',500,{ status:false, error:{ code:4003, message:'Message from router B' } },done) }) it('should respond router-error-a from nested router-b',(done)=>{ let app = getApp(app=>{ let routerA = getRouterA() routerA.use('/b',getRouterB()) app.use('/a',routerA) }) testApp(app,'/a/b/error-a',500,{ status:false, error:{ code:4001, message:'Message from router A' } },done) }) it('should use pool cache',(done)=>{ let app = getApp() testApp(app,'/',200,{ status:true, data:'hi from app' },()=>{ testApp(app,'/',200,{ status:true, data:'hi from app' },done) }) }) })
import Ember from "ember"; import OperisPpfateststeptypeController from 'ember-app/controllers/operis-ppfa-test-step-type'; var PpfateststeptypeController = OperisPpfateststeptypeController.extend({ actions: { delete: function( item ) { Ember.Logger.info('Item is:', item); item.on('didDelete', this, function () { this.transitionToRoute('ppfa-test-step-types.index', {queryParams: {page: 1}}); }); item.destroyRecord(); } } }); export default PpfateststeptypeController;
require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({"./lang/ro":[function(require,module,exports){ module.exports = { accepted: ':attribute trebuie acceptat.', after: ':attribute trebuie să fie după :after.', after_or_equal: ':attribute trebuie să fie egal sau după :after_or_equal.', alpha: 'Câmpul :attribute rebuie să conțină numai caractere alfabetice.', alpha_dash: 'Câmpul:attribute poate conține numai caractere alfanumerice, precum și liniuțe și subliniere.', alpha_num: 'Câmpul :attribute trebuie să fie alfanumeric.', before: ':attribute trebuie să fie înainte :before.', before_or_equal: ':attribute trebuie să fie egal sau înainte :before_or_equal.', between: ':attribute trebuie să fie între :min și :max.', confirmed: 'Confirmarea :attribute nu se potrivește.', email: 'Formatul :attribute nu este valid.', date: ':attribute nu este un format de dată valid.', def: 'Atributul :attribute are erori.', digits: ':attribute trebuie să aibă :digits cifre.', digits_between: 'Câmpul :attribute trebuie să aibă între :min și :max cifre.', different: ':attribute și :different trebuie sa fie diferite.', in: 'Atributul selectat :attribute nu este valid.', integer: ':attribute trebuie să fie un număr întreg.', hex: 'Câmpul :attribute trebuie să aibă format hexazecimal.', min: { numeric: ':attribute trebuie să fie mai mare de :min.', string: ':attribute trebuie să contină cel puțin :min caractere.' }, max: { numeric: ':attribute nu trebuie să fie mai mare de :max.', string: ':attribute poate să contină maxim :max caractere.' }, not_in: ':attribute selectat nu este valid.', numeric: ':attribute trebuie sa fie un număr.', present: ':attribute trebuie sa fie prezent(dar poate fi gol).', required: ' Câmpul :attribute este obligatoriu.', required_if: 'Câmpul :attribute este obligatoriu cănd :other este :value.', required_unless: 'Câmpul :attribute este obligatoriu cănd :other nu este :value.', required_with: 'Câmpul :attribute este obligatoriu cănd :field este completat.', required_with_all: 'Câmpul :attribute este obligatoriu cănd :fields sunt completate.', required_without: 'Câmpul :attribute este obligatoriu cănd :field nu este completat.', required_without_all: 'Câmpul :attribute este obligatoriu cănd :fields nu sunt completate.', same: 'Câmpurile :attribute și :same trebuie să fie egale.', size: { numeric: ':attribute trebuie să fie :size.', string: ':attribute trebuie să contina :size caractere.' }, string: ':attribute trebuie să fie un contina doar caractere alfabetice.', url: 'Formatul :attribute nu este valid.', regex: 'Formatul :attribute nu este valid.', attributes: {} }; },{}]},{},[]);
var J = require('JSUS').JSUS; module.exports = function(settings, headers) { /*var coins = settings.pp.COINS; var values = [ Math.floor(coins/2, 10), coins, 0 ];*/ return { "x": 0, "title": "Quiz",/* "beforeStarting": "Before starting the game answer the following questions:", "Q": "Q", "howManyCoins": "How many coins will you divide with your partner?", "vals": J.shuffle(values), "ifYouAreTheBidder": "If you are a bidder what happens if your partner reject your offer?", "howMuchYouGet": [ "He does not get anything, I keep my share.", "I get everything.", "He gets what I offered, I get nothing.", "Both get nothing." ], "considerTheFollowing": "Consider the following scenario. Four players (A,B,C,D) are playing. B disconnects for more than " + settings.pp.WAIT_TIME + " seconds, and the game is terminated. What happens then?", "disconnect": [ "A,C,D are paid only the show up fee. B is not paid at all.", "A,C,D are paid the show up fee plus the bonus collected so far. B is paid only the show up fee.", "A,C,D are paid the show up fee plus the bonus collected so far. B is not paid at all.", "All players are paid only the show up fee.", "All players are paid the show up fee and the bonus collected so far." ], "clickHere": "Click here to check your answers, and start the game.", "correctAnswers": "Correct Answers:"*/ }; };
'use strict'; angular.module('app') .controller('MainController', function($scope, $log, DeckService, PlayerService, BoardService, GameService) { $scope.title = 'Flash Duel'; $scope.game = GameService; BoardService.reset(); $scope.board = BoardService.board; $scope.players = PlayerService.players; $scope.numCardsRemaining = function numCardsRemaining() { return DeckService.deck.length; }; $scope.discardPile = function discardPile() { return DeckService.discardPile; }; });
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { Component, Input, HostListener } from '@angular/core'; import './user-component.css'; export let UserComponent = class UserComponent { over() { this.popOver = true; } out() { setTimeout(() => this.popOver = false, 2000); } callUser() { this.winRef.nativeWindow.mainrtc.UI.userCall(this.user.name); } }; __decorate([ Input(), __metadata('design:type', Object) ], UserComponent.prototype, "winRef", void 0); __decorate([ HostListener('mouseover'), __metadata('design:type', Function), __metadata('design:paramtypes', []), __metadata('design:returntype', void 0) ], UserComponent.prototype, "over", null); __decorate([ HostListener('mouseleave'), __metadata('design:type', Function), __metadata('design:paramtypes', []), __metadata('design:returntype', void 0) ], UserComponent.prototype, "out", null); UserComponent = __decorate([ Component({ selector: "user", template: ` <div class="user-root"> <pop-over [popOver]="popOver"></pop-over> <div class="user-preview"> <div class="user-inf"> <div class="user-main"> <div id="user-name">{{ user.name}}</div> <div id="dot"></div> </div> <div id="user-status"> {{"Hi, wanna sing you a song"}}</div> </div> <div class="user-call"> <img (click)='callUser()' id="icon-call"/> </div> </div> </div>`, inputs: ['user'] }), __metadata('design:paramtypes', []) ], UserComponent); //directives: [PopOver],
$(document).ready(function() { $(".form-category").blur(function(){ var category = this.value; //el value que tiene el input para luego enviar por POST var id = $("#appbundle_category_id").val(); $.ajax({ url: '/dashboard/category/name-test', data: {category: category, id: id}, type: 'POST', success: function(response){ if(response == "used"){ $(".form-category").css("border", "1px solid red"); }else{ $(".form-category").css("border", "1px solid green"); } } }); }); });
/*global Wizard, TemplateManager, Backbone, _, $*/ Wizard.Views = Wizard.Views || {}; (function () { 'use strict'; Wizard.Views.PaymentView = Backbone.View.extend({ template: 'js/templates/payment.html', className: 'row', events: { 'click #next': 'nextStep', 'click #back': 'previousStep' }, bindings: { '#cc-name': 'ccName', '#cc-type': 'ccType', '#cc-number': 'ccNumber', '#cc-exp-date': 'ccExpDate', '#cc-security-code': 'ccSecurityCode' }, initialize: function () { var view = this; function log() { console.log(JSON.stringify(view.model.changed)); } var verify = _.debounce(log, 1000); view.listenTo(view.model, 'change', verify); }, render: function () { var view = this; Wizard.templateManager.template( view.template ) .done(function (content) { view.$el.html( content( view.model.attributes ) ); view.stickit(); }); return this; }, nextStep: function (event) { event.preventDefault(); if (this.validate()) { Wizard.state = 'success'; this.trigger('wizard:success'); } }, previousStep: function (event) { event.preventDefault(); Wizard.state = 'verify'; this.trigger('wizard:verify'); }, validate: function() { var valid = true, $ccName = this.$('#cc-name'), $ccType = this.$('#cc-type'), $ccNumber = this.$('#cc-number'), $ccExpDate = this.$('#cc-exp-date'), $ccSecurityCode = this.$('#cc-security-code'); if ($ccName.val() === '') { if (!$ccName.hasClass('error')) { $ccName.addClass('error') .parents('label').addClass('error') .after('<small class="error">Invalid entry</small>'); } valid = false; } else { if ($ccName.hasClass('error')) { $ccName.removeClass('error') .parents('label').removeClass('error') .next().remove(); } } if ($ccType.val() === '') { if (!$ccType.hasClass('error')) { $ccType.addClass('error') .parents('label').addClass('error') .after('<small class="error">Invalid entry</small>'); } valid = false; } else { if ($ccType.hasClass('error')) { $ccType.removeClass('error') .parents('label').removeClass('error') .next().remove(); } } if ($ccNumber.val() === '') { if (!$ccNumber.hasClass('error')) { $ccNumber.addClass('error') .parents('label').addClass('error') .after('<small class="error">Invalid entry</small>'); } valid = false; } else { if ($ccNumber.hasClass('error')) { $ccNumber.removeClass('error') .parents('label').removeClass('error') .next().remove(); } } if ($ccExpDate.val() === '') { if (!$ccExpDate.hasClass('error')) { $ccExpDate.addClass('error') .parents('label').addClass('error') .after('<small class="error">Invalid entry</small>'); } valid = false; } else { if ($ccExpDate.hasClass('error')) { $ccExpDate.removeClass('error') .parents('label').removeClass('error') .next().remove(); } } if ($ccSecurityCode.val() === '') { if (!$ccSecurityCode.hasClass('error')) { $ccSecurityCode.addClass('error') .parents('label').addClass('error') .after('<small class="error">Invalid entry</small>'); } valid = false; } else { if ($ccSecurityCode.hasClass('error')) { $ccSecurityCode.removeClass('error') .parents('label').removeClass('error') .next().remove(); } } return valid; } }); })();
import React, { Component, PropTypes } from 'react' import classNames from 'classnames' import treeViewSpanTypes from '../../../constants/treeViewSpanType' import treeViewItemTypes from '../../../constants/treeViewItemType' import TreeViewSpan from './TreeViewSpan' import ServerListItemIcon from './ServerListItemIcon' import OptionsButton from '../../OptionsButton' export default class ServerListItem extends Component { static propTypes = { treeViewSpans: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.oneOf(Object.values(treeViewSpanTypes))), PropTypes.oneOf(Object.values(treeViewSpanTypes)) ]).isRequired, isExpanded: PropTypes.bool.isRequired, onToggleExpand: PropTypes.func, onSelected: PropTypes.func, isSelected: PropTypes.bool, itemType: PropTypes.oneOf(Object.values(treeViewItemTypes)).isRequired, name: PropTypes.string, title: PropTypes.string } static defaultProps = { treeViewSpans: treeViewSpanTypes.TREE_VIEW_EMPTY_SPAN, isExpanded: false, isSelected: false, name: '' } render () { const spanTypes = this.props.treeViewSpans.length !== undefined ? this.props.treeViewSpans : [this.props.treeViewSpans] const isExpandable = this.props.itemType !== treeViewItemTypes.TREE_VIEW_KEY_ITEM return ( <li className={classNames( 'server-list-item', this.props.isSelected ? 'selected' : '' )} title={this.props.title} tabIndex={0} onClick={() => this.props.onSelected && this.props.onSelected()} onDoubleClick={() => isExpandable && this.props.onToggleExpand()} > {spanTypes.map((spanType, spanTypeIndex) => ( <TreeViewSpan // eslint-disable-next-line react/no-array-index-key key={spanType + spanTypeIndex} spanType={spanType} isExpandable={isExpandable && (spanTypeIndex === spanTypes.length - 1)} isExpanded={this.props.isExpanded} onToggleExpand={this.props.onToggleExpand} /> ))} <ServerListItemIcon treeViewItemType={this.props.itemType} isExpanded={this.props.isExpanded} /> <span className='server-list-item-name'> <span className='server-list-item-name-text'> {this.props.name} </span> </span> <span className='options-button-container'> <OptionsButton /> </span> </li> ) } }
// Karma configuration // Generated on Tue Oct 06 2015 22:50:17 GMT-0430 (Venezuela Standard Time) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ './app/temp/tests/browserified_tests.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome', 'Firefox'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }) }
/** * @author Kai Salmen / www.kaisalmen.de */ 'use strict'; if ( KSX.nav === undefined ) KSX.nav = {}; if ( KSX.nav.help === undefined ) KSX.nav.help; KSX.nav.help = { show: true, ownText: false } KSX.nav.allowNavMenuToggle = false; KSX.nav.divNavMenuArea = null; KSX.nav.divNavMenuButton = null; KSX.nav.divNavHelpButton = null; KSX.nav.divNavHelpArea = null; KSX.nav.toggleNavMenu = function ( menu, help ) { if ( menu || help ) KSX.nav.allowNavMenuToggle = true; if ( KSX.nav.allowNavMenuToggle ) { if ( menu ) { KSX.nav.divNavMenuArea.style.display = 'inline'; } else { KSX.nav.divNavMenuArea.style.display = 'none'; } if ( KSX.nav.divNavHelpArea != null ) { if ( help ) { KSX.nav.divNavHelpArea.style.display = 'inline'; } else { KSX.nav.divNavHelpArea.style.display = 'none'; } } if ( menu || help ) { KSX.nav.hideNavButtons(); } else { KSX.nav.showNavButtons(); } } if ( ! ( menu || help ) && KSX.nav.allowNavMenuToggle ) { KSX.nav.allowNavMenuToggle = false; } }; KSX.nav.hideNavButtons = function () { KSX.nav.divNavMenuButton.style.display = 'none'; if ( KSX.nav.divNavHelpButton != null ) KSX.nav.divNavHelpButton.style.display = 'none'; }; KSX.nav.showNavButtons = function () { KSX.nav.divNavMenuButton.style.display = 'inline'; if ( KSX.nav.divNavHelpButton != null ) KSX.nav.divNavHelpButton.style.display = 'inline'; }; KSX.nav.intergrateMenu = function () { var menuContent = document.querySelector( 'link[rel="import"]' ).import; var parent = document.body; // bind variables imported from NavMenu.src KSX.nav.divNavMenuArea = document.importNode( menuContent.getElementById( 'navMenuArea' ), true ); KSX.nav.divNavMenuButton = document.importNode( menuContent.getElementById( 'navMenuButton' ), true ); if ( KSX.nav.help.show ) { KSX.nav.divNavHelpButton = document.importNode( menuContent.getElementById( 'navHelpButton' ), true ); if ( KSX.nav.help.ownText ) { KSX.nav.divNavHelpArea = document.getElementById( 'navHelpArea' ); } else { KSX.nav.divNavHelpArea = document.importNode( menuContent.getElementById( 'navHelpArea' ), true ); parent.insertBefore( KSX.nav.divNavHelpArea, parent.children[ 1 ] ); } parent.insertBefore( KSX.nav.divNavHelpButton, parent.children[ 1 ] ); } parent.insertBefore( KSX.nav.divNavMenuArea, parent.children[ 1 ] ); parent.insertBefore( KSX.nav.divNavMenuButton, parent.children[ 1 ] ); };
angular.module('factories').factory('TrackerBadge', function ($rootScope, $window, $api, Badge) { var TrackerBadge = function (tracker) { this.tracker = angular.copy(tracker); this.description = 'Total bounty on this tracker'; Badge.apply(this, arguments); }; TrackerBadge.prototype = new Badge(); TrackerBadge.prototype.baseFrontendUrl = function () { return window.BS_ENV.www_host + 'trackers/' + this.tracker.slug; }; TrackerBadge.prototype.imageUrl = function () { return window.BS_ENV.api_host + 'badge/tracker?' + $api.toKeyValue({ tracker_id: this.tracker.id }); }; TrackerBadge.prototype.utmParams = function () { return { utm_source: this.tracker.id, utm_medium: 'shield', utm_campaign: 'TRACKER_BADGE' }; }; return TrackerBadge; });
import { connect } from 'react-redux' import AppCard from '../components/appcard' import Actions from '../actions/appcard' const mapStateToProps = (state) => { return state } const mapDispatchToProps = (dispatch) => { return { handleAdd: () => { dispatch(Actions.increment()) }, handleCut: () => { dispatch(Actions.decrement()) } } } export default connect( mapStateToProps, mapDispatchToProps )(AppCard)
const userService = require('../../service/user') module.exports = async (ctx) => { ctx.body = await userService.findAsync() }
'use strict'; var emit = require("./emit"); var emission = require("./emission"); var on = require("./on"); var AMQP = require("./amqp"); var event = require('./event'); module.exports = function(serviceName){ var transport = AMQP(); if(!serviceName){ throw new Error("Service name must be given as an argument"); } var channel = transport.getChannel(); return { on: function(eventName, callback){ validateOn(eventName, callback); return on(serviceName, channel, "*." + eventName, callback, serviceName + "-" + eventName) }, alwaysOn: function(eventName, callback){ validateOn(eventName, callback); return on(serviceName, channel, "*." + eventName, callback) }, emit: function(eventName, payload){ return emit(event(serviceName, eventName, payload), channel); }, emitChain: function(eventName, payload){ return emission(event(serviceName, eventName, payload), channel); }, shutdown: function(){ return transport.shutdown(); } }; }; function validateOn(eventName, callback) { if (!eventName) { throw new Error("Event name must be specified"); } if (!callback) { throw new Error("Callback must be provided"); } if (typeof callback != "function") { throw new Error("Callback must be a function"); } }
/** * Created by ssgonchar on 27.01.2016. */ /** * -------------------------------------------------------------------------------------------------------------------- * Используется паттерн Контроллер Элементов. * Данный паттерн состоит из двух представлений, одно из которых управляет коллекцией элементов (AppView), а второе * работает с отдельными элементами (TodoView). * -------------------------------------------------------------------------------------------------------------------- */ var app = app || {}; /** * Представление задачи TodoView. * Нижний уровень пользовательского интерфейса. */ app.TodoView = Backbone.View.extend({ /** * DOM элемент задачи представляет собой тег списка. */ tagName: 'li', className: 'list-group-item list-group-item-success', /** * Кешировании функции шаблона для отдельного элемента. */ template: _.template($('#item-template').html()), /** * Добавление обработчиков событий. */ events: { 'click .toggle': 'togglecompleted', 'dblclick label': 'edit', 'click .destroy': 'clear', 'keypress .edit': 'updateOnEnter', 'blur .edit': 'close' }, /** * Вызывается при создании экземпляра. * Представление TodoView прослушивает события модели Todo и выполняет повторное отображение. * Связь 1 к 1. */ initialize: function () { this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'destroy', this.remove); this.listenTo(this.model, 'visible', this.toggleVisible); }, /** * Повторно отображает заголовки задач. */ render: function () { if(this.model.get('completed')) { this.$el .removeClass("list-group-item-success") .addClass("list-group-item-default"); } else { this.$el .removeClass("list-group-item-default") .addClass("list-group-item-success"); } this.$el.html(this.template(this.model.toJSON())); this.$el.toggleClass('completed', this.model.get('completed')); this.toggleVisible(); this.$input = this.$('.edit'); return this; }, /** * Переключение видимости элемента. */ toggleVisible: function() { this.$el.toggleClass('hidden', this.isHidden()); }, /** * Определяет должен ли элемент быть виден. */ isHidden: function() { var isCompleted = this.model.get('completed'); return ( // Только для скрытых: (!isCompleted && app.TodoFilter === 'completed') || (isCompleted && app.TodoFilter === 'active') ); }, /** * Переключение состояния completed модели. */ togglecompleted: function () { this.model.toggle(); }, /** * Переключение в режим редактирования. */ edit: function() { this.$el.addClass('editing'); this.$input.focus(); }, /** * Закрытие режима редактирования. * Сохранение изменнений. */ close: function() { var value = this.$input.val().trim(); if(value) { this.model.save({ title: value }); } else { this.clear(); } this.$el.removeClass('editing'); }, /** * Завершение редактиования по нажатию ENTER */ updateOnEnter: function(event) { if(event.which === ENTER_KEY) { this.close(); } }, /** * Удаление элемента, уничтожение модели в локальном хранилище и ее представления. */ clear: function() { this.model.destroy(); } });
// Download the Node helper library from twilio.com/docs/node/install // These identifiers are your accountSid and authToken from // https://www.twilio.com/console // To set up environmental variables, see http://twil.io/secure const accountSid = process.env.TWILIO_ACCOUNT_SID; const authToken = process.env.TWILIO_AUTH_TOKEN; const client = require('twilio')(accountSid, authToken); client.authorizedConnectApps.each(authorizedApp => console.log(authorizedApp.connectAppHomepageUrl) );
/*Главная вьюха приложения*/ ;(function(){ 'use strict'; window.views = window.views || {}; window.views.List = window.views.List || {}; var View = Backbone.View.extend({ // главный элемент вьюхи - в котором отрисовывается контент el : $('#content'), // шаблон списка задач template: $('#listTpl').html(), // статус по умолчанию status: 'waiting', events: { // удаление таска 'click .remove' : 'remove', // Добавить таск 'click .add' : 'add', // сохранение данных таска 'click .save' : 'save', // изменение статуса таска 'change .change_status' : 'change_status' }, initialize: function () { _.bindAll(this,'remove','add','save','change_status'); // добавляем шаблон для отрисовки логики добавления таска this.item_template = $('#itemTpl').html(); return; }, render : function(status){ this.status = status; // достаем данные из хранилища var data = this.model.fetch(); if (status === 'all') { // тут выведутся все таски data = this.model.toJSON(); } else { data = _.where(this.model.toJSON(),{ status : status }); } // кешируем шаблон Mustache.parse(this.template); // рендерим шаблон Mustache.parse(this.template); var markup = Mustache.render(this.template, { tasks: data }); var el = $(this.el); el.html(markup) ; // устанавливаем значение статусов для каждого таска _.each(data,function(el,i,list){ $('select[task_id="'+el.id+'"]').val(el.status); }); }, // удаление таска из хранилища и из памяти remove : function(evt){ var el = $(evt.target); var id = el.attr('task_id'); var removed = this.model.get(id); this.model.remove_item(removed); el.parent().parent().remove(); }, // показвыаем gui для добавления задачи add: function(evt){ this.status = 'warning'; this.router.navigate('filter/'+this.status); this.router.views.nav.set_active(this.status); this.render(this.status); $(this.el).find('.list:first').before(this.item_template); }, // сохранение данных задачи save : function(evt){ var val = $(evt.target).prev().children()[0].value; this.model.add_item({ task : val, status : this.status}); this.render(this.status); }, // изменение статуса задачи change_status : function(evt){ var el = $(evt.target); var status = el.val(); this.model.change_item({ id : el.attr('task_id'), status : status }); var par = el.parent().parent(); par.removeClass('alert-danger alert-success alert-warning'); par.addClass('alert-'+status); this.router.navigate('filter/'+status); this.router.views.nav.set_active(status); this.render(status); } }); var v = new View(); // инициаоизация объекта задачи window.views.List.initialize = function(opts){ v.model = opts.model; return v; }; })();
'use strict'; // github module doc: http://mikedeboer.github.io/node-github var GitHubApi = require('github'), extend = require('extend'), LABELS = { NEEDS_FORMATTING: 'needs: user story/bug format', NEEDS_COMMIT_GUIDELINES: 'needs: commit guidelines', VOTE_10: 'votes: +10', VOTE_20: 'votes: +20', VOTE_50: 'votes: +50' }, CONTRIBUTING = { URL: 'https://github.com/CodeCorico/MemoryOverflow/blob/master/CONTRIBUTING.md', USERSTORY: '#write-a-user-story-for-a-new-feature', BUG: '#write-a-how-to-reproduce-for-a-bug', COMMIT: '#commit-message-format', TYPES: '#type' }, COMMIT_TYPES = ['mo', 'chore', 'feat', 'fix', 'test', 'card', 'rules', 'tpl', 'style', 'refactor', 'perf'], VOTE_SYMBOL = '+1'; module.exports = function githubController(config, callback) { config = extend(true, { USER_AGENT: '', USER_AGENT_EMAIL: '', SECRET: '', MEMORYOVERFLOW_OWNER: '', MEMORYOVERFLOW_PROJECT: '', event: '', post: '' }, config); var issue = config.post.issue || config.post.pull_request, github = _github(config.MEMORYOVERFLOW_OWNER, config.MEMORYOVERFLOW_PROJECT, config.USER_AGENT, config.SECRET); // get issue labels for PR if(!issue.labels) { github.exec(github.issues.getIssueLabels, { number: issue.number }, function(error, labels) { issue.labels = labels; _controller(config, github, issue, callback); }); return; } _controller(config, github, issue, callback); }; function _github(OWNER, PROJECT, AGENT, SECRET) { var github = new GitHubApi({ version: '3.0.0' }); github.authenticate({ type: 'basic', username: AGENT, password: SECRET }); github.exec = function(func, msg, callback) { func(extend(true, msg, { owner: OWNER, repo: PROJECT }), callback); }; return github; } function _controller(config, github, issue, callback) { var rules = [], labels = issue.labels.map(function(label) { return label.name; }), labelsOrigin = JSON.stringify(labels); // new issue if(config.event == 'issues' && config.post.action == 'opened') { _checkIssueMessage(rules, labels, issue); _applyChanges(rules, issue, labels, labelsOrigin, github, callback); return; } // new PR else if(config.event == 'pull_request' && config.post.action == 'opened') { // add/remove label and post comment _checkPR(rules, labels, issue, github, true, function() { _applyChanges(rules, issue, labels, labelsOrigin, github, callback); }); return; } // commented issue (or PR) else if(config.event == 'issue_comment' && config.post.action == 'created') { var comment = config.post.comment; // if PR if(issue.pull_request) { // just add/remove label console.log('checkPR'); _checkPR(rules, labels, issue, github, false, function() { // update votes label console.log('checkVotes'); _checkVotes(rules, labels, issue, comment, github, config.USER_AGENT, function() { console.log('applyChanges', labels, labelsOrigin); _applyChanges(rules, issue, labels, labelsOrigin, github, callback); }); }); } // if simple issue else { // remove needs formating label case if(labels.indexOf(LABELS.NEEDS_FORMATTING) > -1 && issue.user.login == comment.user.login) { _checkIssueFormatting(rules, labels, issue); } // update votes label _checkVotes(rules, labels, issue, comment, github, config.USER_AGENT, function() { _applyChanges(rules, issue, labels, labelsOrigin, github, callback); }); } return; } callback(); } function _issueIsFormatted(issue) { var userstoryRegex = /^as a .* i want .* so that/gi, bugRegex = /^\*\*bug\*\*\n\n((.|\n)*)\n\n\*\*how to reproduce\*\*/gi, body = issue.body .replace(/\r\n/g, '\n') .replace(/\r/g, '\n'); return body && (userstoryRegex.test(body) || bugRegex.test(body)); } function _checkIssueMessage(rules, labels, issue) { if(!_issueIsFormatted(issue)) { rules.push( 'Your issue should be in [User Story](USERSTORY_LINK) or [Bug](BUG_LINK) format.' .replace(/USERSTORY_LINK/g, CONTRIBUTING.URL + CONTRIBUTING.USERSTORY) .replace(/BUG_LINK/g, CONTRIBUTING.URL + CONTRIBUTING.BUG) ); labels.push(LABELS.NEEDS_FORMATTING); } } function _checkIssueFormatting(rules, labels, issue) { if(_issueIsFormatted(issue)) { var index = labels.indexOf(LABELS.NEEDS_FORMATTING); if(index > -1) { labels.splice(index, 1); } } } function _checkVotes(rules, labels, issue, comment, github, USER_AGENT, callback) { if(comment.body.indexOf(VOTE_SYMBOL) > -1) { var voteLabels = [], labelKey; for(labelKey in LABELS) { if(labelKey.indexOf('VOTE_') === 0) { voteLabels.push(labelKey); } } voteLabels.sort(); github.exec(github.issues.getComments, { number: issue.number }, function(error, comments) { for(var i = 0, len = voteLabels.length; i < len; i++) { var index = labels.indexOf(LABELS[voteLabels[i]]); if(index > -1) { labels.splice(index, 1); } } var votes = 0; if(comments && comments.length > 0) { for(var i = 0, len = comments.length; i < len; i++) { if( issue.user.login != comments[i].user.login && comments[i].user.login.toLowerCase() != USER_AGENT.toLowerCase() && comments[i].body.indexOf(VOTE_SYMBOL) > -1 ) { votes++; } } } for(var i = voteLabels.length - 1; i >= 0; i--) { var number = parseInt(voteLabels[i].replace('VOTE_', ''), 10); if(votes >= number) { labels.push(LABELS[voteLabels[i]]); break; } } callback(); }); return; } callback(); } function _checkPR(rules, labels, issue, github, postComment, callback) { github.exec(github.pullRequests.getCommits, { number: issue.number }, function(error, commits) { if(!commits) { callback(); return; } for(var i = 0, len = commits.length; i < len; i++) { var commit = commits[i], messageRegex = /^(\w+)\([\w -\$]+\): .*/, // <type>(<scope>): <subject> message = commit.commit.message .replace(/\r\n/g, '\n') .replace(/\r/g, '\n'), subject = message.split('\n')[0], index = labels.indexOf(LABELS.NEEDS_COMMIT_GUIDELINES); if(index > -1) { labels.splice(index, 1); } var search = messageRegex.exec(subject); console.log(labels); console.log(search); if(!search) { if(postComment) { rules.push( 'Your commit SHA does not match the [Commit message format](COMMIT_LINK).' .replace(/SHA/g, commit.sha) .replace(/COMMIT_LINK/g, CONTRIBUTING.URL + CONTRIBUTING.COMMIT) ); } labels.push(LABELS.NEEDS_COMMIT_GUIDELINES); } else if(search.length < 2 || COMMIT_TYPES.indexOf(search[1].toLowerCase()) === -1) { if(postComment) { rules.push( 'Your commit SHA uses an [unallowed type](TYPES_LINK).' .replace(/SHA/g, commit.sha) .replace(/COMMIT_LINK/g, CONTRIBUTING.URL + CONTRIBUTING.COMMIT) ); } labels.push(LABELS.NEEDS_COMMIT_GUIDELINES); } } callback(); }); } function _applyChanges(rules, issue, labels, labelsOrigin, github, callback) { var checkbox = '- [ ] ', labelsChanged = labelsOrigin != JSON.stringify(labels); if(rules.length > 0) { var commentBody = ':+1: Thanks for your contribution **Agent ' + issue.user.login + '!**\n\n' + 'However, The Machine has very specific contribution rules. Please update your contribution by following these goals:\n' + checkbox + rules.join('\n' + checkbox) + '\n\n' + 'When you have updated your work, add a comment below to inform me.'; github.exec(github.issues.createComment, { number: issue.number, body: commentBody }, function() { }); } if(labelsChanged) { github.exec(github.issues.edit, { number: issue.number, labels: labels }, function() { }); } callback(); }
'use strict'; var binomCI = require( './../lib' ); console.log( binomCI(682, 925, {'level': 0.95}) );
/* * The MIT License (MIT) * * Copyright (c) 2015-2022 Elior "Mallowigi" Boukhobza * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * */ module.exports = { rules: { attr: { 'rule::selector': 'viewBox', }, }, };
/** @babel */ /** @jsx etch.dom */ import SelectListView from 'atom-select-list' import etch from 'etch' import dedent from 'dedent' import CodeBlock from './code-block' export default class ExampleSelectListView { constructor () { this.jsExampleCode = dedent` import SelectListView from 'atom-select-list' const selectListView = new SelectListView({ items: ['one', 'two', 'three'], elementForItem: (item) => { const li = document.createElement('li') li.textContent = item return li }, didConfirmSelection: (item) => { console.log('confirmed', item) }, didCancelSelection: () => { console.log('cancelled') } }) ` etch.initialize(this) } elementForItem (item) { const li = document.createElement('li') li.textContent = item return li } didConfirmSelection (item) { console.log('confirmed', item) } didCancelSelection () { console.log('cancelled') } render () { return ( <div className='example'> <div className='example-rendered'> <atom-panel className='modal'> <SelectListView items={['one', 'two', 'three']} elementForItem={this.elementForItem.bind(this)} onDidConfirmSelection={this.didConfirmSelection.bind(this)} onDidCancelSelection={this.didCancelSelection.bind(this)} /> </atom-panel> </div> <div className='example-code show-example-space-pen'> <CodeBlock cssClass='example-space-pen' grammarScopeName='source.js' code={this.jsExampleCode} /> </div> </div> ) } update () { } }
import React from 'react'; import SimpleExamples from './SimpleExamples'; import SimpleExamplesRaw from '!!raw!./SimpleExamples'; import FakeSCSS from '!!raw!./_fake.scss'; export default [{ title: 'Simple Examples', code: ` /* SimpleExamples.jsx */ ${SimpleExamplesRaw} \`\`\` \`\`\`scss /* _fake.scss */ ${FakeSCSS} `, children: <SimpleExamples />, }];
const getUri = require('get-uri') module.exports = uri => new Promise((resolve, reject) => { getUri(uri, (err, stream) => { if (err) { reject(err) } else { resolve(stream) } }) })
;(function () { describe('scrollFix directive', function () { var elem, scope; beforeEach(module('alv-ch-ng.scroll')); beforeEach(inject(function ($rootScope, $compile) { scope = $rootScope; elem = angular.element('<div scroll-fix style="width: 200px;">testContent</div>'); $compile(elem)(scope); scope.$digest(); })); it('renders the select element as required.', function() { inject(function () { expect(elem.attr('id')).toBeTruthy(); expect(elem.attr('id')).toContain('random'); expect(elem.hasClass('scroll-fixed')).toBeTruthy(); }); } ); }); }());
import { BufferReader } from "./BufferReader.js"; import { BufferWriter } from "./BufferWriter.js"; var FIXED_LENGTH = 22, SIGNATURE = 0x06054b50; // "PK\005\006" export class ZipEndHeader { constructor() { this.disk = 0; this.startDisk = 0; this.volumeEntries = 0; this.totalEntries = 0; this.size = 0; this.offset = 0; this.commentLength = 0; } get headerSize() { return FIXED_LENGTH + this.variableSize; } get variableSize() { return this.commentLength; } write(buffer) { if (buffer === void 0) buffer = new Buffer(this.headerSize); else if (buffer.length < this.headerSize) throw new Error("Insufficient buffer"); var w = new BufferWriter(buffer); w.writeUInt32LE(SIGNATURE); w.writeUInt16LE(this.disk); w.writeUInt16LE(this.startDisk); w.writeUInt16LE(this.volumeEntries); w.writeUInt16LE(this.totalEntries); w.writeUInt32LE(this.size); w.writeUInt32LE(this.offset); w.writeUInt16LE(this.commentLength); return buffer; } static get LENGTH() { return FIXED_LENGTH; } static get SIGNATURE() { return SIGNATURE; } static fromBuffer(buffer) { var h = new this(); var r = new BufferReader(buffer); if (r.readUInt32LE() !== SIGNATURE) throw new Error("Invalid END header"); h.disk = r.readUInt16LE(); h.startDisk = r.readUInt16LE(); h.volumeEntries = r.readUInt16LE(); h.totalEntries = r.readUInt16LE(); h.size = r.readUInt32LE(); h.offset = r.readUInt32LE(); h.commentLength = r.readUInt16LE(); return h; } }
//on click of the submit button, capture the values from user input $('.submit-button').click(function(e) { e.preventDefault(); var topic = $('.topic').val().trim(); var author = $('.author').val().trim(); var threadTitle = $('.thread-title').val().trim(); if (!threadTitle) { alert('Please add a thread title.') } else { var newThread = { threadTitle: threadTitle, topic: topic, author: author, }; //post to the threads page $.post("/threads", newThread, function(res) { var currentURL = window.location.origin; window.location.href = (currentURL + '/forum/' + topic); }); } });
export const ShellComponent = { template: require('./shell.html'), controller: ShellController }; function ShellController($scope, $mdSidenav, authService, roleCheckerService, events, icons, AppSettings, PlatformThemes, Me, FeatureFlags, featureFlagKeys, _) { 'ngInject'; $scope._ = _; const ctrl = this; ctrl.AppSettings = AppSettings; ctrl.PlatformThemes = PlatformThemes; ctrl.FeatureFlags = FeatureFlags; ctrl.featureFlagKeys = featureFlagKeys; ctrl.Me = Me; ctrl.announcementsIcon = icons.announcements; ctrl.homeIcon = icons.home; ctrl.platformThemeIcon = icons.platformThemes; ctrl.searchIcon = icons.search; ctrl.isAdmin = false; ctrl.isLimitedAdmin = false; ctrl.flagMessages = [ { flag: 'agreed_to_terms_of_service', state: 'terms-of-service', text: 'Agree to the Terms of Service' }, { flag: 'completed_hub_onboarding', state: 'onboarding.hub-setup', text: 'Complete your hub setup' }, { flag: 'completed_services_onboarding', state: 'onboarding.services', text: 'Complete your services onboarding' } ]; ctrl.myAccountNavStates = [ { title: 'Terms of Service', state: 'terms-of-service', icon: icons.termsOfService }, { title: 'Hub Setup', state: 'onboarding.hub-setup', icon: icons.hubSetup }, { title: 'Services Onboarding', state: 'onboarding.services', icon: icons.services }, { title: 'Connected Identities', state: 'identities', icon: icons.identities } ]; ctrl.orgNavStates = [ { title: 'Projects', state: 'projects.list', activeState: 'projects', icon: icons.projects, featureFlags: [featureFlagKeys.projects] } ]; ctrl.helpNavStates = [ { title: 'Search', state: 'help.search', icon: ctrl.searchIcon, featureFlags: [featureFlagKeys.helpSearch] }, { title: 'Support Requests', state: 'help.support.requests.overview', activeState: 'help.support.requests', icon: icons.supportRequests, featureFlags: [featureFlagKeys.supportRequests] }, { title: 'About the Hub', state: 'help.faq', icon: icons.info } ]; ctrl.limitedAdminNavStates = [ { title: 'Costs Reports', state: 'costs-reports.list', activeState: 'costs-reports', icon: icons.costsReports } ]; ctrl.adminNavStates = [ { title: 'Announcements', state: 'announcements.editor.list', activeState: 'announcements.editor', icon: ctrl.announcementsIcon, featureFlags: [featureFlagKeys.announcements] }, { title: 'Announcement Templates', state: 'announcements.templates.list', activeState: 'announcements.templates', icon: ctrl.announcementsIcon, featureFlags: [featureFlagKeys.announcements] }, { title: 'Costs Reports', state: 'costs-reports.list', activeState: 'costs-reports', icon: icons.costsReports }, { title: 'Docs Sources', state: 'docs-sources.list', activeState: 'docs-sources', icon: icons.docsSources }, { title: 'Q&A Entries', state: 'qa-entries.list', activeState: 'qa-entries', icon: icons.qaEntries }, { title: 'Pinned Help Entries', state: 'pinned-help-entries', icon: icons.pinnedHelpEntries }, { title: 'Users', state: 'users', icon: icons.users }, { title: 'Platform Themes', state: 'platform-themes.editor.list', activeState: 'platform-themes.editor', icon: ctrl.platformThemeIcon }, { title: 'Support Request Templates', state: 'help.support.request-templates.list', activeState: 'help.support.request-templates', icon: icons.supportRequests, featureFlags: [featureFlagKeys.supportRequests] }, { title: 'Contact Lists', state: 'contact-lists.list', icon: icons.contactList }, { title: 'Kubernetes Tokens Sync', state: 'kubernetes.tokens-sync', icon: icons.syncTokens, featureFlags: [ featureFlagKeys.kubernetesTokensSync, featureFlagKeys.kubernetesTokens ] }, { title: 'Kubernetes Clusters', state: 'kubernetes.clusters.list', icon: icons.kubernetesClusters, featureFlags: [featureFlagKeys.kubernetesTokens] }, { title: 'Kubernetes RBAC Groups', state: 'kubernetes.groups.list', icon: icons.kubernetesGroups, featureFlags: [featureFlagKeys.kubernetesTokens] }, { title: 'Kubernetes Namespaces', state: 'kubernetes.namespaces.list', icon: icons.kubernetesNamespaces, featureFlags: [featureFlagKeys.kubernetesTokens] }, { title: 'Kubernetes User Tokens', state: 'kubernetes.user-tokens.list', icon: icons.kubernetesTokens, featureFlags: [featureFlagKeys.kubernetesTokens] }, { title: 'Kubernetes Robot Tokens', state: 'kubernetes.robot-tokens.list', icon: icons.kubernetesTokens, featureFlags: [featureFlagKeys.kubernetesTokens] }, { title: 'Feature Flags', state: 'feature-flags', icon: icons.featureFlags }, { title: 'App Settings', state: 'app-settings', icon: icons.appSettings } ]; ctrl.toggleMenu = toggleMenu; ctrl.isAuthenticated = isAuthenticated; ctrl.shouldShowSection = shouldShowSection; init(); function init() { $scope.$on(events.auth.updated, () => { if (isAuthenticated()) { refresh(); } else { ctrl.isAdmin = false; } }); if (isAuthenticated()) { refresh(); } } function refresh() { loadAdminStatus(); PlatformThemes.refresh(); } function loadAdminStatus() { roleCheckerService .hasHubRole('admin') .then(hasRole => { ctrl.isAdmin = hasRole; if (!hasRole) { roleCheckerService .hasHubRole('limited_admin') .then(hasRole => { ctrl.isLimitedAdmin = hasRole; }); } }); } function toggleMenu() { $mdSidenav('left').toggle(); } function isAuthenticated() { return authService.isAuthenticated(); } function shouldShowSection(section) { return section.some(e => { return !_.has(e, 'featureFlags') || FeatureFlags.allEnabled(e.featureFlags); }); } }
angular.module('casa').controller('ARImageController', [ '$scope', '$cordovaGeolocation', '$stateParams', '$ionicModal', '$ionicPopup', 'LocationsService', 'InstructionsService', function( $scope, $cordovaGeolocation, $stateParams, $ionicModal, $ionicPopup, LocationsService, InstructionsService ) { // lets do some fun var video = document.getElementById('webcam'); var canvas = document.getElementById('canvas'); try { var attempts = 0; var readyListener = function (event) { findVideoSize(); }; var findVideoSize = function () { if (video.videoWidth > 0 && video.videoHeight > 0) { video.removeEventListener('loadeddata', readyListener); onDimensionsReady(video.videoWidth, video.videoHeight); } else { if (attempts < 10) { attempts++; setTimeout(findVideoSize, 200); } else { onDimensionsReady(640, 480); } } }; var onDimensionsReady = function (width, height) { demo_app(width, height); compatibility.requestAnimationFrame(tick); }; video.addEventListener('loadeddata', readyListener); compatibility.getUserMedia({ video: true }, function (stream) { try { video.src = compatibility.URL.createObjectURL(stream); } catch (error) { video.src = stream; } setTimeout(function () { video.play(); demo_app(); compatibility.requestAnimationFrame(tick); }, 500); }, function (error) { console.log("error gum"); //$('#canvas').hide(); //$('#log').hide(); //$('#no_rtc').html('<h4>WebRTC not available.</h4>'); //$('#no_rtc').show(); }); } catch (error) { console.log("error a"); //$('#canvas').hide(); //$('#log').hide(); //$('#no_rtc').html('<h4>Something goes wrong...</h4>'); //$('#no_rtc').show(); } //var stat = new profiler(); var gui, ctx, canvasWidth, canvasHeight; var img_u8; function demo_app(videoWidth, videoHeight) { canvasWidth = canvas.width; canvasHeight = canvas.height; ctx = canvas.getContext('2d'); ctx.fillStyle = "rgb(0,255,0)"; ctx.strokeStyle = "rgb(0,255,0)"; img_u8 = new jsfeat.matrix_t(640, 480, jsfeat.U8_t | jsfeat.C1_t); //stat.add("grayscale"); } function tick() { compatibility.requestAnimationFrame(tick); //stat.new_frame(); if (video.readyState === video.HAVE_ENOUGH_DATA) { ctx.drawImage(video, 0, 0, 640, 480); var imageData = ctx.getImageData(0, 0, 640, 480); //stat.start("grayscale"); jsfeat.imgproc.grayscale(imageData.data, 640, 480, img_u8); //stat.stop("grayscale"); // render result back to canvas var data_u32 = new Uint32Array(imageData.data.buffer); var alpha = (0xff << 24); var i = img_u8.cols * img_u8.rows, pix = 0; while (--i >= 0) { pix = img_u8.data[i]; data_u32[i] = alpha | (pix << 16) | (pix << 8) | pix; } ctx.putImageData(imageData, 0, 0); //$('#log').html(stat.log()); } } //$(window).unload(function () { // video.pause(); // video.src = null; //}); }]);
import React, {PropTypes} from 'react'; import LinkList from '../../../LinkList'; import {Cell, Grid, Textfield, Icon, Button, FABButton} from 'react-mdl'; import './LinkView.scss'; const checkMark = (<div className="checkmark"></div>); const sortByCategory = (list) => { const sorted = Object.keys(list).reduce((prev, cur) => { const curObj = list[cur]; if (curObj.category && !curObj.category.length) { if (!prev.Uncategorized) { prev.Uncategorized = {}; } prev.Uncategorized[cur] = curObj; } else if (curObj.category) { curObj.category.forEach(cat => { if (!prev[cat]) { prev[cat] = {}; } prev[cat][cur] = curObj; }); } return prev; }, {}); return sorted; }; export default class LinkView extends React.Component { static propTypes = { linkList: PropTypes.object, selectLinkToAdd: PropTypes.func, toBeAddedLinkList: PropTypes.array, sortByCategory: PropTypes.bool, style: PropTypes.object, } constructor(props) { super(); this.sorted = undefined; if (props.linkList && Object.keys(props.linkList).length && props.sortByCategory) { this.sorted = sortByCategory(props.linkList); } this.state = { expanded: new Set(this.sorted ? Object.keys(this.sorted) : []), }; } render() { const isAllExpanded = !!this.sorted && Object.keys(this.sorted).length === this.state.expanded.size; return (<Grid style={this.props.style}> <Cell col={10} style={{margin: 0, height: '100%', overflow: 'auto'}}> { this.props.linkList && Object.keys(this.props.linkList).length && !this.props.sortByCategory && <LinkList data={this.props.linkList} onSelect={this.props.selectLinkToAdd} selectedList={this.props.toBeAddedLinkList} selectable selectedMarker={checkMark}/> } { this.sorted && <Button style={{position: 'absolute', right: '20%', margin: 15, zIndex: 2}} onClick={() => { isAllExpanded ? this.setState({expanded: new Set([])}) : this.setState({expanded: new Set(Object.keys(this.sorted))}); }}>{ isAllExpanded ? 'Collapse all' : 'Expand all'}</Button> } { this.sorted && <div>{Object.keys(this.sorted).map(category => { const catExpanded = this.state.expanded.has(category); return ( <section key={category} style={{position: 'relative', minHeight: 48}}> <FABButton mini riple onClick={() =>{ if (catExpanded) { this.state.expanded.delete(category); return this.setState({expanded: this.state.expanded}); } return this.setState({expanded: this.state.expanded.add(category)}); }} className={`link-view__expand-icon${catExpanded ? ' expanded' : ''}`}><Icon name="add"/></FABButton> <h5 className="link-view__category-title">{category}</h5> <div className="link-view__category-content"> <LinkList data={this.sorted[category]} onSelect={this.props.selectLinkToAdd} selectedList={this.props.toBeAddedLinkList} selectable selectedMarker={checkMark}/> </div> </section> );})}</div> } </Cell> <Cell col={2}> <Textfield floatingLabel label="Filter" /> <section> <h5 style={{fontWeight: 300}}>Custom Link:</h5> <div style={{paddingLeft: '2rem'}}> <Textfield label="Name" /> <Textfield label="Url" /> <Textfield label="Icon" /> <Button ripple raised accent onClick={(event) => {}}>Add</Button> <Button onClick={() => {}}>Clear</Button> </div> </section> </Cell> </Grid>); } }
const Formatter = require('./formatter') const Tracker = require('./tracker') // Problem with errors is that output can be interleaved, so we need to gather // up the lines of output after a failed assertion, or else the output of other // assertions get interleaved. // // The first formatting style that comes to mind would be one that grouped all // the failed assertions under their failed test, but that means waiting for a // full test to load. There are test with a great many failures, one of the // automated tests, like the one in Timezone that tests every clock transition // in the world since the dawn of standardized time. We might run out of memory // if a test of that nature is really broken and really chatty about it. // // What we're going to do for a stab at this problem is create a queue, as we do // with progress, and one go at a time. Chances are the queue will be empty. If // there is one long running test interleaved with a quick test, then the quick // test will be done quickly, and the long running test can take over. If two // long running test are interleaved, then we might want to view the tests one // at a time by piping the test through `grep`, or piping it through `sort`, // before passing it to `proof errors`. module.exports = function (arguable, state, runner, writable) { var queue = [] var failed = {} var programs = {} var offset = runner != 0 || ! writable.npm ? 2 : 3 var backlog = {} var planned const format = new Formatter({ color: ! arguable.ultimate.monochrome, progress: false, width: arguable.ultimate.width, delimiter: '\u0000' }) const tracker = new Tracker return function (event) { var out = [] if (event.type === 'run') { planned = false backlog[event.file] = [ { type: 'out', message: '' }, { type: 'out', message: '>--' }, { type: 'out', message: '' } ] } let program = tracker.update(event) if (failed[event.file]) { failed[event.file].events.push(event) if (event.type === 'test' && event.message.ok) { delete failed[event.file] } } else if ((event.type === 'bail') || (event.type === 'test' && !(event.message.ok)) || (event.type === 'exit' && (event.message[0] || !planned || (program.expected != program.actual)))) { queue.push(failed[event.file] = { events: backlog[event.file].concat([event]) }) if (event.type === 'test') { backlog[event.file].length = 3 } else { delete backlog[event.file] } } else if (event.type === 'plan') { planned = true } else if (event.type === 'test') { backlog[event.file].length = 3 } else if (event.type === 'exit') { delete backlog[event.file] } else if (event.type !== 'eof') { backlog[event.file].push(event) } else if (offset !== 2) { state.code = 1 } while (queue.length && queue[0].events.length) { event = queue[0].events.shift() if (offset-- > 0) { continue } switch (event.type) { case 'bail': out.push(format.write(`> :fail:. ${event.file}: Bail out! ${event.message}`)) break case 'test': /* if (!planned) { process.stdout.write('> ' + (colorize.red('\u2718')) + ' ' + event.file + ': no plan given: ' + event.message + '\n') planned = true } else */ if (event.message.ok) { queue.shift() } else { out.push(format.write(`> :fail:. ${event.file}: ${event.message.message}`)) } break case 'err': case 'out': out.push('' + event.message + '\n') break case 'exit': if (event.message[0] || !planned || (program.actual != program.expected)) { var line = [] line.push(`> :fail:. ${event.file}`) if (!planned) { line.push(': no plan given') } else if (program.actual != program.expected) { line.push(': expected ' + program.expected + ' test' + (program.expected == 1 ? '' : 's') + ' but got ' + program.actual) } line.push(': exited with code ' + program.code) out.push(format.write(line.join(''))) } queue.shift() break } } for (const line of out) { writable.write(line) } } }
/** * * Not included, not served, not used, not anything * * This file exists to shut IDEA syntax inspections up * * @author Oleksii Khilkevych * @since 02.12.12 */ window.stopWatch = function(str) { }; window.R = {};
export { default } from './SelectResourceDialog';
process.mixin(require("../common")); var finished1 = false; var finished2 = false; var finished3 = false; var finished4 = false; var finished5 = false; var finished6 = false; var finished7 = false; before("sqlite", function (db) { // Connect to a valid database db.addListener('error', debug); var store = db.get_store("foo", { name: String, age: Number }); var data = {name: "Tim", age: 27}; var data3; // Save some data store.save(data, function (id) { assert.equal(id, 1); finished1 = true; // Load it back and check store.get(data._id, function (data2) { assert.deepEqual(data2, data); finished2 = true; // Change some data and save update. data.age = 28; store.save(data, function (id) { assert.equal(id, undefined); finished3 = true; // Load it back to make sure it really changed. store.get(data._id, function (data2) { assert.deepEqual(data2, data); finished4 = true; }); // Create another row in parallel to the last get data3 = {name: "Bob", age: 105}; store.save(data3, function (id) { assert.equal(data3._id, id); assert.equal(id, 2); finished5 = true; // store.remove(data3, function () { assert.equal(data3._id, undefined); finished8 = true; store.each(function (row) { assert.deepEqual(row, data); finished6 = true; }, function () { finished7 = true; }); store.all(function (all) { assert.deepEqual(all[0], data); finished9 = true; store.nuke(function () { store.all(function (all) { assert.equal(all.length, 0); finished10 = true; }); }); }); }); }); }) }); }); }); process.addListener('exit', function () { assert.ok(finished1, "SAVE INSERT failed"); assert.ok(finished2, "GET failed"); assert.ok(finished3, "SAVE UPDATE failed"); assert.ok(finished4, "SAVE UPDATE verify failed"); assert.ok(finished5, "EACH failed"); assert.ok(finished6, "EACH finish failed"); assert.ok(finished7, "SECOND INSERT failed"); assert.ok(finished8, "REMOVE failed"); assert.ok(finished9, "ALL failed"); assert.ok(finished10, "NUKE failed"); });
version https://git-lfs.github.com/spec/v1 oid sha256:1221dcc39a83078bc7e155cb512966f756885ea43de52f48ab9a3a1830bac556 size 69247
define([ 'ui-components/rb-definition-list' ], function (rbDefinitionList) { describe('rb-definition-list-item', function () { var $rootScope, $scope, isolatedScope, $compile, element, compileTemplate; beforeEach(angular.mock.module(rbDefinitionList.name)); beforeEach(inject(function (_$compile_, _$rootScope_) { $rootScope = _$rootScope_; $scope = _$rootScope_.$new({}); $compile = _$compile_; // Compile directive, apply scope and fetch new isolated scope compileTemplate = function (template) { element = $compile(template)($scope); $scope.$apply(); isolatedScope = element.isolateScope(); }; })); describe('rendering', function () { it('should render with a "li" tagname', function () { compileTemplate('<rb-definition-list-item></rb-definition-list-item>'); expect(element[0].tagName.toLowerCase()).toEqual('li'); }); it('should attach an icon to the li when present', function () { compileTemplate('<rb-definition-list-item icon="anyicon"></rb-definition-list-item>'); var icons = element[0].getElementsByClassName('DefinitionList-icon'), icon = angular.element(icons[0]); expect(icons.length).toBe(1); expect(icon.hasClass('DefinitionList-icon--anyicon')).toBe(true); }); it('should not attach an icon to the dt when not present', function () { compileTemplate('<rb-definition-list-item></rb-definition-list-item>'); expect(element.find('icon').length).toBe(0); }); it('should display a label for the dt', function () { compileTemplate('<rb-definition-list-item label="anylabel"></rb-definition-list-item>'); expect(element.find('h3').text()).toContain('anylabel'); }); it('should render transcluded elements into the details', function () { compileTemplate('<rb-definition-list-item><span>Transcluded detail</span></rb-definition-list-item>'); var body = angular.element(element[0].getElementsByClassName('DefinitionList-body')[0]); expect(body.html()).toContain('Transcluded detail'); }); }); }); });
var assert = require('chai').assert , bufferEqual = require('buffer-equal') , Crc64 = require('../../build/Release/Crc64.node').Crc64; describe('jsr-rdb (crc)', function() { var expected = new Buffer([0xCA, 0xD9, 0xB8, 0xC4, 0x14, 0xD9, 0xC6, 0xE9]); it('should calculate CRC-64 for byte array', function(done) { var crc = new Crc64() , data = new Buffer('123456789', 'ascii'); crc.push(data); assert.isTrue(bufferEqual(crc.value(), expected)); done(); }); it('should calculate CRC-64 for multiple byte arrays', function(done) { var crc = new Crc64() , data1 = new Buffer('12', 'ascii') , data2 = new Buffer('345', 'ascii') , data3 = new Buffer('6789', 'ascii'); crc.push(data1); crc.push(data2); crc.push(data3); assert.isTrue(bufferEqual(crc.value(), expected)); done(); }); })
'use strict'; const semverValid = require('semver').valid; const shell = require('shelljs'); const log = require('./log'); module.exports = function getLatestTag(verbose, prefix) { if (verbose === undefined) verbose = false; const regex = /tag:\s*(.+?)[,\)]/gi; const cmd = 'git log --date-order --tags --simplify-by-decoration --pretty=format:"%d"'; const data = shell.exec(cmd, {silent: true}).stdout; let latestTag = null; data.split('\n').some(function(decorations) { let match; while (match = regex.exec(decorations)) { // eslint-disable-line no-cond-assign const tag = match[1]; if (tag.startsWith(prefix)) { const semanticVersion = tag.replace(prefix, ''); if (semverValid(semanticVersion)) { latestTag = tag; return true; } } } }); if (latestTag) { if (verbose) log.info('>> Your latest semantic tag is: ', latestTag); latestTag = `${latestTag}..HEAD`; } else { log.info('>> No SemVer tag found. It seems like your first release? Initial release will be set to v1.0.0 as per npmjs specification.'); latestTag = 'HEAD'; } return latestTag; };
/** * DevExtreme (viz/components/consts.js) * Version: 16.2.5 * Build date: Mon Feb 27 2017 * * Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED * EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml */ "use strict"; module.exports = { events: { mouseover: "mouseover", mouseout: "mouseout", mousemove: "mousemove", touchstart: "touchstart", touchmove: "touchmove", touchend: "touchend", mousedown: "mousedown", mouseup: "mouseup", click: "click", selectSeries: "selectseries", deselectSeries: "deselectseries", selectPoint: "selectpoint", deselectPoint: "deselectpoint", showPointTooltip: "showpointtooltip", hidePointTooltip: "hidepointtooltip" }, states: { hover: "hover", normal: "normal", selection: "selection", normalMark: 0, hoverMark: 1, selectedMark: 2, applyHover: "applyHover", applySelected: "applySelected", resetItem: "resetItem" }, pieLabelIndent: 30, pieLabelSpacing: 10, pieSeriesSpacing: 4 };
var Backbone = require('backbone'); var Todo = require('../models/Todo'); var Todos = module.exports = Backbone.Collection.extend({ model: Todo, url: '/api/things' });
var through = require('through2'); var gulpmatch = require('gulp-match'); function isArray ( arg ) { return Object.prototype.toString.call(arg) === '[object Array]'; } function gulpCondition ( condition, transformA, transformB ) { function applyTransforms ( context, file, transforms, callback ) { if ( isArray(transforms) ) { // Clone array because we are shifting stuff out of it. transforms = Array.prototype.slice.call(transforms, 0); } else { transforms = [transforms]; } function next () { var transform = transforms.shift(); if ( transform ) { transform.once('data', function ( newFile ) { file = newFile; next(); }); transform.write(file); } else { context.push(file); callback(); } } next(); } return through.obj(function ( file, enc, callback ) { var that = this; if ( gulpmatch(file, condition) ) { if ( transformA ) { applyTransforms(this, file, transformA, callback); return; } } else { if ( transformB ) { applyTransforms(this, file, transformB, callback); return; } } this.push(file); callback(); }); } module.exports = gulpCondition;
module.exports = function(sequelize, DataTypes){ //return sequelize.define('Quiz', {pregunta:DataTypes.STRING, respuesta: DataTypes.STRING}); return sequelize.define('Quiz', { pregunta:{ type:DataTypes.STRING, validate:{notEmpty:{msg:"-> Falta pregunta"}} }, respuesta: { type:DataTypes.STRING, validate:{notEmpty:{msg:"-> Falta respuesta"}} }, categoria: { type:DataTypes.STRING } } ); }
import { Meteor } from 'meteor/meteor'; import './register.html'; Template.regist.helpers({ }); Template.regist.events({ 'submit #regist'(event, instance) { var subdomain = event.target.subdomain.value; var name = event.target.name.value; var address = event.target.address.value; var phone = event.target.phone.value; var fax = event.target.fax.value; var about_url =event.target.about_url.value == ""? null: event.target.about_url.value; var scale = parseInt(event.target.scale.value); var agent_name = event.target.agent_name.value; var agent_email = event.target.agent_email.value; var agent_phone = event.target.agent_phone.value; var agent_title = event.target.agent_title.value; console.log(subdomain); Meteor.call('company.agent.add',subdomain, name, address, phone, fax, scale, about_url, agent_name, agent_email, agent_phone, agent_title, (error,results) => { if (error) { console.log(error.error); } else { console.log(results); } }); } });
// DEPENDENCIES // ============================================================================= import { isEmpty, isString } from "lodash"; // METHODS // ============================================================================= /** * List from localstorage. * * @method list * @param {object} window * @param {string} key */ function list(window, key) { // list data let data = window.localStorage.getItem(key); // data should always be a string, but just in case if (isString(data)) { data = JSON.parse(data); } // is empty? if (isEmpty(data)) { return []; } // otherwise... return data; } // EXPORT // ============================================================================= export default list;
'use strict'; angular .module('fli.look') .controller('look.content.pinterest.board.ctrl', function ($scope, $parse, pinterest, item) { var vm = this; vm.href = item.href; function setResult(res) { vm.pins = $parse('data.pins')(res) || []; $scope.pinterest.user = $parse('data.user')(res); } pinterest.boards($scope.pinterest.pathname) .success(setResult); });
Package.describe({ name: 'cosmos:running', version: '0.2.1', summary: 'Ordered startup functions ', git: 'http://github.com/elidoran/cosmos-running', documentation: 'README.md' }); var cs = [ 'client', 'server' ] Package.onUse(function(api) { api.versionsFrom('1.2'); api.use([ 'tracker', // onChange uses Tracker 'reactive-var', // _value is a ReactiveVar 'coffeescript@1.0.11', 'cosmos:chain@0.4.1' ], cs); api.addFiles([ 'export.js', 'running.coffee' ], cs); api.export('Running', cs); }); Package.onTest(function(api) { api.use(['tinytest', 'coffeescript@1.0.11']); api.use('cosmos:running'); api.addFiles([ 'test/running-tests.coffee' ], cs); });
require('babel-core/register') var webpack = require('webpack') var WebpackDevServer = require('webpack-dev-server') var webpackConfig = require('./_development').default var config = require('../../config').default var paths = config.get('utils_paths') // webpackConfig.context = '/Users/koalahuang/Code/vue-vuex' var compiler = webpack(webpackConfig) var server = new WebpackDevServer(compiler, { // webpack-dev-server options contentBase: `http://${config.get('server_host')}:${config.get('server_port')}`, // or: contentBase: "http://localhost/", hot: true, // Enable special support for Hot Module Replacement // Page is no longer updated, but a "webpackHotUpdate" message is send to the content // Use "webpack/hot/dev-server" as additional module in your entry point // Note: this does _not_ add the `HotModuleReplacementPlugin` like the CLI option does. // Set this as true if you want to access dev server from arbitrary url. // This is handy if you are using a html5 router. historyApiFallback: true, // Set this if you want webpack-dev-server to delegate a single path to an arbitrary server. // Use "*" to proxy all paths to the specified server. // This is useful if you want to get rid of 'http://localhost:8080/' in script[src], // and has many other use cases (see https://github.com/webpack/webpack-dev-server/pull/127 ). // proxy: { // '/api/*': `http://${config.get('server_host')}:${config.get('server_port')}` // }, // webpack-dev-middleware options quiet: false, noInfo: false, lazy: false, inline: true, filename: "app.js", watchOptions: { aggregateTimeout: 300, poll: 1000 }, publicPath: '/public/', headers: {'Access-Control-Allow-Origin': '*'}, stats: { colors: true }, }) console.log('port', config.get('webpack_port')) server.listen(config.get('webpack_port'), "localhost", function() { console.log('webpack dev server started!') })
'use strict'; var fs = require('fs'); var path = require('path'); var dns = require('dns'); var net = require('net'); var util = require("util"); var events = require("events"); var utils = require('./utils'); var sock = require('./line_socket'); var logger = require('./logger'); var config = require('./config'); var constants = require('./constants'); var trans = require('./transaction'); var plugins = require('./plugins'); var async = require('async'); var Address = require('./address').Address; var TimerQueue = require('./timer_queue'); var date_to_str = utils.date_to_str; var existsSync = utils.existsSync; var FsyncWriteStream = require('./fsync_writestream'); var core_consts = require('constants'); var WRITE_EXCL = core_consts.O_CREAT | core_consts.O_TRUNC | core_consts.O_WRONLY | core_consts.O_EXCL; var MAX_UNIQ = 10000; var host = require('os').hostname().replace(/\\/, '\\057').replace(/:/, '\\072'); var fn_re = /^(\d+)_(\d+)_/; // I like how this looks like a person var queue_dir = path.resolve(config.get('queue_dir') || (process.env.HARAKA + '/queue')); var uniq = Math.round(Math.random() * MAX_UNIQ); var cfg; exports.load_config = function () { cfg = config.get('outbound.ini', { booleans: [ '-disabled', '-always_split', '-enable_tls', // TODO: default to enabled in Haraka 3.0 '-ipv6_enabled', ], }, function () { exports.load_config(); }).main; // legacy config file support. Remove in Haraka 4.0 if (!cfg.enable_tls && config.get('outbound.enable_tls')) { cfg.enable_tls = true; } if (!cfg.maxTempFailures) { cfg.maxTempFailures = config.get('outbound.maxTempFailures') || 13; } if (!cfg.concurrency_max) { cfg.concurrency_max = config.get('outbound.concurrency_max') || 100; } if (!cfg.ipv6_enabled && config.get('outbound.ipv6_enabled')) { cfg.ipv6_enabled = true; } }; exports.load_config(); var load_queue = async.queue(function (file, cb) { var hmail = new HMailItem(file, path.join(queue_dir, file)); exports._add_file(hmail); hmail.once('ready', cb); }, cfg.concurrency_max); var in_progress = 0; var delivery_queue = async.queue(function (hmail, cb) { in_progress++; hmail.next_cb = function () { in_progress--; cb(); }; hmail.send(); }, cfg.concurrency_max); var temp_fail_queue = new TimerQueue(); var queue_count = 0; exports.get_stats = function () { return in_progress + '/' + delivery_queue.length() + '/' + temp_fail_queue.length(); }; exports.list_queue = function (cb) { this._load_cur_queue(null, "_list_file", cb); }; exports.stat_queue = function (cb) { var self = this; this._load_cur_queue(null, "_stat_file", function () { return cb(self.stats()); }); }; exports.scan_queue_pids = function (cb) { var self = this; fs.readdir(queue_dir, function (err, files) { if (err) { self.logerror("Failed to load queue directory (" + queue_dir + "): " + err); return cb(err); } var pids = {}; files.forEach(function (file) { if (/^\./.test(file)) { // dot-file... self.logwarn("Removing left over dot-file: " + file); return fs.unlink(file, function () {}); } // Format: $time_$attempts_$pid_$uniq.$host var match = /^\d+_\d+_(\d+)_\d+\./.exec(file); if (!match) { self.logerror("Unrecognised file in queue directory: " + queue_dir + '/' + file); return; } pids[match[1]] = true; }); return cb(null, Object.keys(pids)); }); }; process.on('message', function (msg) { if (msg.event && msg.event === 'outbound.load_pid_queue') { exports.load_pid_queue(msg.data); return; } if (msg.event && msg.event === 'outbound.flush_queue') { exports.flush_queue(); return; } // ignores the message }); exports.flush_queue = function () { temp_fail_queue.drain(); }; exports.load_pid_queue = function (pid) { this.loginfo("Loading queue for pid: " + pid); this.load_queue(pid); }; exports.load_queue = function (pid) { // Initialise and load queue // we create the dir here because this is used when Haraka is running // properly. // no reason not to do this stuff syncronously - we're just loading here if (!existsSync(queue_dir)) { this.logdebug("Creating queue directory " + queue_dir); try { fs.mkdirSync(queue_dir, 493); // 493 == 0755 } catch (err) { if (err.code !== 'EEXIST') { logger.logerror("Error creating queue directory: " + err); throw err; } } } this._load_cur_queue(pid, "_add_file"); }; exports._load_cur_queue = function (pid, cb_name, cb) { var self = this; self.loginfo("Loading outbound queue from ", queue_dir); fs.readdir(queue_dir, function (err, files) { if (err) { return self.logerror("Failed to load queue directory (" + queue_dir + "): " + err); } self.cur_time = new Date(); // set this once so we're not calling it a lot self.load_queue_files(pid, cb_name, files); if (cb) cb(); }); }; exports.load_queue_files = function (pid, cb_name, files) { var self = this; if (files.length === 0) return; if (cfg.disabled && cb_name === '_add_file') { // try again in 1 second if delivery is disabled setTimeout(function () {self.load_queue_files(pid, cb_name, files);}, 1000); return; } if (pid) { // Pre-scan to rename PID files to my PID: this.loginfo("Grabbing queue files for pid: " + pid); async.eachLimit(files, 200, function (file, cb) { var match = /^(\d+)(_\d+_)(\d+)(_\d+\..*)$/.exec(file); if (match && match[3] == pid) { var next_process = match[1]; var new_filename = match[1] + match[2] + process.pid + match[4]; // self.loginfo("Renaming: " + file + " to " + new_filename); fs.rename(queue_dir + '/' + file, queue_dir + '/' + new_filename, function (err) { if (err) { self.logerror("Unable to rename queue file: " + file + " to " + new_filename + " : " + err); return cb(); } if (next_process <= self.cur_time) { load_queue.push(new_filename); } else { temp_fail_queue.add(next_process - self.cur_time, function () { load_queue.push(new_filename);}); } // self.loginfo("Done"); cb(); }); } else if (/^\./.test(file)) { // dot-file... self.logwarn("Removing left over dot-file: " + file); return fs.unlink(queue_dir + "/" + file, function (err) { if (err) { self.logerror("Error removing dot-file: " + file + ": " + err); } cb(); }); } else { // Do this because otherwise we blow the stack async.setImmediate(cb); } }, function (err) { if (err) { // no error cases yet, but log anyway self.logerror("Error fixing up queue files: " + err); } self.loginfo("Done fixing up old PID queue files"); self.loginfo(delivery_queue.length() + " files in my delivery queue"); self.loginfo(load_queue.length() + " files in my load queue"); self.loginfo(temp_fail_queue.length() + " files in my temp fail queue"); }); } else { self.loginfo("Loading the queue..."); files.forEach(function (file) { if (/^\./.test(file)) { // dot-file... self.logwarn("Removing left over dot-file: " + file); return fs.unlink(queue_dir + "/" + file, function () {}); } var matches = file.match(fn_re); if (!matches) { self.logerror("Unrecognised file in queue folder: " + file); return; } var next_process = matches[1]; if (cb_name === '_add_file') { if (next_process <= self.cur_time) { load_queue.push(file); } else { temp_fail_queue.add(next_process - self.cur_time, function () { load_queue.push(file);}); } } else { self[cb_name](file); } }); } }; exports._add_file = function (hmail) { var self = this; // this.loginfo("Adding file: " + hmail.filename); if (hmail.next_process < this.cur_time) { delivery_queue.push(hmail); } else { temp_fail_queue.add(hmail.next_process - this.cur_time, function () { delivery_queue.push(hmail);}); } }; exports._list_file = function (file) { // TODO: output more data here? console.log("Q: " + file); }; exports._stat_file = function () { queue_count++; }; exports.stats = function () { // TODO: output more data here var results = { queue_dir: queue_dir, queue_count: queue_count, }; return results; }; function _next_uniq () { var result = uniq++; if (uniq >= MAX_UNIQ) { uniq = 1; } return result; } function _fname () { var time = new Date().getTime(); return time + '_0_' + process.pid + "_" + _next_uniq() + '.' + host; } exports.send_email = function () { var self = this; if (arguments.length === 2) { this.loginfo("Sending email as a transaction"); return this.send_trans_email(arguments[0], arguments[1]); } var from = arguments[0], to = arguments[1], contents = arguments[2]; var next = arguments[3]; this.loginfo("Sending email via params"); var transaction = trans.createTransaction(); this.loginfo("Created transaction: " + transaction.uuid); // set MAIL FROM address, and parse if it's not an Address object if (from instanceof Address) { transaction.mail_from = from; } else { try { from = new Address(from); } catch (err) { return next(constants.deny, "Malformed from: " + err); } transaction.mail_from = from; } // Make sure to is an array if (!(Array.isArray(to))) { // turn into an array to = [ to ]; } if (to.length === 0) { return next(constants.deny, "No recipients for email"); } // Set RCPT TO's, and parse each if it's not an Address object. for (var i=0,l=to.length; i < l; i++) { if (!(to[i] instanceof Address)) { try { to[i] = new Address(to[i]); } catch (err) { return next(constants.deny, "Malformed to address (" + to[i] + "): " + err); } } } transaction.rcpt_to = to; // Set data_lines to lines in contents var match; var re = /^([^\n]*\n?)/; while (match = re.exec(contents)) { var line = match[1]; line = line.replace(/\n?$/, '\r\n'); // make sure it ends in \r\n transaction.add_data(new Buffer(line)); contents = contents.substr(match[1].length); if (contents.length === 0) { break; } } transaction.message_stream.add_line_end(); this.send_trans_email(transaction, next); }; exports.send_trans_email = function (transaction, next) { var self = this; // add in potentially missing headers if (!transaction.header.get_all('Message-Id').length) { this.loginfo("Adding missing Message-Id header"); transaction.add_header('Message-Id', '<' + transaction.uuid + '@' + config.get('me') + '>'); } if (!transaction.header.get_all('Date').length) { this.loginfo("Adding missing Date header"); transaction.add_header('Date', date_to_str(new Date())); } transaction.add_leading_header('Received', '(Haraka outbound); ' + date_to_str(new Date())); var deliveries = []; var always_split = cfg.always_split; if (always_split) { this.logdebug("always split"); transaction.rcpt_to.forEach(function (rcpt) { deliveries.push({domain: rcpt.host, rcpts: [ rcpt ]}); }); } else { // First get each domain var recips = {}; transaction.rcpt_to.forEach(function (rcpt) { var domain = rcpt.host; if (!recips[domain]) { recips[domain] = []; } recips[domain].push(rcpt); }); Object.keys(recips).forEach(function (domain) { deliveries.push({'domain': domain, 'rcpts': recips[domain]}); }); } var hmails = []; var ok_paths = []; var todo_index = 1; async.forEachSeries(deliveries, function (deliv, cb) { var todo = new TODOItem(deliv.domain, deliv.rcpts, transaction); todo.uuid = todo.uuid + '.' + todo_index; todo_index++; self.process_delivery(ok_paths, todo, hmails, cb); }, function (err) { if (err) { for (var i=0,l=ok_paths.length; i<l; i++) { fs.unlink(ok_paths[i], function () {}); } if (next) next(constants.deny, err); return; } for (var j=0; j<hmails.length; j++) { var hmail = hmails[j]; delivery_queue.push(hmail); } if (next) { next(constants.ok, "Message Queued (" + transaction.uuid + ")"); } }); }; exports.process_delivery = function (ok_paths, todo, hmails, cb) { var self = this; this.loginfo("Processing domain: " + todo.domain); var fname = _fname(); var tmp_path = path.join(queue_dir, '.' + fname); var ws = new FsyncWriteStream(tmp_path, { flags: WRITE_EXCL }); // var ws = fs.createWriteStream(tmp_path, { flags: WRITE_EXCL }); ws.on('close', function () { var dest_path = path.join(queue_dir, fname); fs.rename(tmp_path, dest_path, function (err) { if (err) { self.logerror("Unable to rename tmp file!: " + err); fs.unlink(tmp_path, function () {}); cb("Queue error"); } else { hmails.push(new HMailItem (fname, dest_path, todo.notes)); ok_paths.push(dest_path); cb(); } }); }); ws.on('error', function (err) { self.logerror("Unable to write queue file (" + fname + "): " + err); ws.destroy(); fs.unlink(tmp_path, function () {}); cb("Queueing failed"); }); self.build_todo(todo, ws, function () { todo.message_stream.pipe(ws, { line_endings: '\r\n', dot_stuffing: true, ending_dot: false }); }); }; exports.build_todo = function (todo, ws, write_more) { // Replacer function to exclude items from the queue file header function exclude_from_json(key, value) { switch (key) { case 'message_stream': return undefined; default: return value; } } var todo_str = new Buffer(JSON.stringify(todo, exclude_from_json)); // since JS has no pack() we have to manually write the bytes of a long var todo_length = new Buffer(4); var todo_l = todo_str.length; todo_length[3] = todo_l & 0xff; todo_length[2] = (todo_l >> 8) & 0xff; todo_length[1] = (todo_l >> 16) & 0xff; todo_length[0] = (todo_l >> 24) & 0xff; var buf = Buffer.concat([todo_length, todo_str], todo_str.length + 4); var continue_writing = ws.write(buf); if (continue_writing) return write_more(); ws.once('drain', write_more); }; exports.split_to_new_recipients = function (hmail, recipients, response, cb) { var self = this; if (recipients.length === hmail.todo.rcpt_to.length) { // Split to new for no reason - increase refcount and return self hmail.refcount++; return cb(hmail); } var fname = _fname(); var tmp_path = path.join(queue_dir, '.' + fname); var ws = new FsyncWriteStream(tmp_path, { flags: WRITE_EXCL }); // var ws = fs.createWriteStream(tmp_path, { flags: WRITE_EXCL }); var err_handler = function (err, location) { self.logerror("Error while splitting to new recipients (" + location + "): " + err); hmail.bounce("Error splitting to new recipients: " + err); }; ws.on('error', function (err) { err_handler(err, "tmp file writer");}); var writing = false; var write_more = function () { if (writing) return; writing = true; var rs = hmail.data_stream(); rs.pipe(ws, {end: false}); rs.on('error', function (err) { err_handler(err, "hmail.data_stream reader"); }); rs.on('end', function () { ws.on('close', function () { var dest_path = path.join(queue_dir, fname); fs.rename(tmp_path, dest_path, function (err) { if (err) { err_handler(err, "tmp file rename"); } else { var split_mail = new HMailItem (fname, dest_path); split_mail.once('ready', function () { cb(split_mail); }); } }); }); ws.destroySoon(); return; }); }; ws.on('error', function (err) { self.logerror("Unable to write queue file (" + fname + "): " + err); ws.destroy(); hmail.bounce("Error re-queueing some recipients: " + err); }); var new_todo = JSON.parse(JSON.stringify(hmail.todo)); new_todo.rcpt_to = recipients; self.build_todo(new_todo, ws, write_more); }; // TODOItem - queue file header data function TODOItem (domain, recipients, transaction) { this.queue_time = Date.now(); this.domain = domain; this.rcpt_to = recipients; this.mail_from = transaction.mail_from; this.message_stream = transaction.message_stream; this.notes = transaction.notes; this.uuid = transaction.uuid; return this; } ///////////////////////////////////////////////////////////////////////////// // HMailItem - encapsulates an individual outbound mail item var dummy_func = function () {}; function HMailItem (filename, path, notes) { events.EventEmitter.call(this); var matches = filename.match(fn_re); if (!matches) { throw new Error("Bad filename: " + filename); } this.path = path; this.filename = filename; this.next_process = matches[1]; this.num_failures = matches[2]; this.notes = notes || {}; this.refcount = 1; this.todo = null; this.file_size = 0; this.next_cb = dummy_func; this.bounce_error = null; this.size_file(); } util.inherits(HMailItem, events.EventEmitter); exports.HMailItem = HMailItem; // populate log functions - so we can use hooks for (var key in logger) { if (key.match(/^log\w/)) { exports[key] = (function (key) { return function () { var args = ["[outbound] "]; for (var i=0, l=arguments.length; i<l; i++) { args.push(arguments[i]); } logger[key].apply(logger, args); }; })(key); HMailItem.prototype[key] = (function (key) { return function () { var args = [ this ]; for (var i=0, l=arguments.length; i<l; i++) { args.push(arguments[i]); } logger[key].apply(logger, args); }; })(key); } } HMailItem.prototype.data_stream = function () { return fs.createReadStream(this.path, {start: this.data_start, end: this.file_size}); }; HMailItem.prototype.size_file = function () { var self = this; fs.stat(self.path, function (err, stats) { if (err) { // we are fucked... guess I need somewhere for this to go self.logerror("Error obtaining file size: " + err); self.temp_fail("Error obtaining file size"); } else { self.file_size = stats.size; self.read_todo(); } }); }; HMailItem.prototype.read_todo = function () { var self = this; var tl_reader = fs.createReadStream(self.path, {start: 0, end: 3}); tl_reader.on('error', function (err) { self.logerror("Error reading queue file: " + self.path + ": " + err); return self.temp_fail("Error reading queue file: " + err); }); tl_reader.on('data', function (buf) { // I'm making the assumption here we won't ever read less than 4 bytes // as no filesystem on the planet should be that dumb... tl_reader.destroy(); var todo_len = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]; var td_reader = fs.createReadStream(self.path, {encoding: 'utf8', start: 4, end: todo_len + 3}); self.data_start = todo_len + 4; var todo = ''; td_reader.on('data', function (str) { todo += str; if (Buffer.byteLength(todo) === todo_len) { // we read everything self.todo = JSON.parse(todo); self.todo.rcpt_to = self.todo.rcpt_to.map(function (a) { return new Address (a); }); self.todo.mail_from = new Address (self.todo.mail_from); self.emit('ready'); } }); td_reader.on('end', function () { if (Buffer.byteLength(todo) !== todo_len) { self.logcrit("Didn't find right amount of data in todo!"); fs.rename(self.path, path.join(queue_dir, "error." + self.filename), function (err) { if (err) { self.logerror("Error creating error file after todo read failure (" + self.filename + "): " + err); } }); self.emit('error', "Didn't find right amount of data in todo!"); // Note nothing picks this up yet } }); }); }; HMailItem.prototype.send = function () { if (cfg.disabled) { // try again in 1 second if delivery is disabled this.logdebug("delivery disabled temporarily. Retrying in 1s."); var hmail = this; setTimeout(function () { hmail.send(); }, 1000); return; } if (!this.todo) { var self = this; this.once('ready', function () { self._send(); }); } else { this._send(); } }; HMailItem.prototype._send = function () { plugins.run_hooks('send_email', this); }; HMailItem.prototype.send_email_respond = function (retval, delay_seconds) { if (retval === constants.delay) { // Try again in 'delay' seconds. this.logdebug("Delivery of this email delayed for " + delay_seconds + " seconds"); var hmail = this; hmail.next_cb(); temp_fail_queue.add(delay_seconds * 1000, function () { delivery_queue.push(hmail); }); } else { this.logdebug("Sending mail: " + this.filename); this.get_mx(); } }; HMailItem.prototype.get_mx = function () { var domain = this.todo.domain; plugins.run_hooks('get_mx', this, domain); }; HMailItem.prototype.get_mx_respond = function (retval, mx) { switch(retval) { case constants.ok: var mx_list; if (Array.isArray(mx)) { mx_list = mx; } else if (typeof mx === "object") { mx_list = [mx]; } else { // assume string var matches = /^(.*?)(:(\d+))?$/.exec(mx); if (!matches) { throw("get_mx returned something that doesn't match hostname or hostname:port"); } mx_list = [{priority: 0, exchange: matches[1], port: matches[3]}]; } this.logdebug("Got an MX from Plugin: " + this.todo.domain + " => 0 " + mx); return this.found_mx(null, mx_list); case constants.deny: this.logwarn("get_mx plugin returned DENY: " + mx); return this.bounce("No MX for " + this.domain); case constants.denysoft: this.logwarn("get_mx plugin returned DENYSOFT: " + mx); return this.temp_fail("Temporary MX lookup error for " + this.domain); } var hmail = this; // if none of the above return codes, drop through to this... exports.lookup_mx(this.todo.domain, function (err, mxs) { hmail.found_mx(err, mxs); }); }; exports.lookup_mx = function lookup_mx (domain, cb) { var mxs = []; // Possible DNS errors // NODATA // FORMERR // BADRESP // NOTFOUND // BADNAME // TIMEOUT // CONNREFUSED // NOMEM // DESTRUCTION // NOTIMP // EREFUSED // SERVFAIL // default wrap_mx just returns our object with "priority" and "exchange" keys var wrap_mx = function (a) { return a; }; var process_dns = function (err, addresses) { if (err) { if (err.code === 'ENODATA') { // Most likely this is a hostname with no MX record // Drop through and we'll get the A record instead. return 0; } cb(err); } else if (addresses && addresses.length) { for (var i=0,l=addresses.length; i < l; i++) { var mx = wrap_mx(addresses[i]); // hmail.logdebug("Got an MX from DNS: " + hmail.todo.domain + " => " + mx.priority + " " + mx.exchange); mxs.push(mx); } cb(null, mxs); } else { // return zero if we need to keep trying next option return 0; } return 1; }; dns.resolveMx(domain, function(err, addresses) { if (process_dns(err, addresses)) { return; } // if MX lookup failed, we lookup an A record. To do that we change // wrap_mx() to return same thing as resolveMx() does. wrap_mx = function (a) { return {priority:0,exchange:a}; }; dns.resolve(domain, function(err, addresses) { if (process_dns(err, addresses)) { return; } err = new Error("Found nowhere to deliver to"); err.code = 'NOMX'; cb(err); }); }); }; HMailItem.prototype.found_mx = function (err, mxs) { if (err) { this.logerror("MX Lookup for " + this.todo.domain + " failed: " + err); if (err.code === dns.NXDOMAIN || err.code === 'ENOTFOUND') { this.bounce("No Such Domain: " + this.todo.domain); } else if (err.code === 'NOMX') { this.bounce("Nowhere to deliver mail to for domain: " + this.todo.domain); } else { // every other error is transient this.temp_fail("DNS lookup failure: " + err); } } else { // got MXs var mxlist = sort_mx(mxs); // support draft-delany-nullmx-02 if (mxlist.length === 1 && mxlist[0].priority === 0 && mxlist[0].exchange === '') { return this.bounce("Domain " + this.todo.domain + " sends and receives no email (NULL MX)"); } // duplicate each MX for each ip address family this.mxlist = []; for (var mx in mxlist) { if (cfg.ipv6_enabled) { this.mxlist.push( { exchange: mxlist[mx].exchange, priority: mxlist[mx].priority, port: mxlist[mx].port, using_lmtp: mxlist[mx].using_lmtp, family: 'AAAA' }, { exchange: mxlist[mx].exchange, priority: mxlist[mx].priority, port: mxlist[mx].port, using_lmtp: mxlist[mx].using_lmtp, family: 'A' } ); } else { mxlist[mx].family = 'A'; this.mxlist.push(mxlist[mx]); } } this.mxlist = mxlist; this.try_deliver(); } }; // MXs must be sorted by priority order, but matched priorities must be // randomly shuffled in that list, so this is a bit complex. function sort_mx (mx_list) { var sorted = mx_list.sort(function (a,b) { return a.priority - b.priority; }); // This isn't a very good shuffle but it'll do for now. for (var i=0,l=sorted.length-1; i<l; i++) { if (sorted[i].priority === sorted[i+1].priority) { if (Math.round(Math.random())) { // 0 or 1 var j = sorted[i]; sorted[i] = sorted[i+1]; sorted[i+1] = j; } } } return sorted; } HMailItem.prototype.try_deliver = function () { var self = this; // check if there are any MXs left if (this.mxlist.length === 0) { return this.temp_fail("Tried all MXs"); } var mx = this.mxlist.shift(); var host = mx.exchange; // IP or IP:port if (net.isIP(host)) { self.hostlist = [ host ]; return self.try_deliver_host(mx); } host = mx.exchange; var family = mx.family; this.loginfo("Looking up " + family + " records for: " + host); // now we have a host, we have to lookup the addresses for that host // and try each one in order they appear dns.resolve(host, family, function (err, addresses) { if (err) { self.logerror("DNS lookup of " + host + " failed: " + err); return self.try_deliver(); // try next MX } if (addresses.length === 0) { // NODATA or empty host list self.logerror("DNS lookup of " + host + " resulted in no data"); return self.try_deliver(); // try next MX } self.hostlist = addresses; self.try_deliver_host(mx); }); }; var smtp_regexp = /^(\d{3})([ -])(?:(\d\.\d\.\d)\s)?(.*)/; HMailItem.prototype.try_deliver_host = function (mx) { if (this.hostlist.length === 0) { return this.try_deliver(); // try next MX } // Allow transaction notes to set outbound IP if (!mx.bind && this.todo.notes.outbound_ip) { mx.bind = this.todo.notes.outbound_ip; } var host = this.hostlist.shift(); var port = mx.port || 25; var socket = sock.connect({port: port, host: host, localAddress: mx.bind}); var self = this; var processing_mail = true; this.loginfo("Attempting to deliver to: " + host + ":" + port + (mx.using_lmtp ? " using LMTP" : "") + " (" + delivery_queue.length() + ") (" + temp_fail_queue.length() + ")"); socket.on('error', function (err) { if (processing_mail) { self.logerror("Ongoing connection failed to " + host + ":" + port + " : " + err); processing_mail = false; // try the next MX self.try_deliver_host(mx); } }); socket.on('close', function () { if (processing_mail) { processing_mail = false; return self.try_deliver_host(mx); } }); socket.setTimeout(30 * 1000); // TODO: make this configurable socket.on('connect', function () { socket.setTimeout(300 * 1000); // TODO: make this configurable }); var command = mx.using_lmtp ? 'connect_lmtp' : 'connect'; var response = []; var recip_index = 0; var recipients = this.todo.rcpt_to; var lmtp_rcpt_idx = 0; var data_marker = 0; var last_recip = null; var ok_recips = []; var fail_recips = []; var bounce_recips = []; var secured = false; var smtp_properties = { "tls": false, "max_size": 0, "eightbitmime": false, "enh_status_codes": false, }; var send_command = function (cmd, data) { if (!socket.writable) { self.logerror("Socket writability went away"); if (processing_mail) { processing_mail = false; return self.try_deliver_host(mx); } return; } var line = cmd + (data ? (' ' + data) : ''); if (cmd === 'dot' || cmd === 'dot_lmtp') { line = '.'; } self.logprotocol("C: " + line); socket.write(line + "\r\n"); command = cmd.toLowerCase(); response = []; }; var process_ehlo_data = function () { for (var i=0,l=response.length; i < l; i++) { var r = response[i]; if (r.toUpperCase() === '8BITMIME') { smtp_properties.eightbitmime = true; } else if (r.toUpperCase() === 'STARTTLS') { smtp_properties.tls = true; } else if (r.toUpperCase() === 'ENHANCEDSTATUSCODES') { smtp_properties.enh_status_codes = true; } else { var matches; matches = r.match(/^SIZE\s+(\d+)$/); if (matches) { smtp_properties.max_size = matches[1]; } } } if (smtp_properties.tls && cfg.enable_tls && !secured) { socket.on('secure', function () { // Set this flag so we don't try STARTTLS again if it // is incorrectly offered at EHLO once we are secured. secured = true; send_command(mx.using_lmtp ? 'LHLO' : 'EHLO', config.get('me')); }); send_command('STARTTLS'); } else { send_command('MAIL', 'FROM:' + self.todo.mail_from); } }; var finish_processing_mail = function (success) { if (fail_recips.length) { self.refcount++; exports.split_to_new_recipients(self, fail_recips, "Some recipients temporarily failed", function (hmail) { self.discard(); hmail.temp_fail("Some recipients temp failed: " + fail_recips.join(', '), { rcpt: fail_recips, mx: mx }); }); } if (bounce_recips.length) { self.refcount++; exports.split_to_new_recipients(self, bounce_recips, "Some recipients rejected", function (hmail) { self.discard(); hmail.bounce("Some recipients failed: " + bounce_recips.join(', '), { rcpt: bounce_recips, mx: mx }); }); } processing_mail = false; if (success) { var reason = response.join(' '); self.delivered(host, port, (mx.using_lmtp ? 'LMTP' : 'SMTP'), mx.exchange, reason, ok_recips, fail_recips, bounce_recips, secured); } else { self.discard(); } send_command('QUIT'); }; socket.on('timeout', function () { if (processing_mail) { self.logerror("Outbound connection timed out to " + host + ":" + port); processing_mail = false; socket.end(); self.try_deliver_host(mx); } }); socket.on('line', function (line) { if (!processing_mail) { if (command !== 'quit') { self.logprotocol("Received data after stopping processing: " + line); } return; } self.logprotocol("S: " + line); var matches = smtp_regexp.exec(line); if (matches) { var reason; var code = matches[1], cont = matches[2], extc = matches[3], rest = matches[4]; response.push(rest); if (cont === ' ') { if (code.match(/^4/)) { if (/^rcpt/.test(command) || command === 'dot_lmtp') { if (command === 'dot_lmtp') last_recip = ok_recips.shift(); // this recipient was rejected reason = code + ' ' + ((extc) ? extc + ' ' : '') + response.join(' '); self.lognotice('recipient ' + last_recip + ' deferred: ' + reason); last_recip.reason = reason; fail_recips.push(last_recip); if (command === 'dot_lmtp') { response = []; if (ok_recips.length === 0) { return finish_processing_mail(true); } } } else { reason = response.join(' '); send_command('QUIT'); processing_mail = false; return self.temp_fail("Upstream error: " + code + " " + ((extc) ? extc + ' ' : '') + reason); } } else if (code.match(/^5/)) { if (command === 'ehlo') { // EHLO command was rejected; fall-back to HELO return send_command('HELO', config.get('me')); } if (/^rcpt/.test(command) || command === 'dot_lmtp') { if (command === 'dot_lmtp') last_recip = ok_recips.shift(); reason = code + ' ' + ((extc) ? extc + ' ' : '') + response.join(' '); self.lognotice('recipient ' + last_recip + ' rejected: ' + reason); last_recip.reason = reason; bounce_recips.push(last_recip); if (command === 'dot_lmtp') { response = []; if (ok_recips.length === 0) { return finish_processing_mail(true); } } } else { reason = response.join(' '); send_command('QUIT'); processing_mail = false; return self.bounce(reason, { mx: mx }); } } switch (command) { case 'connect': send_command('EHLO', config.get('me')); break; case 'connect_lmtp': send_command('LHLO', config.get('me')); break; case 'lhlo': case 'ehlo': process_ehlo_data(); break; case 'starttls': var key = config.get('tls_key.pem', 'binary'); var cert = config.get('tls_cert.pem', 'binary'); var tls_options = { key: key, cert: cert }; smtp_properties = {}; socket.upgrade(tls_options, function (authorized, verifyError, cert, cipher) { self.loginfo('secured:' + ((cipher) ? ' cipher=' + cipher.name + ' version=' + cipher.version : '') + ' verified=' + authorized + ((verifyError) ? ' error="' + verifyError + '"' : '' ) + ((cert && cert.subject) ? ' cn="' + cert.subject.CN + '"' + ' organization="' + cert.subject.O + '"' : '') + ((cert && cert.issuer) ? ' issuer="' + cert.issuer.O + '"' : '') + ((cert && cert.valid_to) ? ' expires="' + cert.valid_to + '"' : '') + ((cert && cert.fingerprint) ? ' fingerprint=' + cert.fingerprint : '')); }); break; case 'helo': send_command('MAIL', 'FROM:' + self.todo.mail_from); break; case 'mail': last_recip = recipients[recip_index]; recip_index++; send_command('RCPT', 'TO:' + last_recip.format()); break; case 'rcpt': if (last_recip && code.match(/^250/)) { ok_recips.push(last_recip); } if (recip_index === recipients.length) { // End of RCPT TOs if (ok_recips.length > 0) { send_command('DATA'); } else { finish_processing_mail(false); } } else { last_recip = recipients[recip_index]; recip_index++; send_command('RCPT', 'TO:' + last_recip.format()); } break; case 'data': var data_stream = self.data_stream(); data_stream.on('data', function (data) { self.logdata("C: " + data); }); data_stream.on('error', function (err) { self.logerror("Reading from the data stream failed: " + err); }); data_stream.on('end', function () { send_command(mx.using_lmtp ? 'dot_lmtp' : 'dot'); }); data_stream.pipe(socket, {end: false}); break; case 'dot': finish_processing_mail(true); break; case 'dot_lmtp': if (code.match(/^2/)) lmtp_rcpt_idx++; if (lmtp_rcpt_idx === ok_recips.length) { finish_processing_mail(true); } break; case 'quit': socket.end(); break; default: // should never get here - means we did something // wrong. throw new Error("Unknown command: " + command); } } } else { // Unrecognised response. self.logerror("Unrecognised response from upstream server: " + line); processing_mail = false; socket.end(); return self.bounce("Unrecognised response from upstream server: " + line, {mx: mx}); } }); }; function populate_bounce_message (from, to, reason, hmail, cb) { var values = { date: utils.date_to_str(new Date()), me: config.get('me'), from: from, to: to, recipients: hmail.todo.rcpt_to.join(', '), reason: reason, extended_reason: hmail.todo.rcpt_to.map(function (recip) { if (recip.reason) { return recip.original + ': ' + recip.reason; } }).join('\n'), pid: process.pid, msgid: '<' + utils.uuid() + '@' + config.get('me') + '>', }; var bounce_msg_ = config.get('outbound.bounce_message', 'data'); var bounce_msg = bounce_msg_.map(function (item) { return item.replace(/\{(\w+)\}/g, function (i, word) { return values[word] || '?'; }) + '\n'; }); var data_stream = hmail.data_stream(); data_stream.on('data', function (data) { bounce_msg.push(data.toString().replace(/\r?\n/g, "\n")); }); data_stream.on('end', function () { cb(null, bounce_msg); }); data_stream.on('error', function (err) { cb(err); }); } HMailItem.prototype.bounce = function (err, opts) { this.loginfo("bouncing mail: " + err); if (!this.todo) { // haven't finished reading the todo, delay here... var self = this; self.once('ready', function () { self._bounce(err); }); return; } this._bounce(err, opts); }; HMailItem.prototype._bounce = function (err, opts) { err = new Error(err); if (opts) { err.mx = opts.mx; err.deferred_rcpt = opts.fail_recips; err.bounced_rcpt = opts.bounce_recips; } this.bounce_error = err; plugins.run_hooks("bounce", this, err); }; HMailItem.prototype.bounce_respond = function (retval, msg) { if (retval !== constants.cont) { this.loginfo("plugin responded with: " + retval + ". Not sending bounce."); return this.discard(); // calls next_cb } var self = this; var err = this.bounce_error; if (!this.todo.mail_from.user) { // double bounce - mail was already a bounce return this.double_bounce("Mail was already a bounce"); } var from = new Address ('<>'); var recip = new Address (this.todo.mail_from.user, this.todo.mail_from.host); populate_bounce_message(from, recip, err, this, function (err, data_lines) { if (err) { return self.double_bounce("Error populating bounce message: " + err); } exports.send_email(from, recip, data_lines.join(''), function (code, msg) { if (code === constants.deny) { // failed to even queue the mail return self.double_bounce("Unable to queue the bounce message. Not sending bounce!"); } self.discard(); }); }); }; HMailItem.prototype.double_bounce = function (err) { this.logerror("Double bounce: " + err); fs.unlink(this.path, function () {}); this.next_cb(); // TODO: fill this in... ? // One strategy is perhaps log to an mbox file. What do other servers do? // Another strategy might be delivery "plugins" to cope with this. }; HMailItem.prototype.delivered = function (ip, port, mode, host, response, ok_recips, fail_recips, bounce_recips, secured) { var delay = (Date.now() - this.todo.queue_time)/1000; this.lognotice("delivered file=" + this.filename + ' domain="' + this.todo.domain + '"' + ' host="' + host + '"' + ' ip=' + ip + ' port=' + port + ' mode=' + mode + ' tls=' + ((secured) ? 'Y' : 'N') + ' response="' + response + '"' + ' delay=' + delay + ' fails=' + this.num_failures + ' rcpts=' + ok_recips.length + '/' + fail_recips.length + '/' + bounce_recips.length); plugins.run_hooks("delivered", this, [host, ip, response, delay, port, mode, ok_recips, secured]); }; HMailItem.prototype.discard = function () { this.refcount--; if (this.refcount === 0) { // Remove the file. fs.unlink(this.path, function () {}); this.next_cb(); } }; HMailItem.prototype.temp_fail = function (err, extra) { this.num_failures++; // Test for max failures which is configurable. if (this.num_failures >= (cfg.maxTempFailures)) { return this.bounce("Too many failures (" + err + ")", extra); } // basic strategy is we exponentially grow the delay to the power // two each time, starting at 2 ** 6 seconds // Note: More advanced options should be explored in the future as the // last delay is 2**17 secs (1.5 days), which is a bit long... Exim has a max delay of // 6 hours (configurable) and the expire time is also configurable... But // this is good enough for now. var delay = Math.pow(2, (this.num_failures + 5)); plugins.run_hooks('deferred', this, {delay: delay, err: err}); }; HMailItem.prototype.deferred_respond = function (retval, msg, params) { if (retval !== constants.cont && retval !== constants.denysoft) { this.loginfo("plugin responded with: " + retval + ". Not deferring. Deleting mail."); return this.discard(); // calls next_cb } var delay = params.delay * 1000; if (retval === constants.denysoft) { delay = parseInt(msg, 10) * 1000; } var until = Date.now() + delay; this.loginfo("Temp failing " + this.filename + " for " + (delay/1000) + " seconds: " + params.err); var new_filename = this.filename.replace(/^(\d+)_(\d+)_/, until + '_' + this.num_failures + '_'); var hmail = this; fs.rename(this.path, path.join(queue_dir, new_filename), function (err) { if (err) { return hmail.bounce("Error re-queueing email: " + err); } hmail.path = path.join(queue_dir, new_filename); hmail.filename = new_filename; hmail.next_cb(); temp_fail_queue.add(delay, function () { delivery_queue.push(hmail); }); }); }; // The following handler has an impact on outgoing mail. It does remove the queue file. HMailItem.prototype.delivered_respond = function (retval, msg) { if (retval !== constants.cont && retval !== constants.ok) { this.logwarn("delivered plugin responded with: " + retval + " msg=" + msg + "."); } this.discard(); };
export default { // The web server of Hakkero Project. server: '', wsServer: '' };
sweetApp.controller('contactController', function ($scope) { });
import React, { Component, PropTypes } from 'react'; import Helmet from 'react-helmet'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { IntlProvider, FormattedMessage } from 'react-intl'; import config from 'config'; import NavBar from 'components/NavBar/NavBar'; import { changeLocale } from 'redux/modules/i18n'; import * as i18n from './i18n'; // Intl Polyfill for Internet Explorer import Intl from 'intl'; // eslint-disable-line // Global scss import 'theme/app.scss'; class App extends Component { static propTypes = { dispatch: PropTypes.func.isRequired, children: PropTypes.object.isRequired, locale: PropTypes.string.isRequired, locales: PropTypes.array.isRequired }; constructor(props) { super(props); this.onLocaleClick = this.onLocaleClick.bind(this); } onLocaleClick(locale) { this.props.dispatch(changeLocale(locale)); } render() { const styles = require('./App.scss'); const { locale, locales } = this.props; const logo = require('./../../../static/logo.jpg'); return ( <IntlProvider key="intl" locale={locale} messages={i18n[locale]}> <div className={styles.app}> <Helmet {...config.app.head} /> <NavBar locale={locale} locales={locales} onLocaleClick={this.onLocaleClick} logo={logo}> <Link to="/" className="h2"><FormattedMessage id="navigation.home"/></Link> <Link to="/links" className="h2"><FormattedMessage id="navigation.useful_links"/></Link> <Link to="/about" className="h2"><FormattedMessage id="navigation.about"/></Link> </NavBar> <div className={styles.container}> {this.props.children} </div> </div> </IntlProvider> ); } } function mapStateToProps(state) { return { locale: state.i18n.locale, locales: state.i18n.locales }; } export default connect(mapStateToProps)(App);
'use strict'; // Declare app level module which depends on filters, and services angular.module('testSPA', [ 'ngRoute', 'testSPA.filters', 'testSPA.services', 'testSPA.directives', 'testSPA.controllers', 'testSPA.navBar', 'testSPA.investmentsComponent', 'testSPA.sectorComponent', 'testSPA.transactionsComponent', 'testSPA.investmentFilter', 'testSPA.investmentPage' ]). config(['$routeProvider', function($routeProvider) { $routeProvider.when('/home', {templateUrl: 'partials/home-page.html', controller: 'HomeCtrl'}); $routeProvider.when('/about', {templateUrl: 'partials/about-page.html', controller: 'AboutCtrl'}); $routeProvider.when('/investment/:id', { templateUrl: 'partials/investment-page.html', controller: 'InvestmentPageCtrl' }); $routeProvider.otherwise({ redirectTo: '/home' }); }]);
import LifeFlare from '../entities/LifeFlare'; class God extends Phaser.Sprite { constructor(game, direction, x, y, textureKey0, textureKey1, textureKey2, textureKey3, textureKey4, textureKey5) { super(game, x, y, textureKey0); this.textureKey0 = textureKey0; this.textureKey1 = textureKey1; this.textureKey2 = textureKey2; this.textureKey3 = textureKey3; this.textureKey4 = textureKey4; this.textureKey5 = textureKey5; this.anchor.x = 0.5; this.anchor.y = 0.5; this.animations.add('default'); this.animations.play('default', 30, true); this.game.add.tween(this).to({y: 135}, 2000, Phaser.Easing.Quadratic.InOut, true, 0, 1000, true); this.game.stage.addChild(this); this.level = 0; this.skills = {}; this.scale.x *= direction; this.lifeParticles = []; } subtractLife(number) { if (this.lastEvent) { this.game.time.events.remove(this.lastEvent); this.lastEvent = null; } this.animate("a5"); this.lastEvent = this.game.time.events.add(Phaser.Timer.SECOND * 2, this.restore, this); if (this.lifeParticles.length > 0) { for (let i = 0; i < number; i++) { if (this.lifeParticles.length <= 0) { break; } let p = this.lifeParticles.pop(); p.destroy(); } } } addLife(number) { let x = this.initialX; if (this.lifeParticles.length > 0) { x = this.lifeParticles[this.lifeParticles.length - 1].fire.x; } console.log(x); for (let i = 1; i < number + 1; i++) { if (this.lifeParticles.length < 10) { this.lifeParticles.push(new LifeFlare(this.game, x + i * 35, 250)); } else { break; } } } setLife(x) { this.initialX = x; for (let i = 1; i < 11; i++) { this.lifeParticles.push(new LifeFlare(this.game, this.initialX + i * 35, 250)); } } addSkill(key, skill) { this.skills[key] = skill; skill.setOwner(this); } restore() { this.loadTexture(this.textureKey0, 0); this.animations.play('default'); } animate(key) { switch (key) { case 'a1': this.loadTexture(this.textureKey1, 0); this.animations.add('a1'); this.animations.play('a1', 30, true); break; case 'a2': this.loadTexture(this.textureKey2, 0); this.animations.add('a2'); this.animations.play('a2', 30, true); break; case 'a3': this.loadTexture(this.textureKey3, 0); this.animations.add('a3'); this.animations.play('a3', 30, true); break; case 'a4': this.loadTexture(this.textureKey4, 0); this.animations.add('a4'); this.animations.play('a4', 30, true); break; case 'a5': this.loadTexture(this.textureKey5, 0); this.animations.add('a5'); this.animations.play('a5', 30, true); break; } } attack1(enemy) { if (this.lastEvent) { this.game.time.events.remove(this.lastEvent); this.lastEvent = null; } this.animate(this.activateSkillKey1); this.lastEvent = this.game.time.events.add(Phaser.Timer.SECOND * this.activeSkill1.duration, this.restore, this); this.activeSkill1.performAction(enemy); } attack2(enemy) { if (this.lastEvent) { this.game.time.events.remove(this.lastEvent); this.lastEvent = null; } this.animate(this.activateSkillKey2); this.lastEvent = this.game.time.events.add(Phaser.Timer.SECOND * this.activeSkill2.duration, this.restore, this); this.activeSkill2.performAction(enemy); } attack3(enemy) { if (this.lastEvent) { this.game.time.events.remove(this.lastEvent); this.lastEvent = null; } if (this.lifeParticles.length >= 3) { this.animate("a1"); this.lastEvent = this.game.time.events.add(Phaser.Timer.SECOND * 2, this.restore, this); enemy.god.subtractLife(enemy.god.lifeParticles.length - 1); return true; } else { return false; } } show2RandomSkills(x1, x2) { if (this.activeSkill1) { this.activeSkill1.removeFromGame(); } if (this.activeSkill2) { this.activeSkill2.removeFromGame(); } let skills = ['a1', 'a2', 'a3', 'a4']; this.activateSkillKey1 = skills[Math.floor(Math.random() * skills.length)]; let i = skills.indexOf(this.activateSkillKey1); if (i != -1) { skills.splice(i, 1); } this.activateSkillKey2 = skills[Math.floor(Math.random() * skills.length)]; this.activeSkill1 = this.skills[this.activateSkillKey1]; this.activeSkill2 = this.skills[this.activateSkillKey2]; this.activeSkill1.addToGame(this.game, x1, 510); this.activeSkill2.addToGame(this.game, x2, 510); } } export default God;
var Stream = require('stream'); var deepEqual = require('deep-equal'); var defined = require('defined'); var path = require('path'); var inherits = require('util').inherits; var EventEmitter = require('events').EventEmitter; module.exports = Test; var nextTick = typeof setImmediate !== 'undefined' ? setImmediate : process.nextTick ; inherits(Test, EventEmitter); function Test (name_, opts_, cb_) { var self = this; var name = '(anonymous)'; var opts = {}; var cb; for (var i = 0; i < arguments.length; i++) { switch (typeof arguments[i]) { case 'string': name = arguments[i]; break; case 'object': opts = arguments[i] || opts; break; case 'function': cb = arguments[i]; } } this.readable = true; this.name = name || '(anonymous)'; this.assertCount = 0; this._skip = opts.skip || false; this._plan = undefined; this._cb = cb; this._progeny = []; this._ok = true; } Test.prototype.run = function () { if (this._skip) { return this.end(); } this.emit('prerun'); try { this._cb(this); } catch (err) { this.error(err); this.end(); return; } this.emit('run'); }; Test.prototype.test = function (name, opts, cb) { var t = new Test(name, opts, cb); this._progeny.push(t); this.emit('test', t); }; Test.prototype.comment = function (msg) { this.emit('result', msg.trim().replace(/^#\s*/, '')); }; Test.prototype.plan = function (n) { this._plan = n; this.emit('plan', n); }; Test.prototype.end = function () { var self = this; if (this._progeny.length) { var t = this._progeny.shift(); t.on('end', function () { self.end() }); return; } if (!this.ended) this.emit('end'); if (this._plan !== undefined && !this._planError && this.assertCount !== this._plan) { this._planError = t
var searchData= [ ['kernelid_632',['KernelId',['../namespacektt.html#a47b4d6f1468a13007692b8bd5dbe42ba',1,'ktt']]] ];
describe('Server', function(){ var io = require('socket.io-client'); var Server = require('../../src/server'); var Config = require('../../src/config'); var server; var fakeApp = new Object(); fakeApp.Config = new Config({ server: { port: 30661 } }); fakeApp.log = function() {}; fakeApp.error = function() {}; //Start server beforeEach(function() { server = new Server(); server.initialize(fakeApp); }); it('add client', function() { var fakeClient = new Object(); server.add_client(fakeClient); expect(server.clients[0].ident).not.toBe(null); expect(server.clients[0].client).toBe(fakeClient); expect(server.clients.length).toBe(1); }); it('add multiple client', function() { server.add_client(new Object()); server.add_client(new Object()); server.add_client(new Object()); expect(server.clients.length).toBe(3); }); it('add multiple clients and remove them', function() { var ident1 = server.add_client(new Object()); var ident2 = server.add_client(new Object()); var ident3 = server.add_client(new Object()); server.remove_client(ident1); server.remove_client(ident2); server.remove_client(ident3); expect(server.clients.length).toBe(0); }); it('check single client connect then disconnect', function(done) { server.start(); var socket = io.connect('http://localhost:'+fakeApp.Config.read('server.port')); socket.on('connect', function(){ socket.on('disconnect',function() { server.stop(); setTimeout(function() { expect(server.clients.length).toBe(0); done(); },50); }); expect(server.clients.length).toBe(1); socket.close(); }); }); });
//for application bootstrap App = new Backbone.Marionette.Application(); // add some Regions App.addRegions({ // drawRegion: Perber.Region.Draw, mainRegion: '#main', headerRegion: '#header', toolbarRegion:'#toolbar', sidebarRegion:'#sidebar', // videosRegion: "#videos", // overlayRegion: "#overlay", // loadingRegion: "#loadingWave", // modalRegion:Perber.Region.Modal, }); App.addInitializer(function(){ Perber.user = new Perber.Model.Me(Perber.config.user); // Perber.user.start(); Perber.users = new Perber.Collection.Users(); Perber.activity = new Perber.Collection.ActivitysItems(); // show main and speak pannel App.mainRegion.show( // new Perber.View.Speakpanel() new Perber.View.Activity({ // new Perber.View.PerberItem() collection: Perber.activity, user : Perber.user }) ); App.headerRegion.show( new Perber.View.Navbar() ); // App.toolbarRegion.show( // new Perber.View.Toolbar(), // ); App.sidebarRegion.show( new Perber.View.Sidebar() ); }); $(function(){ App.start(); });
'use strict' module.exports = require('./node')
import G6 from '@antv/g6'; /** * 该案例演示,当点击叶子节点时,如何动态向树图中添加多条数据。 * 主要演示changeData的用法。 */ const width = document.getElementById('container').scrollWidth; const height = document.getElementById('container').scrollHeight || 500; const graph = new G6.TreeGraph({ container: 'container', width, height, pixelRatio: 2, modes: { default: [ 'collapse-expand', 'drag-canvas' ] }, fitView: true, layout: { type: 'compactBox', direction: 'LR', defalutPosition: [], getId: function getId(d) { return d.id; }, getHeight: function getHeight() { return 16; }, getWidth: function getWidth() { return 16; }, getVGap: function getVGap() { return 50; }, getHGap: function getHGap() { return 100; } } }); graph.node(function(node) { return { size: 16, anchorPoints: [[ 0, 0.5 ], [ 1, 0.5 ]], style: { fill: '#DEE9FF', stroke: '#5B8FF9' }, label: node.id, labelCfg: { position: node.children && node.children.length > 0 ? 'left' : 'right' } }; }); let i = 0; graph.edge(function() { i++; return { shape: 'cubic-horizontal', color: '#A3B1BF', label: i }; }); const data = { isRoot: true, id: 'Root', style: { fill: 'red' }, children: [{ id: 'SubTreeNode1', raw: {}, children: [{ id: 'SubTreeNode1.1' }, { id: 'SubTreeNode1.2', children: [{ id: 'SubTreeNode1.2.1' }, { id: 'SubTreeNode1.2.2' }, { id: 'SubTreeNode1.2.3' }] }] }, { id: 'SubTreeNode2', children: [{ id: 'SubTreeNode2.1' }] }, { id: 'SubTreeNode3', children: [{ id: 'SubTreeNode3.1' }, { id: 'SubTreeNode3.2' }, { id: 'SubTreeNode3.3' }] }, { id: 'SubTreeNode4' }, { id: 'SubTreeNode5' }, { id: 'SubTreeNode6' }] }; graph.data(data); graph.render(); let count = 0; graph.on('node:click', function(evt) { const item = evt.item; const nodeId = item.get('id'); const model = item.getModel(); const children = model.children; if (!children || children.length === 0) { const childData = [{ id: 'child-data-' + count, shape: 'rect', children: [{ id: 'x-' + count }, { id: 'y-' + count }] }, { id: 'child-data1-' + count, children: [{ id: 'x1-' + count }, { id: 'y1-' + count }] }]; const parentData = graph.findDataById(nodeId); if (!parentData.children) { parentData.children = []; } // 如果childData是一个数组,则直接赋值给parentData.children // 如果是一个对象,则使用parentData.children.push(obj) parentData.children = childData; graph.changeData(); count++; } });
'use strict' const db = require('APP/db') const Review = db.model('reviews') const {mustBeLoggedIn, forbidden} = require('./auth.filters') module.exports = require('express').Router() .get('/', // The forbidden middleware will fail *all* requests to list users. // Remove it if you want to allow anyone to list all users on the site. // // If you want to only let admins list all the users, then you'll // have to add a role column to the users table to support // the concept of admin users. forbidden('listing reviews is not allowed'), (req, res, next) => Review.findAll() .then(reviews => res.json(reviews)) .catch(next)) .post('/', (req, res, next) => Review.create(req.body) .then(review => res.status(201).json(review)) .catch(next)) .get('/:id', // TO DO: make sure that this review belongs to user and review (req, res, next) => Review.findById(req.params.id) .then(review => { res.json(review)}) .catch(next)) .put('/:id', // TO DO: make sure that this review belongs to user and review // must be logged in to edit? mustBeLoggedIn, (req, res, next) => Review.findById(req.params.id) .then(review => review.update(req.body)) .then(updatedreview => res.json(updatedreview)) .catch(next)) .delete('/:id', // TO DO: make sure that this user is Admin mustBeLoggedIn, (req, res, next) => Review.findById(req.params.id) .then(review => review.destroy()) .then(wasDestroyedBool => { if (wasDestroyedBool) { res.sendStatus(204) } else { const err = Error('review not destroyed') err.status = 400 throw err } }) .catch(next))
'use strict'; const joi = require('joi'); /** * Результат проверки. * * @typedef {Object} ValidationResult * @property {Boolean} isValid * @property {String} [message] */ /** * Проверяет запрос на соответствие схемам. * * @param {express.Request} req * @param {Object} schemas * @returns {ValidationResult} */ module.exports = function (req, schemas) { let result = validate(req.params, schemas.params); if (!result.isValid) { return result; } result = validate(req.query, schemas.query); if (!result.isValid) { return result; } result = validate(req.body, schemas.body); if (!result.isValid) { return result; } return validate(req.headers, schemas.headers); }; function validate(value, schema) { if (!value || !schema) { return {isValid: true}; } const result = joi.validate(value, schema, {allowUnknown: true}); if (result.error) { return { isValid: false, message: result.error.details[0].message }; } return {isValid: true}; }
/** * ### Actions functions * * Common functions that will be available on all actions * * @module Models/actions */ "use strict"; const path = require("path"); const factory = require("./factory"); const utils = require(path.resolve(__dirname, "../lib/utils")); const state = require(utils.getModulePath("lib/state")); // Will be garbage-collected as soon as the definitive actions model will be // created const tempModel = factory.createModel("action"); const actions = Object.assign(tempModel, { /** * Perform an action * Since actions are functions that interact with the universe they need * two major references : * - The State: which will allow them to interact with it * - Other actions: so that actions composition can be possible * To keep a clean, evolvable API, it is a best practice to communicate * with objects (so they can be destructured at call and return). * @param {String} id - Action name * @param {Object} parameters - Action Parameters * @return {Mixed} Action result */ performAction: (id, parameters) => tempModel .getById(id)({ internals: { state: state, actions: tempModel.getAll() }, parameters: parameters }) }); actions.init({}); module.exports = actions;
var PageTransitions = (function() { var $main = jQuery( '#pt-main' ), $hamburger = jQuery('.hamburger'), pageMain = '.pt-page-main', pageMenu = '.pt-page-menu', isAnimating = false, endCurrPage = false, endNextPage = false, animEndEventNames = { 'WebkitAnimation' : 'webkitAnimationEnd', 'OAnimation' : 'oAnimationEnd', 'msAnimation' : 'MSAnimationEnd', 'animation' : 'animationend' }, // animation end event name animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ], // support css animations support = Modernizr.cssanimations, initialized = false; function onEndAnimation( outpage, inpage ) { if(!endCurrPage || !endNextPage){ return; } jQuery(outpage).attr( 'class', jQuery(outpage).data( 'originalClassList' ) ); jQuery(inpage).attr( 'class', jQuery(inpage).data( 'originalClassList' ) + ' pt-page-current' ); isAnimating = false; } function animate(current,next,action){ if( isAnimating ) { return false; } isAnimating = true; var $nextPage = jQuery(next); var $currPage = jQuery(current); var outClass, inClass; if(action === "left"){ outClass = 'pt-page-moveToRightFade'; inClass = 'pt-page-current pt-page-moveFromLeftFade'; } else { outClass = 'pt-page-moveToLeftFade'; inClass = 'pt-page-current pt-page-moveFromRightFade'; } $currPage.addClass( outClass ); $currPage.on( animEndEventName, function() { // $currPage.off( animEndEventName ); endCurrPage = true; onEndAnimation( current, next ); } ); $nextPage.addClass(inClass ) ; $nextPage.on( animEndEventName, function() { // $nextPage.off( animEndEventName ); endNextPage = true; onEndAnimation( current, next ); } ); } function init() { jQuery(pageMain).addClass( 'pt-page-current' ); $hamburger.click(function(){ if(!initialized){ initialized = true; jQuery('.pt-page').each( function() { jQuery( this ).data( 'originalClassList', jQuery( this ).attr( 'class' ).replace("pt-page-current", "")); } ); } var action = ""; if(jQuery(this).hasClass('is-active')){ //close currPage = pageMenu; nextPage = pageMain; action = "right"; } else { //open currPage = pageMain; nextPage = pageMenu; action = "left"; } animate(currPage,nextPage,action); }); } init(); return { init : init, animate : animate }; })(); // PageTransitions.animate('.pt-page-menu','.pt-page-main','right');
'use strict'; /** * Module dependencies */ var path = require('path'), config = require(path.resolve('./config/config')); /** * Instructors module init function. */ module.exports = function (app, db) { };
const Discord = require('discord.js'); module.exports = (client, message, args) => { message.channel.send({embed:{ color: 3447003, author: { name: message.guild.name, icon_url: message.guild.iconURL }, title: `Informações do servidor`, /*url: "http://google.com",*/ description: `${message.guild.name}`, fields: [ { name: `Nome: `, value: `${message.guild.name}` /*value: "[link](http://google.com)."*/ , "inline": true }, { name: `Número do ID: `, value: `${message.guild.id}`, "inline": true }, { name: `Localização: `, value: `${message.guild.region}`, "inline": true }, { name: `Data de criação: `, value: `${message.guild.createdAt}` }, { name: `Dono: `, value: `${message.guild.owner.user.tag}`, "inline": true }, { name: `Apelido: `, value: `${message.guild.owner.nickname}`, "inline": true }, { name: `Número do ID do dono: `, value: `${message.guild.owner.user.id}`, "inline": true }, { name: `Cargos existentes: `, value: message.guild.roles.map(role => role.name).join(', ') }, { name: `Total de canais: `, value: `${message.guild.channels.filter(chan => chan.type === 'voice').size} voz / ${message.guild.channels.filter(chan => chan.type === 'text').size} texto`, "inline": true }, { name: `Total de BoTs: `, value: `${message.guild.members.filter(member => member.user.bot).size}`, "inline": true }, { name: `Usuários cadastrados: `, value: `${message.guild.memberCount}`, "inline": true } //não use as roles fora das embeds(normal text) (vai chamar a atenção de todo mundo online) ], timestamp: new Date(), footer: { icon_url: client.user.avatarURL , text: "© Verificado em" } } }).then(msg => { msg.delete(60000) }); message.delete(60000); };
//# dc.js Getting Started and How-To Guide 'use strict'; /* jshint globalstrict: true */ /* global dc,d3,crossfilter,colorbrewer */ Math.average = function() { var cnt, tot, i; cnt = arguments.length; tot = i = 0; while (i < cnt) tot+= arguments[i++]; return tot / cnt; } // ### Create Chart Objects // Create chart objects assocated with the container elements identified by the css selector. // Note: It is often a good idea to have these objects accessible at the global scope so that they can be modified or filtered by other page controls. var catname = myCatArray; var pieNumber = catname.length; var catChart = []; for (var i=0;i<=pieNumber;i++){ var text = "#" + catname[i]; catChart[i] = dc.pieChart(text); } var histoChart = dc.barChart("#histo-chart"); var statChart = dc.barChart("#stat-chart"); var quarterChart = dc.pieChart("#quarter-chart"); var fractionChart = dc.pieChart("#fraction-chart"); var dayOfWeekChart = dc.rowChart("#day-of-week-chart"); var ribosomeBarsChart = dc.rowChart("#ribosome-bars-chart"); /* d3.csv("humanVSrat_merged.csv", function (csv) { alert(csv[0][1]); }); */ function houston(variable){return variable;} //var moveChart = dc.lineChart("#monthly-move-chart"); //var volumeChart = dc.barChart("#monthly-volume-chart"); //var yearlyBubbleChart = dc.bubbleChart("#yearly-bubble-chart"); // ### Anchor Div for Charts /* // A div anchor that can be identified by id <div id="your-chart"></div> // Title or anything you want to add above the chart <div id="chart"><span>Days by Gain or Loss</span></div> // ##### .turnOnControls() // If a link with css class "reset" is present then the chart // will automatically turn it on/off based on whether there is filter // set on this chart (slice selection for pie chart and brush // selection for bar chart). Enable this with `chart.turnOnControls(true)` <div id="chart"> <a class="reset" href="javascript:myChart.filterAll();dc.redrawAll();" style="display: none;">reset</a> </div> // dc.js will also automatically inject applied current filter value into // any html element with css class set to "filter" <div id="chart"> <span class="reset" style="display: none;">Current filter: <span class="filter"></span></span> </div> */ //### Load your data //Data can be loaded through regular means with your //favorite javascript library // //```javascript //d3.csv("data.csv", function(data) {...}; //d3.json("data.json", function(data) {...}; //jQuery.getJson("data.json", function(data){...}); //``` // //var myCSVfileName = "humanVSrat_merged.csv"; var getKeys = function(obj){ var keys = []; for(var key in obj){ keys.push(key); } return keys; } //myCSVfileNmae = transduct(); var mycatlist = []; d3.csv(myCSVfileName, function (data) { /* since its a csv file we need to format the data a bit */ var numberFormat = d3.format(".2f"); var totalpident = 0; //Initialize of Data Formats data.forEach(function (d) { d.pident = +d.pident; totalpident += d.pident; d.count = 1; for(var i=0;i<=pieNumber;i++){ d[catname[i]] = +d[catname[i]]; } }); // document.write(totalpident); //### Create Crossfilter Dimensions and Groups //See the [crossfilter API](https://github.com/square/crossfilter/wiki/API-Reference) for reference. var ndx = crossfilter(data); var all = ndx.groupAll(); var dimensions = []; var thegroups = []; for(var i=0;i<=pieNumber;i++){ dimensions[i] = ndx.dimension(function (d) { return d[catname[i]] == 1 ? "Yes":"No"; }); thegroups[i] = dimensions[i].group(); } /* var category1Var = ndx.dimension(function (d) { return d.category1 == 1 ? "Yes":"No"; }); var category1Group = category1Var.group(); var category2Var = ndx.dimension(function (d) { return d[category2] == 1 ? "Yes":"No"; }); var category2Group = category2Var.group(); var category3Var = ndx.dimension(function (d) { return d[category3] == 1 ? "Yes":"No"; }); var category3Group = category3Var.group(); var category4Var = ndx.dimension(function (d) { return d[category4] == 1 ? "Yes":"No"; }); var category4Group = category4Var.group(); var category5Var = ndx.dimension(function (d) { return d[category5] == 1 ? "Yes":"No"; }); var category5Group = category5Var.group(); var category6Var = ndx.dimension(function (d) { return d[category6] == 1 ? "Yes":"No"; }); var category6Group = category6Var.group(); var category7Var = ndx.dimension(function (d) { return d.category7 == 1 ? "Yes":"No"; }); var category7Group = category7Var.group(); var category8Var = ndx.dimension(function (d) { return d.category8 == 1 ? "Yes":"No"; }); var category8Group = category8Var.group(); var category9Var = ndx.dimension(function (d) { return d.category9 == 1 ? "Yes":"No"; }); var category9Group = category9Var.group(); var category10Var = ndx.dimension(function (d) { return d.category10 == 1 ? "Yes":"No"; }); var category10Group = category10Var.group(); var category11Var = ndx.dimension(function (d) { return d.category11 == 1 ? "Yes":"No"; }); var category11Group = category11Var.group(); var category12Var = ndx.dimension(function (d) { return d.category12 == 1 ? "Yes":"No"; }); var category12Group = category12Var.group(); */ var anyVarOri = "morpho"; var anyVar = ndx.dimension(function (d) { return d[anyVarOri] == 1 ? "Yes":"No"; }); var anyGroup = anyVar.group(); // create categorical dimension var gainOrLoss = ndx.dimension(function (d) { return d.chemo == 1 ? "Yes":"No"; }); var signal = ndx.dimension(function (d) { return d.signal == 1 ? "Yes":"No"; }); // produce counts records in the dimension var gainOrLossGroup = gainOrLoss.group(); var signalGroup = signal.group(); var ribosome = ndx.dimension(function (d) { return d.ribosom == 1 ? "Yes":"No"; }); var ribosomeGroup = ribosome.group(); var riboCount = ndx.dimension(function (d) { var coun = 0; if (d.chemo == 1){ var coun = coun + 1 } return coun; }); var riboCountGroup = riboCount.group(); var enzyme = ndx.dimension(function (d) { return d.enzyme == 1 ? "Yes":"No"; }); var enzymeGroup = enzyme.group(); var enzymeCount = ndx.dimension(function (d) { var coun = 0; if (d.enzyme == 1){ var coun = coun + 1 } return coun; }); var enzymeCountGroup = riboCount.group(); var GPCR = ndx.dimension(function (d) { return d.GPCR == 1 ? "Yes":"No"; }); var GPCRGroup = GPCR.group(); var GPCRCount = ndx.dimension(function (d) { var coun = 0; if (d.GPCR == 1){ var coun = coun + 1 } return coun; }); var GPCRCountGroup = GPCRCount.group(); var morpho = ndx.dimension(function (d) { return d.morpho == 1 ? "Yes":"No"; }); var morphoGroup = morpho.group(); var morphoCount = ndx.dimension(function (d) { var coun = 0; if (d.morpho == 1){ var coun = coun + 1 } return coun; }); var morphoCountGroup = morphoCount.group(); // determine a histogram of percent changes var myhistogram = ndx.dimension(function(d) { return Math.round(d.pident); }); var myhistogramGroup = myhistogram.group(); var mean = ndx.dimension(function(d) { var themean = Math.average(d.pident); return themean; }); var meanGroup = mean.group(); // summerize volume by quarter var fraction = ndx.dimension(function(d){ return d.count; }); var fractionGroup = fraction.group().reduceSum(function(d) { return d.count;}); var quarter = ndx.dimension(function (d) { var month = d.pident; if (month <= 25) return "Q1"; else if (month > 25 && month <= 50) return "Q2"; else if (month > 50 && month <= 75) return "Q3"; else return "Q4"; }); var quarterGroup = quarter.group().reduceSum(function (d) { return d.pident; }); var pieWidth = 145 var pieHeight = 120 var pieRadius = 50 /* // counts per weekday var dayOfWeek = ndx.dimension(function (d) { var day = d.chemo; var name=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]; return day+"."+name[day]; }); var dayOfWeekGroup = dayOfWeek.group(); */ //### Define Chart Attributes //Define chart attributes using fluent methods. See the [dc API Reference](https://github.com/dc-js/dc.js/blob/master/web/docs/api-1.7.0.md) for more information // // //#### Bubble Chart //Create a bubble chart and use the given css selector as anchor. You can also specify //an optional chart group for this chart to be scoped within. When a chart belongs //to a specific group then any interaction with such chart will only trigger redraw //on other charts within the same chart group. /* dc.bubbleChart("#yearly-bubble-chart", "chartGroup") */ /* yearlyBubbleChart .width(990) // (optional) define chart width, :default = 200 .height(250) // (optional) define chart height, :default = 200 .transitionDuration(1500) // (optional) define chart transition duration, :default = 750 .margins({top: 10, right: 50, bottom: 30, left: 40}) .dimension(yearlyDimension) //Bubble chart expect the groups are reduced to multiple values which would then be used //to generate x, y, and radius for each key (bubble) in the group .group(yearlyPerformanceGroup) .colors(colorbrewer.RdYlGn[9]) // (optional) define color function or array for bubbles .colorDomain([-500, 500]) //(optional) define color domain to match your data domain if you want to bind data or color //##### Accessors //Accessor functions are applied to each value returned by the grouping // //* `.colorAccessor` The returned value will be mapped to an internal scale to determine a fill color //* `.keyAccessor` Identifies the `X` value that will be applied against the `.x()` to identify pixel location //* `.valueAccessor` Identifies the `Y` value that will be applied agains the `.y()` to identify pixel location //* `.radiusValueAccessor` Identifies the value that will be applied agains the `.r()` determine radius size, by default this maps linearly to [0,100] .colorAccessor(function (d) { return d.value.absGain; }) .keyAccessor(function (p) { return p.value.absGain; }) .valueAccessor(function (p) { return p.value.percentageGain; }) .radiusValueAccessor(function (p) { return p.value.fluctuationPercentage; }) .maxBubbleRelativeSize(0.3) .x(d3.scale.linear().domain([-2500, 2500])) .y(d3.scale.linear().domain([-100, 100])) .r(d3.scale.linear().domain([0, 4000])) //##### Elastic Scaling //`.elasticX` and `.elasticX` determine whether the chart should rescale each axis to fit data. //The `.yAxisPadding` and `.xAxisPadding` add padding to data above and below their max values in the same unit domains as the Accessors. .elasticY(true) .elasticX(true) .yAxisPadding(100) .xAxisPadding(500) .renderHorizontalGridLines(true) // (optional) render horizontal grid lines, :default=false .renderVerticalGridLines(true) // (optional) render vertical grid lines, :default=false .xAxisLabel('Index Gain') // (optional) render an axis label below the x axis .yAxisLabel('Index Gain %') // (optional) render a vertical axis lable left of the y axis //#### Labels and Titles //Labels are displaed on the chart for each bubble. Titles displayed on mouseover. .renderLabel(true) // (optional) whether chart should render labels, :default = true .label(function (p) { return p.key; }) .renderTitle(true) // (optional) whether chart should render titles, :default = false .title(function (p) { return [p.key, "Index Gain: " + numberFormat(p.value.absGain), "Index Gain in Percentage: " + numberFormat(p.value.percentageGain) + "%", "Fluctuation / Index Ratio: " + numberFormat(p.value.fluctuationPercentage) + "%"] .join("\n"); }) //#### Customize Axis //Set a custom tick format. Note `.yAxis()` returns an axis object, so any additional method chaining applies to the axis, not the chart. .yAxis().tickFormat(function (v) { return v + "%"; }); */ // #### Pie/Donut Chart // Create a pie chart and use the given css selector as anchor. You can also specify // an optional chart group for this chart to be scoped within. When a chart belongs // to a specific group then any interaction with such chart will only trigger redraw // on other charts within the same chart group. for(var i=0;i<=pieNumber;i++){ var temp = catChart[i]; catChart[i] .width(pieWidth) .height(pieHeight) .radius(pieRadius) .dimension(dimensions[i]) .group(thegroups[i]) .label(function (d) { if (temp.hasFilter() && !temp.hasFilter(d.key)) return d.key + "(0%)"; return d.key + "(" + Math.floor(d.value / all.value() * 100) + "%)"; }); } fractionChart .width(240) .height(120) .radius(60) .dimension(fraction) .group(fractionGroup) /* // (optional) whether chart should render labels, :default = true .renderLabel(true) // (optional) if inner radius is used then a donut chart will be generated instead of pie chart .innerRadius(40) // (optional) define chart transition duration, :default = 350 .transitionDuration(500) // (optional) define color array for slices .colors(['#3182bd', '#6baed6', '#9ecae1', '#c6dbef', '#dadaeb']) // (optional) define color domain to match your data domain if you want to bind data or color .colorDomain([-1750, 1644]) // (optional) define color value accessor .colorAccessor(function(d, i){return d.value;}) */ quarterChart.width(pieWidth) // .colors(['#3182bd', '#6baed6', '#9ecae1', "red"]) .height(pieHeight) .radius(pieRadius) .innerRadius(20) .dimension(quarter) .group(quarterGroup); //#### Row Chart dayOfWeekChart.width(240) .height(120) .margins({top: 20, left: 10, right: 10, bottom: 20}) .group(signalGroup) .dimension(signal) // assign colors to each value in the x scale domain .ordinalColors(['#3182bd', '#6baed6', '#9ecae1', '#c6dbef', '#dadaeb']) .label(function (d) { return d.key.split(".")[1]; }) // title sets the row text .title(function (d) { return d.value; }) .elasticX(true) .xAxis().ticks(4); ribosomeBarsChart.width(120) .height(100) .margins({top: 20, left: 10, right: 10, bottom: 20}) .group(riboCountGroup) .dimension(riboCount) // assign colors to each value in the x scale domain .ordinalColors(['#3182bd', '#6baed6', '#9ecae1', '#c6dbef', '#dadaeb']) .label(function (d) { if (d.key==1){return "Yes";} else{return "No";} }) // title sets the row text .title(function (d) { return d.value; }) .elasticX(true) .xAxis().ticks(2); //#### Bar Chart // Create a bar chart and use the given css selector as anchor. You can also specify // an optional chart group for this chart to be scoped within. When a chart belongs // to a specific group then any interaction with such chart will only trigger redraw // on other charts within the same chart group. /* dc.barChart("#volume-month-chart") */ histoChart.width(800) .height(280) .margins({top: 10, right: 50, bottom: 30, left: 40}) .dimension(myhistogram) .group(myhistogramGroup) .colors("grey") .elasticY(true) .yAxisLabel('Pair Counts') .xAxisLabel('Identity') // (optional) whether bar should be center to its x value. Not needed for ordinal chart, :default=false .centerBar(true) // (optional) set gap between bars manually in px, :default=2 .gap(1) // (optional) set filter brush rounding .round(dc.round.floor) .alwaysUseRounding(true) .x(d3.scale.linear().domain([0, 101])) .renderHorizontalGridLines(true) // customize the filter displayed in the control span .filterPrinter(function (filters) { var filter = filters[0], s = ""; s += numberFormat(filter[0]) + "% -> " + numberFormat(filter[1]) + "%"; return s; }) .filterPrinter(function (filters) { var filter = filters[0], s = ""; s += numberFormat(filter[0]) + "% -------> " + numberFormat(filter[1]) + "%"; return s; }); statChart.width(200) .height(300) .dimension(mean) .group(meanGroup) .x(d3.scale.linear().domain([0, 101])) .filterPrinter(function (filters) { var filter = filters[0], s=""; s+= filter[0] + "ppppp----->" + filter[1]; return s; }); /*histogramChart.width(420) .height(180) .margins({top: 10, right: 50, bottom: 30, left: 40}) .dimension(myhistogram) .group(myhistogramGroup) .elasticY(true) // (optional) whether bar should be center to its x value. Not needed for ordinal chart, :default=false .centerBar(true) // (optional) set gap between bars manually in px, :default=2 .gap(1) // (optional) set filter brush rounding .round(dc.round.floor) .alwaysUseRounding(true) .x(d3.scale.linear().domain([-25, 25])) .renderHorizontalGridLines(true) // customize the filter displayed in the control span .filterPrinter(function (filters) { var filter = filters[0], s = ""; s += numberFormat(filter[0]) + "% -> " + numberFormat(filter[1]) + "%"; return s; });*/ // Customize axis histoChart.xAxis().tickFormat( function (v) { return v + "%"; }); histoChart.yAxis().ticks(5); dc.dataCount(".dc-data-count") .dimension(ndx) .group(all); /* histogramChart.xAxis().tickFormat( function (v) { return v + "%"; }); histogramChart.yAxis().ticks(5); //#### Stacked Area Chart //Specify an area chart, by using a line chart with `.renderArea(true)` moveChart .renderArea(true) .width(990) .height(200) .transitionDuration(1000) .margins({top: 30, right: 50, bottom: 25, left: 40}) .dimension(moveMonths) .mouseZoomable(true) // Specify a range chart to link the brush extent of the range with the zoom focue of the current chart. .rangeChart(volumeChart) .x(d3.time.scale().domain([new Date(1985, 0, 1), new Date(2012, 11, 31)])) .round(d3.time.month.round) .xUnits(d3.time.months) .elasticY(true) .renderHorizontalGridLines(true) .legend(dc.legend().x(800).y(10).itemHeight(13).gap(5)) .brushOn(false) // Add the base layer of the stack with group. The second parameter specifies a series name for use in the legend // The `.valueAccessor` will be used for the base layer .group(indexAvgByMonthGroup, "Monthly Index Average") .valueAccessor(function (d) { return d.value.avg; }) // stack additional layers with `.stack`. The first paramenter is a new group. // The second parameter is the series name. The third is a value accessor. .stack(monthlyMoveGroup, "Monthly Index Move", function (d) { return d.value; }) // title can be called by any stack layer. .title(function (d) { var value = d.value.avg ? d.value.avg : d.value; if (isNaN(value)) value = 0; return dateFormat(d.key) + "\n" + numberFormat(value); }); volumeChart.width(990) .height(40) .margins({top: 0, right: 50, bottom: 20, left: 40}) .dimension(moveMonths) .group(volumeByMonthGroup) .centerBar(true) .gap(1) .x(d3.time.scale().domain([new Date(1985, 0, 1), new Date(2012, 11, 31)])) .round(d3.time.month.round) .alwaysUseRounding(true) .xUnits(d3.time.months); /* //#### Data Count // Create a data count widget and use the given css selector as anchor. You can also specify // an optional chart group for this chart to be scoped within. When a chart belongs // to a specific group then any interaction with such chart will only trigger redraw // on other charts within the same chart group. <div id="data-count"> <span class="filter-count"></span> selected out of <span class="total-count"></span> records </div> dc.dataCount(".dc-data-count") .dimension(ndx) .group(all); //#### Data Table // Create a data table widget and use the given css selector as anchor. You can also specify // an optional chart group for this chart to be scoped within. When a chart belongs // to a specific group then any interaction with such chart will only trigger redraw // on other charts within the same chart group. <!-- anchor div for data table --> <div id="data-table"> <!-- create a custom header --> <div class="header"> <span>Date</span> <span>Open</span> <span>Close</span> <span>Change</span> <span>Volume</span> </div> <!-- data rows will filled in here --> </div> */ dc.dataTable(".dc-data-table") .dimension(mean) // data table does not use crossfilter group but rather a closure // as a grouping function .size(2) // (optional) max number of records to be shown, :default = 25 // dynamic columns creation using an array of closures .columns([ function (d) { return d.pident; } ]) // (optional) sort using the given field, :default = function(d){return d;} // (optional) sort order, :default ascending .order(d3.ascending) // (optional) custom renderlet to post-process chart using D3 .renderlet(function (table) { table.selectAll(".dc-table-group").classed("info", true); }); /* //#### Geo Choropleth Chart //Create a choropleth chart and use the given css selector as anchor. You can also specify //an optional chart group for this chart to be scoped within. When a chart belongs //to a specific group then any interaction with such chart will only trigger redraw //on other charts within the same chart group. dc.geoChoroplethChart("#us-chart") .width(990) // (optional) define chart width, :default = 200 .height(500) // (optional) define chart height, :default = 200 .transitionDuration(1000) // (optional) define chart transition duration, :default = 1000 .dimension(states) // set crossfilter dimension, dimension key should match the name retrieved in geo json layer .group(stateRaisedSum) // set crossfilter group // (optional) define color function or array for bubbles .colors(["#ccc", "#E2F2FF","#C4E4FF","#9ED2FF","#81C5FF","#6BBAFF","#51AEFF","#36A2FF","#1E96FF","#0089FF","#0061B5"]) // (optional) define color domain to match your data domain if you want to bind data or color .colorDomain([-5, 200]) // (optional) define color value accessor .colorAccessor(function(d, i){return d.value;}) // Project the given geojson. You can call this function mutliple times with different geojson feed to generate // multiple layers of geo paths. // // * 1st param - geo json data // * 2nd param - name of the layer which will be used to generate css class // * 3rd param - (optional) a function used to generate key for geo path, it should match the dimension key // in order for the coloring to work properly .overlayGeoJson(statesJson.features, "state", function(d) { return d.properties.name; }) // (optional) closure to generate title for path, :default = d.key + ": " + d.value .title(function(d) { return "State: " + d.key + "\nTotal Amount Raised: " + numberFormat(d.value ? d.value : 0) + "M"; }); //#### Bubble Overlay Chart // Create a overlay bubble chart and use the given css selector as anchor. You can also specify // an optional chart group for this chart to be scoped within. When a chart belongs // to a specific group then any interaction with such chart will only trigger redraw // on other charts within the same chart group. dc.bubbleOverlay("#bubble-overlay") // bubble overlay chart does not generate it's own svg element but rather resue an existing // svg to generate it's overlay layer .svg(d3.select("#bubble-overlay svg")) .width(990) // (optional) define chart width, :default = 200 .height(500) // (optional) define chart height, :default = 200 .transitionDuration(1000) // (optional) define chart transition duration, :default = 1000 .dimension(states) // set crossfilter dimension, dimension key should match the name retrieved in geo json layer .group(stateRaisedSum) // set crossfilter group // closure used to retrieve x value from multi-value group .keyAccessor(function(p) {return p.value.absGain;}) // closure used to retrieve y value from multi-value group .valueAccessor(function(p) {return p.value.percentageGain;}) // (optional) define color function or array for bubbles .colors(["#ccc", "#E2F2FF","#C4E4FF","#9ED2FF","#81C5FF","#6BBAFF","#51AEFF","#36A2FF","#1E96FF","#0089FF","#0061B5"]) // (optional) define color domain to match your data domain if you want to bind data or color .colorDomain([-5, 200]) // (optional) define color value accessor .colorAccessor(function(d, i){return d.value;}) // closure used to retrieve radius value from multi-value group .radiusValueAccessor(function(p) {return p.value.fluctuationPercentage;}) // set radius scale .r(d3.scale.linear().domain([0, 3])) // (optional) whether chart should render labels, :default = true .renderLabel(true) // (optional) closure to generate label per bubble, :default = group.key .label(function(p) {return p.key.getFullYear();}) // (optional) whether chart should render titles, :default = false .renderTitle(true) // (optional) closure to generate title per bubble, :default = d.key + ": " + d.value .title(function(d) { return "Title: " + d.key; }) // add data point to it's layer dimension key that matches point name will be used to // generate bubble. multiple data points can be added to bubble overlay to generate // multiple bubbles .point("California", 100, 120) .point("Colorado", 300, 120) // (optional) setting debug flag to true will generate a transparent layer on top of // bubble overlay which can be used to obtain relative x,y coordinate for specific // data point, :default = false .debug(true); */ //#### Rendering //simply call renderAll() to render all charts on the page dc.renderAll(); /* // or you can render charts belong to a specific chart group dc.renderAll("group"); // once rendered you can call redrawAll to update charts incrementally when data // change without re-rendering everything dc.redrawAll(); // or you can choose to redraw only those charts associated with a specific chart group dc.redrawAll("group"); */ }); //#### Version //Determine the current version of dc with `dc.version` d3.selectAll("#version").text(dc.version);
/* custom js */