code
stringlengths
2
1.05M
'use strict'; /** * @ngdoc directive * @name ng.directive:ngIf * @restrict A * * @description * The `ngIf` directive removes and recreates a portion of the DOM tree (HTML) * conditionally based on **"falsy"** and **"truthy"** values, respectively, evaluated within * an {expression}. In other words, if the expression assigned to **ngIf evaluates to a false * value** then **the element is removed from the DOM** and **if true** then **a clone of the * element is reinserted into the DOM**. * * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the * element in the DOM rather than changing its visibility via the `display` css property. A common * case when this difference is significant is when using css selectors that rely on an element's * position within the DOM (HTML), such as the `:first-child` or `:last-child` pseudo-classes. * * Note that **when an element is removed using ngIf its scope is destroyed** and **a new scope * is created when the element is restored**. The scope created within `ngIf` inherits from * its parent scope using * {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}. * An important implication of this is if `ngModel` is used within `ngIf` to bind to * a javascript primitive defined in the parent scope. In this case any modifications made to the * variable within the child scope will override (hide) the value in the parent scope. * * Also, `ngIf` recreates elements using their compiled state. An example scenario of this behavior * is if an element's class attribute is directly modified after it's compiled, using something like * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element * the added class will be lost because the original compiled state is used to regenerate the element. * * Additionally, you can provide animations via the ngAnimate module to animate the **enter** * and **leave** effects. * * @animations * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container * leave - happens just before the ngIf contents are removed from the DOM * * @element ANY * @scope * @param {expression} ngIf If the {@link guide/expression expression} is falsy then * the element is removed from the DOM tree (HTML). * * @example <example animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/> Show when checked: <span ng-if="checked" class="animate-if"> I'm removed when the checkbox is unchecked. </span> </file> <file name="animations.css"> .animate-if { background:white; border:1px solid black; padding:10px; } .animate-if.ng-enter, .animate-if.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; } .animate-if.ng-enter, .animate-if.ng-leave.ng-leave-active { opacity:0; } .animate-if.ng-enter.ng-enter-active, .animate-if.ng-leave { opacity:1; } </file> </example> */ var ngIfDirective = ['$animate', function($animate) { return { transclude: 'element', priority: 1000, terminal: true, restrict: 'A', compile: function (element, attr, transclude) { return function ($scope, $element, $attr) { var childElement, childScope; $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { if (childElement) { $animate.leave(childElement); childElement = undefined; } if (childScope) { childScope.$destroy(); childScope = undefined; } if (toBoolean(value)) { childScope = $scope.$new(); transclude(childScope, function (clone) { childElement = clone; $animate.enter(clone, $element.parent(), $element); }); } }); } } } }];
import { put } from 'redux-saga/effects'; import { meRequestSuccess, meRequestFailed, setLoggedInStatus, } from '../actions'; import { getMeFromToken, } from '../sagas'; describe('Request Me From Token Saga', () => { let getMeFromTokenGenerator; beforeEach(() => { global.sessionStorage = jest.fn(); global.sessionStorage.setItem = jest.fn(); global.sessionStorage.removeItem = jest.fn(); getMeFromTokenGenerator = getMeFromToken({ token: 'exampletoken', }); const testCall = getMeFromTokenGenerator.next().value; expect(testCall).toMatchSnapshot(); }); describe('OnSuccess', () => { it('should dispatch meRequestSuccess on success', () => { const fixture = { username: 'testusername', }; const callDescriptor = getMeFromTokenGenerator.next(fixture).value; expect(callDescriptor).toEqual(put(meRequestSuccess(fixture))); }); it('should set jwtToken in sessionStorage', () => { const fixture = { username: 'testusername', token: 'token', }; getMeFromTokenGenerator.next(fixture); expect(global.sessionStorage.setItem).toHaveBeenCalledWith('jwtToken', fixture.token); }); it('should dispatch setLoggedInStatus on success', () => { const fixture = { username: 'testusername', }; getMeFromTokenGenerator.next(fixture); const callDescriptor = getMeFromTokenGenerator.next().value; expect(callDescriptor).toEqual(put(setLoggedInStatus(true))); }); }); describe('OnFail', () => { it('should dispatch meRequestFailed on failure', () => { const fixture = { message: 'message', }; const callDescriptor = getMeFromTokenGenerator.throw(fixture).value; expect(callDescriptor).toEqual(put(meRequestFailed(fixture.message))); }); it('should remove jwtToken', () => { const fixture = { message: 'message', }; getMeFromTokenGenerator.throw(fixture); expect(global.sessionStorage.removeItem).toHaveBeenCalledWith('jwtToken'); }); it('should dispatch setLoggedInStatus on fail', () => { const fixture = { username: 'testusername', }; getMeFromTokenGenerator.throw(fixture); const callDescriptor = getMeFromTokenGenerator.next().value; expect(callDescriptor).toEqual(put(setLoggedInStatus(false))); }); }); });
export { default } from 'ember-cli-mgmco-common/models/user';
app.directive('sharePanel', function() { return { restrict: 'A', controller: 'SharePanelController', templateUrl: 'partials/editor/share-panel.html', link: function(scope, element, attr){ } } });
// Generated by CoffeeScript 1.10.0 (function() { var USAGE, clog, isCommand, run; clog = require("./clog").clog; isCommand = function(arg, commands) { return commands.reduce(function(memo, c) { if (arg[c]) { memo = true; } return memo; }, false); }; USAGE = "Usage: clog [files] [options]\n\nDescription:\n\n Static analysis tool for CoffeeScript code quality.\n\nFiles:\n\n Space separated paths files or directories.\n Directories will be recursed to find\n .coffee, .coffee.md, and .litcoffee files to be analyzed\n\nOptions:\n\n -h, --help display this message\n -v, --version display the current version"; run = function(argv) { var message, printOptions; message = USAGE; if (isCommand(argv, ["h", "help"])) { message = USAGE; } else if (isCommand(argv, ["v", "version"])) { message = clog.VERSION; } else if (argv._.length) { if (isCommand(argv, ["p", "pretty-print"])) { printOptions = { indentSpace: 2 }; } else { printOptions = {}; } message = clog.report(argv._, printOptions); } return message; }; module.exports = run; }).call(this);
var my_srs = { "input_srs": "4326", "output_srs": "2154", "srs_dict": { "2154": { "name": "RGF93 / Lambert-93", "type": "proj", "x_label": "X (m)", "y_label": "Y (m)", "def": 'PROJCS["RGF93 / Lambert-93",GEOGCS["RGF93",DATUM["Reseau_Geodesique_Francais_1993",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6171"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4171"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",49],PARAMETER["standard_parallel_2",44],PARAMETER["latitude_of_origin",46.5],PARAMETER["central_meridian",3],PARAMETER["false_easting",700000],PARAMETER["false_northing",6600000],AUTHORITY["EPSG","2154"],AXIS["X",EAST],AXIS["Y",NORTH]]' }, "3948": { "name": "RGF93 / CC48", "type": "proj", "x_label": "X (m)", "y_label": "Y (m)", "def": 'PROJCS["RGF93 / CC48",GEOGCS["RGF93",DATUM["Reseau_Geodesique_Francais_1993",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6171"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4171"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",47.25],PARAMETER["standard_parallel_2",48.75],PARAMETER["latitude_of_origin",48],PARAMETER["central_meridian",3],PARAMETER["false_easting",1700000],PARAMETER["false_northing",7200000],AUTHORITY["EPSG","3948"],AXIS["X",EAST],AXIS["Y",NORTH]]' }, "3949": { "name": "RGF93 / CC49", "type": "proj", "x_label": "X (m)", "y_label": "Y (m)", "def": 'PROJCS["RGF93 / CC49",GEOGCS["RGF93",DATUM["Reseau_Geodesique_Francais_1993",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6171"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4171"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Lambert_Conformal_Conic_2SP"],PARAMETER["standard_parallel_1",48.25],PARAMETER["standard_parallel_2",49.75],PARAMETER["latitude_of_origin",49],PARAMETER["central_meridian",3],PARAMETER["false_easting",1700000],PARAMETER["false_northing",8200000],AUTHORITY["EPSG","3949"],AXIS["X",EAST],AXIS["Y",NORTH]]' }, "4171": { "name": "RGF93", "type": "geo", "x_label": "Lon (°)", "y_label": "Lat (°)", "def": 'GEOGCS["RGF93",DATUM["Reseau_Geodesique_Francais_1993",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6171"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4171"]]' }, "4326": { "name": "WGS 84", "type": "geo", "x_label": "Lon (°)", "y_label": "Lat (°)", "def": 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]' } } };
$(function(){ var sources = { 'small': { 'src': 'http://placehold.it/320x240', 'min': null, 'max': 319 }, 'medium': { 'src': 'http://placehold.it/640x460', 'min': 320, 'max': 639 }, 'large': { 'src': 'http://placehold.it/800x600', 'min': 640, 'max': null } }; function getSourceDefinition() { var sourceDefinition = []; $.each(sources, function (name, source) { sourceDefinition.push( '[' + source.src + ', (' + (source.min !== null ? 'min-width: ' + source.min : '') + (source.min !== null && source.max !== null ? ', ' : '') + (source.max !== null ? 'max-width: ' + source.max : '') + ')]' ) }); return sourceDefinition.join(', '); } // QUnit var log = []; var testName; QUnit.done(function (test_results) { var tests = []; for(var i = 0, len = log.length; i < len; i++) { var details = log[i]; tests.push({ name: details.name, result: details.result, expected: details.expected, actual: details.actual, source: details.source }); } test_results.tests = tests; window.global_test_results = test_results; }); QUnit.testStart(function(testDetails){ QUnit.log(function(details){ if (!details.result) { details.name = testDetails.name; log.push(details); } }); }); QUnit.test('static-full', function(assert){ var container = $('#test-static-full'); var img = container.find('img'); var done = assert.async(); container.pufferfish({ 'afterChange': function(event){ assert.equal(sources.large.src, event.element.attr('src'), 'static image should be using larger image source'); done(); } }); }); QUnit.test('static-half', function(assert){ var container = $('#test-static-half'); var img = container.find('img'); var done = assert.async(); container.pufferfish({ 'afterChange': function(event){ assert.equal(sources.medium.src, event.element.attr('src'), 'static image should be using smaller image source'); done(); } }); }); QUnit.test('async-full', function(assert){ var container = $('#test-async-full'); var img = $('<img>', {'data-pufferfish': getSourceDefinition()}).appendTo(container); var done = assert.async(); container.pufferfish({ 'afterChange': function(event){ assert.equal(sources.large.src, event.element.attr('src'), 'async added image should be using larger image source'); done(); } }); }); QUnit.test('async-half', function(assert){ var container = $('#test-async-half'); var img = $('<img>', {'data-pufferfish': getSourceDefinition()}).appendTo(container); var done = assert.async(); container.pufferfish({ 'afterChange': function(event){ assert.equal(sources.medium.src, event.element.attr('src'), 'async added image should be using smaller image source'); done(); } }); }); QUnit.test('static-resize', function(assert){ var container = $('#test-static-resize'); var img = container.find('img'); var doneLarge = assert.async(); var doneMedium = assert.async(); var doneSmall = assert.async(); container.width(200); container.pufferfish({ 'afterChange': function(event){ var width = container.width(); if(width == 200){ assert.equal(sources.small.src, event.element.attr('src'), 'small image source should be used when container is 200px wide'); doneSmall(); container.width(500); $.pufferfish.reflow(); } else if(width === 500){ assert.equal(sources.medium.src, event.element.attr('src'), 'medium image source should be used when container is 500px wide'); doneMedium(); container.width(700); $.pufferfish.reflow(); } else if(width === 700){ assert.equal(sources.large.src, event.element.attr('src'), 'large image source should be used when container is 700px wide'); doneLarge(); } } }); }); QUnit.test('prevent-default', function(assert){ var container = $('#test-prevent-default'); var img = container.find('img'); var done = assert.async(); container.pufferfish({ 'onChange': function(event){ event.preventDefault(); }, 'afterChange': function(event){ assert.equal('http://placehold.it/50x50', event.element.attr('src')); done(); } }); }); QUnit.test('not-visible', function(assert){ var container = $('#test-not-visible'); var img = container.find('img'); var done = assert.async(); container.pufferfish({ 'afterChange': function(event){ assert.equal(undefined, event.element.attr('src'), 'hidden image should have no src'); done(); } }); }); QUnit.test('visible-inline', function(assert){ var container = $('#test-visible-inline'); var img = container.find('img'); var done = assert.async(); container.pufferfish({ 'afterChange': function(event){ assert.notEqual(undefined, event.element.attr('src'), 'inline image should have src'); done(); } }); }); QUnit.start(); });
Polymer({ is: 'expr-splash-screen' });
require.config({ paths: { jquery : '<%= bowerDirectory %>/jquery/jquery', underscore : '<%= bowerDirectory %>/underscore/underscore', 'underscore.string' : '<%= bowerDirectory %>/underscore.string/dist/underscore.string.min', backbone : '<%= bowerDirectory %>/backbone/backbone', 'backbone.wreqr' : '<%= bowerDirectory %>/marionette/public/javascripts/backbone.wreqr', 'backbone.babysitter' : '<%= bowerDirectory %>/marionette/public/javascripts/backbone.babysitter', 'backbone.relational' : '<%= bowerDirectory %>/backbone-relational/backbone-relational', 'backbone.pageable' : '<%= bowerDirectory %>/backbone-pageable/lib/backbone-pageable', marionette : '<%= bowerDirectory %>/marionette/lib/core/amd/backbone.marionette', backgrid : '<%= bowerDirectory %>/backgrid/lib/backgrid', bootstrap : '<%= bowerDirectory %>/sass-bootstrap/dist/js/bootstrap', jade : '<%= bowerDirectory %>/require-jade/jade', text : '<%= bowerDirectory %>/requirejs-text/text', moment : '<%= bowerDirectory %>/moment/moment', app : 'app', collections : 'collections', lib : 'lib', models : 'models', templates : 'templates', views : 'views' }, shim: { underscore: { exports: '_' }, 'underscore.string': { deps: ['underscore'], exports: '_.string' }, bootstrap: { deps: ['jquery'] }, backbone: { deps: ['underscore', 'jquery'], exports: 'Backbone' }, 'backbone.babysitter': { deps: ['backbone'] }, 'backbone.wreqr': { deps: ['backbone', 'backbone.babysitter'], exports: 'Backbone.Wreqr' }, 'backbone.relational': { deps: ['backbone'], exports: 'Backbone.RelationalModel' }, // marionette: { // deps: ['backbone', 'backbone.wreqr', 'backbone.babysitter'], // exports: 'Backbone.Marionette' // }, backgrid: { deps: ['backbone', 'backbone.pageable'], exports: 'Backgrid' }, moment: { exports: 'moment' } }, deps: [ // 'jquery', 'bootstrap', // 'underscore', // 'moment', 'main' ] });
/* Gulpfile for repository d3.js template Reference: https://css-tricks.com/gulp-for-beginners/ */ /* NODE MODULES */ var gulp = require('gulp'); var runSequence = require('run-sequence'); var gulpIf = require('gulp-if'); var browserSync = require('browser-sync').create(); var useref = require('gulp-useref'); var uglify = require('gulp-uglify'); var cssnano = require('gulp-cssnano'); var del = require('del'); /* PRIMARY GULP TASKS */ // turn on development environemnt gulp.task('default', function(callback){ runSequence(['browserSync', 'watch'], callback ); }); // Build /app -> /dist gulp.task('build', function(callback){ runSequence('clean:dist', ['concat', 'images', 'data'], callback ); }); /* HELPER FUNCTIONS */ // Listens for file changes, reloads on save gulp.task('watch', ['browserSync'], function(){ gulp.watch('app/*.html', browserSync.reload); gulp.watch('app/css/**/*.css', browserSync.reload); gulp.watch('app/js/**/*.js', browserSync.reload); gulp.watch('app/data/**/*.*', browserSync.reload); gulp.watch('app/images/**/*.*',browserSync.reload); }); // Sets up development server gulp.task('browserSync', function(){ browserSync.init({ server: { baseDir: 'app' }, }); }); // concats js and css files (ignores inline js/css) gulp.task('concat', function(){ return gulp.src('app/*.html') .pipe(useref()) .pipe(gulpIf('*.js', uglify())) .pipe(gulpIf('*.css', cssnano())) .pipe(gulp.dest('dist')); }); // Image handling (just pass-through now) gulp.task('images', function(){ return gulp.src('app/images/**/*.+(png|jpg|jpeg|gif|svg)') .pipe(gulp.dest('dist/images')); }); // Pipe anything in app data folder to dist data folder gulp.task('data', function(){ return gulp.src('app/data/**/*.*') .pipe(gulp.dest('dist/data')); }); // Cleans dist folder gulp.task('clean:dist', function() { return del.sync('dist'); });
describe( require('../../__fixtures/utils/test_helper') .create() .testName(__filename, 3), function() { var Mesh = require('../../..'); it('can call disconnect() without connecting', function(done) { new Mesh.MeshClient({ port: 1 }).disconnect(done); }); } );
'use strict' const app = require('./app') const pkg = require('./package') const PORT = process.env.PORT || 5000 const server = app.listen(PORT, function () { const port = server.address().port console.log(`${pkg.name} version ${pkg.version} listening on port ${port}`) })
/* * * Utility Functions * */ exports.setDebug = function(val) { debug = !! val; }; exports.isDebug = function() { return debug; }; exports.dateToArray = function(dateObj) { if (typeof dateObj !== 'object') dateObj = new Date(dateObj); return [ dateObj.getFullYear(), dateObj.getMonth() + 1, dateObj.getDate(), dateObj.getHours(), dateObj.getMinutes(), dateObj.getSeconds() ]; };
//------------------------------------------------------------------------------- // // Project: EOxClient <https://github.com/EOX-A/EOxClient> // Authors: Daniel Santillan <daniel.santillan@eox.at> // //------------------------------------------------------------------------------- // Copyright (C) 2014 EOX IT Services GmbH // // 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 of this Software or works derived from this Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //------------------------------------------------------------------------------- (function() { 'use strict'; var root = this; root.require([ 'backbone', 'communicator', 'app' ], function( Backbone, Communicator, App ) { var ContentController = Backbone.Marionette.Controller.extend({ initialize: function(options){ this.listenTo(Communicator.mediator, "dialog:open:about", this.onDialogOpenAbout); this.listenTo(Communicator.mediator, "ui:open:layercontrol", this.onLayerControlOpen); this.listenTo(Communicator.mediator, "ui:open:toolselection", this.onToolSelectionOpen); }, onDialogOpenAbout: function(event){ App.dialogRegion.show(App.DialogContentView); }, onLayerControlOpen: function(event){ //We have to render the layout before we can //call show() on the layout's regions if (_.isUndefined(App.layout.isClosed) || App.layout.isClosed) { App.leftSideBar.show(App.layout); App.layout.baseLayers.show(App.baseLayerView); App.layout.products.show(App.productsView); App.layout.overlays.show(App.overlaysView); } else { App.layout.close(); } }, onToolSelectionOpen: function(event){ if (_.isUndefined(App.toolLayout.isClosed) || App.toolLayout.isClosed) { App.rightSideBar.show(App.toolLayout); App.toolLayout.selection.show(App.selectionToolsView); App.toolLayout.visualization.show(App.visualizationToolsView); } else { App.toolLayout.close(); } } }); return new ContentController(); }); }).call( this );
(function () { 'use strict'; /* var position = { latitude: 78.23423423, longitude: 13.123124142 } deferred.resolve(position); */ function GeolocationService($q, $rootScope, $window, $http) { var service = {}; var geoloc = null; service.getLocation = function () { var deferred = $q.defer(); // Use geo postion from config file if it is defined if (typeof config.geoPosition != 'undefined' && typeof config.geoPosition.latitude != 'undefined' && typeof config.geoPosition.longitude != 'undefined') { deferred.resolve({ coords: { latitude: config.geoPosition.latitude, longitude: config.geoPosition.longitude, }, }); } else { if (geoloc !== null) { console.log("Cached Geolocation", geoloc); return (geoloc); } $http.get("https://maps.googleapis.com/maps/api/browserlocation/json?browser=chromium").then( function (result) { var location = angular.fromJson(result).data.location deferred.resolve({ 'coords': { 'latitude': location.lat, 'longitude': location.lng } }) }, function (err) { console.debug("Failed to retrieve geolocation.", err) deferred.reject("Failed to retrieve geolocation.") }); } geoloc = deferred.promise; return deferred.promise; } return service; } angular.module('SmartMirror') .factory('GeolocationService', GeolocationService); } ());
export default { colors: { primary: '#3579f5', secondary: 'black', background: 'black' }, content: { padding: '0 0.75em 1em', width: '400px' }, trigger: { color: 'white', hoverColor: 'white', backgroundColor: 'black', hoverBackgroundColor: '#111', border: 'none', padding: '14px 1.25em', borderRadius: '6px', fontSize: '14px' }, input: { backgroundColor: 'rgba(255, 255, 255, 0.15)', padding: '1em', color: 'white', fontSize: '14px', borderRadius: '4px', border: 'none' }, label: { fontSize: '12px' }, tab: { color: 'rgba(255, 255, 255, 0.8)', border: 'none', borderRadius: '4px', padding: '1em', backgroundColor: 'rgba(255, 255, 255, 0.15)' }, uploadButton: { color: 'white', hoverColor: 'white', border: 'none', hoverBorder: 'none', backgroundColor: '#222', hoverBackgroundColor: '#323232' }, image: { border: 'none' } }
var quote = '', author = '' $(document).ready(() => { $.ajaxSetup({ cache: false }) getQuote(writeQuote) $('.primary').click(() => { $('.typed-cursor').remove() $('.quote, .author').empty() getQuote(writeQuote) }) $('.secondary').click(() => { let options = { url: 'https://twitter.com/intent/tweet?text=', quote: quote, author: author } window.open(options.url + options.quote + '- ' + options.author, '', 'width=550px, height=420px') }) }) function getQuote(cb) { displayText(false) // recursively get quotes until there is a one that fits twitter's specifications $.ajax({ url: 'http://api.forismatic.com/api/1.0/', jsonp: 'method=getQuote&lang=en&format=jsonp&jsonp', dataType: 'jsonp', success: (data) => { let tweet = data.quoteText + '- ' + data.quoteAuthor if (tweet.length > 140) { return getQuote(cb) } else { displayText(true) cb(data) } } }) } function writeQuote(data) { quote = data.quoteText, author = data.quoteAuthor || 'Anonymous' let typedOptions = { strings: ['"' + quote + '"'], typeSpeed: 0, contentType: 'text', callback: () => { typedOptions.strings = [author] $('.typed-cursor').remove() delete typedOptions.callback $('.author').typed(typedOptions) } } $('.quote').typed(typedOptions) } function displayText(bool) { if (bool) { $('#loader').hide() $('#text .row').show() } else { $('#loader').show() $('#text .row').hide() } }
#!/usr/bin/mongo lucy db.binaries.ensureIndex({"package": 1}); db.binaries.ensureIndex({"package": -1}); db.binaries.ensureIndex({"source": -1}); db.binaries.ensureIndex({"source": 1}); db.jobs.ensureIndex({"package": -1}); db.jobs.ensureIndex({"package": 1}); db.jobs.ensureIndex({"job": 1}); db.jobs.ensureIndex({"job": -1}); db.jobs.ensureIndex({"builder": -1}); db.jobs.ensureIndex({"builder": 1}); db.jobs.ensureIndex({"finished_at": 1}); db.jobs.ensureIndex({"finished_at": -1}); db.jobs.ensureIndex({"builder": 1, "finished_at": 1, "type": 1, "suite": 1, "arch": 1}); db.jobs.ensureIndex({"builder": -1, "finished_at": -1, "type": -1, "suite": -1, "arch": -1}); db.jobs.ensureIndex({"assigned_at": 1, "builder": 1, "finished_at": 1}); db.jobs.ensureIndex({"assigned_at": -1, "builder": -1, "finished_at": -1}); db.jobs.ensureIndex({"builder": -1, "finished_at": -1}); db.machines.ensureIndex({"gpg": 1}); db.machines.ensureIndex({"gpg": -1}); db.machines.ensureIndex({"owner": -1}); db.machines.ensureIndex({"owner": 1}); db.machines.ensureIndex({"auth": 1}); db.machines.ensureIndex({"auth": -1}); db.machines.ensureIndex({"last_ping": 1}); db.machines.ensureIndex({"last_ping": -1}); db.reports.ensureIndex({"package": 1}); db.reports.ensureIndex({"package": -1}); db.sources.ensureIndex({"owner": 1}); db.sources.ensureIndex({"owner": -1}); db.sources.ensureIndex({"group": 1}); db.sources.ensureIndex({"group": -1}); db.sources.ensureIndex({"updated_at": 1}); db.sources.ensureIndex({"updated_at": -1}); db.sources.ensureIndex({"group": 1, "updated_at": 1}); db.sources.ensureIndex({"group": 1, "updated_at": -1}); db.sources.ensureIndex({"group": -1, "updated_at": 1}); db.sources.ensureIndex({"group": -1, "updated_at": -1}); db.reports.ensureIndex({"package": -1}); db.reports.ensureIndex({"package": 1}); db.binaries.ensureIndex({"source": 1}); db.binaries.ensureIndex({"source": -1}); db.users.ensureIndex({"email": 1}); db.users.ensureIndex({"email": -1}); db.users.ensureIndex({"gpg": 1}); db.users.ensureIndex({"gpg": -1}); print("complete.");
import { combineReducers } from 'redux'; import { routeReducer } from 'redux-simple-router'; import application from './application'; import bids from './bids'; import items from './items'; const rootReducer = combineReducers({ bids, items, application, routing: routeReducer }); export default rootReducer;
import ACTIONS, { uri } from './index' import { Map } from 'immutable' import { fetchGeoJson, fetchStatsJson } from './mapActions' import store from '../configureStore' /** * Simple function to change the year * @param {String} year */ export function changeYear (year) { return () => { store.dispatch({ type: ACTIONS.CHANGE_YEAR, year }) console.log('Year change') fetchGeoJson() } } /** * Convert branch to the display name * TODO: Consider moving this to metadata.json * @param {String} branch */ export function convertBranch (branch) { switch (branch) { case 'federal': return 'U.S. House Districts' case 'lower': return 'P.A. House Districts' case 'upper': return 'P.A. Senate Districts' default: return branch } } /** * onLoad functions checks on the availability of the META-Data */ export function onLoad () { const { mapDataReducer } = store.getState() // REVIEW: Potentially unnecessary check if (mapDataReducer.geoFiles.size < 1) { pullMetaData() return } fetchGeoJson() } /** * pullMetaData triggers an ajax action and loads necessary data if needed */ export function pullMetaData () { const { META_DATA } = ACTIONS window.fetch(uri + 'metaData.json') .then(rsp => { rsp.json().then(json => { const geoFiles = Map(json.geoFiles) const { statsFiles } = json store.dispatch({ type: META_DATA, geoFiles, statsFiles, branch: Object.keys(geoFiles)[0] }) fetchGeoJson() fetchStatsJson() }) }) .catch(e => console.error(e)) }
// Custom function to fill in the data of the `restante` column. // [todo] improve this functionality !!! function restantUpkeep(){ var date = sheet(0).getRange("A1").getValue().split(' '); var initialMonth = date[0], year = parseInt(date[1]); var monthsObj = months(year); // [todo] replace with Object.keys(months(year)) var monthsArray = []; for (month in monthsObj) { monthsArray.push(month); } // [todo] duplicate code with billDate() function. var position = monthsArray.indexOf(initialMonth); var billMonth = monthsArray[(position + 2) % 12]; var localYear = year; if (billMonth == 'IANUARIE' || billMonth == 'FEBRUARIE') { localYear += 1; } var localMonths = months(localYear); var dueDate = new Date(localYear, localMonths[initialMonth][0]+1, 1); var lateDate = Math.round((new Date() - dueDate)/(1000*60*60*24)), sumPenalties = [], sumBoxe = []; // The spreadsheet `evidenta chitante` has a sheet with all generated sheets and their IDs sorted by month and year. var sheetIds = SpreadsheetApp.openById('0ApG54gFt9Qs9dGNSRGY0Zm5ONDZrZUY4SXJlbWEzNFE').getSheetByName('sheet ids'), lastSheetId = sheetIds.getRange("B"+(firstRow(sheetIds,1)-2)).getValue(), lastSheet = SpreadsheetApp.openById(lastSheetId); if (lateDate >= 0) { var lastRestRentRange = sheet(10,lastSheet).getRange(2,16,10,1).getValues(), // 'rest plată' last month restantRange = sheet(10).getRange(2,15,10,1), // 'restanțe' current month restantRangeValues = restantRange.getValues(), lastBalanceRangeA = sheet(8,lastSheet).getRange('C10:C11').getValues(), //lastBalanceRangeP = sheet(8,lastSheet).getRange('F10:F13').getValues(), balanceRangeA = sheet(8).getRange('C10:C11'), //balanceRangeP = sheet(8).getRange('F10:F13'), balanceValuesA = balanceRangeA.getValues(), //balanceValuesP = balanceRangeP.getValues(), lastBankSold = sheet(7,lastSheet).getRange('F'+(firstRow(sheet(7,lastSheet),3)-1)).getValue(), lastBoxaSold = sheet(9,lastSheet).getRange('F'+(firstRow(sheet(9,lastSheet),12)-1)).getValue(), lastRentSold = sheet(10,lastSheet).getRange('H'+(firstRow(sheet(10,lastSheet),18)-1)).getValue(), lastInterestSold = sheet(12,lastSheet).getRange('F'+(firstRow(sheet(12,lastSheet),3)-1)).getValue(), lastFactSold = sheet(13,lastSheet).getRange('F'+(firstRow(sheet(13,lastSheet),3)-1)).getValue(), lastPenaltiesSold = sheet(14,lastSheet).getRange('F'+(firstRow(sheet(14,lastSheet),12)-1)).getValue(), lastSalSold = sheet(17,lastSheet).getRange('F'+(firstRow(sheet(17,lastSheet),17)-1)).getValue(); // Set current rents for (var k = 0; k < 10; k++) { if (lastRestRentRange[k][0] > 0 && lastRestRentRange[k][0] < 0.01) lastRestRentRange[k][0] = 0; restantRangeValues[k][0] = lastRestRentRange[k][0]; } restantRange.setValues(restantRangeValues); // Set current 'balance' solds for (var l = 0; l < 2; l++) { balanceValuesA[l][0] = lastBalanceRangeA[l][0]; //balanceValuesP[l][0] = lastBalanceRangeP[l][0]; } balanceRangeA.setValues(balanceValuesA); //balanceRangeP.setValues(balanceValuesP); // Set initial solds in fonds sheet(7).getRange('F2').setValue(lastBankSold); sheet(9).getRange('F11').setValue(lastBoxaSold); sheet(10).getRange('H17').setValue(lastRentSold); sheet(12).getRange('F2').setValue(lastInterestSold); sheet(13).getRange('F2').setValue(lastFactSold); sheet(14).getRange('F11').setValue(lastPenaltiesSold); sheet(17).getRange('F16').setValue(lastSalSold); // Set 'taxă boxă' cashings var boxaRange = sheet(9).getRange('A12:D17'), taxaRange = sheet(9).getRange('B2:B7').getValues(), date = '12.' + (position + 2) % 12 + '.' + localYear; boxaRange.setValues([ [date,initialMonth,'Taxă boxă - sc. A',taxaRange[0]], [date,initialMonth,'Taxă boxă - sc. B',taxaRange[1]], [date,initialMonth,'Taxă boxă - sc. C',taxaRange[2]], [date,initialMonth,'Taxă boxă - sc. D',taxaRange[3]], [date,initialMonth,'Taxă boxă - sc. E',taxaRange[4]], [date,initialMonth,'Taxă boxă - sc. F',taxaRange[5]] ]); // Set current fond, restant upkeep, penalties for (var i = 1; i < 7; i++) { var lastRange = sheet(i,lastSheet).getRange(9,getColumnIndexByName(sheet(i,lastSheet), 'restTotalIntretinere')+1,44,4).getValues(), //last 4 'rest' columns lastRestantUpkeep, restantUpkeepRange = sheet(i).getRange(9,getColumnIndexByName(sheet(i), 'intretinere')+1,44,1), //current 'rest intretinere' column lastRestPenaltiesRange = sheet(i,lastSheet).getRange(9,getColumnIndexByName(sheet(i,lastSheet), 'restPenalitati')+1,44,1).getValues(), //last 'rest penalitati' column penaltiesRange = sheet(i).getRange(9,getColumnIndexByName(sheet(i), 'penalitati01zi')+1,44,1), //current 'penalties' column penalties = []; if (initialMonth == 'APRILIE' || initialMonth == 'MAI' || initialMonth == 'IUNIE') var fondRange = sheet(i).getRange(9,getColumnIndexByName(sheet(i), 'fondRulment')+1,44,1), //current 'fond rulment' fondRangeValues = fondRange.getValues(); if (initialMonth == 'MAI' || initialMonth == 'IUNIE' || initialMonth == 'IULIE') var lastRestFondRange = sheet(i,lastSheet).getRange(9,getColumnIndexByName(sheet(i,lastSheet), 'restRulment')+1,44,1).getValues(); //last 'rest rulment' for (var j = 0; j < lastRange.length; j++) { // set sums from last month between 0 and 0.01 to 0 if( (lastRange[j][0] > 0 && lastRange[j][0] < 0.01) || (lastRange[j][1] > 0 && lastRange[j][1] < 0.01) || (lastRange[j][2] > 0 && lastRange[j][2] < 0.01)) { lastRange[j][0] = 0; lastRange[j][1] = 0; lastRange[j][2] = 0; } switch(initialMonth) { case 'APRILIE': lastRange[j][1] = 0; lastRange[j][0] = lastRange[j][0] + lastRange[j][2]; lastRange[j][2] = lastRange[j][2]; fondRangeValues[j][0] = 0; break; case 'MAI': case 'IUNIE': if (lastRange[j][3] > 0 && lastRange[j][3] < 0.01) lastRange[j][3] = 0; lastRange[j][0] = lastRange[j][0] + lastRange[j][3]; lastRange[j][2] = lastRange[j][3]; fondRangeValues[j][0] = lastRestFondRange[j][0]; break; case'IULIE': if (lastRange[j][3] > 0 && lastRange[j][3] < 0.01) lastRange[j][3] = 0; lastRange[j][0] = lastRange[j][0] + lastRange[j][1] + lastRange[j][3]; lastRange[j][2] = lastRange[j][3]; break; default: lastRange[j][0] = lastRange[j][0] + lastRange[j][2]; lastRange[j][2] = lastRange[j][2]; } lastRestantUpkeep = lastRange[j][2]; lastRange[j].splice(1,3); lastRange[j][0] = lastRange[j][0].toFixed(2); var clone = lastRange[j].slice(0); penalties.push(clone); if (lastRestantUpkeep > 0) penalties[j][0] = (lastRestPenaltiesRange[j][0] + lastRestantUpkeep*0.03).toFixed(2); else penalties[j][0] = lastRestPenaltiesRange[j][0]; } restantUpkeepRange.setValues(lastRange); penaltiesRange.setValues(penalties); if (fondRange) fondRange.setValues(lastRestFondRange); sumPenalties.push((sheet(i,lastSheet).getRange(53,getColumnIndexByName(sheet(i,lastSheet), 'penalitati01zi')+1,1,1).getValue() -sheet(i,lastSheet).getRange(53,getColumnIndexByName(sheet(i,lastSheet), 'restPenalitati')+1,1,1).getValue()).toFixed(2)); sumBoxe.push(sheet(i,lastSheet).getRange(53,getColumnIndexByName(sheet(i,lastSheet), 'taxaBoxe')+1,1,1).getValue()); } } var values = [ [sumPenalties[0]], [sumPenalties[1]], [sumPenalties[2]], [sumPenalties[3]], [sumPenalties[4]], [sumPenalties[5]] ]; sheet(0).getRange('P2').setValue(sheet(0,lastSheet).getRange('P2').getValue()); sheet(14).getRange('B2:B7').setValues(values); }
'use strict'; var T = require('../lib'); var Q = require('q'); var main = function(){ var obj = {simple : 1, compound : {key : 1}}; // Make object transactionable T.transactionable(obj); // You can also specify which keys to include or exclude // Object attributes which cannot be deepcopyed must be excluded // (like reference to outer resources or circular reference) // T.transactionable(obj, {includeKeys : 'key1 key2'}); // T.transactionable(obj, {excludeKeys : 'key1 key2'}); // Execute code in a new 'connection' (the 'connection/lock/commit/rollback' terminologies are similar to traditional database) T.execute(function(){ return Q.fcall(function(){ // lock obj for write // lock from other execute content will block // and read from other execute content will always see old value until commit // You can also lock multiple objects by T.lock([obj1, obj2]); return T.lock(obj); }) .then(function(){ obj.simple = 2; // Set 'simple' value // obj.compound.key = 2; // Oops! Don't do this! var compound = obj.compound; // Retrieve 'compound' value compound.key = 2; obj.compound = compound; // Set 'compound' value T.commit(); // All locks will be released after commit or rollback console.log(obj.simple); // Read only access // obj.simple = 3; // Oops! should lock first }) .then(function(){ return T.lock(obj); }) .then(function(){ obj.simple = 3; throw new Error('Exception here!'); }) .then(function(){ T.commit(); // This will not execute }, function(err){ T.rollback(); // Should rolled back }) .then(function(){ console.log(obj.simple); // output: 2 }); }); }; if (require.main === module) { main(); }
/*! jQuery UI - v1.11.4 - 2015-03-21 * http://jqueryui.com * Includes: core.js, widget.js, mouse.js, draggable.js, droppable.js * Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { /*! * jQuery UI Core 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/ui-core/ */ // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.11.4", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ scrollParent: function( includeHidden ) { var position = this.css( "position" ), excludeStaticParent = position === "absolute", overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/, scrollParent = this.parents().filter( function() { var parent = $( this ); if ( excludeStaticParent && parent.css( "position" ) === "static" ) { return false; } return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) ); }).eq( 0 ); return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }, uniqueId: (function() { var uuid = 0; return function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + ( ++uuid ); } }); }; })(), removeUniqueId: function() { return this.each(function() { if ( /^ui-id-\d+$/.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap='#" + mapName + "']" )[ 0 ]; return !!img && visible( img ); } return ( /^(input|select|textarea|button|object)$/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), disableSelection: (function() { var eventType = "onselectstart" in document.createElement( "div" ) ? "selectstart" : "mousedown"; return function() { return this.bind( eventType + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }; })(), enableSelection: function() { return this.unbind( ".ui-disableSelection" ); }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; } }); // $.ui.plugin is deprecated. Use $.widget() extensions instead. $.ui.plugin = { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args, allowDisconnected ) { var i, set = instance.plugins[ name ]; if ( !set ) { return; } if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }; /*! * jQuery UI Widget 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ var widget_uuid = 0, widget_slice = Array.prototype.slice; $.cleanData = (function( orig ) { return function( elems ) { var events, elem, i; for ( i = 0; (elem = elems[i]) != null; i++ ) { try { // Only trigger remove when necessary to save time events = $._data( elem, "events" ); if ( events && events.remove ) { $( elem ).triggerHandler( "remove" ); } // http://bugs.jquery.com/ticket/8235 } catch ( e ) {} } orig( elems ); }; })( $.cleanData ); $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = widget_slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = widget_slice.call( arguments, 1 ), returnValue = this; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { // Allow multiple hashes to be passed on init if ( args.length ) { options = $.widget.extend.apply( null, [ options ].concat(args) ); } this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} ); if ( instance._init ) { instance._init(); } } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = widget_uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( arguments.length === 1 ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( arguments.length === 1 ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled", !!value ); // If the widget is becoming disabled, then nothing is interactive if ( value ) { this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } } return this; }, enable: function() { return this._setOptions({ disabled: false }); }, disable: function() { return this._setOptions({ disabled: true }); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^([\w:-]*)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); // Clear the stack to avoid memory leaks (#10056) this.bindings = $( this.bindings.not( element ).get() ); this.focusable = $( this.focusable.not( element ).get() ); this.hoverable = $( this.hoverable.not( element ).get() ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); var widget = $.widget; /*! * jQuery UI Mouse 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/mouse/ */ var mouseHandled = false; $( document ).mouseup( function() { mouseHandled = false; }); var mouse = $.widget("ui.mouse", { version: "1.11.4", options: { cancel: "input,textarea,button,select,option", distance: 1, delay: 0 }, _mouseInit: function() { var that = this; this.element .bind("mousedown." + this.widgetName, function(event) { return that._mouseDown(event); }) .bind("click." + this.widgetName, function(event) { if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) { $.removeData(event.target, that.widgetName + ".preventClickEvent"); event.stopImmediatePropagation(); return false; } }); this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind("." + this.widgetName); if ( this._mouseMoveDelegate ) { this.document .unbind("mousemove." + this.widgetName, this._mouseMoveDelegate) .unbind("mouseup." + this.widgetName, this._mouseUpDelegate); } }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart if ( mouseHandled ) { return; } this._mouseMoved = false; // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var that = this, btnIsLeft = (event.which === 1), // event.target.nodeName works around a bug in IE 8 with // disabled inputs (#7620) elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { that.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // Click event may never have fired (Gecko & Opera) if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) { $.removeData(event.target, this.widgetName + ".preventClickEvent"); } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return that._mouseMove(event); }; this._mouseUpDelegate = function(event) { return that._mouseUp(event); }; this.document .bind( "mousemove." + this.widgetName, this._mouseMoveDelegate ) .bind( "mouseup." + this.widgetName, this._mouseUpDelegate ); event.preventDefault(); mouseHandled = true; return true; }, _mouseMove: function(event) { // Only check for mouseups outside the document if you've moved inside the document // at least once. This prevents the firing of mouseup in the case of IE<9, which will // fire a mousemove event if content is placed under the cursor. See #7778 // Support: IE <9 if ( this._mouseMoved ) { // IE mouseup check - mouseup happened when mouse was out of window if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) { return this._mouseUp(event); // Iframe mouseup check - mouseup occurred in another document } else if ( !event.which ) { return this._mouseUp( event ); } } if ( event.which || event.button ) { this._mouseMoved = true; } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { this.document .unbind( "mousemove." + this.widgetName, this._mouseMoveDelegate ) .unbind( "mouseup." + this.widgetName, this._mouseUpDelegate ); if (this._mouseStarted) { this._mouseStarted = false; if (event.target === this._mouseDownEvent.target) { $.data(event.target, this.widgetName + ".preventClickEvent", true); } this._mouseStop(event); } mouseHandled = false; return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(/* event */) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(/* event */) {}, _mouseDrag: function(/* event */) {}, _mouseStop: function(/* event */) {}, _mouseCapture: function(/* event */) { return true; } }); /*! * jQuery UI Draggable 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/draggable/ */ $.widget("ui.draggable", $.ui.mouse, { version: "1.11.4", widgetEventPrefix: "drag", options: { addClasses: true, appendTo: "parent", axis: false, connectToSortable: false, containment: false, cursor: "auto", cursorAt: false, grid: false, handle: false, helper: "original", iframeFix: false, opacity: false, refreshPositions: false, revert: false, revertDuration: 500, scope: "default", scroll: true, scrollSensitivity: 20, scrollSpeed: 20, snap: false, snapMode: "both", snapTolerance: 20, stack: false, zIndex: false, // callbacks drag: null, start: null, stop: null }, _create: function() { if ( this.options.helper === "original" ) { this._setPositionRelative(); } if (this.options.addClasses){ this.element.addClass("ui-draggable"); } if (this.options.disabled){ this.element.addClass("ui-draggable-disabled"); } this._setHandleClassName(); this._mouseInit(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "handle" ) { this._removeHandleClassName(); this._setHandleClassName(); } }, _destroy: function() { if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) { this.destroyOnClear = true; return; } this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" ); this._removeHandleClassName(); this._mouseDestroy(); }, _mouseCapture: function(event) { var o = this.options; this._blurActiveElement( event ); // among others, prevent a drag on a resizable-handle if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) { return false; } //Quit if we're not on a valid handle this.handle = this._getHandle(event); if (!this.handle) { return false; } this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix ); return true; }, _blockFrames: function( selector ) { this.iframeBlocks = this.document.find( selector ).map(function() { var iframe = $( this ); return $( "<div>" ) .css( "position", "absolute" ) .appendTo( iframe.parent() ) .outerWidth( iframe.outerWidth() ) .outerHeight( iframe.outerHeight() ) .offset( iframe.offset() )[ 0 ]; }); }, _unblockFrames: function() { if ( this.iframeBlocks ) { this.iframeBlocks.remove(); delete this.iframeBlocks; } }, _blurActiveElement: function( event ) { var document = this.document[ 0 ]; // Only need to blur if the event occurred on the draggable itself, see #10527 if ( !this.handleElement.is( event.target ) ) { return; } // support: IE9 // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { // Support: IE9, IE10 // If the <body> is blurred, IE will switch windows, see #9520 if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) { // Blur any element that currently has focus, see #4261 $( document.activeElement ).blur(); } } catch ( error ) {} }, _mouseStart: function(event) { var o = this.options; //Create and append the visible helper this.helper = this._createHelper(event); this.helper.addClass("ui-draggable-dragging"); //Cache the helper size this._cacheHelperProportions(); //If ddmanager is used for droppables, set the global draggable if ($.ui.ddmanager) { $.ui.ddmanager.current = this; } /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Store the helper's css position this.cssPosition = this.helper.css( "position" ); this.scrollParent = this.helper.scrollParent( true ); this.offsetParent = this.helper.offsetParent(); this.hasFixedAncestor = this.helper.parents().filter(function() { return $( this ).css( "position" ) === "fixed"; }).length > 0; //The element's absolute position on the page minus margins this.positionAbs = this.element.offset(); this._refreshOffsets( event ); //Generate the original position this.originalPosition = this.position = this._generatePosition( event, false ); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Set a containment if given in the options this._setContainment(); //Trigger event + callbacks if (this._trigger("start", event) === false) { this._clear(); return false; } //Recache the helper size this._cacheHelperProportions(); //Prepare the droppable offsets if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } // Reset helper's right/bottom css if they're set and set explicit width/height instead // as this prevents resizing of elements with right/bottom set (see #7772) this._normalizeRightBottom(); this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStart(this, event); } return true; }, _refreshOffsets: function( event ) { this.offset = { top: this.positionAbs.top - this.margins.top, left: this.positionAbs.left - this.margins.left, scroll: false, parent: this._getParentOffset(), relative: this._getRelativeOffset() }; this.offset.click = { left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }; }, _mouseDrag: function(event, noPropagation) { // reset any necessary cached properties (see #5009) if ( this.hasFixedAncestor ) { this.offset.parent = this._getParentOffset(); } //Compute the helpers position this.position = this._generatePosition( event, true ); this.positionAbs = this._convertPositionTo("absolute"); //Call plugins and callbacks and use the resulting position if something is returned if (!noPropagation) { var ui = this._uiHash(); if (this._trigger("drag", event, ui) === false) { this._mouseUp({}); return false; } this.position = ui.position; } this.helper[ 0 ].style.left = this.position.left + "px"; this.helper[ 0 ].style.top = this.position.top + "px"; if ($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } return false; }, _mouseStop: function(event) { //If we are using droppables, inform the manager about the drop var that = this, dropped = false; if ($.ui.ddmanager && !this.options.dropBehaviour) { dropped = $.ui.ddmanager.drop(this, event); } //if a drop comes from outside (a sortable) if (this.dropped) { dropped = this.dropped; this.dropped = false; } if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { if (that._trigger("stop", event) !== false) { that._clear(); } }); } else { if (this._trigger("stop", event) !== false) { this._clear(); } } return false; }, _mouseUp: function( event ) { this._unblockFrames(); //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStop(this, event); } // Only need to focus if the event occurred on the draggable itself, see #10527 if ( this.handleElement.is( event.target ) ) { // The interaction is over; whether or not the click resulted in a drag, focus the element this.element.focus(); } return $.ui.mouse.prototype._mouseUp.call(this, event); }, cancel: function() { if (this.helper.is(".ui-draggable-dragging")) { this._mouseUp({}); } else { this._clear(); } return this; }, _getHandle: function(event) { return this.options.handle ? !!$( event.target ).closest( this.element.find( this.options.handle ) ).length : true; }, _setHandleClassName: function() { this.handleElement = this.options.handle ? this.element.find( this.options.handle ) : this.element; this.handleElement.addClass( "ui-draggable-handle" ); }, _removeHandleClassName: function() { this.handleElement.removeClass( "ui-draggable-handle" ); }, _createHelper: function(event) { var o = this.options, helperIsFunction = $.isFunction( o.helper ), helper = helperIsFunction ? $( o.helper.apply( this.element[ 0 ], [ event ] ) ) : ( o.helper === "clone" ? this.element.clone().removeAttr( "id" ) : this.element ); if (!helper.parents("body").length) { helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo)); } // http://bugs.jqueryui.com/ticket/9446 // a helper function can return the original element // which wouldn't have been set to relative in _create if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) { this._setPositionRelative(); } if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) { helper.css("position", "absolute"); } return helper; }, _setPositionRelative: function() { if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) { this.element[ 0 ].style.position = "relative"; } }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = { left: +obj[0], top: +obj[1] || 0 }; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _isRootNode: function( element ) { return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ]; }, _getParentOffset: function() { //Get the offsetParent and cache its position var po = this.offsetParent.offset(), document = this.document[ 0 ]; // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } if ( this._isRootNode( this.offsetParent[ 0 ] ) ) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0) }; }, _getRelativeOffset: function() { if ( this.cssPosition !== "relative" ) { return { top: 0, left: 0 }; } var p = this.element.position(), scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: p.top - ( parseInt(this.helper.css( "top" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ), left: p.left - ( parseInt(this.helper.css( "left" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 ) }; }, _cacheMargins: function() { this.margins = { left: (parseInt(this.element.css("marginLeft"), 10) || 0), top: (parseInt(this.element.css("marginTop"), 10) || 0), right: (parseInt(this.element.css("marginRight"), 10) || 0), bottom: (parseInt(this.element.css("marginBottom"), 10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var isUserScrollable, c, ce, o = this.options, document = this.document[ 0 ]; this.relativeContainer = null; if ( !o.containment ) { this.containment = null; return; } if ( o.containment === "window" ) { this.containment = [ $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left, $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top, $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left, $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment === "document") { this.containment = [ 0, 0, $( document ).width() - this.helperProportions.width - this.margins.left, ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment.constructor === Array ) { this.containment = o.containment; return; } if ( o.containment === "parent" ) { o.containment = this.helper[ 0 ].parentNode; } c = $( o.containment ); ce = c[ 0 ]; if ( !ce ) { return; } isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) ); this.containment = [ ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ), ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ), ( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right, ( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom ]; this.relativeContainer = c; }, _convertPositionTo: function(d, pos) { if (!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod) ) }; }, _generatePosition: function( event, constrainPosition ) { var containment, co, top, left, o = this.options, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ), pageX = event.pageX, pageY = event.pageY; // Cache the scroll if ( !scrollIsRootNode || !this.offset.scroll ) { this.offset.scroll = { top: this.scrollParent.scrollTop(), left: this.scrollParent.scrollLeft() }; } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ // If we are not dragging yet, we won't check for options if ( constrainPosition ) { if ( this.containment ) { if ( this.relativeContainer ){ co = this.relativeContainer.offset(); containment = [ this.containment[ 0 ] + co.left, this.containment[ 1 ] + co.top, this.containment[ 2 ] + co.left, this.containment[ 3 ] + co.top ]; } else { containment = this.containment; } if (event.pageX - this.offset.click.left < containment[0]) { pageX = containment[0] + this.offset.click.left; } if (event.pageY - this.offset.click.top < containment[1]) { pageY = containment[1] + this.offset.click.top; } if (event.pageX - this.offset.click.left > containment[2]) { pageX = containment[2] + this.offset.click.left; } if (event.pageY - this.offset.click.top > containment[3]) { pageY = containment[3] + this.offset.click.top; } } if (o.grid) { //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950) top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY; pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX; pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } if ( o.axis === "y" ) { pageX = this.originalPageX; } if ( o.axis === "x" ) { pageY = this.originalPageY; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) ) }; }, _clear: function() { this.helper.removeClass("ui-draggable-dragging"); if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) { this.helper.remove(); } this.helper = null; this.cancelHelperRemoval = false; if ( this.destroyOnClear ) { this.destroy(); } }, _normalizeRightBottom: function() { if ( this.options.axis !== "y" && this.helper.css( "right" ) !== "auto" ) { this.helper.width( this.helper.width() ); this.helper.css( "right", "auto" ); } if ( this.options.axis !== "x" && this.helper.css( "bottom" ) !== "auto" ) { this.helper.height( this.helper.height() ); this.helper.css( "bottom", "auto" ); } }, // From now on bulk stuff - mainly helpers _trigger: function( type, event, ui ) { ui = ui || this._uiHash(); $.ui.plugin.call( this, type, [ event, ui, this ], true ); // Absolute position and offset (see #6884 ) have to be recalculated after plugins if ( /^(drag|start|stop)/.test( type ) ) { this.positionAbs = this._convertPositionTo( "absolute" ); ui.offset = this.positionAbs; } return $.Widget.prototype._trigger.call( this, type, event, ui ); }, plugins: {}, _uiHash: function() { return { helper: this.helper, position: this.position, originalPosition: this.originalPosition, offset: this.positionAbs }; } }); $.ui.plugin.add( "draggable", "connectToSortable", { start: function( event, ui, draggable ) { var uiSortable = $.extend( {}, ui, { item: draggable.element }); draggable.sortables = []; $( draggable.options.connectToSortable ).each(function() { var sortable = $( this ).sortable( "instance" ); if ( sortable && !sortable.options.disabled ) { draggable.sortables.push( sortable ); // refreshPositions is called at drag start to refresh the containerCache // which is used in drag. This ensures it's initialized and synchronized // with any changes that might have happened on the page since initialization. sortable.refreshPositions(); sortable._trigger("activate", event, uiSortable); } }); }, stop: function( event, ui, draggable ) { var uiSortable = $.extend( {}, ui, { item: draggable.element }); draggable.cancelHelperRemoval = false; $.each( draggable.sortables, function() { var sortable = this; if ( sortable.isOver ) { sortable.isOver = 0; // Allow this sortable to handle removing the helper draggable.cancelHelperRemoval = true; sortable.cancelHelperRemoval = false; // Use _storedCSS To restore properties in the sortable, // as this also handles revert (#9675) since the draggable // may have modified them in unexpected ways (#8809) sortable._storedCSS = { position: sortable.placeholder.css( "position" ), top: sortable.placeholder.css( "top" ), left: sortable.placeholder.css( "left" ) }; sortable._mouseStop(event); // Once drag has ended, the sortable should return to using // its original helper, not the shared helper from draggable sortable.options.helper = sortable.options._helper; } else { // Prevent this Sortable from removing the helper. // However, don't set the draggable to remove the helper // either as another connected Sortable may yet handle the removal. sortable.cancelHelperRemoval = true; sortable._trigger( "deactivate", event, uiSortable ); } }); }, drag: function( event, ui, draggable ) { $.each( draggable.sortables, function() { var innermostIntersecting = false, sortable = this; // Copy over variables that sortable's _intersectsWith uses sortable.positionAbs = draggable.positionAbs; sortable.helperProportions = draggable.helperProportions; sortable.offset.click = draggable.offset.click; if ( sortable._intersectsWith( sortable.containerCache ) ) { innermostIntersecting = true; $.each( draggable.sortables, function() { // Copy over variables that sortable's _intersectsWith uses this.positionAbs = draggable.positionAbs; this.helperProportions = draggable.helperProportions; this.offset.click = draggable.offset.click; if ( this !== sortable && this._intersectsWith( this.containerCache ) && $.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) { innermostIntersecting = false; } return innermostIntersecting; }); } if ( innermostIntersecting ) { // If it intersects, we use a little isOver variable and set it once, // so that the move-in stuff gets fired only once. if ( !sortable.isOver ) { sortable.isOver = 1; // Store draggable's parent in case we need to reappend to it later. draggable._parent = ui.helper.parent(); sortable.currentItem = ui.helper .appendTo( sortable.element ) .data( "ui-sortable-item", true ); // Store helper option to later restore it sortable.options._helper = sortable.options.helper; sortable.options.helper = function() { return ui.helper[ 0 ]; }; // Fire the start events of the sortable with our passed browser event, // and our own helper (so it doesn't create a new one) event.target = sortable.currentItem[ 0 ]; sortable._mouseCapture( event, true ); sortable._mouseStart( event, true, true ); // Because the browser event is way off the new appended portlet, // modify necessary variables to reflect the changes sortable.offset.click.top = draggable.offset.click.top; sortable.offset.click.left = draggable.offset.click.left; sortable.offset.parent.left -= draggable.offset.parent.left - sortable.offset.parent.left; sortable.offset.parent.top -= draggable.offset.parent.top - sortable.offset.parent.top; draggable._trigger( "toSortable", event ); // Inform draggable that the helper is in a valid drop zone, // used solely in the revert option to handle "valid/invalid". draggable.dropped = sortable.element; // Need to refreshPositions of all sortables in the case that // adding to one sortable changes the location of the other sortables (#9675) $.each( draggable.sortables, function() { this.refreshPositions(); }); // hack so receive/update callbacks work (mostly) draggable.currentItem = draggable.element; sortable.fromOutside = draggable; } if ( sortable.currentItem ) { sortable._mouseDrag( event ); // Copy the sortable's position because the draggable's can potentially reflect // a relative position, while sortable is always absolute, which the dragged // element has now become. (#8809) ui.position = sortable.position; } } else { // If it doesn't intersect with the sortable, and it intersected before, // we fake the drag stop of the sortable, but make sure it doesn't remove // the helper by using cancelHelperRemoval. if ( sortable.isOver ) { sortable.isOver = 0; sortable.cancelHelperRemoval = true; // Calling sortable's mouseStop would trigger a revert, // so revert must be temporarily false until after mouseStop is called. sortable.options._revert = sortable.options.revert; sortable.options.revert = false; sortable._trigger( "out", event, sortable._uiHash( sortable ) ); sortable._mouseStop( event, true ); // restore sortable behaviors that were modfied // when the draggable entered the sortable area (#9481) sortable.options.revert = sortable.options._revert; sortable.options.helper = sortable.options._helper; if ( sortable.placeholder ) { sortable.placeholder.remove(); } // Restore and recalculate the draggable's offset considering the sortable // may have modified them in unexpected ways. (#8809, #10669) ui.helper.appendTo( draggable._parent ); draggable._refreshOffsets( event ); ui.position = draggable._generatePosition( event, true ); draggable._trigger( "fromSortable", event ); // Inform draggable that the helper is no longer in a valid drop zone draggable.dropped = false; // Need to refreshPositions of all sortables just in case removing // from one sortable changes the location of other sortables (#9675) $.each( draggable.sortables, function() { this.refreshPositions(); }); } } }); } }); $.ui.plugin.add("draggable", "cursor", { start: function( event, ui, instance ) { var t = $( "body" ), o = instance.options; if (t.css("cursor")) { o._cursor = t.css("cursor"); } t.css("cursor", o.cursor); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._cursor) { $("body").css("cursor", o._cursor); } } }); $.ui.plugin.add("draggable", "opacity", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("opacity")) { o._opacity = t.css("opacity"); } t.css("opacity", o.opacity); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._opacity) { $(ui.helper).css("opacity", o._opacity); } } }); $.ui.plugin.add("draggable", "scroll", { start: function( event, ui, i ) { if ( !i.scrollParentNotHidden ) { i.scrollParentNotHidden = i.helper.scrollParent( false ); } if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] && i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) { i.overflowOffset = i.scrollParentNotHidden.offset(); } }, drag: function( event, ui, i ) { var o = i.options, scrolled = false, scrollParent = i.scrollParentNotHidden[ 0 ], document = i.document[ 0 ]; if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) { if ( !o.axis || o.axis !== "x" ) { if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY < o.scrollSensitivity ) { scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed; } else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) { scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed; } } if ( !o.axis || o.axis !== "y" ) { if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX < o.scrollSensitivity ) { scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed; } else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) { scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed; } } } else { if (!o.axis || o.axis !== "x") { if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } } if (!o.axis || o.axis !== "y") { if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } } if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(i, event); } } }); $.ui.plugin.add("draggable", "snap", { start: function( event, ui, i ) { var o = i.options; i.snapElements = []; $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() { var $t = $(this), $o = $t.offset(); if (this !== i.element[0]) { i.snapElements.push({ item: this, width: $t.outerWidth(), height: $t.outerHeight(), top: $o.top, left: $o.left }); } }); }, drag: function( event, ui, inst ) { var ts, bs, ls, rs, l, r, t, b, i, first, o = inst.options, d = o.snapTolerance, x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; for (i = inst.snapElements.length - 1; i >= 0; i--){ l = inst.snapElements[i].left - inst.margins.left; r = l + inst.snapElements[i].width; t = inst.snapElements[i].top - inst.margins.top; b = t + inst.snapElements[i].height; if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) { if (inst.snapElements[i].snapping) { (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = false; continue; } if (o.snapMode !== "inner") { ts = Math.abs(t - y2) <= d; bs = Math.abs(b - y1) <= d; ls = Math.abs(l - x2) <= d; rs = Math.abs(r - x1) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left; } } first = (ts || bs || ls || rs); if (o.snapMode !== "outer") { ts = Math.abs(t - y1) <= d; bs = Math.abs(b - y2) <= d; ls = Math.abs(l - x1) <= d; rs = Math.abs(r - x2) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left; } } if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) { (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = (ts || bs || ls || rs || first); } } }); $.ui.plugin.add("draggable", "stack", { start: function( event, ui, instance ) { var min, o = instance.options, group = $.makeArray($(o.stack)).sort(function(a, b) { return (parseInt($(a).css("zIndex"), 10) || 0) - (parseInt($(b).css("zIndex"), 10) || 0); }); if (!group.length) { return; } min = parseInt($(group[0]).css("zIndex"), 10) || 0; $(group).each(function(i) { $(this).css("zIndex", min + i); }); this.css("zIndex", (min + group.length)); } }); $.ui.plugin.add("draggable", "zIndex", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("zIndex")) { o._zIndex = t.css("zIndex"); } t.css("zIndex", o.zIndex); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._zIndex) { $(ui.helper).css("zIndex", o._zIndex); } } }); var draggable = $.ui.draggable; /*! * jQuery UI Droppable 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/droppable/ */ $.widget( "ui.droppable", { version: "1.11.4", widgetEventPrefix: "drop", options: { accept: "*", activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: "default", tolerance: "intersect", // callbacks activate: null, deactivate: null, drop: null, out: null, over: null }, _create: function() { var proportions, o = this.options, accept = o.accept; this.isover = false; this.isout = true; this.accept = $.isFunction( accept ) ? accept : function( d ) { return d.is( accept ); }; this.proportions = function( /* valueToWrite */ ) { if ( arguments.length ) { // Store the droppable's proportions proportions = arguments[ 0 ]; } else { // Retrieve or derive the droppable's proportions return proportions ? proportions : proportions = { width: this.element[ 0 ].offsetWidth, height: this.element[ 0 ].offsetHeight }; } }; this._addToManager( o.scope ); o.addClasses && this.element.addClass( "ui-droppable" ); }, _addToManager: function( scope ) { // Add the reference and positions to the manager $.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || []; $.ui.ddmanager.droppables[ scope ].push( this ); }, _splice: function( drop ) { var i = 0; for ( ; i < drop.length; i++ ) { if ( drop[ i ] === this ) { drop.splice( i, 1 ); } } }, _destroy: function() { var drop = $.ui.ddmanager.droppables[ this.options.scope ]; this._splice( drop ); this.element.removeClass( "ui-droppable ui-droppable-disabled" ); }, _setOption: function( key, value ) { if ( key === "accept" ) { this.accept = $.isFunction( value ) ? value : function( d ) { return d.is( value ); }; } else if ( key === "scope" ) { var drop = $.ui.ddmanager.droppables[ this.options.scope ]; this._splice( drop ); this._addToManager( value ); } this._super( key, value ); }, _activate: function( event ) { var draggable = $.ui.ddmanager.current; if ( this.options.activeClass ) { this.element.addClass( this.options.activeClass ); } if ( draggable ){ this._trigger( "activate", event, this.ui( draggable ) ); } }, _deactivate: function( event ) { var draggable = $.ui.ddmanager.current; if ( this.options.activeClass ) { this.element.removeClass( this.options.activeClass ); } if ( draggable ){ this._trigger( "deactivate", event, this.ui( draggable ) ); } }, _over: function( event ) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.hoverClass ) { this.element.addClass( this.options.hoverClass ); } this._trigger( "over", event, this.ui( draggable ) ); } }, _out: function( event ) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.hoverClass ) { this.element.removeClass( this.options.hoverClass ); } this._trigger( "out", event, this.ui( draggable ) ); } }, _drop: function( event, custom ) { var draggable = custom || $.ui.ddmanager.current, childrenIntersection = false; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return false; } this.element.find( ":data(ui-droppable)" ).not( ".ui-draggable-dragging" ).each(function() { var inst = $( this ).droppable( "instance" ); if ( inst.options.greedy && !inst.options.disabled && inst.options.scope === draggable.options.scope && inst.accept.call( inst.element[ 0 ], ( draggable.currentItem || draggable.element ) ) && $.ui.intersect( draggable, $.extend( inst, { offset: inst.element.offset() } ), inst.options.tolerance, event ) ) { childrenIntersection = true; return false; } }); if ( childrenIntersection ) { return false; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.activeClass ) { this.element.removeClass( this.options.activeClass ); } if ( this.options.hoverClass ) { this.element.removeClass( this.options.hoverClass ); } this._trigger( "drop", event, this.ui( draggable ) ); return this.element; } return false; }, ui: function( c ) { return { draggable: ( c.currentItem || c.element ), helper: c.helper, position: c.position, offset: c.positionAbs }; } }); $.ui.intersect = (function() { function isOverAxis( x, reference, size ) { return ( x >= reference ) && ( x < ( reference + size ) ); } return function( draggable, droppable, toleranceMode, event ) { if ( !droppable.offset ) { return false; } var x1 = ( draggable.positionAbs || draggable.position.absolute ).left + draggable.margins.left, y1 = ( draggable.positionAbs || draggable.position.absolute ).top + draggable.margins.top, x2 = x1 + draggable.helperProportions.width, y2 = y1 + draggable.helperProportions.height, l = droppable.offset.left, t = droppable.offset.top, r = l + droppable.proportions().width, b = t + droppable.proportions().height; switch ( toleranceMode ) { case "fit": return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b ); case "intersect": return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half case "pointer": return isOverAxis( event.pageY, t, droppable.proportions().height ) && isOverAxis( event.pageX, l, droppable.proportions().width ); case "touch": return ( ( y1 >= t && y1 <= b ) || // Top edge touching ( y2 >= t && y2 <= b ) || // Bottom edge touching ( y1 < t && y2 > b ) // Surrounded vertically ) && ( ( x1 >= l && x1 <= r ) || // Left edge touching ( x2 >= l && x2 <= r ) || // Right edge touching ( x1 < l && x2 > r ) // Surrounded horizontally ); default: return false; } }; })(); /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { "default": [] }, prepareOffsets: function( t, event ) { var i, j, m = $.ui.ddmanager.droppables[ t.options.scope ] || [], type = event ? event.type : null, // workaround for #2317 list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack(); droppablesLoop: for ( i = 0; i < m.length; i++ ) { // No disabled and non-accepted if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) { continue; } // Filter out elements in the current dragged item for ( j = 0; j < list.length; j++ ) { if ( list[ j ] === m[ i ].element[ 0 ] ) { m[ i ].proportions().height = 0; continue droppablesLoop; } } m[ i ].visible = m[ i ].element.css( "display" ) !== "none"; if ( !m[ i ].visible ) { continue; } // Activate the droppable if used directly from draggables if ( type === "mousedown" ) { m[ i ]._activate.call( m[ i ], event ); } m[ i ].offset = m[ i ].element.offset(); m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth, height: m[ i ].element[ 0 ].offsetHeight }); } }, drop: function( draggable, event ) { var dropped = false; // Create a copy of the droppables in case the list changes during the drop (#9116) $.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() { if ( !this.options ) { return; } if ( !this.options.disabled && this.visible && $.ui.intersect( draggable, this, this.options.tolerance, event ) ) { dropped = this._drop.call( this, event ) || dropped; } if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { this.isout = true; this.isover = false; this._deactivate.call( this, event ); } }); return dropped; }, dragStart: function( draggable, event ) { // Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003) draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() { if ( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } }); }, drag: function( draggable, event ) { // If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if ( draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } // Run through all droppables and check their positions based on specific tolerance options $.each( $.ui.ddmanager.droppables[ draggable.options.scope ] || [], function() { if ( this.options.disabled || this.greedyChild || !this.visible ) { return; } var parentInstance, scope, parent, intersects = $.ui.intersect( draggable, this, this.options.tolerance, event ), c = !intersects && this.isover ? "isout" : ( intersects && !this.isover ? "isover" : null ); if ( !c ) { return; } if ( this.options.greedy ) { // find droppable parents with same scope scope = this.options.scope; parent = this.element.parents( ":data(ui-droppable)" ).filter(function() { return $( this ).droppable( "instance" ).options.scope === scope; }); if ( parent.length ) { parentInstance = $( parent[ 0 ] ).droppable( "instance" ); parentInstance.greedyChild = ( c === "isover" ); } } // we just moved into a greedy child if ( parentInstance && c === "isover" ) { parentInstance.isover = false; parentInstance.isout = true; parentInstance._out.call( parentInstance, event ); } this[ c ] = true; this[c === "isout" ? "isover" : "isout"] = false; this[c === "isover" ? "_over" : "_out"].call( this, event ); // we just moved out of a greedy child if ( parentInstance && c === "isout" ) { parentInstance.isout = false; parentInstance.isover = true; parentInstance._over.call( parentInstance, event ); } }); }, dragStop: function( draggable, event ) { draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" ); // Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003) if ( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } } }; var droppable = $.ui.droppable; }));
import * as React from 'react' import { shallow } from 'enzyme' import Product from './Product' const setup = props => { const component = shallow( <Product {...props} /> ) return { component: component } } describe('Product component', () => { it('should render title and price', () => { const { component } = setup({ title: 'Test Product', price: 9.99 }) expect(component.text()).toBe('Test Product - $9.99') }) describe('when given inventory', () => { it('should render title, price, and inventory', () => { const { component } = setup({ title: 'Test Product', price: 9.99, quantity: 6 }) expect(component.text()).toBe('Test Product - $9.99 x 6') }) }) })
// Quartz.Drawing.Texture var Texture; (function () { Texture = qz.Texture = function (image , sourceOffset , sourceSize , offset , size) { if (image instanceof Loader.Image) image = image.image; /** * Doku oluşturulacak resim */ this.image = image; /** * Resimden alınacak parcanın x ve y kordinatları * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage * buradaki sx,sy */ this.sourceOffset = Point(sourceOffset); /** * Resimden alınacak parçanın width ve height değerleri * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage * buradaki sWidth , sHeight */ this.sourceSize = sourceSize ? Size(sourceSize) : Size(image).clone().sub(this.sourceOffset); /** * Çizime başlanacak x ve y kordinatları */ this.offset = Point(offset); /** * Çizim yapılacak canvasın boyutu */ this.size = size ? Size(size) : this.sourceSize.clone().sum(this.offset); /** * Kaplamanın tutulacağı canvas * @type {Element} * @private */ this._canvas = document.createElement('canvas'); /** * Kaplama Canvasının contexti * @type {CanvasRenderingContext2D} * @private */ this._context = this._canvas.getContext('2d'); this.update(); }; Util.assign(Texture.prototype , { /** * Dokuyu Canvasa Çizer */ update: function () { var so = this.sourceOffset, ss = this.sourceSize, co = this.offset, cs = this.size, context = this._context, canvas = this._canvas, image = this.image instanceof Texture ? this.image.getBufferCanvas() : this.image; canvas.width = cs.width; canvas.height = cs.height; context.clearRect(0 , 0 , cs.width , cs.height); context.drawImage(image , so.x , so.y , ss.width , ss.height , co.x , co.y , ss.width , ss.height); } , clone: function () { return new Texture(this.image); }, getBufferCanvas: function () { return this._canvas; } }); })();
version https://git-lfs.github.com/spec/v1 oid sha256:cf05016712db5c35988c927f4f5484ae5d72ead944b834aaf0af8c1f3a5ba25d size 113016
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import addEmoji from '../../../modifiers/addEmoji'; import Groups from './Groups'; import Nav from './Nav'; import ToneSelect from './ToneSelect'; export default class Popover extends Component { static propTypes = { cacheBustParam: PropTypes.string.isRequired, imagePath: PropTypes.string.isRequired, imageType: PropTypes.string.isRequired, theme: PropTypes.object.isRequired, store: PropTypes.object.isRequired, groups: PropTypes.arrayOf(PropTypes.object).isRequired, emojis: PropTypes.object.isRequired, toneSelectOpenDelay: PropTypes.number.isRequired, isOpen: PropTypes.bool, useNativeArt: PropTypes.bool, }; static defaultProps = { isOpen: false, }; state = { activeGroup: 0, showToneSelect: false, }; componentDidMount() { window.addEventListener('mouseup', this.onMouseUp); } componentWillUnmount() { window.removeEventListener('mouseup', this.onMouseUp); } onMouseDown = () => { this.mouseDown = true; }; onMouseUp = () => { this.mouseDown = false; if (this.activeEmoji) { this.activeEmoji.deselect(); this.activeEmoji = null; if (this.state.showToneSelect) { this.closeToneSelect(); } else if (this.toneSelectTimer) { clearTimeout(this.toneSelectTimer); this.toneSelectTimer = null; } } }; onWheel = (e) => e.preventDefault(); onEmojiSelect = (emoji) => { const newEditorState = addEmoji( this.props.store.getEditorState(), emoji, ); this.props.store.setEditorState(newEditorState); }; onEmojiMouseDown = (emojiEntry, toneSet) => { this.activeEmoji = emojiEntry; if (toneSet) { this.openToneSelectWithTimer(toneSet); } }; onGroupSelect = (groupIndex) => { this.groups.scrollToGroup(groupIndex); }; onGroupScroll = (groupIndex) => { if (groupIndex !== this.state.activeGroup) { this.setState({ activeGroup: groupIndex, }); } }; openToneSelectWithTimer = (toneSet) => { this.toneSelectTimer = setTimeout(() => { this.toneSelectTimer = null; this.openToneSelect(toneSet); }, this.props.toneSelectOpenDelay); } openToneSelect = (toneSet) => { this.toneSet = toneSet; this.setState({ showToneSelect: true, }); }; closeToneSelect = () => { this.toneSet = []; this.setState({ showToneSelect: false, }); }; checkMouseDown = () => this.mouseDown; mouseDown = false; activeEmoji = null; toneSet = []; toneSelectTimer = null; renderToneSelect = () => { if (this.state.showToneSelect) { const { cacheBustParam, imagePath, imageType, theme = {} } = this.props; const containerBounds = this.container.getBoundingClientRect(); const areaBounds = this.groups.container.getBoundingClientRect(); const entryBounds = this.activeEmoji.button.getBoundingClientRect(); // Translate TextRectangle coords to CSS relative coords const bounds = { areaBounds: { left: areaBounds.left - containerBounds.left, right: containerBounds.right - areaBounds.right, top: areaBounds.top - containerBounds.top, bottom: containerBounds.bottom - areaBounds.bottom, width: areaBounds.width, height: areaBounds.width, }, entryBounds: { left: entryBounds.left - containerBounds.left, right: containerBounds.right - entryBounds.right, top: entryBounds.top - containerBounds.top, bottom: containerBounds.bottom - entryBounds.bottom, width: entryBounds.width, height: entryBounds.width, } }; return ( <ToneSelect theme={theme} bounds={bounds} toneSet={this.toneSet} imagePath={imagePath} imageType={imageType} cacheBustParam={cacheBustParam} onEmojiSelect={this.onEmojiSelect} /> ); } return null; }; render() { const { cacheBustParam, imagePath, imageType, theme = {}, groups = [], emojis, isOpen = false, useNativeArt, } = this.props; const className = isOpen ? theme.emojiSelectPopover : theme.emojiSelectPopoverClosed; const { activeGroup } = this.state; return ( <div className={className} onMouseDown={this.onMouseDown} onWheel={this.onWheel} ref={(element) => { this.container = element; }} > <h3 className={theme.emojiSelectPopoverTitle}> {groups[activeGroup].title} </h3> <Groups theme={theme} groups={groups} emojis={emojis} imagePath={imagePath} imageType={imageType} cacheBustParam={cacheBustParam} checkMouseDown={this.checkMouseDown} onEmojiSelect={this.onEmojiSelect} onEmojiMouseDown={this.onEmojiMouseDown} onGroupScroll={this.onGroupScroll} ref={(element) => { this.groups = element; }} useNativeArt={useNativeArt} /> <Nav theme={theme} groups={groups} activeGroup={activeGroup} onGroupSelect={this.onGroupSelect} /> {this.renderToneSelect()} </div> ); } }
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('password-strength', 'Integration | Component | password strength', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{password-strength}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#password-strength}} template block text {{/password-strength}} `); assert.equal(this.$().text().trim(), 'template block text'); });
var util, Path= require('path'), fs = require('fs'); var jasmine = require('./index'); try { util = require('util') } catch(e) { util = require('sys') } var helperCollection = require('./spec-collection'); var specFolders = []; var watchFolders = []; // The following line keeps the jasmine setTimeout in the proper scope jasmine.setTimeout = jasmine.getGlobal().setTimeout; jasmine.setInterval = jasmine.getGlobal().setInterval; for (var key in jasmine) global[key] = jasmine[key]; var isVerbose = false; var showColors = true; // Disable if we're not on a TTY if (!process.stdout.isTTY) { showColors = false; } var teamcity = process.env.TEAMCITY_PROJECT_NAME || false; var useRequireJs = false; var extensions = "js"; var match = '.'; var matchall = false; var autotest = false; var useHelpers = true; var forceExit = false; var captureExceptions = false; var includeStackTrace = true; var growl = false; var junitreport = { report: false, savePath : "./reports/", useDotNotation: true, consolidate: true } var args = process.argv.slice(2); var existsSync = fs.existsSync || Path.existsSync; while(args.length) { var arg = args.shift(); switch(arg) { case '--version': printVersion(); case '--color': showColors = true; break; case '--noColor': case '--nocolor': showColors = false; break; case '--verbose': isVerbose = true; break; case '--coffee': try { require('coffeescript/register'); // support CoffeeScript >=1.7.0 } catch ( e ) { require('coffeescript'); // support CoffeeScript <=1.6.3 } extensions = "js|coffee|litcoffee"; break; case '-m': case '--match': match = args.shift(); break; case '--matchall': matchall = true; break; case '--junitreport': junitreport.report = true; break; case '--output': junitreport.savePath = args.shift(); break; case '--teamcity': teamcity = true; break; case '--requireJsSetup': var setup = args.shift(); if(!existsSync(setup)) throw new Error("RequireJS setup '" + setup + "' doesn't exist!"); useRequireJs = setup; break; case '--runWithRequireJs': useRequireJs = useRequireJs || true; break; case '--nohelpers': useHelpers = false; break; case '--test-dir': var dir = args.shift(); if(!existsSync(dir)) throw new Error("Test root path '" + dir + "' doesn't exist!"); specFolders.push(dir); // NOTE: Does not look from current working directory. break; case '--autotest': autotest = true; break; case '--watch': var nextWatchDir; // Add the following arguments, until we see another argument starting with '-' while (args[0] && args[0][0] !== '-') { nextWatchDir = args.shift(); watchFolders.push(nextWatchDir); if (!existsSync(nextWatchDir)) throw new Error("Watch path '" + nextWatchDir + "' doesn't exist!"); } break; case '--forceexit': forceExit = true; break; case '--captureExceptions': captureExceptions = true; break; case '--noStack': includeStackTrace = false; break; case '--growl': growl = true; break; case '--config': var configKey = args.shift(); var configValue = args.shift(); process.env[configKey]=configValue; break; case '-h': help(); default: if (arg.match(/^--params=.*/)) { break; } if (arg.match(/^--/)) help(); if (arg.match(/^\/.*/)) { specFolders.push(arg); } else { specFolders.push(Path.join(process.cwd(), arg)); } break; } } if (specFolders.length === 0) { help(); } else { // Check to see if all our files exist for (var idx = 0; idx < specFolders.length; idx++) { if (!existsSync(specFolders[idx])) { console.log("File: " + specFolders[idx] + " is missing."); return; } } } if (autotest) { var patterns = ['**/*.js']; if (extensions.indexOf("coffee") !== -1) { patterns.push('**/*.coffee'); } require('./autotest').start(specFolders, watchFolders, patterns); return; } var exitCode = 0; if (captureExceptions) { process.on('uncaughtException', function(e) { console.error(e.stack || e); exitCode = 1; process.exit(exitCode); }); } process.on("exit", onExit); function onExit(requestedExitCode) { process.removeListener("exit", onExit); process.exit(requestedExitCode || exitCode); } var onComplete = function(runner, log) { process.stdout.write('\n'); if (runner.results().failedCount == 0) { exitCode = 0; } else { exitCode = 1; } if (forceExit) { process.exit(exitCode); } }; if(useHelpers){ specFolders.forEach(function(path){ jasmine.loadHelpersInFolder(path, new RegExp("helpers?\\.(" + extensions + ")$", 'i')); }) } try { var regExpSpec = new RegExp(match + (matchall ? "" : "spec\\.") + "(" + extensions + ")$", 'i') } catch (error) { console.error("Failed to build spec-matching regex: " + error); process.exit(2); } var options = { specFolders: specFolders, onComplete: onComplete, isVerbose: isVerbose, showColors: showColors, teamcity: teamcity, useRequireJs: useRequireJs, regExpSpec: regExpSpec, junitreport: junitreport, includeStackTrace: includeStackTrace, growl: growl } jasmine.executeSpecsInFolder(options); function help(){ process.stdout.write([ 'USAGE: jasmine-node [--color|--noColor] [--verbose] [--coffee] directory' , '' , 'Options:' , ' --autotest - rerun automatically the specs when a file changes' , ' --watch PATH - when used with --autotest, watches the given path(s) and runs all tests if a change is detected' , ' --color - use color coding for output' , ' --noColor - do not use color coding for output' , ' -m, --match REGEXP - load only specs containing "REGEXPspec"' , ' --matchall - relax requirement of "spec" in spec file names' , ' --verbose - print extra information per each test run' , ' --coffee - load coffeescript which allows execution .coffee files' , ' --junitreport - export tests results as junitreport xml format' , ' --output - defines the output folder for junitreport files' , ' --teamcity - converts all console output to teamcity custom test runner commands. (Normally auto detected.)' , ' --growl - display test run summary in a growl notification (in addition to other outputs)' , ' --runWithRequireJs - loads all specs using requirejs instead of node\'s native require method' , ' --requireJsSetup - file run before specs to include and configure RequireJS' , ' --test-dir - the absolute root directory path where tests are located' , ' --nohelpers - does not load helpers.' , ' --forceexit - force exit once tests complete.' , ' --captureExceptions- listen to global exceptions, report them and exit (interferes with Domains)' , ' --config NAME VALUE- set a global variable in process.env' , ' --noStack - suppress the stack trace generated from a test failure' , ' --version - show the current version' , ' -h, --help - display this help and exit' , '' ].join("\n")); process.exit(-1); } function printVersion(){ console.log("1.14.?"); process.exit(0); }
var fs = require('fs'); const { resolve } = require('path'); /* color-thief.umd.js duplicated as color-thief.min.js for legacy support In Color Thief v2.1 <= there was one distribution file (dist/color-thief.min.js) and it exposed a global variable ColorThief. Starting from v2.2, the package includes multiple dist files for the various module systems. One of these is the UMD format which falls back to a global variable if the requirejs AMD format is not being used. This file is called color-thief.umd.js in the dist folder. We want to keep supporting the previous users who were loading dist/color-thief.min.js and expecting a global var. For this reason we're duplicating the UMD compatible file and giving it that name. */ const umdRelPath = 'dist/color-thief.umd.js'; const legacyRelPath = 'dist/color-thief.min.js'; const umdPath = resolve(process.cwd(), umdRelPath); const legacyPath = resolve(process.cwd(), legacyRelPath); fs.copyFile(umdPath, legacyPath, (err) => { if (err) throw err; console.log(`${umdRelPath} copied to ${legacyRelPath}.`); }); const srcNodeRelPath = 'src/color-thief-node.js'; const distNodeRelPath = 'dist/color-thief.js'; const srcNodePath = resolve(process.cwd(), srcNodeRelPath); const distNodePath = resolve(process.cwd(), distNodeRelPath); fs.copyFile(srcNodePath, distNodePath, (err) => { if (err) throw err; console.log(`${srcNodeRelPath} copied to ${distNodeRelPath}.`); });
/*! * node-grape * Copyright(c) 2015 Bluse * MIT Licensed */ var sqlite3 = require('sqlite3').verbose(); module.exports = { workerError:function(err, req, res, next){ process.send({action:'error',data:{url:req.url,headers:JSON.stringify(req.headers),name:err.name,message:err.message,stack:err.stack}}) res.writeHead(500); res.end('Internet Server Error!'); }, workerRecordError:function(err,url,headers){ process.send({action:'error',data:{url:url,headers:headers,name:err.name,message:err.message,stack:err.stack}}) }, workerRecord:function(url,msg){ process.send({action:'record',data:{url:url,fromUserName:msg.fromUserName,toUserName:msg.toUserName,msgType:msg.msgType,message:JSON.stringify(msg)}}); }, workerApiRecord:function(api,option,data,costTime){ process.send({action:'apiRecord',data:{url:api,option:JSON.stringify(option),data:data,costTime:costTime}}); }, workerLog:function(log){ process.send({action:'log',data:{identity:'Worker',pid:process.pid,log:log}}); }, masterLog:function(log){ this.log({identity:'Master',pid:process.pid,log:log}) }, /** * Master start logger handler */ init:function(){ if( typeof global.logDbHandler == 'undefined' ) newLog(); }, error: function(err){ var date = new Date(); global.logDbHandler.run('INSERT INTO errors (url,headers,name,message,stack,createTime) VALUES (?,?,?,?,?,?)', err.url, err.headers || '', err.name || '', err.message || '', err.stack || '', date.toLocaleTimeString()+'.'+date.getMilliseconds()); }, record: function(msg){ var date = new Date(); global.logDbHandler.run('INSERT INTO receiveLog (url,fromUserName,toUserName,msgType,message,createTime) VALUES (?,?,?,?,?,?)', msg.url, msg.fromUserName || '', msg.toUserName || '', msg.msgType || '', JSON.stringify(msg) || '', date.toLocaleTimeString()+'.'+date.getMilliseconds()); }, apiRecord: function(msg){ var date = new Date(); global.logDbHandler.run('INSERT INTO apiLog (url,option,data,costTime,createTime) VALUES (?,?,?,?,?)', msg.url, msg.option || '', msg.data || '', msg.costTime || '', date.toLocaleTimeString()+'.'+date.getMilliseconds()); }, log: function(log){ var date = new Date(); global.logDbHandler.run('INSERT INTO log (createTime,identity,pid,log) VALUES (?,?,?,?)', date.toLocaleTimeString()+'.'+date.getMilliseconds(), log.identity || '', log.pid || '', log.log || ''); } }; /** * 割日志 */ function cutLog(){ global.logDbHandler.close(); newLog(); } function newLog(){ var date = new Date(); global.logDbHandler = new sqlite3.Database(__dirname+'/../logs/'+date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+'.log.db'); var errorTableSql = 'CREATE TABLE "main"."errors" ('+ ' "id" INTEGER PRIMARY KEY AUTOINCREMENT,'+ ' "url" TEXT,'+ ' "headers" TEXT,'+ ' "name" TEXT,'+ ' "message" TEXT,'+ ' "stack" TEXT,'+ ' "checked" INTEGER DEFAULT (0),'+ ' "createTime" TEXT'+ ');'; var receiveLogTableSql = 'CREATE TABLE "main"."receiveLog" ('+ ' "id" INTEGER PRIMARY KEY AUTOINCREMENT,'+ ' "url" TEXT,'+ ' "fromUserName" TEXT,'+ ' "toUserName" TEXT,'+ ' "msgType" TEXT,'+ ' "message" TEXT,'+ ' "createTime" TEXT'+ ');'; var logApiTableSql = 'CREATE TABLE "main"."apiLog" ('+ ' "id" INTEGER PRIMARY KEY AUTOINCREMENT,'+ ' "url" TEXT,'+ ' "option" TEXT,'+ ' "data" TEXT,'+ ' "costTime" TEXT,'+ ' "createTime" TEXT'+ ');'; var logTableSql = 'CREATE TABLE "main"."log" ('+ ' "id" INTEGER PRIMARY KEY AUTOINCREMENT,'+ ' "createTime" TEXT,'+ ' "identity" TEXT,'+ ' "pid" INTEGER,'+ ' "log" TEXT'+ ');'; global.logDbHandler.run('select * from errors limit 1',function(e){ if( e && typeof e.message == 'string' && e.message.search('no such table')){ global.logDbHandler.run(errorTableSql); global.logDbHandler.run(receiveLogTableSql); global.logDbHandler.run(logApiTableSql); global.logDbHandler.run(logTableSql); } }); var tomorrow = new Date(new Date().valueOf() + 3600*24*1000 +1000).toLocaleDateString(); var timeout = new Date(tomorrow) - new Date(); setTimeout(cutLog,timeout); }
/* global it, describe, expect, beforeEach */ var VersionableMap = require('../dist/versionable-collections').VersionableMap; describe('VersionableMap', function () { 'use strict'; it('should be defined as a function', function () { expect(typeof VersionableMap).toBe('function'); }); it('should has base "class" VersionableCollection', function () { var map = new VersionableMap(); expect(map instanceof VersionableMap).toBeTruthy(); }); it('should has only a single key for its instances called _version', function () { var map = new VersionableMap(); expect(Object.keys(map)).toEqual(['_version']); }); describe('methods', function () { var map; beforeEach(function () { map = new VersionableMap(); }); it('should define set method which changes the version', function () { var oldVersion = map._version; map.set('key', 'value'); expect(oldVersion).not.toBe(map._version); }); it('should define a get method which doesn\'t change the version', function () { map.set('foo', 'bar'); var oldVersion = map._version; expect(map.get('foo')).toBe('bar'); expect(map._version).toBe(oldVersion); }); it('should define a remove method, which changes the' + 'version, when the key is removed', function () { map.set('foo', 'bar'); var oldVersion = map._version; map.remove('foo'); expect(map._version).not.toBe(oldVersion); }); it('should define a remove method, which does not' + 'change the version, when the key doesn\'t exists', function () { var oldVersion = map._version; map.remove('foo'); expect(map._version).toBe(oldVersion); }); it('should define method keys which returns all keys of the collection', function () { map.set('key0', 1); map.set('key1', 1); var keys = map.keys(); expect(keys.indexOf('key0') >= 0).toBeTruthy(); expect(keys.indexOf('key1') >= 0).toBeTruthy(); }); }); });
/* ractive.js v0.5.5 2014-07-13 - commit 8b1d34ef http://ractivejs.org http://twitter.com/RactiveJS Released under the MIT License. */ ( function( global ) { 'use strict'; var noConflict = global.Ractive; /* config/defaults/options.js */ var options = function() { // These are both the values for Ractive.defaults // as well as the determination for whether an option // value will be placed on Component.defaults // (versus directly on Component) during an extend operation var defaultOptions = { // render placement: el: void 0, append: false, // template: template: { v: 1, t: [] }, // parse: preserveWhitespace: false, sanitize: false, stripComments: true, // data & binding: data: {}, computed: {}, magic: false, modifyArrays: true, adapt: [], isolated: false, twoway: true, lazy: false, // transitions: noIntro: false, transitionsEnabled: true, complete: void 0, // css: noCssTransform: false, // debug: debug: false }; return defaultOptions; }(); /* config/defaults/easing.js */ var easing = { linear: function( pos ) { return pos; }, easeIn: function( pos ) { return Math.pow( pos, 3 ); }, easeOut: function( pos ) { return Math.pow( pos - 1, 3 ) + 1; }, easeInOut: function( pos ) { if ( ( pos /= 0.5 ) < 1 ) { return 0.5 * Math.pow( pos, 3 ); } return 0.5 * ( Math.pow( pos - 2, 3 ) + 2 ); } }; /* circular.js */ var circular = []; /* utils/hasOwnProperty.js */ var hasOwn = Object.prototype.hasOwnProperty; /* utils/isArray.js */ var isArray = function() { var toString = Object.prototype.toString; // thanks, http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ return function( thing ) { return toString.call( thing ) === '[object Array]'; }; }(); /* utils/isObject.js */ var isObject = function() { var toString = Object.prototype.toString; return function( thing ) { return thing && toString.call( thing ) === '[object Object]'; }; }(); /* utils/isNumeric.js */ var isNumeric = function( thing ) { return !isNaN( parseFloat( thing ) ) && isFinite( thing ); }; /* config/defaults/interpolators.js */ var interpolators = function( circular, hasOwnProperty, isArray, isObject, isNumeric ) { var interpolators, interpolate, cssLengthPattern; circular.push( function() { interpolate = circular.interpolate; } ); cssLengthPattern = /^([+-]?[0-9]+\.?(?:[0-9]+)?)(px|em|ex|%|in|cm|mm|pt|pc)$/; interpolators = { number: function( from, to ) { var delta; if ( !isNumeric( from ) || !isNumeric( to ) ) { return null; } from = +from; to = +to; delta = to - from; if ( !delta ) { return function() { return from; }; } return function( t ) { return from + t * delta; }; }, array: function( from, to ) { var intermediate, interpolators, len, i; if ( !isArray( from ) || !isArray( to ) ) { return null; } intermediate = []; interpolators = []; i = len = Math.min( from.length, to.length ); while ( i-- ) { interpolators[ i ] = interpolate( from[ i ], to[ i ] ); } // surplus values - don't interpolate, but don't exclude them either for ( i = len; i < from.length; i += 1 ) { intermediate[ i ] = from[ i ]; } for ( i = len; i < to.length; i += 1 ) { intermediate[ i ] = to[ i ]; } return function( t ) { var i = len; while ( i-- ) { intermediate[ i ] = interpolators[ i ]( t ); } return intermediate; }; }, object: function( from, to ) { var properties, len, interpolators, intermediate, prop; if ( !isObject( from ) || !isObject( to ) ) { return null; } properties = []; intermediate = {}; interpolators = {}; for ( prop in from ) { if ( hasOwnProperty.call( from, prop ) ) { if ( hasOwnProperty.call( to, prop ) ) { properties.push( prop ); interpolators[ prop ] = interpolate( from[ prop ], to[ prop ] ); } else { intermediate[ prop ] = from[ prop ]; } } } for ( prop in to ) { if ( hasOwnProperty.call( to, prop ) && !hasOwnProperty.call( from, prop ) ) { intermediate[ prop ] = to[ prop ]; } } len = properties.length; return function( t ) { var i = len, prop; while ( i-- ) { prop = properties[ i ]; intermediate[ prop ] = interpolators[ prop ]( t ); } return intermediate; }; }, cssLength: function( from, to ) { var fromMatch, toMatch, fromUnit, toUnit, fromValue, toValue, unit, delta; if ( from !== 0 && typeof from !== 'string' || to !== 0 && typeof to !== 'string' ) { return null; } fromMatch = cssLengthPattern.exec( from ); toMatch = cssLengthPattern.exec( to ); fromUnit = fromMatch ? fromMatch[ 2 ] : ''; toUnit = toMatch ? toMatch[ 2 ] : ''; if ( fromUnit && toUnit && fromUnit !== toUnit ) { return null; } unit = fromUnit || toUnit; fromValue = fromMatch ? +fromMatch[ 1 ] : 0; toValue = toMatch ? +toMatch[ 1 ] : 0; delta = toValue - fromValue; if ( !delta ) { return function() { return fromValue + unit; }; } return function( t ) { return fromValue + t * delta + unit; }; } }; return interpolators; }( circular, hasOwn, isArray, isObject, isNumeric ); /* config/svg.js */ var svg = function() { var svg; if ( typeof document === 'undefined' ) { svg = false; } else { svg = document && document.implementation.hasFeature( 'http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1' ); } return svg; }(); /* utils/removeFromArray.js */ var removeFromArray = function( array, member ) { var index = array.indexOf( member ); if ( index !== -1 ) { array.splice( index, 1 ); } }; /* utils/Promise.js */ var Promise = function() { var _Promise, PENDING = {}, FULFILLED = {}, REJECTED = {}; if ( typeof Promise === 'function' ) { // use native Promise _Promise = Promise; } else { _Promise = function( callback ) { var fulfilledHandlers = [], rejectedHandlers = [], state = PENDING, result, dispatchHandlers, makeResolver, fulfil, reject, promise; makeResolver = function( newState ) { return function( value ) { if ( state !== PENDING ) { return; } result = value; state = newState; dispatchHandlers = makeDispatcher( state === FULFILLED ? fulfilledHandlers : rejectedHandlers, result ); // dispatch onFulfilled and onRejected handlers asynchronously wait( dispatchHandlers ); }; }; fulfil = makeResolver( FULFILLED ); reject = makeResolver( REJECTED ); try { callback( fulfil, reject ); } catch ( err ) { reject( err ); } promise = { // `then()` returns a Promise - 2.2.7 then: function( onFulfilled, onRejected ) { var promise2 = new _Promise( function( fulfil, reject ) { var processResolutionHandler = function( handler, handlers, forward ) { // 2.2.1.1 if ( typeof handler === 'function' ) { handlers.push( function( p1result ) { var x; try { x = handler( p1result ); resolve( promise2, x, fulfil, reject ); } catch ( err ) { reject( err ); } } ); } else { // Forward the result of promise1 to promise2, if resolution handlers // are not given handlers.push( forward ); } }; // 2.2 processResolutionHandler( onFulfilled, fulfilledHandlers, fulfil ); processResolutionHandler( onRejected, rejectedHandlers, reject ); if ( state !== PENDING ) { // If the promise has resolved already, dispatch the appropriate handlers asynchronously wait( dispatchHandlers ); } } ); return promise2; } }; promise[ 'catch' ] = function( onRejected ) { return this.then( null, onRejected ); }; return promise; }; _Promise.all = function( promises ) { return new _Promise( function( fulfil, reject ) { var result = [], pending, i, processPromise; if ( !promises.length ) { fulfil( result ); return; } processPromise = function( i ) { promises[ i ].then( function( value ) { result[ i ] = value; if ( !--pending ) { fulfil( result ); } }, reject ); }; pending = i = promises.length; while ( i-- ) { processPromise( i ); } } ); }; _Promise.resolve = function( value ) { return new _Promise( function( fulfil ) { fulfil( value ); } ); }; _Promise.reject = function( reason ) { return new _Promise( function( fulfil, reject ) { reject( reason ); } ); }; } return _Promise; // TODO use MutationObservers or something to simulate setImmediate function wait( callback ) { setTimeout( callback, 0 ); } function makeDispatcher( handlers, result ) { return function() { var handler; while ( handler = handlers.shift() ) { handler( result ); } }; } function resolve( promise, x, fulfil, reject ) { // Promise Resolution Procedure var then; // 2.3.1 if ( x === promise ) { throw new TypeError( 'A promise\'s fulfillment handler cannot return the same promise' ); } // 2.3.2 if ( x instanceof _Promise ) { x.then( fulfil, reject ); } else if ( x && ( typeof x === 'object' || typeof x === 'function' ) ) { try { then = x.then; } catch ( e ) { reject( e ); // 2.3.3.2 return; } // 2.3.3.3 if ( typeof then === 'function' ) { var called, resolvePromise, rejectPromise; resolvePromise = function( y ) { if ( called ) { return; } called = true; resolve( promise, y, fulfil, reject ); }; rejectPromise = function( r ) { if ( called ) { return; } called = true; reject( r ); }; try { then.call( x, resolvePromise, rejectPromise ); } catch ( e ) { if ( !called ) { // 2.3.3.3.4.1 reject( e ); // 2.3.3.3.4.2 called = true; return; } } } else { fulfil( x ); } } else { fulfil( x ); } } }(); /* utils/normaliseRef.js */ var normaliseRef = function() { var regex = /\[\s*(\*|[0-9]|[1-9][0-9]+)\s*\]/g; return function normaliseRef( ref ) { return ( ref || '' ).replace( regex, '.$1' ); }; }(); /* shared/getInnerContext.js */ var getInnerContext = function( fragment ) { do { if ( fragment.context ) { return fragment.context; } } while ( fragment = fragment.parent ); return ''; }; /* utils/isEqual.js */ var isEqual = function( a, b ) { if ( a === null && b === null ) { return true; } if ( typeof a === 'object' || typeof b === 'object' ) { return false; } return a === b; }; /* shared/createComponentBinding.js */ var createComponentBinding = function( circular, isArray, isEqual ) { var runloop; circular.push( function() { return runloop = circular.runloop; } ); var Binding = function( ractive, keypath, otherInstance, otherKeypath, priority ) { this.root = ractive; this.keypath = keypath; this.priority = priority; this.otherInstance = otherInstance; this.otherKeypath = otherKeypath; this.bind(); this.value = this.root.viewmodel.get( this.keypath ); }; Binding.prototype = { setValue: function( value ) { var this$0 = this; // Only *you* can prevent infinite loops if ( this.updating || this.counterpart && this.counterpart.updating ) { this.value = value; return; } // Is this a smart array update? If so, it'll update on its // own, we shouldn't do anything if ( isArray( value ) && value._ractive && value._ractive.setting ) { return; } if ( !isEqual( value, this.value ) ) { this.updating = true; // TODO maybe the case that `value === this.value` - should that result // in an update rather than a set? runloop.addViewmodel( this.otherInstance.viewmodel ); this.otherInstance.viewmodel.set( this.otherKeypath, value ); this.value = value; // TODO will the counterpart update after this line, during // the runloop end cycle? may be a problem... runloop.scheduleTask( function() { return this$0.updating = false; } ); } }, bind: function() { this.root.viewmodel.register( this.keypath, this ); }, rebind: function( newKeypath ) { this.unbind(); this.keypath = newKeypath; this.counterpart.otherKeypath = newKeypath; this.bind(); }, unbind: function() { this.root.viewmodel.unregister( this.keypath, this ); } }; return function createComponentBinding( component, parentInstance, parentKeypath, childKeypath ) { var hash, childInstance, bindings, priority, parentToChildBinding, childToParentBinding; hash = parentKeypath + '=' + childKeypath; bindings = component.bindings; if ( bindings[ hash ] ) { // TODO does this ever happen? return; } bindings[ hash ] = true; childInstance = component.instance; priority = component.parentFragment.priority; parentToChildBinding = new Binding( parentInstance, parentKeypath, childInstance, childKeypath, priority ); bindings.push( parentToChildBinding ); if ( childInstance.twoway ) { childToParentBinding = new Binding( childInstance, childKeypath, parentInstance, parentKeypath, 1 ); bindings.push( childToParentBinding ); parentToChildBinding.counterpart = childToParentBinding; childToParentBinding.counterpart = parentToChildBinding; } }; }( circular, isArray, isEqual ); /* shared/resolveRef.js */ var resolveRef = function( normaliseRef, getInnerContext, createComponentBinding ) { var ancestorErrorMessage, getOptions; ancestorErrorMessage = 'Could not resolve reference - too many "../" prefixes'; getOptions = { evaluateWrapped: true }; return function resolveRef( ractive, ref, fragment ) { var context, key, index, keypath, parentValue, hasContextChain, parentKeys, childKeys, parentKeypath, childKeypath; ref = normaliseRef( ref ); // If a reference begins '~/', it's a top-level reference if ( ref.substr( 0, 2 ) === '~/' ) { return ref.substring( 2 ); } // If a reference begins with '.', it's either a restricted reference or // an ancestor reference... if ( ref.charAt( 0 ) === '.' ) { return resolveAncestorReference( getInnerContext( fragment ), ref ); } // ...otherwise we need to find the keypath key = ref.split( '.' )[ 0 ]; do { context = fragment.context; if ( !context ) { continue; } hasContextChain = true; parentValue = ractive.viewmodel.get( context, getOptions ); if ( parentValue && ( typeof parentValue === 'object' || typeof parentValue === 'function' ) && key in parentValue ) { return context + '.' + ref; } } while ( fragment = fragment.parent ); // Root/computed property? if ( key in ractive.data || key in ractive.viewmodel.computations ) { return ref; } // If this is an inline component, and it's not isolated, we // can try going up the scope chain if ( ractive._parent && !ractive.isolated ) { fragment = ractive.component.parentFragment; // Special case - index refs if ( fragment.indexRefs && ( index = fragment.indexRefs[ ref ] ) !== undefined ) { // Create an index ref binding, so that it can be rebound letter if necessary. // It doesn't have an alias since it's an implicit binding, hence `...[ ref ] = ref` ractive.component.indexRefBindings[ ref ] = ref; ractive.viewmodel.set( ref, index, true ); return; } keypath = resolveRef( ractive._parent, ref, fragment ); if ( keypath ) { // We need to create an inter-component binding // If parent keypath is 'one.foo' and child is 'two.foo', we bind // 'one' to 'two' as it's more efficient and avoids edge cases parentKeys = keypath.split( '.' ); childKeys = ref.split( '.' ); while ( parentKeys.length > 1 && childKeys.length > 1 && parentKeys[ parentKeys.length - 1 ] === childKeys[ childKeys.length - 1 ] ) { parentKeys.pop(); childKeys.pop(); } parentKeypath = parentKeys.join( '.' ); childKeypath = childKeys.join( '.' ); ractive.viewmodel.set( childKeypath, ractive._parent.viewmodel.get( parentKeypath ), true ); createComponentBinding( ractive.component, ractive._parent, parentKeypath, childKeypath ); return ref; } } // If there's no context chain, and the instance is either a) isolated or // b) an orphan, then we know that the keypath is identical to the reference if ( !hasContextChain ) { return ref; } if ( ractive.viewmodel.get( ref ) !== undefined ) { return ref; } }; function resolveAncestorReference( baseContext, ref ) { var contextKeys; // {{.}} means 'current context' if ( ref === '.' ) return baseContext; contextKeys = baseContext ? baseContext.split( '.' ) : []; // ancestor references (starting "../") go up the tree if ( ref.substr( 0, 3 ) === '../' ) { while ( ref.substr( 0, 3 ) === '../' ) { if ( !contextKeys.length ) { throw new Error( ancestorErrorMessage ); } contextKeys.pop(); ref = ref.substring( 3 ); } contextKeys.push( ref ); return contextKeys.join( '.' ); } // not an ancestor reference - must be a restricted reference (prepended with "." or "./") if ( !baseContext ) { return ref.replace( /^\.\/?/, '' ); } return baseContext + ref.replace( /^\.\//, '.' ); } }( normaliseRef, getInnerContext, createComponentBinding ); /* global/TransitionManager.js */ var TransitionManager = function( removeFromArray ) { var TransitionManager = function( callback, parent ) { this.callback = callback; this.parent = parent; this.intros = []; this.outros = []; this.children = []; this.totalChildren = this.outroChildren = 0; this.detachQueue = []; this.outrosComplete = false; if ( parent ) { parent.addChild( this ); } }; TransitionManager.prototype = { addChild: function( child ) { this.children.push( child ); this.totalChildren += 1; this.outroChildren += 1; }, decrementOutros: function() { this.outroChildren -= 1; check( this ); }, decrementTotal: function() { this.totalChildren -= 1; check( this ); }, add: function( transition ) { var list = transition.isIntro ? this.intros : this.outros; list.push( transition ); }, remove: function( transition ) { var list = transition.isIntro ? this.intros : this.outros; removeFromArray( list, transition ); check( this ); }, init: function() { this.ready = true; check( this ); }, detachNodes: function() { this.detachQueue.forEach( detach ); this.children.forEach( detachNodes ); } }; function detach( element ) { element.detach(); } function detachNodes( tm ) { tm.detachNodes(); } function check( tm ) { if ( !tm.ready || tm.outros.length || tm.outroChildren ) return; // If all outros are complete, and we haven't already done this, // we notify the parent if there is one, otherwise // start detaching nodes if ( !tm.outrosComplete ) { if ( tm.parent ) { tm.parent.decrementOutros( tm ); } else { tm.detachNodes(); } tm.outrosComplete = true; } // Once everything is done, we can notify parent transition // manager and call the callback if ( !tm.intros.length && !tm.totalChildren ) { if ( typeof tm.callback === 'function' ) { tm.callback(); } if ( tm.parent ) { tm.parent.decrementTotal(); } } } return TransitionManager; }( removeFromArray ); /* global/runloop.js */ var runloop = function( circular, removeFromArray, Promise, resolveRef, TransitionManager ) { var batch, runloop, unresolved = []; runloop = { start: function( instance, returnPromise ) { var promise, fulfilPromise; if ( returnPromise ) { promise = new Promise( function( f ) { return fulfilPromise = f; } ); } batch = { previousBatch: batch, transitionManager: new TransitionManager( fulfilPromise, batch && batch.transitionManager ), views: [], tasks: [], viewmodels: [] }; if ( instance ) { batch.viewmodels.push( instance.viewmodel ); } return promise; }, end: function() { flushChanges(); batch.transitionManager.init(); batch = batch.previousBatch; }, addViewmodel: function( viewmodel ) { if ( batch ) { if ( batch.viewmodels.indexOf( viewmodel ) === -1 ) { batch.viewmodels.push( viewmodel ); } } else { viewmodel.applyChanges(); } }, registerTransition: function( transition ) { transition._manager = batch.transitionManager; batch.transitionManager.add( transition ); }, addView: function( view ) { batch.views.push( view ); }, addUnresolved: function( thing ) { unresolved.push( thing ); }, removeUnresolved: function( thing ) { removeFromArray( unresolved, thing ); }, // synchronise node detachments with transition ends detachWhenReady: function( thing ) { batch.transitionManager.detachQueue.push( thing ); }, scheduleTask: function( task ) { if ( !batch ) { task(); } else { batch.tasks.push( task ); } } }; circular.runloop = runloop; return runloop; function flushChanges() { var i, thing, changeHash; for ( i = 0; i < batch.viewmodels.length; i += 1 ) { thing = batch.viewmodels[ i ]; changeHash = thing.applyChanges(); if ( changeHash ) { thing.ractive.fire( 'change', changeHash ); } } batch.viewmodels.length = 0; attemptKeypathResolution(); // Now that changes have been fully propagated, we can update the DOM // and complete other tasks for ( i = 0; i < batch.views.length; i += 1 ) { batch.views[ i ].update(); } batch.views.length = 0; for ( i = 0; i < batch.tasks.length; i += 1 ) { batch.tasks[ i ](); } batch.tasks.length = 0; // If updating the view caused some model blowback - e.g. a triple // containing <option> elements caused the binding on the <select> // to update - then we start over if ( batch.viewmodels.length ) return flushChanges(); } function attemptKeypathResolution() { var array, thing, keypath; if ( !unresolved.length ) { return; } // see if we can resolve any unresolved references array = unresolved.splice( 0, unresolved.length ); while ( thing = array.pop() ) { if ( thing.keypath ) { continue; } keypath = resolveRef( thing.root, thing.ref, thing.parentFragment ); if ( keypath !== undefined ) { // If we've resolved the keypath, we can initialise this item thing.resolve( keypath ); } else { // If we can't resolve the reference, try again next time unresolved.push( thing ); } } } }( circular, removeFromArray, Promise, resolveRef, TransitionManager ); /* utils/createBranch.js */ var createBranch = function() { var numeric = /^\s*[0-9]+\s*$/; return function( key ) { return numeric.test( key ) ? [] : {}; }; }(); /* viewmodel/prototype/get/magicAdaptor.js */ var viewmodel$get_magicAdaptor = function( runloop, createBranch, isArray ) { var magicAdaptor, MagicWrapper; try { Object.defineProperty( {}, 'test', { value: 0 } ); magicAdaptor = { filter: function( object, keypath, ractive ) { var keys, key, parentKeypath, parentWrapper, parentValue; if ( !keypath ) { return false; } keys = keypath.split( '.' ); key = keys.pop(); parentKeypath = keys.join( '.' ); // If the parent value is a wrapper, other than a magic wrapper, // we shouldn't wrap this property if ( ( parentWrapper = ractive.viewmodel.wrapped[ parentKeypath ] ) && !parentWrapper.magic ) { return false; } parentValue = ractive.get( parentKeypath ); // if parentValue is an array that doesn't include this member, // we should return false otherwise lengths will get messed up if ( isArray( parentValue ) && /^[0-9]+$/.test( key ) ) { return false; } return parentValue && ( typeof parentValue === 'object' || typeof parentValue === 'function' ); }, wrap: function( ractive, property, keypath ) { return new MagicWrapper( ractive, property, keypath ); } }; MagicWrapper = function( ractive, value, keypath ) { var keys, objKeypath, template, siblings; this.magic = true; this.ractive = ractive; this.keypath = keypath; this.value = value; keys = keypath.split( '.' ); this.prop = keys.pop(); objKeypath = keys.join( '.' ); this.obj = objKeypath ? ractive.get( objKeypath ) : ractive.data; template = this.originalDescriptor = Object.getOwnPropertyDescriptor( this.obj, this.prop ); // Has this property already been wrapped? if ( template && template.set && ( siblings = template.set._ractiveWrappers ) ) { // Yes. Register this wrapper to this property, if it hasn't been already if ( siblings.indexOf( this ) === -1 ) { siblings.push( this ); } return; } // No, it hasn't been wrapped createAccessors( this, value, template ); }; MagicWrapper.prototype = { get: function() { return this.value; }, reset: function( value ) { if ( this.updating ) { return; } this.updating = true; this.obj[ this.prop ] = value; // trigger set() accessor runloop.addViewmodel( this.ractive.viewmodel ); this.ractive.viewmodel.mark( this.keypath ); this.updating = false; }, set: function( key, value ) { if ( this.updating ) { return; } if ( !this.obj[ this.prop ] ) { this.updating = true; this.obj[ this.prop ] = createBranch( key ); this.updating = false; } this.obj[ this.prop ][ key ] = value; }, teardown: function() { var template, set, value, wrappers, index; // If this method was called because the cache was being cleared as a // result of a set()/update() call made by this wrapper, we return false // so that it doesn't get torn down if ( this.updating ) { return false; } template = Object.getOwnPropertyDescriptor( this.obj, this.prop ); set = template && template.set; if ( !set ) { // most likely, this was an array member that was spliced out return; } wrappers = set._ractiveWrappers; index = wrappers.indexOf( this ); if ( index !== -1 ) { wrappers.splice( index, 1 ); } // Last one out, turn off the lights if ( !wrappers.length ) { value = this.obj[ this.prop ]; Object.defineProperty( this.obj, this.prop, this.originalDescriptor || { writable: true, enumerable: true, configurable: true } ); this.obj[ this.prop ] = value; } } }; } catch ( err ) { magicAdaptor = false; } return magicAdaptor; function createAccessors( originalWrapper, value, template ) { var object, property, oldGet, oldSet, get, set; object = originalWrapper.obj; property = originalWrapper.prop; // Is this template configurable? if ( template && !template.configurable ) { // Special case - array length if ( property === 'length' ) { return; } throw new Error( 'Cannot use magic mode with property "' + property + '" - object is not configurable' ); } // Time to wrap this property if ( template ) { oldGet = template.get; oldSet = template.set; } get = oldGet || function() { return value; }; set = function( v ) { if ( oldSet ) { oldSet( v ); } value = oldGet ? oldGet() : v; set._ractiveWrappers.forEach( updateWrapper ); }; function updateWrapper( wrapper ) { var keypath, ractive; wrapper.value = value; if ( wrapper.updating ) { return; } ractive = wrapper.ractive; keypath = wrapper.keypath; wrapper.updating = true; runloop.start( ractive ); ractive.viewmodel.mark( keypath ); runloop.end(); wrapper.updating = false; } // Create an array of wrappers, in case other keypaths/ractives depend on this property. // Handily, we can store them as a property of the set function. Yay JavaScript. set._ractiveWrappers = [ originalWrapper ]; Object.defineProperty( object, property, { get: get, set: set, enumerable: true, configurable: true } ); } }( runloop, createBranch, isArray ); /* config/magic.js */ var magic = function( magicAdaptor ) { return !!magicAdaptor; }( viewmodel$get_magicAdaptor ); /* config/namespaces.js */ var namespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg', xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace', xmlns: 'http://www.w3.org/2000/xmlns/' }; /* utils/createElement.js */ var createElement = function( svg, namespaces ) { var createElement; // Test for SVG support if ( !svg ) { createElement = function( type, ns ) { if ( ns && ns !== namespaces.html ) { throw 'This browser does not support namespaces other than http://www.w3.org/1999/xhtml. The most likely cause of this error is that you\'re trying to render SVG in an older browser. See http://docs.ractivejs.org/latest/svg-and-older-browsers for more information'; } return document.createElement( type ); }; } else { createElement = function( type, ns ) { if ( !ns || ns === namespaces.html ) { return document.createElement( type ); } return document.createElementNS( ns, type ); }; } return createElement; }( svg, namespaces ); /* config/isClient.js */ var isClient = function() { var isClient = typeof document === 'object'; return isClient; }(); /* utils/defineProperty.js */ var defineProperty = function( isClient ) { var defineProperty; try { Object.defineProperty( {}, 'test', { value: 0 } ); if ( isClient ) { Object.defineProperty( document.createElement( 'div' ), 'test', { value: 0 } ); } defineProperty = Object.defineProperty; } catch ( err ) { // Object.defineProperty doesn't exist, or we're in IE8 where you can // only use it with DOM objects (what the fuck were you smoking, MSFT?) defineProperty = function( obj, prop, desc ) { obj[ prop ] = desc.value; }; } return defineProperty; }( isClient ); /* utils/defineProperties.js */ var defineProperties = function( createElement, defineProperty, isClient ) { var defineProperties; try { try { Object.defineProperties( {}, { test: { value: 0 } } ); } catch ( err ) { // TODO how do we account for this? noMagic = true; throw err; } if ( isClient ) { Object.defineProperties( createElement( 'div' ), { test: { value: 0 } } ); } defineProperties = Object.defineProperties; } catch ( err ) { defineProperties = function( obj, props ) { var prop; for ( prop in props ) { if ( props.hasOwnProperty( prop ) ) { defineProperty( obj, prop, props[ prop ] ); } } }; } return defineProperties; }( createElement, defineProperty, isClient ); /* Ractive/prototype/shared/add.js */ var Ractive$shared_add = function( isNumeric ) { return function add( root, keypath, d ) { var value; if ( typeof keypath !== 'string' || !isNumeric( d ) ) { throw new Error( 'Bad arguments' ); } value = +root.get( keypath ) || 0; if ( !isNumeric( value ) ) { throw new Error( 'Cannot add to a non-numeric value' ); } return root.set( keypath, value + d ); }; }( isNumeric ); /* Ractive/prototype/add.js */ var Ractive$add = function( add ) { return function Ractive$add( keypath, d ) { return add( this, keypath, d === undefined ? 1 : +d ); }; }( Ractive$shared_add ); /* utils/normaliseKeypath.js */ var normaliseKeypath = function( normaliseRef ) { var leadingDot = /^\.+/; return function normaliseKeypath( keypath ) { return normaliseRef( keypath ).replace( leadingDot, '' ); }; }( normaliseRef ); /* config/vendors.js */ var vendors = [ 'o', 'ms', 'moz', 'webkit' ]; /* utils/requestAnimationFrame.js */ var requestAnimationFrame = function( vendors ) { var requestAnimationFrame; // If window doesn't exist, we don't need requestAnimationFrame if ( typeof window === 'undefined' ) { requestAnimationFrame = null; } else { // https://gist.github.com/paulirish/1579671 ( function( vendors, lastTime, window ) { var x, setTimeout; if ( window.requestAnimationFrame ) { return; } for ( x = 0; x < vendors.length && !window.requestAnimationFrame; ++x ) { window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ]; } if ( !window.requestAnimationFrame ) { setTimeout = window.setTimeout; window.requestAnimationFrame = function( callback ) { var currTime, timeToCall, id; currTime = Date.now(); timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) ); id = setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall ); lastTime = currTime + timeToCall; return id; }; } }( vendors, 0, window ) ); requestAnimationFrame = window.requestAnimationFrame; } return requestAnimationFrame; }( vendors ); /* utils/getTime.js */ var getTime = function() { var getTime; if ( typeof window !== 'undefined' && window.performance && typeof window.performance.now === 'function' ) { getTime = function() { return window.performance.now(); }; } else { getTime = function() { return Date.now(); }; } return getTime; }(); /* shared/animations.js */ var animations = function( rAF, getTime, runloop ) { var queue = []; var animations = { tick: function() { var i, animation, now; now = getTime(); runloop.start(); for ( i = 0; i < queue.length; i += 1 ) { animation = queue[ i ]; if ( !animation.tick( now ) ) { // animation is complete, remove it from the stack, and decrement i so we don't miss one queue.splice( i--, 1 ); } } runloop.end(); if ( queue.length ) { rAF( animations.tick ); } else { animations.running = false; } }, add: function( animation ) { queue.push( animation ); if ( !animations.running ) { animations.running = true; rAF( animations.tick ); } }, // TODO optimise this abort: function( keypath, root ) { var i = queue.length, animation; while ( i-- ) { animation = queue[ i ]; if ( animation.root === root && animation.keypath === keypath ) { animation.stop(); } } } }; return animations; }( requestAnimationFrame, getTime, runloop ); /* utils/warn.js */ var warn = function() { /* global console */ var warn, warned = {}; if ( typeof console !== 'undefined' && typeof console.warn === 'function' && typeof console.warn.apply === 'function' ) { warn = function( message, allowDuplicates ) { if ( !allowDuplicates ) { if ( warned[ message ] ) { return; } warned[ message ] = true; } console.warn( message ); }; } else { warn = function() {}; } return warn; }(); /* config/options/css/transform.js */ var transform = function() { var selectorsPattern = /(?:^|\})?\s*([^\{\}]+)\s*\{/g, commentsPattern = /\/\*.*?\*\//g, selectorUnitPattern = /((?:(?:\[[^\]+]\])|(?:[^\s\+\>\~:]))+)((?::[^\s\+\>\~]+)?\s*[\s\+\>\~]?)\s*/g, mediaQueryPattern = /^@media/, dataRvcGuidPattern = /\[data-rvcguid="[a-z0-9-]+"]/g; return function transformCss( css, guid ) { var transformed, addGuid; addGuid = function( selector ) { var selectorUnits, match, unit, dataAttr, base, prepended, appended, i, transformed = []; selectorUnits = []; while ( match = selectorUnitPattern.exec( selector ) ) { selectorUnits.push( { str: match[ 0 ], base: match[ 1 ], modifiers: match[ 2 ] } ); } // For each simple selector within the selector, we need to create a version // that a) combines with the guid, and b) is inside the guid dataAttr = '[data-rvcguid="' + guid + '"]'; base = selectorUnits.map( extractString ); i = selectorUnits.length; while ( i-- ) { appended = base.slice(); // Pseudo-selectors should go after the attribute selector unit = selectorUnits[ i ]; appended[ i ] = unit.base + dataAttr + unit.modifiers || ''; prepended = base.slice(); prepended[ i ] = dataAttr + ' ' + prepended[ i ]; transformed.push( appended.join( ' ' ), prepended.join( ' ' ) ); } return transformed.join( ', ' ); }; if ( dataRvcGuidPattern.test( css ) ) { transformed = css.replace( dataRvcGuidPattern, '[data-rvcguid="' + guid + '"]' ); } else { transformed = css.replace( commentsPattern, '' ).replace( selectorsPattern, function( match, $1 ) { var selectors, transformed; // don't transform media queries! if ( mediaQueryPattern.test( $1 ) ) return match; selectors = $1.split( ',' ).map( trim ); transformed = selectors.map( addGuid ).join( ', ' ) + ' '; return match.replace( $1, transformed ); } ); } return transformed; }; function trim( str ) { if ( str.trim ) { return str.trim(); } return str.replace( /^\s+/, '' ).replace( /\s+$/, '' ); } function extractString( unit ) { return unit.str; } }(); /* config/options/css/css.js */ var css = function( transformCss ) { var cssConfig = { name: 'css', extend: extend, init: function() {} }; function extend( Parent, proto, options ) { var guid = proto.constructor._guid, css; if ( css = getCss( options.css, options, guid ) || getCss( Parent.css, Parent, guid ) ) { proto.constructor.css = css; } } function getCss( css, target, guid ) { if ( !css ) { return; } return target.noCssTransform ? css : transformCss( css, guid ); } return cssConfig; }( transform ); /* utils/wrapMethod.js */ var wrapMethod = function() { return function( method, superMethod, force ) { if ( force || needsSuper( method, superMethod ) ) { return function() { var hasSuper = '_super' in this, _super = this._super, result; this._super = superMethod; result = method.apply( this, arguments ); if ( hasSuper ) { this._super = _super; } return result; }; } else { return method; } }; function needsSuper( method, superMethod ) { return typeof superMethod === 'function' && /_super/.test( method ); } }(); /* config/options/data.js */ var data = function( wrap ) { var dataConfig = { name: 'data', extend: extend, init: init, reset: reset }; return dataConfig; function combine( Parent, target, options ) { var value = options.data || {}, parentValue = getAddedKeys( Parent.prototype.data ); return dispatch( parentValue, value ); } function extend( Parent, proto, options ) { proto.data = combine( Parent, proto, options ); } function init( Parent, ractive, options ) { var value = options.data, result = combine( Parent, ractive, options ); if ( typeof result === 'function' ) { result = result.call( ractive, value ) || value; } return ractive.data = result || {}; } function reset( ractive ) { var result = this.init( ractive.constructor, ractive, ractive ); if ( result ) { ractive.data = result; return true; } } function getAddedKeys( parent ) { // only for functions that had keys added if ( typeof parent !== 'function' || !Object.keys( parent ).length ) { return parent; } // copy the added keys to temp 'object', otherwise // parent would be interpreted as 'function' by dispatch var temp = {}; copy( parent, temp ); // roll in added keys return dispatch( parent, temp ); } function dispatch( parent, child ) { if ( typeof child === 'function' ) { return extendFn( child, parent ); } else if ( typeof parent === 'function' ) { return fromFn( child, parent ); } else { return fromProperties( child, parent ); } } function copy( from, to, fillOnly ) { for ( var key in from ) { if ( fillOnly && key in to ) { continue; } to[ key ] = from[ key ]; } } function fromProperties( child, parent ) { child = child || {}; if ( !parent ) { return child; } copy( parent, child, true ); return child; } function fromFn( child, parentFn ) { return function( data ) { var keys; if ( child ) { // Track the keys that our on the child, // but not on the data. We'll need to apply these // after the parent function returns. keys = []; for ( var key in child ) { if ( !data || !( key in data ) ) { keys.push( key ); } } } // call the parent fn, use data if no return value data = parentFn.call( this, data ) || data; // Copy child keys back onto data. The child keys // should take precedence over whatever the // parent did with the data. if ( keys && keys.length ) { data = data || {}; keys.forEach( function( key ) { data[ key ] = child[ key ]; } ); } return data; }; } function extendFn( childFn, parent ) { var parentFn; if ( typeof parent !== 'function' ) { // copy props to data parentFn = function( data ) { fromProperties( data, parent ); }; } else { parentFn = function( data ) { // give parent function it's own this._super context, // otherwise this._super is from child and // causes infinite loop parent = wrap( parent, function() {}, true ); return parent.call( this, data ) || data; }; } return wrap( childFn, parentFn ); } }( wrapMethod ); /* config/errors.js */ var errors = { missingParser: 'Missing Ractive.parse - cannot parse template. Either preparse or use the version that includes the parser', mergeComparisonFail: 'Merge operation: comparison failed. Falling back to identity checking', noComponentEventArguments: 'Components currently only support simple events - you cannot include arguments. Sorry!', noTemplateForPartial: 'Could not find template for partial "{name}"', noNestedPartials: 'Partials ({{>{name}}}) cannot contain nested inline partials', evaluationError: 'Error evaluating "{uniqueString}": {err}', badArguments: 'Bad arguments "{arguments}". I\'m not allowed to argue unless you\'ve paid.', failedComputation: 'Failed to compute "{key}": {err}', missingPlugin: 'Missing "{name}" {plugin} plugin. You may need to download a {plugin} via http://docs.ractivejs.org/latest/plugins#{plugin}s', badRadioInputBinding: 'A radio input can have two-way binding on its name attribute, or its checked attribute - not both', noRegistryFunctionReturn: 'A function was specified for "{name}" {registry}, but no {registry} was returned' }; /* config/types.js */ var types = { TEXT: 1, INTERPOLATOR: 2, TRIPLE: 3, SECTION: 4, INVERTED: 5, CLOSING: 6, ELEMENT: 7, PARTIAL: 8, COMMENT: 9, DELIMCHANGE: 10, MUSTACHE: 11, TAG: 12, ATTRIBUTE: 13, CLOSING_TAG: 14, COMPONENT: 15, NUMBER_LITERAL: 20, STRING_LITERAL: 21, ARRAY_LITERAL: 22, OBJECT_LITERAL: 23, BOOLEAN_LITERAL: 24, GLOBAL: 26, KEY_VALUE_PAIR: 27, REFERENCE: 30, REFINEMENT: 31, MEMBER: 32, PREFIX_OPERATOR: 33, BRACKETED: 34, CONDITIONAL: 35, INFIX_OPERATOR: 36, INVOCATION: 40, SECTION_IF: 50, SECTION_UNLESS: 51, SECTION_EACH: 52, SECTION_WITH: 53 }; /* utils/create.js */ var create = function() { var create; try { Object.create( null ); create = Object.create; } catch ( err ) { // sigh create = function() { var F = function() {}; return function( proto, props ) { var obj; if ( proto === null ) { return {}; } F.prototype = proto; obj = new F(); if ( props ) { Object.defineProperties( obj, props ); } return obj; }; }(); } return create; }(); /* parse/Parser/expressions/shared/errors.js */ var parse_Parser_expressions_shared_errors = { expectedExpression: 'Expected a JavaScript expression', expectedParen: 'Expected closing paren' }; /* parse/Parser/expressions/primary/literal/numberLiteral.js */ var numberLiteral = function( types ) { // bulletproof number regex from https://gist.github.com/Rich-Harris/7544330 var numberPattern = /^(?:[+-]?)(?:(?:(?:0|[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/; return function( parser ) { var result; if ( result = parser.matchPattern( numberPattern ) ) { return { t: types.NUMBER_LITERAL, v: result }; } return null; }; }( types ); /* parse/Parser/expressions/primary/literal/booleanLiteral.js */ var booleanLiteral = function( types ) { return function( parser ) { var remaining = parser.remaining(); if ( remaining.substr( 0, 4 ) === 'true' ) { parser.pos += 4; return { t: types.BOOLEAN_LITERAL, v: 'true' }; } if ( remaining.substr( 0, 5 ) === 'false' ) { parser.pos += 5; return { t: types.BOOLEAN_LITERAL, v: 'false' }; } return null; }; }( types ); /* parse/Parser/expressions/primary/literal/stringLiteral/makeQuotedStringMatcher.js */ var makeQuotedStringMatcher = function() { var stringMiddlePattern, escapeSequencePattern, lineContinuationPattern; // Match one or more characters until: ", ', \, or EOL/EOF. // EOL/EOF is written as (?!.) (meaning there's no non-newline char next). stringMiddlePattern = /^(?=.)[^"'\\]+?(?:(?!.)|(?=["'\\]))/; // Match one escape sequence, including the backslash. escapeSequencePattern = /^\\(?:['"\\bfnrt]|0(?![0-9])|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|(?=.)[^ux0-9])/; // Match one ES5 line continuation (backslash + line terminator). lineContinuationPattern = /^\\(?:\r\n|[\u000A\u000D\u2028\u2029])/; // Helper for defining getDoubleQuotedString and getSingleQuotedString. return function( okQuote ) { return function( parser ) { var start, literal, done, next; start = parser.pos; literal = '"'; done = false; while ( !done ) { next = parser.matchPattern( stringMiddlePattern ) || parser.matchPattern( escapeSequencePattern ) || parser.matchString( okQuote ); if ( next ) { if ( next === '"' ) { literal += '\\"'; } else if ( next === '\\\'' ) { literal += '\''; } else { literal += next; } } else { next = parser.matchPattern( lineContinuationPattern ); if ( next ) { // convert \(newline-like) into a \u escape, which is allowed in JSON literal += '\\u' + ( '000' + next.charCodeAt( 1 ).toString( 16 ) ).slice( -4 ); } else { done = true; } } } literal += '"'; // use JSON.parse to interpret escapes return JSON.parse( literal ); }; }; }(); /* parse/Parser/expressions/primary/literal/stringLiteral/singleQuotedString.js */ var singleQuotedString = function( makeQuotedStringMatcher ) { return makeQuotedStringMatcher( '"' ); }( makeQuotedStringMatcher ); /* parse/Parser/expressions/primary/literal/stringLiteral/doubleQuotedString.js */ var doubleQuotedString = function( makeQuotedStringMatcher ) { return makeQuotedStringMatcher( '\'' ); }( makeQuotedStringMatcher ); /* parse/Parser/expressions/primary/literal/stringLiteral/_stringLiteral.js */ var stringLiteral = function( types, getSingleQuotedString, getDoubleQuotedString ) { return function( parser ) { var start, string; start = parser.pos; if ( parser.matchString( '"' ) ) { string = getDoubleQuotedString( parser ); if ( !parser.matchString( '"' ) ) { parser.pos = start; return null; } return { t: types.STRING_LITERAL, v: string }; } if ( parser.matchString( '\'' ) ) { string = getSingleQuotedString( parser ); if ( !parser.matchString( '\'' ) ) { parser.pos = start; return null; } return { t: types.STRING_LITERAL, v: string }; } return null; }; }( types, singleQuotedString, doubleQuotedString ); /* parse/Parser/expressions/shared/patterns.js */ var patterns = { name: /^[a-zA-Z_$][a-zA-Z_$0-9]*/ }; /* parse/Parser/expressions/shared/key.js */ var key = function( getStringLiteral, getNumberLiteral, patterns ) { var identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/; // http://mathiasbynens.be/notes/javascript-properties // can be any name, string literal, or number literal return function( parser ) { var token; if ( token = getStringLiteral( parser ) ) { return identifier.test( token.v ) ? token.v : '"' + token.v.replace( /"/g, '\\"' ) + '"'; } if ( token = getNumberLiteral( parser ) ) { return token.v; } if ( token = parser.matchPattern( patterns.name ) ) { return token; } }; }( stringLiteral, numberLiteral, patterns ); /* parse/Parser/expressions/primary/literal/objectLiteral/keyValuePair.js */ var keyValuePair = function( types, getKey ) { return function( parser ) { var start, key, value; start = parser.pos; // allow whitespace between '{' and key parser.allowWhitespace(); key = getKey( parser ); if ( key === null ) { parser.pos = start; return null; } // allow whitespace between key and ':' parser.allowWhitespace(); // next character must be ':' if ( !parser.matchString( ':' ) ) { parser.pos = start; return null; } // allow whitespace between ':' and value parser.allowWhitespace(); // next expression must be a, well... expression value = parser.readExpression(); if ( value === null ) { parser.pos = start; return null; } return { t: types.KEY_VALUE_PAIR, k: key, v: value }; }; }( types, key ); /* parse/Parser/expressions/primary/literal/objectLiteral/keyValuePairs.js */ var keyValuePairs = function( getKeyValuePair ) { return function getKeyValuePairs( parser ) { var start, pairs, pair, keyValuePairs; start = parser.pos; pair = getKeyValuePair( parser ); if ( pair === null ) { return null; } pairs = [ pair ]; if ( parser.matchString( ',' ) ) { keyValuePairs = getKeyValuePairs( parser ); if ( !keyValuePairs ) { parser.pos = start; return null; } return pairs.concat( keyValuePairs ); } return pairs; }; }( keyValuePair ); /* parse/Parser/expressions/primary/literal/objectLiteral/_objectLiteral.js */ var objectLiteral = function( types, getKeyValuePairs ) { return function( parser ) { var start, keyValuePairs; start = parser.pos; // allow whitespace parser.allowWhitespace(); if ( !parser.matchString( '{' ) ) { parser.pos = start; return null; } keyValuePairs = getKeyValuePairs( parser ); // allow whitespace between final value and '}' parser.allowWhitespace(); if ( !parser.matchString( '}' ) ) { parser.pos = start; return null; } return { t: types.OBJECT_LITERAL, m: keyValuePairs }; }; }( types, keyValuePairs ); /* parse/Parser/expressions/shared/expressionList.js */ var expressionList = function( errors ) { return function getExpressionList( parser ) { var start, expressions, expr, next; start = parser.pos; parser.allowWhitespace(); expr = parser.readExpression(); if ( expr === null ) { return null; } expressions = [ expr ]; // allow whitespace between expression and ',' parser.allowWhitespace(); if ( parser.matchString( ',' ) ) { next = getExpressionList( parser ); if ( next === null ) { parser.error( errors.expectedExpression ); } next.forEach( append ); } function append( expression ) { expressions.push( expression ); } return expressions; }; }( parse_Parser_expressions_shared_errors ); /* parse/Parser/expressions/primary/literal/arrayLiteral.js */ var arrayLiteral = function( types, getExpressionList ) { return function( parser ) { var start, expressionList; start = parser.pos; // allow whitespace before '[' parser.allowWhitespace(); if ( !parser.matchString( '[' ) ) { parser.pos = start; return null; } expressionList = getExpressionList( parser ); if ( !parser.matchString( ']' ) ) { parser.pos = start; return null; } return { t: types.ARRAY_LITERAL, m: expressionList }; }; }( types, expressionList ); /* parse/Parser/expressions/primary/literal/_literal.js */ var literal = function( getNumberLiteral, getBooleanLiteral, getStringLiteral, getObjectLiteral, getArrayLiteral ) { return function( parser ) { var literal = getNumberLiteral( parser ) || getBooleanLiteral( parser ) || getStringLiteral( parser ) || getObjectLiteral( parser ) || getArrayLiteral( parser ); return literal; }; }( numberLiteral, booleanLiteral, stringLiteral, objectLiteral, arrayLiteral ); /* parse/Parser/expressions/primary/reference.js */ var reference = function( types, patterns ) { var dotRefinementPattern, arrayMemberPattern, getArrayRefinement, globals, keywords; dotRefinementPattern = /^\.[a-zA-Z_$0-9]+/; getArrayRefinement = function( parser ) { var num = parser.matchPattern( arrayMemberPattern ); if ( num ) { return '.' + num; } return null; }; arrayMemberPattern = /^\[(0|[1-9][0-9]*)\]/; // if a reference is a browser global, we don't deference it later, so it needs special treatment globals = /^(?:Array|Date|RegExp|decodeURIComponent|decodeURI|encodeURIComponent|encodeURI|isFinite|isNaN|parseFloat|parseInt|JSON|Math|NaN|undefined|null)$/; // keywords are not valid references, with the exception of `this` keywords = /^(?:break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|throw|try|typeof|var|void|while|with)$/; return function( parser ) { var startPos, ancestor, name, dot, combo, refinement, lastDotIndex; startPos = parser.pos; // we might have a root-level reference if ( parser.matchString( '~/' ) ) { ancestor = '~/'; } else { // we might have ancestor refs... ancestor = ''; while ( parser.matchString( '../' ) ) { ancestor += '../'; } } if ( !ancestor ) { // we might have an implicit iterator or a restricted reference dot = parser.matchString( '.' ) || ''; } name = parser.matchPattern( /^@(?:index|key)/ ) || parser.matchPattern( patterns.name ) || ''; // bug out if it's a keyword if ( keywords.test( name ) ) { parser.pos = startPos; return null; } // if this is a browser global, stop here if ( !ancestor && !dot && globals.test( name ) ) { return { t: types.GLOBAL, v: name }; } combo = ( ancestor || dot ) + name; if ( !combo ) { return null; } while ( refinement = parser.matchPattern( dotRefinementPattern ) || getArrayRefinement( parser ) ) { combo += refinement; } if ( parser.matchString( '(' ) ) { // if this is a method invocation (as opposed to a function) we need // to strip the method name from the reference combo, else the context // will be wrong lastDotIndex = combo.lastIndexOf( '.' ); if ( lastDotIndex !== -1 ) { combo = combo.substr( 0, lastDotIndex ); parser.pos = startPos + combo.length; } else { parser.pos -= 1; } } return { t: types.REFERENCE, n: combo.replace( /^this\./, './' ).replace( /^this$/, '.' ) }; }; }( types, patterns ); /* parse/Parser/expressions/primary/bracketedExpression.js */ var bracketedExpression = function( types, errors ) { return function( parser ) { var start, expr; start = parser.pos; if ( !parser.matchString( '(' ) ) { return null; } parser.allowWhitespace(); expr = parser.readExpression(); if ( !expr ) { parser.error( errors.expectedExpression ); } parser.allowWhitespace(); if ( !parser.matchString( ')' ) ) { parser.error( errors.expectedParen ); } return { t: types.BRACKETED, x: expr }; }; }( types, parse_Parser_expressions_shared_errors ); /* parse/Parser/expressions/primary/_primary.js */ var primary = function( getLiteral, getReference, getBracketedExpression ) { return function( parser ) { return getLiteral( parser ) || getReference( parser ) || getBracketedExpression( parser ); }; }( literal, reference, bracketedExpression ); /* parse/Parser/expressions/shared/refinement.js */ var refinement = function( types, errors, patterns ) { return function getRefinement( parser ) { var start, name, expr; start = parser.pos; parser.allowWhitespace(); // "." name if ( parser.matchString( '.' ) ) { parser.allowWhitespace(); if ( name = parser.matchPattern( patterns.name ) ) { return { t: types.REFINEMENT, n: name }; } parser.error( 'Expected a property name' ); } // "[" expression "]" if ( parser.matchString( '[' ) ) { parser.allowWhitespace(); expr = parser.readExpression(); if ( !expr ) { parser.error( errors.expectedExpression ); } parser.allowWhitespace(); if ( !parser.matchString( ']' ) ) { parser.error( 'Expected \']\'' ); } return { t: types.REFINEMENT, x: expr }; } return null; }; }( types, parse_Parser_expressions_shared_errors, patterns ); /* parse/Parser/expressions/memberOrInvocation.js */ var memberOrInvocation = function( types, getPrimary, getExpressionList, getRefinement, errors ) { return function( parser ) { var current, expression, refinement, expressionList; expression = getPrimary( parser ); if ( !expression ) { return null; } while ( expression ) { current = parser.pos; if ( refinement = getRefinement( parser ) ) { expression = { t: types.MEMBER, x: expression, r: refinement }; } else if ( parser.matchString( '(' ) ) { parser.allowWhitespace(); expressionList = getExpressionList( parser ); parser.allowWhitespace(); if ( !parser.matchString( ')' ) ) { parser.error( errors.expectedParen ); } expression = { t: types.INVOCATION, x: expression }; if ( expressionList ) { expression.o = expressionList; } } else { break; } } return expression; }; }( types, primary, expressionList, refinement, parse_Parser_expressions_shared_errors ); /* parse/Parser/expressions/typeof.js */ var _typeof = function( types, errors, getMemberOrInvocation ) { var getTypeof, makePrefixSequenceMatcher; makePrefixSequenceMatcher = function( symbol, fallthrough ) { return function( parser ) { var expression; if ( expression = fallthrough( parser ) ) { return expression; } if ( !parser.matchString( symbol ) ) { return null; } parser.allowWhitespace(); expression = parser.readExpression(); if ( !expression ) { parser.error( errors.expectedExpression ); } return { s: symbol, o: expression, t: types.PREFIX_OPERATOR }; }; }; // create all prefix sequence matchers, return getTypeof ( function() { var i, len, matcher, prefixOperators, fallthrough; prefixOperators = '! ~ + - typeof'.split( ' ' ); fallthrough = getMemberOrInvocation; for ( i = 0, len = prefixOperators.length; i < len; i += 1 ) { matcher = makePrefixSequenceMatcher( prefixOperators[ i ], fallthrough ); fallthrough = matcher; } // typeof operator is higher precedence than multiplication, so provides the // fallthrough for the multiplication sequence matcher we're about to create // (we're skipping void and delete) getTypeof = fallthrough; }() ); return getTypeof; }( types, parse_Parser_expressions_shared_errors, memberOrInvocation ); /* parse/Parser/expressions/logicalOr.js */ var logicalOr = function( types, getTypeof ) { var getLogicalOr, makeInfixSequenceMatcher; makeInfixSequenceMatcher = function( symbol, fallthrough ) { return function( parser ) { var start, left, right; left = fallthrough( parser ); if ( !left ) { return null; } // Loop to handle left-recursion in a case like `a * b * c` and produce // left association, i.e. `(a * b) * c`. The matcher can't call itself // to parse `left` because that would be infinite regress. while ( true ) { start = parser.pos; parser.allowWhitespace(); if ( !parser.matchString( symbol ) ) { parser.pos = start; return left; } // special case - in operator must not be followed by [a-zA-Z_$0-9] if ( symbol === 'in' && /[a-zA-Z_$0-9]/.test( parser.remaining().charAt( 0 ) ) ) { parser.pos = start; return left; } parser.allowWhitespace(); // right operand must also consist of only higher-precedence operators right = fallthrough( parser ); if ( !right ) { parser.pos = start; return left; } left = { t: types.INFIX_OPERATOR, s: symbol, o: [ left, right ] }; } }; }; // create all infix sequence matchers, and return getLogicalOr ( function() { var i, len, matcher, infixOperators, fallthrough; // All the infix operators on order of precedence (source: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence) // Each sequence matcher will initially fall through to its higher precedence // neighbour, and only attempt to match if one of the higher precedence operators // (or, ultimately, a literal, reference, or bracketed expression) already matched infixOperators = '* / % + - << >> >>> < <= > >= in instanceof == != === !== & ^ | && ||'.split( ' ' ); // A typeof operator is higher precedence than multiplication fallthrough = getTypeof; for ( i = 0, len = infixOperators.length; i < len; i += 1 ) { matcher = makeInfixSequenceMatcher( infixOperators[ i ], fallthrough ); fallthrough = matcher; } // Logical OR is the fallthrough for the conditional matcher getLogicalOr = fallthrough; }() ); return getLogicalOr; }( types, _typeof ); /* parse/Parser/expressions/conditional.js */ var conditional = function( types, getLogicalOr, errors ) { // The conditional operator is the lowest precedence operator, so we start here return function( parser ) { var start, expression, ifTrue, ifFalse; expression = getLogicalOr( parser ); if ( !expression ) { return null; } start = parser.pos; parser.allowWhitespace(); if ( !parser.matchString( '?' ) ) { parser.pos = start; return expression; } parser.allowWhitespace(); ifTrue = parser.readExpression(); if ( !ifTrue ) { parser.error( errors.expectedExpression ); } parser.allowWhitespace(); if ( !parser.matchString( ':' ) ) { parser.error( 'Expected ":"' ); } parser.allowWhitespace(); ifFalse = parser.readExpression(); if ( !ifFalse ) { parser.error( errors.expectedExpression ); } return { t: types.CONDITIONAL, o: [ expression, ifTrue, ifFalse ] }; }; }( types, logicalOr, parse_Parser_expressions_shared_errors ); /* parse/Parser/utils/flattenExpression.js */ var flattenExpression = function( types, isObject ) { return function( expression ) { var refs = [], flattened; extractRefs( expression, refs ); flattened = { r: refs, s: stringify( this, expression, refs ) }; return flattened; }; function quoteStringLiteral( str ) { return JSON.stringify( String( str ) ); } // TODO maybe refactor this? function extractRefs( node, refs ) { var i, list; if ( node.t === types.REFERENCE ) { if ( refs.indexOf( node.n ) === -1 ) { refs.unshift( node.n ); } } list = node.o || node.m; if ( list ) { if ( isObject( list ) ) { extractRefs( list, refs ); } else { i = list.length; while ( i-- ) { extractRefs( list[ i ], refs ); } } } if ( node.x ) { extractRefs( node.x, refs ); } if ( node.r ) { extractRefs( node.r, refs ); } if ( node.v ) { extractRefs( node.v, refs ); } } function stringify( parser, node, refs ) { var stringifyAll = function( item ) { return stringify( parser, item, refs ); }; switch ( node.t ) { case types.BOOLEAN_LITERAL: case types.GLOBAL: case types.NUMBER_LITERAL: return node.v; case types.STRING_LITERAL: return quoteStringLiteral( node.v ); case types.ARRAY_LITERAL: return '[' + ( node.m ? node.m.map( stringifyAll ).join( ',' ) : '' ) + ']'; case types.OBJECT_LITERAL: return '{' + ( node.m ? node.m.map( stringifyAll ).join( ',' ) : '' ) + '}'; case types.KEY_VALUE_PAIR: return node.k + ':' + stringify( parser, node.v, refs ); case types.PREFIX_OPERATOR: return ( node.s === 'typeof' ? 'typeof ' : node.s ) + stringify( parser, node.o, refs ); case types.INFIX_OPERATOR: return stringify( parser, node.o[ 0 ], refs ) + ( node.s.substr( 0, 2 ) === 'in' ? ' ' + node.s + ' ' : node.s ) + stringify( parser, node.o[ 1 ], refs ); case types.INVOCATION: return stringify( parser, node.x, refs ) + '(' + ( node.o ? node.o.map( stringifyAll ).join( ',' ) : '' ) + ')'; case types.BRACKETED: return '(' + stringify( parser, node.x, refs ) + ')'; case types.MEMBER: return stringify( parser, node.x, refs ) + stringify( parser, node.r, refs ); case types.REFINEMENT: return node.n ? '.' + node.n : '[' + stringify( parser, node.x, refs ) + ']'; case types.CONDITIONAL: return stringify( parser, node.o[ 0 ], refs ) + '?' + stringify( parser, node.o[ 1 ], refs ) + ':' + stringify( parser, node.o[ 2 ], refs ); case types.REFERENCE: return '${' + refs.indexOf( node.n ) + '}'; default: parser.error( 'Expected legal JavaScript' ); } } }( types, isObject ); /* parse/Parser/_Parser.js */ var Parser = function( circular, create, hasOwnProperty, getConditional, flattenExpression ) { var Parser, ParseError, leadingWhitespace = /^\s+/; ParseError = function( message ) { this.name = 'ParseError'; this.message = message; try { throw new Error( message ); } catch ( e ) { this.stack = e.stack; } }; ParseError.prototype = Error.prototype; Parser = function( str, options ) { var items, item; this.str = str; this.options = options || {}; this.pos = 0; // Custom init logic if ( this.init ) this.init( str, options ); items = []; while ( this.pos < this.str.length && ( item = this.read() ) ) { items.push( item ); } this.leftover = this.remaining(); this.result = this.postProcess ? this.postProcess( items, options ) : items; }; Parser.prototype = { read: function( converters ) { var pos, i, len, item; if ( !converters ) converters = this.converters; pos = this.pos; len = converters.length; for ( i = 0; i < len; i += 1 ) { this.pos = pos; // reset for each attempt if ( item = converters[ i ]( this ) ) { return item; } } return null; }, readExpression: function() { // The conditional operator is the lowest precedence operator (except yield, // assignment operators, and commas, none of which are supported), so we // start there. If it doesn't match, it 'falls through' to progressively // higher precedence operators, until it eventually matches (or fails to // match) a 'primary' - a literal or a reference. This way, the abstract syntax // tree has everything in its proper place, i.e. 2 + 3 * 4 === 14, not 20. return getConditional( this ); }, flattenExpression: flattenExpression, getLinePos: function() { var lines, currentLine, currentLineEnd, nextLineEnd, lineNum, columnNum; lines = this.str.split( '\n' ); lineNum = -1; nextLineEnd = 0; do { currentLineEnd = nextLineEnd; lineNum++; currentLine = lines[ lineNum ]; nextLineEnd += currentLine.length + 1; } while ( nextLineEnd <= this.pos ); columnNum = this.pos - currentLineEnd; return { line: lineNum + 1, ch: columnNum + 1, text: currentLine, toJSON: function() { return [ this.line, this.ch ]; }, toString: function() { return 'line ' + this.line + ' character ' + this.ch + ':\n' + this.text + '\n' + this.text.substr( 0, this.ch - 1 ).replace( /[\S]/g, ' ' ) + '^----'; } }; }, error: function( err ) { var pos, message; pos = this.getLinePos(); message = err + ' at ' + pos; throw new ParseError( message ); }, matchString: function( string ) { if ( this.str.substr( this.pos, string.length ) === string ) { this.pos += string.length; return string; } }, matchPattern: function( pattern ) { var match; if ( match = pattern.exec( this.remaining() ) ) { this.pos += match[ 0 ].length; return match[ 1 ] || match[ 0 ]; } }, allowWhitespace: function() { this.matchPattern( leadingWhitespace ); }, remaining: function() { return this.str.substring( this.pos ); }, nextChar: function() { return this.str.charAt( this.pos ); } }; Parser.extend = function( proto ) { var Parent = this, Child, key; Child = function( str, options ) { Parser.call( this, str, options ); }; Child.prototype = create( Parent.prototype ); for ( key in proto ) { if ( hasOwnProperty.call( proto, key ) ) { Child.prototype[ key ] = proto[ key ]; } } Child.extend = Parser.extend; return Child; }; circular.Parser = Parser; return Parser; }( circular, create, hasOwn, conditional, flattenExpression ); /* parse/converters/mustache/delimiterChange.js */ var delimiterChange = function() { var delimiterChangePattern = /^[^\s=]+/, whitespacePattern = /^\s+/; return function( parser ) { var start, opening, closing; if ( !parser.matchString( '=' ) ) { return null; } start = parser.pos; // allow whitespace before new opening delimiter parser.allowWhitespace(); opening = parser.matchPattern( delimiterChangePattern ); if ( !opening ) { parser.pos = start; return null; } // allow whitespace (in fact, it's necessary...) if ( !parser.matchPattern( whitespacePattern ) ) { return null; } closing = parser.matchPattern( delimiterChangePattern ); if ( !closing ) { parser.pos = start; return null; } // allow whitespace before closing '=' parser.allowWhitespace(); if ( !parser.matchString( '=' ) ) { parser.pos = start; return null; } return [ opening, closing ]; }; }(); /* parse/converters/mustache/delimiterTypes.js */ var delimiterTypes = [ { delimiters: 'delimiters', isTriple: false, isStatic: false }, { delimiters: 'tripleDelimiters', isTriple: true, isStatic: false }, { delimiters: 'staticDelimiters', isTriple: false, isStatic: true }, { delimiters: 'staticTripleDelimiters', isTriple: true, isStatic: true } ]; /* parse/converters/mustache/type.js */ var type = function( types ) { var mustacheTypes = { '#': types.SECTION, '^': types.INVERTED, '/': types.CLOSING, '>': types.PARTIAL, '!': types.COMMENT, '&': types.TRIPLE }; return function( parser ) { var type = mustacheTypes[ parser.str.charAt( parser.pos ) ]; if ( !type ) { return null; } parser.pos += 1; return type; }; }( types ); /* parse/converters/mustache/handlebarsBlockCodes.js */ var handlebarsBlockCodes = function( types ) { return { 'if': types.SECTION_IF, 'unless': types.SECTION_UNLESS, 'with': types.SECTION_WITH, 'each': types.SECTION_EACH }; }( types ); /* empty/legacy.js */ var legacy = null; /* parse/converters/mustache/content.js */ var content = function( types, mustacheType, handlebarsBlockCodes ) { var indexRefPattern = /^\s*:\s*([a-zA-Z_$][a-zA-Z_$0-9]*)/, arrayMemberPattern = /^[0-9][1-9]*$/, handlebarsBlockPattern = new RegExp( '^(' + Object.keys( handlebarsBlockCodes ).join( '|' ) + ')\\b' ), legalReference; legalReference = /^[a-zA-Z$_0-9]+(?:(\.[a-zA-Z$_0-9]+)|(\[[a-zA-Z$_0-9]+\]))*$/; return function( parser, delimiterType ) { var start, pos, mustache, type, block, expression, i, remaining, index, delimiters, referenceExpression; start = parser.pos; mustache = {}; delimiters = parser[ delimiterType.delimiters ]; if ( delimiterType.isStatic ) { mustache.s = true; } // Determine mustache type if ( delimiterType.isTriple ) { mustache.t = types.TRIPLE; } else { // We need to test for expressions before we test for mustache type, because // an expression that begins '!' looks a lot like a comment if ( parser.remaining()[ 0 ] === '!' && ( expression = parser.readExpression() ) ) { mustache.t = types.INTERPOLATOR; // Was it actually an expression, or a comment block in disguise? parser.allowWhitespace(); if ( parser.matchString( delimiters[ 1 ] ) ) { // expression parser.pos -= delimiters[ 1 ].length; } else { // comment block parser.pos = start; expression = null; } } if ( !expression ) { type = mustacheType( parser ); mustache.t = type || types.INTERPOLATOR; // default // See if there's an explicit section type e.g. {{#with}}...{{/with}} if ( type === types.SECTION ) { if ( block = parser.matchPattern( handlebarsBlockPattern ) ) { mustache.n = block; } parser.allowWhitespace(); } else if ( type === types.COMMENT || type === types.CLOSING ) { remaining = parser.remaining(); index = remaining.indexOf( delimiters[ 1 ] ); if ( index !== -1 ) { mustache.r = remaining.substr( 0, index ); parser.pos += index; return mustache; } } } } if ( !expression ) { // allow whitespace parser.allowWhitespace(); // get expression expression = parser.readExpression(); // With certain valid references that aren't valid expressions, // e.g. {{1.foo}}, we have a problem: it looks like we've got an // expression, but the expression didn't consume the entire // reference. So we need to check that the mustache delimiters // appear next, unless there's an index reference (i.e. a colon) remaining = parser.remaining(); if ( remaining.substr( 0, delimiters[ 1 ].length ) !== delimiters[ 1 ] && remaining.charAt( 0 ) !== ':' ) { pos = parser.pos; parser.pos = start; remaining = parser.remaining(); index = remaining.indexOf( delimiters[ 1 ] ); if ( index !== -1 ) { mustache.r = remaining.substr( 0, index ).trim(); // Check it's a legal reference if ( !legalReference.test( mustache.r ) ) { parser.error( 'Expected a legal Mustache reference' ); } parser.pos += index; return mustache; } parser.pos = pos; } } if ( expression ) { while ( expression.t === types.BRACKETED && expression.x ) { expression = expression.x; } // special case - integers should be treated as array members references, // rather than as expressions in their own right if ( expression.t === types.REFERENCE ) { mustache.r = expression.n; } else { if ( expression.t === types.NUMBER_LITERAL && arrayMemberPattern.test( expression.v ) ) { mustache.r = expression.v; } else if ( referenceExpression = getReferenceExpression( parser, expression ) ) { mustache.rx = referenceExpression; } else { mustache.x = parser.flattenExpression( expression ); } } } // optional index reference if ( i = parser.matchPattern( indexRefPattern ) ) { mustache.i = i; } return mustache; }; // TODO refactor this! it's bewildering function getReferenceExpression( parser, expression ) { var members = [], refinement; while ( expression.t === types.MEMBER && expression.r.t === types.REFINEMENT ) { refinement = expression.r; if ( refinement.x ) { if ( refinement.x.t === types.REFERENCE ) { members.unshift( refinement.x ); } else { members.unshift( parser.flattenExpression( refinement.x ) ); } } else { members.unshift( refinement.n ); } expression = expression.x; } if ( expression.t !== types.REFERENCE ) { return null; } return { r: expression.n, m: members }; } }( types, type, handlebarsBlockCodes, legacy ); /* parse/converters/mustache.js */ var mustache = function( types, delimiterChange, delimiterTypes, mustacheContent, handlebarsBlockCodes ) { var delimiterChangeToken = { t: types.DELIMCHANGE, exclude: true }, handlebarsIndexRefPattern = /^@(?:index|key)$/; return getMustache; function getMustache( parser ) { var types; types = delimiterTypes.slice().sort( function compare( a, b ) { // Sort in order of descending opening delimiter length (longer first), // to protect against opening delimiters being substrings of each other return parser[ b.delimiters ][ 0 ].length - parser[ a.delimiters ][ 0 ].length; } ); return function r( type ) { if ( !type ) { return null; } else { return getMustacheOfType( parser, type ) || r( types.shift() ); } }( types.shift() ); } function getMustacheOfType( parser, delimiterType ) { var start, startPos, mustache, delimiters, children, expectedClose, elseChildren, currentChildren, child, indexRef; start = parser.pos; startPos = parser.getLinePos(); delimiters = parser[ delimiterType.delimiters ]; if ( !parser.matchString( delimiters[ 0 ] ) ) { return null; } // delimiter change? if ( mustache = delimiterChange( parser ) ) { // find closing delimiter or abort... if ( !parser.matchString( delimiters[ 1 ] ) ) { return null; } // ...then make the switch parser[ delimiterType.delimiters ] = mustache; return delimiterChangeToken; } parser.allowWhitespace(); mustache = mustacheContent( parser, delimiterType ); if ( mustache === null ) { parser.pos = start; return null; } // allow whitespace before closing delimiter parser.allowWhitespace(); if ( !parser.matchString( delimiters[ 1 ] ) ) { parser.error( 'Expected closing delimiter \'' + delimiters[ 1 ] + '\' after reference' ); } if ( mustache.t === types.COMMENT ) { mustache.exclude = true; } if ( mustache.t === types.CLOSING ) { parser.sectionDepth -= 1; if ( parser.sectionDepth < 0 ) { parser.pos = start; parser.error( 'Attempted to close a section that wasn\'t open' ); } } // section children if ( isSection( mustache ) ) { parser.sectionDepth += 1; children = []; currentChildren = children; expectedClose = mustache.n; while ( child = parser.read() ) { if ( child.t === types.CLOSING ) { if ( expectedClose && child.r !== expectedClose ) { parser.error( 'Expected {{/' + expectedClose + '}}' ); } break; } // {{else}} tags require special treatment if ( child.t === types.INTERPOLATOR && child.r === 'else' ) { switch ( mustache.n ) { case 'unless': parser.error( '{{else}} not allowed in {{#unless}}' ); break; case 'with': parser.error( '{{else}} not allowed in {{#with}}' ); break; default: currentChildren = elseChildren = []; continue; } } currentChildren.push( child ); } if ( children.length ) { mustache.f = children; // If this is an 'each' section, and it contains an {{@index}} or {{@key}}, // we need to set the index reference accordingly if ( !mustache.i && mustache.n === 'each' && ( indexRef = handlebarsIndexRef( mustache.f ) ) ) { mustache.i = indexRef; } } if ( elseChildren && elseChildren.length ) { mustache.l = elseChildren; } } if ( parser.includeLinePositions ) { mustache.p = startPos.toJSON(); } // Replace block name with code if ( mustache.n ) { mustache.n = handlebarsBlockCodes[ mustache.n ]; } else if ( mustache.t === types.INVERTED ) { mustache.t = types.SECTION; mustache.n = types.SECTION_UNLESS; } return mustache; } function handlebarsIndexRef( fragment ) { var i, child, indexRef; i = fragment.length; while ( i-- ) { child = fragment[ i ]; // Recurse into elements (but not sections) if ( child.t === types.ELEMENT && child.f && ( indexRef = handlebarsIndexRef( child.f ) ) ) { return indexRef; } // Mustache? if ( child.t === types.INTERPOLATOR || child.t === types.TRIPLE || child.t === types.SECTION ) { // Normal reference? if ( child.r && handlebarsIndexRefPattern.test( child.r ) ) { return child.r; } // Expression? if ( child.x && ( indexRef = indexRefContainedInExpression( child.x ) ) ) { return indexRef; } // Reference expression? if ( child.rx && ( indexRef = indexRefContainedInReferenceExpression( child.rx ) ) ) { return indexRef; } } } } function indexRefContainedInExpression( expression ) { var i; i = expression.r.length; while ( i-- ) { if ( handlebarsIndexRefPattern.test( expression.r[ i ] ) ) { return expression.r[ i ]; } } } function indexRefContainedInReferenceExpression( referenceExpression ) { var i, indexRef, member; i = referenceExpression.m.length; while ( i-- ) { member = referenceExpression.m[ i ]; if ( member.r && ( indexRef = indexRefContainedInExpression( member ) ) ) { return indexRef; } if ( member.t === types.REFERENCE && handlebarsIndexRefPattern.test( member.n ) ) { return member.n; } } } function isSection( mustache ) { return mustache.t === types.SECTION || mustache.t === types.INVERTED; } }( types, delimiterChange, delimiterTypes, content, handlebarsBlockCodes ); /* parse/converters/comment.js */ var comment = function( types ) { var OPEN_COMMENT = '<!--', CLOSE_COMMENT = '-->'; return function( parser ) { var startPos, content, remaining, endIndex, comment; startPos = parser.getLinePos(); if ( !parser.matchString( OPEN_COMMENT ) ) { return null; } remaining = parser.remaining(); endIndex = remaining.indexOf( CLOSE_COMMENT ); if ( endIndex === -1 ) { parser.error( 'Illegal HTML - expected closing comment sequence (\'-->\')' ); } content = remaining.substr( 0, endIndex ); parser.pos += endIndex + 3; comment = { t: types.COMMENT, c: content }; if ( parser.includeLinePositions ) { comment.p = startPos.toJSON(); } return comment; }; }( types ); /* config/voidElementNames.js */ var voidElementNames = function() { var voidElementNames = /^(?:area|base|br|col|command|doctype|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i; return voidElementNames; }(); /* parse/converters/utils/getLowestIndex.js */ var getLowestIndex = function( haystack, needles ) { var i, index, lowest; i = needles.length; while ( i-- ) { index = haystack.indexOf( needles[ i ] ); // short circuit if ( !index ) { return 0; } if ( index === -1 ) { continue; } if ( !lowest || index < lowest ) { lowest = index; } } return lowest || -1; }; /* parse/converters/utils/decodeCharacterReferences.js */ var decodeCharacterReferences = function() { var htmlEntities, controlCharacters, namedEntityPattern, hexEntityPattern, decimalEntityPattern; htmlEntities = { quot: 34, amp: 38, apos: 39, lt: 60, gt: 62, nbsp: 160, iexcl: 161, cent: 162, pound: 163, curren: 164, yen: 165, brvbar: 166, sect: 167, uml: 168, copy: 169, ordf: 170, laquo: 171, not: 172, shy: 173, reg: 174, macr: 175, deg: 176, plusmn: 177, sup2: 178, sup3: 179, acute: 180, micro: 181, para: 182, middot: 183, cedil: 184, sup1: 185, ordm: 186, raquo: 187, frac14: 188, frac12: 189, frac34: 190, iquest: 191, Agrave: 192, Aacute: 193, Acirc: 194, Atilde: 195, Auml: 196, Aring: 197, AElig: 198, Ccedil: 199, Egrave: 200, Eacute: 201, Ecirc: 202, Euml: 203, Igrave: 204, Iacute: 205, Icirc: 206, Iuml: 207, ETH: 208, Ntilde: 209, Ograve: 210, Oacute: 211, Ocirc: 212, Otilde: 213, Ouml: 214, times: 215, Oslash: 216, Ugrave: 217, Uacute: 218, Ucirc: 219, Uuml: 220, Yacute: 221, THORN: 222, szlig: 223, agrave: 224, aacute: 225, acirc: 226, atilde: 227, auml: 228, aring: 229, aelig: 230, ccedil: 231, egrave: 232, eacute: 233, ecirc: 234, euml: 235, igrave: 236, iacute: 237, icirc: 238, iuml: 239, eth: 240, ntilde: 241, ograve: 242, oacute: 243, ocirc: 244, otilde: 245, ouml: 246, divide: 247, oslash: 248, ugrave: 249, uacute: 250, ucirc: 251, uuml: 252, yacute: 253, thorn: 254, yuml: 255, OElig: 338, oelig: 339, Scaron: 352, scaron: 353, Yuml: 376, fnof: 402, circ: 710, tilde: 732, Alpha: 913, Beta: 914, Gamma: 915, Delta: 916, Epsilon: 917, Zeta: 918, Eta: 919, Theta: 920, Iota: 921, Kappa: 922, Lambda: 923, Mu: 924, Nu: 925, Xi: 926, Omicron: 927, Pi: 928, Rho: 929, Sigma: 931, Tau: 932, Upsilon: 933, Phi: 934, Chi: 935, Psi: 936, Omega: 937, alpha: 945, beta: 946, gamma: 947, delta: 948, epsilon: 949, zeta: 950, eta: 951, theta: 952, iota: 953, kappa: 954, lambda: 955, mu: 956, nu: 957, xi: 958, omicron: 959, pi: 960, rho: 961, sigmaf: 962, sigma: 963, tau: 964, upsilon: 965, phi: 966, chi: 967, psi: 968, omega: 969, thetasym: 977, upsih: 978, piv: 982, ensp: 8194, emsp: 8195, thinsp: 8201, zwnj: 8204, zwj: 8205, lrm: 8206, rlm: 8207, ndash: 8211, mdash: 8212, lsquo: 8216, rsquo: 8217, sbquo: 8218, ldquo: 8220, rdquo: 8221, bdquo: 8222, dagger: 8224, Dagger: 8225, bull: 8226, hellip: 8230, permil: 8240, prime: 8242, Prime: 8243, lsaquo: 8249, rsaquo: 8250, oline: 8254, frasl: 8260, euro: 8364, image: 8465, weierp: 8472, real: 8476, trade: 8482, alefsym: 8501, larr: 8592, uarr: 8593, rarr: 8594, darr: 8595, harr: 8596, crarr: 8629, lArr: 8656, uArr: 8657, rArr: 8658, dArr: 8659, hArr: 8660, forall: 8704, part: 8706, exist: 8707, empty: 8709, nabla: 8711, isin: 8712, notin: 8713, ni: 8715, prod: 8719, sum: 8721, minus: 8722, lowast: 8727, radic: 8730, prop: 8733, infin: 8734, ang: 8736, and: 8743, or: 8744, cap: 8745, cup: 8746, 'int': 8747, there4: 8756, sim: 8764, cong: 8773, asymp: 8776, ne: 8800, equiv: 8801, le: 8804, ge: 8805, sub: 8834, sup: 8835, nsub: 8836, sube: 8838, supe: 8839, oplus: 8853, otimes: 8855, perp: 8869, sdot: 8901, lceil: 8968, rceil: 8969, lfloor: 8970, rfloor: 8971, lang: 9001, rang: 9002, loz: 9674, spades: 9824, clubs: 9827, hearts: 9829, diams: 9830 }; controlCharacters = [ 8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 141, 381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 157, 382, 376 ]; namedEntityPattern = new RegExp( '&(' + Object.keys( htmlEntities ).join( '|' ) + ');?', 'g' ); hexEntityPattern = /&#x([0-9]+);?/g; decimalEntityPattern = /&#([0-9]+);?/g; return function decodeCharacterReferences( html ) { var result; // named entities result = html.replace( namedEntityPattern, function( match, name ) { if ( htmlEntities[ name ] ) { return String.fromCharCode( htmlEntities[ name ] ); } return match; } ); // hex references result = result.replace( hexEntityPattern, function( match, hex ) { return String.fromCharCode( validateCode( parseInt( hex, 16 ) ) ); } ); // decimal references result = result.replace( decimalEntityPattern, function( match, charCode ) { return String.fromCharCode( validateCode( charCode ) ); } ); return result; }; // some code points are verboten. If we were inserting HTML, the browser would replace the illegal // code points with alternatives in some cases - since we're bypassing that mechanism, we need // to replace them ourselves // // Source: http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Illegal_characters function validateCode( code ) { if ( !code ) { return 65533; } // line feed becomes generic whitespace if ( code === 10 ) { return 32; } // ASCII range. (Why someone would use HTML entities for ASCII characters I don't know, but...) if ( code < 128 ) { return code; } // code points 128-159 are dealt with leniently by browsers, but they're incorrect. We need // to correct the mistake or we'll end up with missing € signs and so on if ( code <= 159 ) { return controlCharacters[ code - 128 ]; } // basic multilingual plane if ( code < 55296 ) { return code; } // UTF-16 surrogate halves if ( code <= 57343 ) { return 65533; } // rest of the basic multilingual plane if ( code <= 65535 ) { return code; } return 65533; } }( legacy ); /* parse/converters/text.js */ var text = function( getLowestIndex, decodeCharacterReferences ) { return function( parser ) { var index, remaining, disallowed, barrier; remaining = parser.remaining(); barrier = parser.inside ? '</' + parser.inside : '<'; if ( parser.inside && !parser.interpolate[ parser.inside ] ) { index = remaining.indexOf( barrier ); } else { disallowed = [ barrier, parser.delimiters[ 0 ], parser.tripleDelimiters[ 0 ], parser.staticDelimiters[ 0 ], parser.staticTripleDelimiters[ 0 ] ]; // http://developers.whatwg.org/syntax.html#syntax-attributes if ( parser.inAttribute === true ) { // we're inside an unquoted attribute value disallowed.push( '"', '\'', '=', '>', '`' ); } else if ( parser.inAttribute ) { disallowed.push( parser.inAttribute ); } index = getLowestIndex( remaining, disallowed ); } if ( !index ) { return null; } if ( index === -1 ) { index = remaining.length; } parser.pos += index; return decodeCharacterReferences( remaining.substr( 0, index ) ); }; }( getLowestIndex, decodeCharacterReferences ); /* parse/converters/element/closingTag.js */ var closingTag = function( types ) { var closingTagPattern = /^([a-zA-Z]{1,}:?[a-zA-Z0-9\-]*)\s*\>/; return function( parser ) { var tag; // are we looking at a closing tag? if ( !parser.matchString( '</' ) ) { return null; } if ( tag = parser.matchPattern( closingTagPattern ) ) { return { t: types.CLOSING_TAG, e: tag }; } // We have an illegal closing tag, report it parser.pos -= 2; parser.error( 'Illegal closing tag' ); }; }( types ); /* parse/converters/element/attribute.js */ var attribute = function( getLowestIndex, getMustache ) { var attributeNamePattern = /^[^\s"'>\/=]+/, unquotedAttributeValueTextPattern = /^[^\s"'=<>`]+/; return getAttribute; function getAttribute( parser ) { var attr, name, value; parser.allowWhitespace(); name = parser.matchPattern( attributeNamePattern ); if ( !name ) { return null; } attr = { name: name }; value = getAttributeValue( parser ); if ( value ) { attr.value = value; } return attr; } function getAttributeValue( parser ) { var start, valueStart, startDepth, value; start = parser.pos; parser.allowWhitespace(); if ( !parser.matchString( '=' ) ) { parser.pos = start; return null; } parser.allowWhitespace(); valueStart = parser.pos; startDepth = parser.sectionDepth; value = getQuotedAttributeValue( parser, '\'' ) || getQuotedAttributeValue( parser, '"' ) || getUnquotedAttributeValue( parser ); if ( parser.sectionDepth !== startDepth ) { parser.pos = valueStart; parser.error( 'An attribute value must contain as many opening section tags as closing section tags' ); } if ( value === null ) { parser.pos = start; return null; } if ( value.length === 1 && typeof value[ 0 ] === 'string' ) { return value[ 0 ]; } return value; } function getUnquotedAttributeValueToken( parser ) { var start, text, index; start = parser.pos; text = parser.matchPattern( unquotedAttributeValueTextPattern ); if ( !text ) { return null; } if ( ( index = text.indexOf( parser.delimiters[ 0 ] ) ) !== -1 ) { text = text.substr( 0, index ); parser.pos = start + text.length; } return text; } function getUnquotedAttributeValue( parser ) { var tokens, token; parser.inAttribute = true; tokens = []; token = getMustache( parser ) || getUnquotedAttributeValueToken( parser ); while ( token !== null ) { tokens.push( token ); token = getMustache( parser ) || getUnquotedAttributeValueToken( parser ); } if ( !tokens.length ) { return null; } parser.inAttribute = false; return tokens; } function getQuotedAttributeValue( parser, quoteMark ) { var start, tokens, token; start = parser.pos; if ( !parser.matchString( quoteMark ) ) { return null; } parser.inAttribute = quoteMark; tokens = []; token = getMustache( parser ) || getQuotedStringToken( parser, quoteMark ); while ( token !== null ) { tokens.push( token ); token = getMustache( parser ) || getQuotedStringToken( parser, quoteMark ); } if ( !parser.matchString( quoteMark ) ) { parser.pos = start; return null; } parser.inAttribute = false; return tokens; } function getQuotedStringToken( parser, quoteMark ) { var start, index, remaining; start = parser.pos; remaining = parser.remaining(); index = getLowestIndex( remaining, [ quoteMark, parser.delimiters[ 0 ], parser.delimiters[ 1 ] ] ); if ( index === -1 ) { parser.error( 'Quoted attribute value must have a closing quote' ); } if ( !index ) { return null; } parser.pos += index; return remaining.substr( 0, index ); } }( getLowestIndex, mustache ); /* utils/parseJSON.js */ var parseJSON = function( Parser, getStringLiteral, getKey ) { // simple JSON parser, without the restrictions of JSON parse // (i.e. having to double-quote keys). // // If passed a hash of values as the second argument, ${placeholders} // will be replaced with those values var JsonParser, specials, specialsPattern, numberPattern, placeholderPattern, placeholderAtStartPattern, onlyWhitespace; specials = { 'true': true, 'false': false, 'undefined': undefined, 'null': null }; specialsPattern = new RegExp( '^(?:' + Object.keys( specials ).join( '|' ) + ')' ); numberPattern = /^(?:[+-]?)(?:(?:(?:0|[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/; placeholderPattern = /\$\{([^\}]+)\}/g; placeholderAtStartPattern = /^\$\{([^\}]+)\}/; onlyWhitespace = /^\s*$/; JsonParser = Parser.extend( { init: function( str, options ) { this.values = options.values; }, postProcess: function( result ) { if ( result.length !== 1 || !onlyWhitespace.test( this.leftover ) ) { return null; } return { value: result[ 0 ].v }; }, converters: [ function getPlaceholder( parser ) { var placeholder; if ( !parser.values ) { return null; } placeholder = parser.matchPattern( placeholderAtStartPattern ); if ( placeholder && parser.values.hasOwnProperty( placeholder ) ) { return { v: parser.values[ placeholder ] }; } }, function getSpecial( parser ) { var special; if ( special = parser.matchPattern( specialsPattern ) ) { return { v: specials[ special ] }; } }, function getNumber( parser ) { var number; if ( number = parser.matchPattern( numberPattern ) ) { return { v: +number }; } }, function getString( parser ) { var stringLiteral = getStringLiteral( parser ), values; if ( stringLiteral && ( values = parser.values ) ) { return { v: stringLiteral.v.replace( placeholderPattern, function( match, $1 ) { return $1 in values ? values[ $1 ] : $1; } ) }; } return stringLiteral; }, function getObject( parser ) { var result, pair; if ( !parser.matchString( '{' ) ) { return null; } result = {}; parser.allowWhitespace(); if ( parser.matchString( '}' ) ) { return { v: result }; } while ( pair = getKeyValuePair( parser ) ) { result[ pair.key ] = pair.value; parser.allowWhitespace(); if ( parser.matchString( '}' ) ) { return { v: result }; } if ( !parser.matchString( ',' ) ) { return null; } } return null; }, function getArray( parser ) { var result, valueToken; if ( !parser.matchString( '[' ) ) { return null; } result = []; parser.allowWhitespace(); if ( parser.matchString( ']' ) ) { return { v: result }; } while ( valueToken = parser.read() ) { result.push( valueToken.v ); parser.allowWhitespace(); if ( parser.matchString( ']' ) ) { return { v: result }; } if ( !parser.matchString( ',' ) ) { return null; } parser.allowWhitespace(); } return null; } ] } ); function getKeyValuePair( parser ) { var key, valueToken, pair; parser.allowWhitespace(); key = getKey( parser ); if ( !key ) { return null; } pair = { key: key }; parser.allowWhitespace(); if ( !parser.matchString( ':' ) ) { return null; } parser.allowWhitespace(); valueToken = parser.read(); if ( !valueToken ) { return null; } pair.value = valueToken.v; return pair; } return function( str, values ) { var parser = new JsonParser( str, { values: values } ); return parser.result; }; }( Parser, stringLiteral, key ); /* parse/converters/element/processDirective.js */ var processDirective = function( parseJSON ) { // TODO clean this up, it's shocking return function( tokens ) { var result, token, colonIndex, directiveName, directiveArgs, parsed; if ( typeof tokens === 'string' ) { if ( tokens.indexOf( ':' ) === -1 ) { return tokens.trim(); } tokens = [ tokens ]; } result = {}; directiveName = []; directiveArgs = []; while ( tokens.length ) { token = tokens.shift(); if ( typeof token === 'string' ) { colonIndex = token.indexOf( ':' ); if ( colonIndex === -1 ) { directiveName.push( token ); } else { // is the colon the first character? if ( colonIndex ) { // no directiveName.push( token.substr( 0, colonIndex ) ); } // if there is anything after the colon in this token, treat // it as the first token of the directiveArgs fragment if ( token.length > colonIndex + 1 ) { directiveArgs[ 0 ] = token.substring( colonIndex + 1 ); } break; } } else { directiveName.push( token ); } } directiveArgs = directiveArgs.concat( tokens ); if ( directiveArgs.length || typeof directiveName !== 'string' ) { result = { // TODO is this really necessary? just use the array n: directiveName.length === 1 && typeof directiveName[ 0 ] === 'string' ? directiveName[ 0 ] : directiveName }; if ( directiveArgs.length === 1 && typeof directiveArgs[ 0 ] === 'string' ) { parsed = parseJSON( '[' + directiveArgs[ 0 ] + ']' ); result.a = parsed ? parsed.value : directiveArgs[ 0 ].trim(); } else { result.d = directiveArgs; } } else { result = directiveName; } return result; }; }( parseJSON ); /* parse/converters/element.js */ var element = function( types, voidElementNames, getMustache, getComment, getText, getClosingTag, getAttribute, processDirective ) { var tagNamePattern = /^[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/, validTagNameFollower = /^[\s\n\/>]/, onPattern = /^on/, proxyEventPattern = /^on-([a-zA-Z$_][a-zA-Z$_0-9\-]+)$/, reservedEventNames = /^(?:change|reset|teardown|update)$/, directives = { 'intro-outro': 't0', intro: 't1', outro: 't2', decorator: 'o' }, exclude = { exclude: true }, converters; // Different set of converters, because this time we're looking for closing tags converters = [ getMustache, getComment, getElement, getText, getClosingTag ]; return getElement; function getElement( parser ) { var start, startPos, element, lowerCaseName, directiveName, match, addProxyEvent, attribute, directive, selfClosing, children, child; start = parser.pos; startPos = parser.getLinePos(); if ( parser.inside ) { return null; } if ( !parser.matchString( '<' ) ) { return null; } // if this is a closing tag, abort straight away if ( parser.nextChar() === '/' ) { return null; } element = { t: types.ELEMENT }; if ( parser.includeLinePositions ) { element.p = startPos.toJSON(); } if ( parser.matchString( '!' ) ) { element.y = 1; } // element name element.e = parser.matchPattern( tagNamePattern ); if ( !element.e ) { return null; } // next character must be whitespace, closing solidus or '>' if ( !validTagNameFollower.test( parser.nextChar() ) ) { parser.error( 'Illegal tag name' ); } addProxyEvent = function( name, directive ) { var directiveName = directive.n || directive; if ( reservedEventNames.test( directiveName ) ) { parser.pos -= directiveName.length; parser.error( 'Cannot use reserved event names (change, reset, teardown, update)' ); } element.v[ name ] = directive; }; // directives and attributes while ( attribute = getAttribute( parser ) ) { // intro, outro, decorator if ( directiveName = directives[ attribute.name ] ) { element[ directiveName ] = processDirective( attribute.value ); } else if ( match = proxyEventPattern.exec( attribute.name ) ) { if ( !element.v ) element.v = {}; directive = processDirective( attribute.value ); addProxyEvent( match[ 1 ], directive ); } else { if ( !parser.sanitizeEventAttributes || !onPattern.test( attribute.name ) ) { if ( !element.a ) element.a = {}; element.a[ attribute.name ] = attribute.value || 0; } } } // allow whitespace before closing solidus parser.allowWhitespace(); // self-closing solidus? if ( parser.matchString( '/' ) ) { selfClosing = true; } // closing angle bracket if ( !parser.matchString( '>' ) ) { return null; } lowerCaseName = element.e.toLowerCase(); if ( !selfClosing && !voidElementNames.test( element.e ) ) { // Special case - if we open a script element, further tags should // be ignored unless they're a closing script element if ( lowerCaseName === 'script' || lowerCaseName === 'style' ) { parser.inside = lowerCaseName; } children = []; while ( child = parser.read( converters ) ) { // Special case - closing section tag if ( child.t === types.CLOSING ) { break; } if ( child.t === types.CLOSING_TAG ) { break; } children.push( child ); } if ( children.length ) { element.f = children; } } parser.inside = null; if ( parser.sanitizeElements && parser.sanitizeElements.indexOf( lowerCaseName ) !== -1 ) { return exclude; } return element; } }( types, voidElementNames, mustache, comment, text, closingTag, attribute, processDirective ); /* parse/utils/trimWhitespace.js */ var trimWhitespace = function() { var leadingWhitespace = /^[ \t\f\r\n]+/, trailingWhitespace = /[ \t\f\r\n]+$/; return function( items, leading, trailing ) { var item; if ( leading ) { item = items[ 0 ]; if ( typeof item === 'string' ) { item = item.replace( leadingWhitespace, '' ); if ( !item ) { items.shift(); } else { items[ 0 ] = item; } } } if ( trailing ) { item = items[ items.length - 1 ]; if ( typeof item === 'string' ) { item = item.replace( trailingWhitespace, '' ); if ( !item ) { items.pop(); } else { items[ items.length - 1 ] = item; } } } }; }(); /* parse/utils/stripStandalones.js */ var stripStandalones = function( types ) { var leadingLinebreak = /^\s*\r?\n/, trailingLinebreak = /\r?\n\s*$/; return function( items ) { var i, current, backOne, backTwo, lastSectionItem; for ( i = 1; i < items.length; i += 1 ) { current = items[ i ]; backOne = items[ i - 1 ]; backTwo = items[ i - 2 ]; // if we're at the end of a [text][comment][text] sequence... if ( isString( current ) && isComment( backOne ) && isString( backTwo ) ) { // ... and the comment is a standalone (i.e. line breaks either side)... if ( trailingLinebreak.test( backTwo ) && leadingLinebreak.test( current ) ) { // ... then we want to remove the whitespace after the first line break items[ i - 2 ] = backTwo.replace( trailingLinebreak, '\n' ); // and the leading line break of the second text token items[ i ] = current.replace( leadingLinebreak, '' ); } } // if the current item is a section, and it is preceded by a linebreak, and // its first item is a linebreak... if ( isSection( current ) && isString( backOne ) ) { if ( trailingLinebreak.test( backOne ) && isString( current.f[ 0 ] ) && leadingLinebreak.test( current.f[ 0 ] ) ) { items[ i - 1 ] = backOne.replace( trailingLinebreak, '\n' ); current.f[ 0 ] = current.f[ 0 ].replace( leadingLinebreak, '' ); } } // if the last item was a section, and it is followed by a linebreak, and // its last item is a linebreak... if ( isString( current ) && isSection( backOne ) ) { lastSectionItem = backOne.f[ backOne.f.length - 1 ]; if ( isString( lastSectionItem ) && trailingLinebreak.test( lastSectionItem ) && leadingLinebreak.test( current ) ) { backOne.f[ backOne.f.length - 1 ] = lastSectionItem.replace( trailingLinebreak, '\n' ); items[ i ] = current.replace( leadingLinebreak, '' ); } } } return items; }; function isString( item ) { return typeof item === 'string'; } function isComment( item ) { return item.t === types.COMMENT || item.t === types.DELIMCHANGE; } function isSection( item ) { return ( item.t === types.SECTION || item.t === types.INVERTED ) && item.f; } }( types ); /* parse/_parse.js */ var parse = function( types, Parser, mustache, comment, element, text, trimWhitespace, stripStandalones ) { // Ractive.parse // =============== // // Takes in a string, and returns an object representing the parsed template. // A parsed template is an array of 1 or more 'templates', which in some // cases have children. // // The format is optimised for size, not readability, however for reference the // keys for each template are as follows: // // * r - Reference, e.g. 'mustache' in {{mustache}} // * t - Type code (e.g. 1 is text, 2 is interpolator...) // * f - Fragment. Contains a template's children // * l - eLse fragment. Contains a template's children in the else case // * e - Element name // * a - map of element Attributes, or proxy event/transition Arguments // * d - Dynamic proxy event/transition arguments // * n - indicates an iNverted section // * i - Index reference, e.g. 'num' in {{#section:num}}content{{/section}} // * v - eVent proxies (i.e. when user e.g. clicks on a node, fire proxy event) // * x - eXpressions // * s - String representation of an expression function // * t0 - intro/outro Transition // * t1 - intro Transition // * t2 - outro Transition // * o - decOrator // * y - is doctYpe // * c - is Content (e.g. of a comment node) // * p - line Position information - array with line number and character position of each node var StandardParser, parse, contiguousWhitespace = /[ \t\f\r\n]+/g, inlinePartialStart = /<!--\s*\{\{\s*>\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\s*}\}\s*-->/, inlinePartialEnd = /<!--\s*\{\{\s*\/\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\s*}\}\s*-->/, preserveWhitespaceElements = /^(?:pre|script|style|textarea)$/i, leadingWhitespace = /^\s+/, trailingWhitespace = /\s+$/; StandardParser = Parser.extend( { init: function( str, options ) { // config this.delimiters = options.delimiters || [ '{{', '}}' ]; this.tripleDelimiters = options.tripleDelimiters || [ '{{{', '}}}' ]; this.staticDelimiters = options.staticDelimiters || [ '[[', ']]' ]; this.staticTripleDelimiters = options.staticTripleDelimiters || [ '[[[', ']]]' ]; this.sectionDepth = 0; this.interpolate = { script: !options.interpolate || options.interpolate.script !== false, style: !options.interpolate || options.interpolate.style !== false }; if ( options.sanitize === true ) { options.sanitize = { // blacklist from https://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/lang/html/html4-elements-whitelist.json elements: 'applet base basefont body frame frameset head html isindex link meta noframes noscript object param script style title'.split( ' ' ), eventAttributes: true }; } this.sanitizeElements = options.sanitize && options.sanitize.elements; this.sanitizeEventAttributes = options.sanitize && options.sanitize.eventAttributes; this.includeLinePositions = options.includeLinePositions; }, postProcess: function( items, options ) { if ( this.sectionDepth > 0 ) { this.error( 'A section was left open' ); } cleanup( items, options.stripComments !== false, options.preserveWhitespace, !options.preserveWhitespace, !options.preserveWhitespace, options.rewriteElse !== false ); return items; }, converters: [ mustache, comment, element, text ] } ); parse = function( template ) { var options = arguments[ 1 ]; if ( options === void 0 ) options = {}; var result, remaining, partials, name, startMatch, endMatch; result = { v: 1 }; if ( inlinePartialStart.test( template ) ) { remaining = template; template = ''; while ( startMatch = inlinePartialStart.exec( remaining ) ) { name = startMatch[ 1 ]; template += remaining.substr( 0, startMatch.index ); remaining = remaining.substring( startMatch.index + startMatch[ 0 ].length ); endMatch = inlinePartialEnd.exec( remaining ); if ( !endMatch || endMatch[ 1 ] !== name ) { throw new Error( 'Inline partials must have a closing delimiter, and cannot be nested' ); } ( partials || ( partials = {} ) )[ name ] = new StandardParser( remaining.substr( 0, endMatch.index ), options ).result; remaining = remaining.substring( endMatch.index + endMatch[ 0 ].length ); } result.p = partials; } result.t = new StandardParser( template, options ).result; return result; }; return parse; function cleanup( items, stripComments, preserveWhitespace, removeLeadingWhitespace, removeTrailingWhitespace, rewriteElse ) { var i, item, previousItem, nextItem, preserveWhitespaceInsideFragment, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment, unlessBlock, key; // First pass - remove standalones and comments etc stripStandalones( items ); i = items.length; while ( i-- ) { item = items[ i ]; // Remove delimiter changes, unsafe elements etc if ( item.exclude ) { items.splice( i, 1 ); } else if ( stripComments && item.t === types.COMMENT ) { items.splice( i, 1 ); } } // If necessary, remove leading and trailing whitespace trimWhitespace( items, removeLeadingWhitespace, removeTrailingWhitespace ); i = items.length; while ( i-- ) { item = items[ i ]; // Recurse if ( item.f ) { preserveWhitespaceInsideFragment = preserveWhitespace || item.t === types.ELEMENT && preserveWhitespaceElements.test( item.e ); if ( !preserveWhitespaceInsideFragment ) { previousItem = items[ i - 1 ]; nextItem = items[ i + 1 ]; // if the previous item was a text item with trailing whitespace, // remove leading whitespace inside the fragment if ( !previousItem || typeof previousItem === 'string' && trailingWhitespace.test( previousItem ) ) { removeLeadingWhitespaceInsideFragment = true; } // and vice versa if ( !nextItem || typeof nextItem === 'string' && leadingWhitespace.test( nextItem ) ) { removeTrailingWhitespaceInsideFragment = true; } } cleanup( item.f, stripComments, preserveWhitespaceInsideFragment, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment, rewriteElse ); // Split if-else blocks into two (an if, and an unless) if ( item.l ) { cleanup( item.l, stripComments, preserveWhitespace, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment, rewriteElse ); if ( rewriteElse ) { unlessBlock = { t: 4, n: types.SECTION_UNLESS, f: item.l }; // copy the conditional based on its type if ( item.r ) { unlessBlock.r = item.r; } if ( item.x ) { unlessBlock.x = item.x; } if ( item.rx ) { unlessBlock.rx = item.rx; } items.splice( i + 1, 0, unlessBlock ); delete item.l; } } } // Clean up element attributes if ( item.a ) { for ( key in item.a ) { if ( item.a.hasOwnProperty( key ) && typeof item.a[ key ] !== 'string' ) { cleanup( item.a[ key ], stripComments, preserveWhitespace, rewriteElse ); } } } } // final pass - fuse text nodes together i = items.length; while ( i-- ) { if ( typeof items[ i ] === 'string' ) { if ( typeof items[ i + 1 ] === 'string' ) { items[ i ] = items[ i ] + items[ i + 1 ]; items.splice( i + 1, 1 ); } if ( !preserveWhitespace ) { items[ i ] = items[ i ].replace( contiguousWhitespace, ' ' ); } if ( items[ i ] === '' ) { items.splice( i, 1 ); } } } } }( types, Parser, mustache, comment, element, text, trimWhitespace, stripStandalones ); /* config/options/groups/optionGroup.js */ var optionGroup = function() { return function createOptionGroup( keys, config ) { var group = keys.map( config ); keys.forEach( function( key, i ) { group[ key ] = group[ i ]; } ); return group; }; }( legacy ); /* config/options/groups/parseOptions.js */ var parseOptions = function( optionGroup ) { var keys, parseOptions; keys = [ 'preserveWhitespace', 'sanitize', 'stripComments', 'delimiters', 'tripleDelimiters' ]; parseOptions = optionGroup( keys, function( key ) { return key; } ); return parseOptions; }( optionGroup ); /* config/options/template/parser.js */ var parser = function( errors, isClient, parse, create, parseOptions ) { var parser = { parse: doParse, fromId: fromId, isHashedId: isHashedId, isParsed: isParsed, getParseOptions: getParseOptions, createHelper: createHelper }; function createHelper( parseOptions ) { var helper = create( parser ); helper.parse = function( template, options ) { return doParse( template, options || parseOptions ); }; return helper; } function doParse( template, parseOptions ) { if ( !parse ) { throw new Error( errors.missingParser ); } return parse( template, parseOptions || this.options ); } function fromId( id, options ) { var template; if ( !isClient ) { if ( options && options.noThrow ) { return; } throw new Error( 'Cannot retrieve template #' + id + ' as Ractive is not running in a browser.' ); } if ( isHashedId( id ) ) { id = id.substring( 1 ); } if ( !( template = document.getElementById( id ) ) ) { if ( options && options.noThrow ) { return; } throw new Error( 'Could not find template element with id #' + id ); } // Do we want to turn this on? /* if ( template.tagName.toUpperCase() !== 'SCRIPT' )) { if ( options && options.noThrow ) { return; } throw new Error( 'Template element with id #' + id + ', must be a <script> element' ); } */ return template.innerHTML; } function isHashedId( id ) { return id.charAt( 0 ) === '#'; } function isParsed( template ) { return !( typeof template === 'string' ); } function getParseOptions( ractive ) { // Could be Ractive or a Component if ( ractive.defaults ) { ractive = ractive.defaults; } return parseOptions.reduce( function( val, key ) { val[ key ] = ractive[ key ]; return val; }, {} ); } return parser; }( errors, isClient, parse, create, parseOptions ); /* config/options/template/template.js */ var template = function( parser, parse ) { var templateConfig = { name: 'template', extend: function extend( Parent, proto, options ) { var template; // only assign if exists if ( 'template' in options ) { template = options.template; if ( typeof template === 'function' ) { proto.template = template; } else { proto.template = parseIfString( template, proto ); } } }, init: function init( Parent, ractive, options ) { var template, fn; // TODO because of prototypal inheritance, we might just be able to use // ractive.template, and not bother passing through the Parent object. // At present that breaks the test mocks' expectations template = 'template' in options ? options.template : Parent.prototype.template; if ( typeof template === 'function' ) { fn = template; template = getDynamicTemplate( ractive, fn ); ractive._config.template = { fn: fn, result: template }; } template = parseIfString( template, ractive ); // TODO the naming of this is confusing - ractive.template refers to [...], // but Component.prototype.template refers to {v:1,t:[],p:[]}... // it's unnecessary, because the developer never needs to access // ractive.template ractive.template = template.t; if ( template.p ) { extendPartials( ractive.partials, template.p ); } }, reset: function( ractive ) { var result = resetValue( ractive ), parsed; if ( result ) { parsed = parseIfString( result, ractive ); ractive.template = parsed.t; extendPartials( ractive.partials, parsed.p, true ); return true; } } }; function resetValue( ractive ) { var initial = ractive._config.template, result; // If this isn't a dynamic template, there's nothing to do if ( !initial || !initial.fn ) { return; } result = getDynamicTemplate( ractive, initial.fn ); // TODO deep equality check to prevent unnecessary re-rendering // in the case of already-parsed templates if ( result !== initial.result ) { initial.result = result; result = parseIfString( result, ractive ); return result; } } function getDynamicTemplate( ractive, fn ) { var helper = parser.createHelper( parser.getParseOptions( ractive ) ); return fn.call( ractive, ractive.data, helper ); } function parseIfString( template, ractive ) { if ( typeof template === 'string' ) { // ID of an element containing the template? if ( template[ 0 ] === '#' ) { template = parser.fromId( template ); } template = parse( template, parser.getParseOptions( ractive ) ); } else if ( template.v !== 1 ) { throw new Error( 'Mismatched template version! Please ensure you are using the latest version of Ractive.js in your build process as well as in your app' ); } return template; } function extendPartials( existingPartials, newPartials, overwrite ) { if ( !newPartials ) return; // TODO there's an ambiguity here - we need to overwrite in the `reset()` // case, but not initially... for ( var key in newPartials ) { if ( overwrite || !existingPartials.hasOwnProperty( key ) ) { existingPartials[ key ] = newPartials[ key ]; } } } return templateConfig; }( parser, parse ); /* config/options/Registry.js */ var Registry = function( create ) { function Registry( name, useDefaults ) { this.name = name; this.useDefaults = useDefaults; } Registry.prototype = { constructor: Registry, extend: function( Parent, proto, options ) { this.configure( this.useDefaults ? Parent.defaults : Parent, this.useDefaults ? proto : proto.constructor, options ); }, init: function( Parent, ractive, options ) { this.configure( this.useDefaults ? Parent.defaults : Parent, ractive, options ); }, configure: function( Parent, target, options ) { var name = this.name, option = options[ name ], registry; registry = create( Parent[ name ] ); for ( var key in option ) { registry[ key ] = option[ key ]; } target[ name ] = registry; }, reset: function( ractive ) { var registry = ractive[ this.name ]; var changed = false; Object.keys( registry ).forEach( function( key ) { var item = registry[ key ]; if ( item._fn ) { if ( item._fn.isOwner ) { registry[ key ] = item._fn; } else { delete registry[ key ]; } changed = true; } } ); return changed; }, findOwner: function( ractive, key ) { return ractive[ this.name ].hasOwnProperty( key ) ? ractive : this.findConstructor( ractive.constructor, key ); }, findConstructor: function( constructor, key ) { if ( !constructor ) { return; } return constructor[ this.name ].hasOwnProperty( key ) ? constructor : this.findConstructor( constructor._parent, key ); }, find: function( ractive, key ) { var this$0 = this; return recurseFind( ractive, function( r ) { return r[ this$0.name ][ key ]; } ); }, findInstance: function( ractive, key ) { var this$0 = this; return recurseFind( ractive, function( r ) { return r[ this$0.name ][ key ] ? r : void 0; } ); } }; function recurseFind( ractive, fn ) { var find, parent; if ( find = fn( ractive ) ) { return find; } if ( !ractive.isolated && ( parent = ractive._parent ) ) { return recurseFind( parent, fn ); } } return Registry; }( create, legacy ); /* config/options/groups/registries.js */ var registries = function( optionGroup, Registry ) { var keys = [ 'adaptors', 'components', 'computed', 'decorators', 'easing', 'events', 'interpolators', 'partials', 'transitions' ], registries = optionGroup( keys, function( key ) { return new Registry( key, key === 'computed' ); } ); return registries; }( optionGroup, Registry ); /* utils/noop.js */ var noop = function() {}; /* utils/wrapPrototypeMethod.js */ var wrapPrototypeMethod = function( noop ) { return function wrap( parent, name, method ) { if ( !/_super/.test( method ) ) { return method; } var wrapper = function wrapSuper() { var superMethod = getSuperMethod( wrapper._parent, name ), hasSuper = '_super' in this, oldSuper = this._super, result; this._super = superMethod; result = method.apply( this, arguments ); if ( hasSuper ) { this._super = oldSuper; } else { delete this._super; } return result; }; wrapper._parent = parent; wrapper._method = method; return wrapper; }; function getSuperMethod( parent, name ) { var method; if ( name in parent ) { var value = parent[ name ]; if ( typeof value === 'function' ) { method = value; } else { method = function returnValue() { return value; }; } } else { method = noop; } return method; } }( noop ); /* config/deprecate.js */ var deprecate = function( warn, isArray ) { function deprecate( options, deprecated, correct ) { if ( deprecated in options ) { if ( !( correct in options ) ) { warn( getMessage( deprecated, correct ) ); options[ correct ] = options[ deprecated ]; } else { throw new Error( getMessage( deprecated, correct, true ) ); } } } function getMessage( deprecated, correct, isError ) { return 'options.' + deprecated + ' has been deprecated in favour of options.' + correct + '.' + ( isError ? ' You cannot specify both options, please use options.' + correct + '.' : '' ); } function deprecateEventDefinitions( options ) { deprecate( options, 'eventDefinitions', 'events' ); } function deprecateAdaptors( options ) { // Using extend with Component instead of options, // like Human.extend( Spider ) means adaptors as a registry // gets copied to options. So we have to check if actually an array if ( isArray( options.adaptors ) ) { deprecate( options, 'adaptors', 'adapt' ); } } return function deprecateOptions( options ) { deprecateEventDefinitions( options ); deprecateAdaptors( options ); }; }( warn, isArray ); /* config/config.js */ var config = function( css, data, defaults, template, parseOptions, registries, wrap, deprecate ) { var custom, options, config; custom = { data: data, template: template, css: css }; options = Object.keys( defaults ).filter( function( key ) { return !registries[ key ] && !custom[ key ] && !parseOptions[ key ]; } ); // this defines the order: config = [].concat( custom.data, parseOptions, options, registries, custom.template, custom.css ); for ( var key in custom ) { config[ key ] = custom[ key ]; } // for iteration config.keys = Object.keys( defaults ).concat( registries.map( function( r ) { return r.name; } ) ).concat( [ 'css' ] ); config.parseOptions = parseOptions; config.registries = registries; function customConfig( method, key, Parent, instance, options ) { custom[ key ][ method ]( Parent, instance, options ); } config.extend = function( Parent, proto, options ) { configure( 'extend', Parent, proto, options ); }; config.init = function( Parent, ractive, options ) { configure( 'init', Parent, ractive, options ); if ( ractive._config ) { ractive._config.options = options; } }; function configure( method, Parent, instance, options ) { deprecate( options ); customConfig( method, 'data', Parent, instance, options ); config.parseOptions.forEach( function( key ) { if ( key in options ) { instance[ key ] = options[ key ]; } } ); for ( var key in options ) { if ( key in defaults && !( key in config.parseOptions ) && !( key in custom ) ) { var value = options[ key ]; instance[ key ] = typeof value === 'function' ? wrap( Parent.prototype, key, value ) : value; } } config.registries.forEach( function( registry ) { registry[ method ]( Parent, instance, options ); } ); customConfig( method, 'template', Parent, instance, options ); customConfig( method, 'css', Parent, instance, options ); } config.reset = function( ractive ) { return config.filter( function( c ) { return c.reset && c.reset( ractive ); } ).map( function( c ) { return c.name; } ); }; return config; }( css, data, options, template, parseOptions, registries, wrapPrototypeMethod, deprecate ); /* shared/interpolate.js */ var interpolate = function( circular, warn, interpolators, config ) { var interpolate = function( from, to, ractive, type ) { if ( from === to ) { return snap( to ); } if ( type ) { var interpol = config.registries.interpolators.find( ractive, type ); if ( interpol ) { return interpol( from, to ) || snap( to ); } warn( 'Missing "' + type + '" interpolator. You may need to download a plugin from [TODO]' ); } return interpolators.number( from, to ) || interpolators.array( from, to ) || interpolators.object( from, to ) || interpolators.cssLength( from, to ) || snap( to ); }; circular.interpolate = interpolate; return interpolate; function snap( to ) { return function() { return to; }; } }( circular, warn, interpolators, config ); /* Ractive/prototype/animate/Animation.js */ var Ractive$animate_Animation = function( warn, runloop, interpolate ) { var Animation = function( options ) { var key; this.startTime = Date.now(); // from and to for ( key in options ) { if ( options.hasOwnProperty( key ) ) { this[ key ] = options[ key ]; } } this.interpolator = interpolate( this.from, this.to, this.root, this.interpolator ); this.running = true; }; Animation.prototype = { tick: function() { var elapsed, t, value, timeNow, index, keypath; keypath = this.keypath; if ( this.running ) { timeNow = Date.now(); elapsed = timeNow - this.startTime; if ( elapsed >= this.duration ) { if ( keypath !== null ) { runloop.start( this.root ); this.root.viewmodel.set( keypath, this.to ); runloop.end(); } if ( this.step ) { this.step( 1, this.to ); } this.complete( this.to ); index = this.root._animations.indexOf( this ); // TODO investigate why this happens if ( index === -1 ) { warn( 'Animation was not found' ); } this.root._animations.splice( index, 1 ); this.running = false; return false; } t = this.easing ? this.easing( elapsed / this.duration ) : elapsed / this.duration; if ( keypath !== null ) { value = this.interpolator( t ); runloop.start( this.root ); this.root.viewmodel.set( keypath, value ); runloop.end(); } if ( this.step ) { this.step( t, value ); } return true; } return false; }, stop: function() { var index; this.running = false; index = this.root._animations.indexOf( this ); // TODO investigate why this happens if ( index === -1 ) { warn( 'Animation was not found' ); } this.root._animations.splice( index, 1 ); } }; return Animation; }( warn, runloop, interpolate ); /* Ractive/prototype/animate.js */ var Ractive$animate = function( isEqual, Promise, normaliseKeypath, animations, Animation ) { var noop = function() {}, noAnimation = { stop: noop }; return function Ractive$animate( keypath, to, options ) { var promise, fulfilPromise, k, animation, animations, easing, duration, step, complete, makeValueCollector, currentValues, collectValue, dummy, dummyOptions; promise = new Promise( function( fulfil ) { fulfilPromise = fulfil; } ); // animate multiple keypaths if ( typeof keypath === 'object' ) { options = to || {}; easing = options.easing; duration = options.duration; animations = []; // we don't want to pass the `step` and `complete` handlers, as they will // run for each animation! So instead we'll store the handlers and create // our own... step = options.step; complete = options.complete; if ( step || complete ) { currentValues = {}; options.step = null; options.complete = null; makeValueCollector = function( keypath ) { return function( t, value ) { currentValues[ keypath ] = value; }; }; } for ( k in keypath ) { if ( keypath.hasOwnProperty( k ) ) { if ( step || complete ) { collectValue = makeValueCollector( k ); options = { easing: easing, duration: duration }; if ( step ) { options.step = collectValue; } } options.complete = complete ? collectValue : noop; animations.push( animate( this, k, keypath[ k ], options ) ); } } if ( step || complete ) { dummyOptions = { easing: easing, duration: duration }; if ( step ) { dummyOptions.step = function( t ) { step( t, currentValues ); }; } if ( complete ) { promise.then( function( t ) { complete( t, currentValues ); } ); } dummyOptions.complete = fulfilPromise; dummy = animate( this, null, null, dummyOptions ); animations.push( dummy ); } return { stop: function() { var animation; while ( animation = animations.pop() ) { animation.stop(); } if ( dummy ) { dummy.stop(); } } }; } // animate a single keypath options = options || {}; if ( options.complete ) { promise.then( options.complete ); } options.complete = fulfilPromise; animation = animate( this, keypath, to, options ); promise.stop = function() { animation.stop(); }; return promise; }; function animate( root, keypath, to, options ) { var easing, duration, animation, from; if ( keypath ) { keypath = normaliseKeypath( keypath ); } if ( keypath !== null ) { from = root.viewmodel.get( keypath ); } // cancel any existing animation // TODO what about upstream/downstream keypaths? animations.abort( keypath, root ); // don't bother animating values that stay the same if ( isEqual( from, to ) ) { if ( options.complete ) { options.complete( options.to ); } return noAnimation; } // easing function if ( options.easing ) { if ( typeof options.easing === 'function' ) { easing = options.easing; } else { easing = root.easing[ options.easing ]; } if ( typeof easing !== 'function' ) { easing = null; } } // duration duration = options.duration === undefined ? 400 : options.duration; // TODO store keys, use an internal set method animation = new Animation( { keypath: keypath, from: from, to: to, root: root, duration: duration, easing: easing, interpolator: options.interpolator, // TODO wrap callbacks if necessary, to use instance as context step: options.step, complete: options.complete } ); animations.add( animation ); root._animations.push( animation ); return animation; } }( isEqual, Promise, normaliseKeypath, animations, Ractive$animate_Animation ); /* Ractive/prototype/detach.js */ var Ractive$detach = function( removeFromArray ) { return function Ractive$detach() { if ( this.el ) { removeFromArray( this.el.__ractive_instances__, this ); } return this.fragment.detach(); }; }( removeFromArray ); /* Ractive/prototype/find.js */ var Ractive$find = function Ractive$find( selector ) { if ( !this.el ) { return null; } return this.fragment.find( selector ); }; /* utils/matches.js */ var matches = function( isClient, vendors, createElement ) { var matches, div, methodNames, unprefixed, prefixed, i, j, makeFunction; if ( !isClient ) { matches = null; } else { div = createElement( 'div' ); methodNames = [ 'matches', 'matchesSelector' ]; makeFunction = function( methodName ) { return function( node, selector ) { return node[ methodName ]( selector ); }; }; i = methodNames.length; while ( i-- && !matches ) { unprefixed = methodNames[ i ]; if ( div[ unprefixed ] ) { matches = makeFunction( unprefixed ); } else { j = vendors.length; while ( j-- ) { prefixed = vendors[ i ] + unprefixed.substr( 0, 1 ).toUpperCase() + unprefixed.substring( 1 ); if ( div[ prefixed ] ) { matches = makeFunction( prefixed ); break; } } } } // IE8... if ( !matches ) { matches = function( node, selector ) { var nodes, parentNode, i; parentNode = node.parentNode; if ( !parentNode ) { // empty dummy <div> div.innerHTML = ''; parentNode = div; node = node.cloneNode(); div.appendChild( node ); } nodes = parentNode.querySelectorAll( selector ); i = nodes.length; while ( i-- ) { if ( nodes[ i ] === node ) { return true; } } return false; }; } } return matches; }( isClient, vendors, createElement ); /* Ractive/prototype/shared/makeQuery/test.js */ var Ractive$shared_makeQuery_test = function( matches ) { return function( item, noDirty ) { var itemMatches = this._isComponentQuery ? !this.selector || item.name === this.selector : matches( item.node, this.selector ); if ( itemMatches ) { this.push( item.node || item.instance ); if ( !noDirty ) { this._makeDirty(); } return true; } }; }( matches ); /* Ractive/prototype/shared/makeQuery/cancel.js */ var Ractive$shared_makeQuery_cancel = function() { var liveQueries, selector, index; liveQueries = this._root[ this._isComponentQuery ? 'liveComponentQueries' : 'liveQueries' ]; selector = this.selector; index = liveQueries.indexOf( selector ); if ( index !== -1 ) { liveQueries.splice( index, 1 ); liveQueries[ selector ] = null; } }; /* Ractive/prototype/shared/makeQuery/sortByItemPosition.js */ var Ractive$shared_makeQuery_sortByItemPosition = function() { return function( a, b ) { var ancestryA, ancestryB, oldestA, oldestB, mutualAncestor, indexA, indexB, fragments, fragmentA, fragmentB; ancestryA = getAncestry( a.component || a._ractive.proxy ); ancestryB = getAncestry( b.component || b._ractive.proxy ); oldestA = ancestryA[ ancestryA.length - 1 ]; oldestB = ancestryB[ ancestryB.length - 1 ]; // remove items from the end of both ancestries as long as they are identical // - the final one removed is the closest mutual ancestor while ( oldestA && oldestA === oldestB ) { ancestryA.pop(); ancestryB.pop(); mutualAncestor = oldestA; oldestA = ancestryA[ ancestryA.length - 1 ]; oldestB = ancestryB[ ancestryB.length - 1 ]; } // now that we have the mutual ancestor, we can find which is earliest oldestA = oldestA.component || oldestA; oldestB = oldestB.component || oldestB; fragmentA = oldestA.parentFragment; fragmentB = oldestB.parentFragment; // if both items share a parent fragment, our job is easy if ( fragmentA === fragmentB ) { indexA = fragmentA.items.indexOf( oldestA ); indexB = fragmentB.items.indexOf( oldestB ); // if it's the same index, it means one contains the other, // so we see which has the longest ancestry return indexA - indexB || ancestryA.length - ancestryB.length; } // if mutual ancestor is a section, we first test to see which section // fragment comes first if ( fragments = mutualAncestor.fragments ) { indexA = fragments.indexOf( fragmentA ); indexB = fragments.indexOf( fragmentB ); return indexA - indexB || ancestryA.length - ancestryB.length; } throw new Error( 'An unexpected condition was met while comparing the position of two components. Please file an issue at https://github.com/RactiveJS/Ractive/issues - thanks!' ); }; function getParent( item ) { var parentFragment; if ( parentFragment = item.parentFragment ) { return parentFragment.owner; } if ( item.component && ( parentFragment = item.component.parentFragment ) ) { return parentFragment.owner; } } function getAncestry( item ) { var ancestry, ancestor; ancestry = [ item ]; ancestor = getParent( item ); while ( ancestor ) { ancestry.push( ancestor ); ancestor = getParent( ancestor ); } return ancestry; } }(); /* Ractive/prototype/shared/makeQuery/sortByDocumentPosition.js */ var Ractive$shared_makeQuery_sortByDocumentPosition = function( sortByItemPosition ) { return function( node, otherNode ) { var bitmask; if ( node.compareDocumentPosition ) { bitmask = node.compareDocumentPosition( otherNode ); return bitmask & 2 ? 1 : -1; } // In old IE, we can piggy back on the mechanism for // comparing component positions return sortByItemPosition( node, otherNode ); }; }( Ractive$shared_makeQuery_sortByItemPosition ); /* Ractive/prototype/shared/makeQuery/sort.js */ var Ractive$shared_makeQuery_sort = function( sortByDocumentPosition, sortByItemPosition ) { return function() { this.sort( this._isComponentQuery ? sortByItemPosition : sortByDocumentPosition ); this._dirty = false; }; }( Ractive$shared_makeQuery_sortByDocumentPosition, Ractive$shared_makeQuery_sortByItemPosition ); /* Ractive/prototype/shared/makeQuery/dirty.js */ var Ractive$shared_makeQuery_dirty = function( runloop ) { return function() { var this$0 = this; if ( !this._dirty ) { this._dirty = true; // Once the DOM has been updated, ensure the query // is correctly ordered runloop.scheduleTask( function() { this$0._sort(); } ); } }; }( runloop ); /* Ractive/prototype/shared/makeQuery/remove.js */ var Ractive$shared_makeQuery_remove = function( nodeOrComponent ) { var index = this.indexOf( this._isComponentQuery ? nodeOrComponent.instance : nodeOrComponent ); if ( index !== -1 ) { this.splice( index, 1 ); } }; /* Ractive/prototype/shared/makeQuery/_makeQuery.js */ var Ractive$shared_makeQuery__makeQuery = function( defineProperties, test, cancel, sort, dirty, remove ) { return function makeQuery( ractive, selector, live, isComponentQuery ) { var query = []; defineProperties( query, { selector: { value: selector }, live: { value: live }, _isComponentQuery: { value: isComponentQuery }, _test: { value: test } } ); if ( !live ) { return query; } defineProperties( query, { cancel: { value: cancel }, _root: { value: ractive }, _sort: { value: sort }, _makeDirty: { value: dirty }, _remove: { value: remove }, _dirty: { value: false, writable: true } } ); return query; }; }( defineProperties, Ractive$shared_makeQuery_test, Ractive$shared_makeQuery_cancel, Ractive$shared_makeQuery_sort, Ractive$shared_makeQuery_dirty, Ractive$shared_makeQuery_remove ); /* Ractive/prototype/findAll.js */ var Ractive$findAll = function( makeQuery ) { return function Ractive$findAll( selector, options ) { var liveQueries, query; if ( !this.el ) { return []; } options = options || {}; liveQueries = this._liveQueries; // Shortcut: if we're maintaining a live query with this // selector, we don't need to traverse the parallel DOM if ( query = liveQueries[ selector ] ) { // Either return the exact same query, or (if not live) a snapshot return options && options.live ? query : query.slice(); } query = makeQuery( this, selector, !!options.live, false ); // Add this to the list of live queries Ractive needs to maintain, // if applicable if ( query.live ) { liveQueries.push( selector ); liveQueries[ '_' + selector ] = query; } this.fragment.findAll( selector, query ); return query; }; }( Ractive$shared_makeQuery__makeQuery ); /* Ractive/prototype/findAllComponents.js */ var Ractive$findAllComponents = function( makeQuery ) { return function Ractive$findAllComponents( selector, options ) { var liveQueries, query; options = options || {}; liveQueries = this._liveComponentQueries; // Shortcut: if we're maintaining a live query with this // selector, we don't need to traverse the parallel DOM if ( query = liveQueries[ selector ] ) { // Either return the exact same query, or (if not live) a snapshot return options && options.live ? query : query.slice(); } query = makeQuery( this, selector, !!options.live, true ); // Add this to the list of live queries Ractive needs to maintain, // if applicable if ( query.live ) { liveQueries.push( selector ); liveQueries[ '_' + selector ] = query; } this.fragment.findAllComponents( selector, query ); return query; }; }( Ractive$shared_makeQuery__makeQuery ); /* Ractive/prototype/findComponent.js */ var Ractive$findComponent = function Ractive$findComponent( selector ) { return this.fragment.findComponent( selector ); }; /* Ractive/prototype/fire.js */ var Ractive$fire = function Ractive$fire( eventName ) { var args, i, len, subscribers = this._subs[ eventName ]; if ( !subscribers ) { return; } args = Array.prototype.slice.call( arguments, 1 ); for ( i = 0, len = subscribers.length; i < len; i += 1 ) { subscribers[ i ].apply( this, args ); } }; /* Ractive/prototype/get.js */ var Ractive$get = function( normaliseKeypath ) { var options = { capture: true }; // top-level calls should be intercepted return function Ractive$get( keypath ) { keypath = normaliseKeypath( keypath ); return this.viewmodel.get( keypath, options ); }; }( normaliseKeypath ); /* utils/getElement.js */ var getElement = function getElement( input ) { var output; if ( !input || typeof input === 'boolean' ) { return; } if ( typeof window === 'undefined' || !document || !input ) { return null; } // We already have a DOM node - no work to do. (Duck typing alert!) if ( input.nodeType ) { return input; } // Get node from string if ( typeof input === 'string' ) { // try ID first output = document.getElementById( input ); // then as selector, if possible if ( !output && document.querySelector ) { output = document.querySelector( input ); } // did it work? if ( output && output.nodeType ) { return output; } } // If we've been given a collection (jQuery, Zepto etc), extract the first item if ( input[ 0 ] && input[ 0 ].nodeType ) { return input[ 0 ]; } return null; }; /* Ractive/prototype/insert.js */ var Ractive$insert = function( getElement ) { return function Ractive$insert( target, anchor ) { if ( !this.rendered ) { // TODO create, and link to, documentation explaining this throw new Error( 'The API has changed - you must call `ractive.render(target[, anchor])` to render your Ractive instance. Once rendered you can use `ractive.insert()`.' ); } target = getElement( target ); anchor = getElement( anchor ) || null; if ( !target ) { throw new Error( 'You must specify a valid target to insert into' ); } target.insertBefore( this.detach(), anchor ); this.el = target; ( target.__ractive_instances__ || ( target.__ractive_instances__ = [] ) ).push( this ); }; }( getElement ); /* Ractive/prototype/merge.js */ var Ractive$merge = function( runloop, isArray, normaliseKeypath ) { return function Ractive$merge( keypath, array, options ) { var currentArray, promise; keypath = normaliseKeypath( keypath ); currentArray = this.viewmodel.get( keypath ); // If either the existing value or the new value isn't an // array, just do a regular set if ( !isArray( currentArray ) || !isArray( array ) ) { return this.set( keypath, array, options && options.complete ); } // Manage transitions promise = runloop.start( this, true ); this.viewmodel.merge( keypath, currentArray, array, options ); runloop.end(); // attach callback as fulfilment handler, if specified if ( options && options.complete ) { promise.then( options.complete ); } return promise; }; }( runloop, isArray, normaliseKeypath ); /* Ractive/prototype/observe/Observer.js */ var Ractive$observe_Observer = function( runloop, isEqual ) { var Observer = function( ractive, keypath, callback, options ) { this.root = ractive; this.keypath = keypath; this.callback = callback; this.defer = options.defer; // Observers are notified before any DOM changes take place (though // they can defer execution until afterwards) this.priority = 0; // default to root as context, but allow it to be overridden this.context = options && options.context ? options.context : ractive; }; Observer.prototype = { init: function( immediate ) { this.value = this.root.viewmodel.get( this.keypath ); if ( immediate !== false ) { this.update(); } }, setValue: function( value ) { var this$0 = this; if ( !isEqual( value, this.value ) ) { this.value = value; if ( this.defer && this.ready ) { runloop.scheduleTask( function() { return this$0.update(); } ); } else { this.update(); } } }, update: function() { // Prevent infinite loops if ( this.updating ) { return; } this.updating = true; this.callback.call( this.context, this.value, this.oldValue, this.keypath ); this.oldValue = this.value; this.updating = false; } }; return Observer; }( runloop, isEqual ); /* shared/getMatchingKeypaths.js */ var getMatchingKeypaths = function( isArray ) { return function getMatchingKeypaths( ractive, pattern ) { var keys, key, matchingKeypaths; keys = pattern.split( '.' ); matchingKeypaths = [ '' ]; while ( key = keys.shift() ) { if ( key === '*' ) { // expand to find all valid child keypaths matchingKeypaths = matchingKeypaths.reduce( expand, [] ); } else { if ( matchingKeypaths[ 0 ] === '' ) { // first key matchingKeypaths[ 0 ] = key; } else { matchingKeypaths = matchingKeypaths.map( concatenate( key ) ); } } } return matchingKeypaths; function expand( matchingKeypaths, keypath ) { var value, key, childKeypath; value = ractive.viewmodel.wrapped[ keypath ] ? ractive.viewmodel.wrapped[ keypath ].get() : ractive.get( keypath ); for ( key in value ) { if ( value.hasOwnProperty( key ) && ( key !== '_ractive' || !isArray( value ) ) ) { // for benefit of IE8 childKeypath = keypath ? keypath + '.' + key : key; matchingKeypaths.push( childKeypath ); } } return matchingKeypaths; } function concatenate( key ) { return function( keypath ) { return keypath ? keypath + '.' + key : key; }; } }; }( isArray ); /* Ractive/prototype/observe/getPattern.js */ var Ractive$observe_getPattern = function( getMatchingKeypaths ) { return function getPattern( ractive, pattern ) { var matchingKeypaths, values; matchingKeypaths = getMatchingKeypaths( ractive, pattern ); values = {}; matchingKeypaths.forEach( function( keypath ) { values[ keypath ] = ractive.get( keypath ); } ); return values; }; }( getMatchingKeypaths ); /* Ractive/prototype/observe/PatternObserver.js */ var Ractive$observe_PatternObserver = function( runloop, isEqual, getPattern ) { var PatternObserver, wildcard = /\*/, slice = Array.prototype.slice; PatternObserver = function( ractive, keypath, callback, options ) { this.root = ractive; this.callback = callback; this.defer = options.defer; this.keypath = keypath; this.regex = new RegExp( '^' + keypath.replace( /\./g, '\\.' ).replace( /\*/g, '([^\\.]+)' ) + '$' ); this.values = {}; if ( this.defer ) { this.proxies = []; } // Observers are notified before any DOM changes take place (though // they can defer execution until afterwards) this.priority = 'pattern'; // default to root as context, but allow it to be overridden this.context = options && options.context ? options.context : ractive; }; PatternObserver.prototype = { init: function( immediate ) { var values, keypath; values = getPattern( this.root, this.keypath ); if ( immediate !== false ) { for ( keypath in values ) { if ( values.hasOwnProperty( keypath ) ) { this.update( keypath ); } } } else { this.values = values; } }, update: function( keypath ) { var values; if ( wildcard.test( keypath ) ) { values = getPattern( this.root, keypath ); for ( keypath in values ) { if ( values.hasOwnProperty( keypath ) ) { this.update( keypath ); } } return; } // special case - array mutation should not trigger `array.*` // pattern observer with `array.length` if ( this.root.viewmodel.implicitChanges[ keypath ] ) { return; } if ( this.defer && this.ready ) { runloop.addObserver( this.getProxy( keypath ) ); return; } this.reallyUpdate( keypath ); }, reallyUpdate: function( keypath ) { var value, keys, args; value = this.root.viewmodel.get( keypath ); // Prevent infinite loops if ( this.updating ) { this.values[ keypath ] = value; return; } this.updating = true; if ( !isEqual( value, this.values[ keypath ] ) || !this.ready ) { keys = slice.call( this.regex.exec( keypath ), 1 ); args = [ value, this.values[ keypath ], keypath ].concat( keys ); this.callback.apply( this.context, args ); this.values[ keypath ] = value; } this.updating = false; }, getProxy: function( keypath ) { var self = this; if ( !this.proxies[ keypath ] ) { this.proxies[ keypath ] = { update: function() { self.reallyUpdate( keypath ); } }; } return this.proxies[ keypath ]; } }; return PatternObserver; }( runloop, isEqual, Ractive$observe_getPattern ); /* Ractive/prototype/observe/getObserverFacade.js */ var Ractive$observe_getObserverFacade = function( normaliseKeypath, Observer, PatternObserver ) { var wildcard = /\*/, emptyObject = {}; return function getObserverFacade( ractive, keypath, callback, options ) { var observer, isPatternObserver, cancelled; keypath = normaliseKeypath( keypath ); options = options || emptyObject; // pattern observers are treated differently if ( wildcard.test( keypath ) ) { observer = new PatternObserver( ractive, keypath, callback, options ); ractive.viewmodel.patternObservers.push( observer ); isPatternObserver = true; } else { observer = new Observer( ractive, keypath, callback, options ); } ractive.viewmodel.register( keypath, observer, isPatternObserver ? 'patternObservers' : 'observers' ); observer.init( options.init ); // This flag allows observers to initialise even with undefined values observer.ready = true; return { cancel: function() { var index; if ( cancelled ) { return; } if ( isPatternObserver ) { index = ractive.viewmodel.patternObservers.indexOf( observer ); ractive.viewmodel.patternObservers.splice( index, 1 ); ractive.viewmodel.unregister( keypath, observer, 'patternObservers' ); } ractive.viewmodel.unregister( keypath, observer, 'observers' ); cancelled = true; } }; }; }( normaliseKeypath, Ractive$observe_Observer, Ractive$observe_PatternObserver ); /* Ractive/prototype/observe.js */ var Ractive$observe = function( isObject, getObserverFacade ) { return function Ractive$observe( keypath, callback, options ) { var observers, map, keypaths, i; // Allow a map of keypaths to handlers if ( isObject( keypath ) ) { options = callback; map = keypath; observers = []; for ( keypath in map ) { if ( map.hasOwnProperty( keypath ) ) { callback = map[ keypath ]; observers.push( this.observe( keypath, callback, options ) ); } } return { cancel: function() { while ( observers.length ) { observers.pop().cancel(); } } }; } // Allow `ractive.observe( callback )` - i.e. observe entire model if ( typeof keypath === 'function' ) { options = callback; callback = keypath; keypath = ''; return getObserverFacade( this, keypath, callback, options ); } keypaths = keypath.split( ' ' ); // Single keypath if ( keypaths.length === 1 ) { return getObserverFacade( this, keypath, callback, options ); } // Multiple space-separated keypaths observers = []; i = keypaths.length; while ( i-- ) { keypath = keypaths[ i ]; if ( keypath ) { observers.push( getObserverFacade( this, keypath, callback, options ) ); } } return { cancel: function() { while ( observers.length ) { observers.pop().cancel(); } } }; }; }( isObject, Ractive$observe_getObserverFacade ); /* Ractive/prototype/shared/trim.js */ var Ractive$shared_trim = function( str ) { return str.trim(); }; /* Ractive/prototype/shared/notEmptyString.js */ var Ractive$shared_notEmptyString = function( str ) { return str !== ''; }; /* Ractive/prototype/off.js */ var Ractive$off = function( trim, notEmptyString ) { return function Ractive$off( eventName, callback ) { var this$0 = this; var eventNames; // if no arguments specified, remove all callbacks if ( !eventName ) { // TODO use this code instead, once the following issue has been resolved // in PhantomJS (tests are unpassable otherwise!) // https://github.com/ariya/phantomjs/issues/11856 // defineProperty( this, '_subs', { value: create( null ), configurable: true }); for ( eventName in this._subs ) { delete this._subs[ eventName ]; } } else { // Handle multiple space-separated event names eventNames = eventName.split( ' ' ).map( trim ).filter( notEmptyString ); eventNames.forEach( function( eventName ) { var subscribers, index; // If we have subscribers for this event... if ( subscribers = this$0._subs[ eventName ] ) { // ...if a callback was specified, only remove that if ( callback ) { index = subscribers.indexOf( callback ); if ( index !== -1 ) { subscribers.splice( index, 1 ); } } else { this$0._subs[ eventName ] = []; } } } ); } return this; }; }( Ractive$shared_trim, Ractive$shared_notEmptyString ); /* Ractive/prototype/on.js */ var Ractive$on = function( trim, notEmptyString ) { return function Ractive$on( eventName, callback ) { var this$0 = this; var self = this, listeners, n, eventNames; // allow mutliple listeners to be bound in one go if ( typeof eventName === 'object' ) { listeners = []; for ( n in eventName ) { if ( eventName.hasOwnProperty( n ) ) { listeners.push( this.on( n, eventName[ n ] ) ); } } return { cancel: function() { var listener; while ( listener = listeners.pop() ) { listener.cancel(); } } }; } // Handle multiple space-separated event names eventNames = eventName.split( ' ' ).map( trim ).filter( notEmptyString ); eventNames.forEach( function( eventName ) { ( this$0._subs[ eventName ] || ( this$0._subs[ eventName ] = [] ) ).push( callback ); } ); return { cancel: function() { self.off( eventName, callback ); } }; }; }( Ractive$shared_trim, Ractive$shared_notEmptyString ); /* shared/getSpliceEquivalent.js */ var getSpliceEquivalent = function( array, methodName, args ) { switch ( methodName ) { case 'splice': return args; case 'sort': case 'reverse': return null; case 'pop': if ( array.length ) { return [ -1 ]; } return null; case 'push': return [ array.length, 0 ].concat( args ); case 'shift': return [ 0, 1 ]; case 'unshift': return [ 0, 0 ].concat( args ); } }; /* shared/summariseSpliceOperation.js */ var summariseSpliceOperation = function( array, args ) { var rangeStart, rangeEnd, newLength, addedItems, removedItems, balance; if ( !args ) { return null; } // figure out where the changes started... rangeStart = +( args[ 0 ] < 0 ? array.length + args[ 0 ] : args[ 0 ] ); // ...and how many items were added to or removed from the array addedItems = Math.max( 0, args.length - 2 ); removedItems = args[ 1 ] !== undefined ? args[ 1 ] : array.length - rangeStart; // It's possible to do e.g. [ 1, 2, 3 ].splice( 2, 2 ) - i.e. the second argument // means removing more items from the end of the array than there are. In these // cases we need to curb JavaScript's enthusiasm or we'll get out of sync removedItems = Math.min( removedItems, array.length - rangeStart ); balance = addedItems - removedItems; newLength = array.length + balance; // We need to find the end of the range affected by the splice if ( !balance ) { rangeEnd = rangeStart + addedItems; } else { rangeEnd = Math.max( array.length, newLength ); } return { rangeStart: rangeStart, rangeEnd: rangeEnd, balance: balance, added: addedItems, removed: removedItems }; }; /* Ractive/prototype/shared/makeArrayMethod.js */ var Ractive$shared_makeArrayMethod = function( isArray, runloop, getSpliceEquivalent, summariseSpliceOperation ) { var arrayProto = Array.prototype; return function( methodName ) { return function( keypath ) { var SLICE$0 = Array.prototype.slice; var args = SLICE$0.call( arguments, 1 ); var array, spliceEquivalent, spliceSummary, promise; array = this.get( keypath ); if ( !isArray( array ) ) { throw new Error( 'Called ractive.' + methodName + '(\'' + keypath + '\'), but \'' + keypath + '\' does not refer to an array' ); } spliceEquivalent = getSpliceEquivalent( array, methodName, args ); spliceSummary = summariseSpliceOperation( array, spliceEquivalent ); arrayProto[ methodName ].apply( array, args ); promise = runloop.start( this, true ); if ( spliceSummary ) { this.viewmodel.splice( keypath, spliceSummary ); } else { this.viewmodel.mark( keypath ); } runloop.end(); return promise; }; }; }( isArray, runloop, getSpliceEquivalent, summariseSpliceOperation ); /* Ractive/prototype/pop.js */ var Ractive$pop = function( makeArrayMethod ) { return makeArrayMethod( 'pop' ); }( Ractive$shared_makeArrayMethod ); /* Ractive/prototype/push.js */ var Ractive$push = function( makeArrayMethod ) { return makeArrayMethod( 'push' ); }( Ractive$shared_makeArrayMethod ); /* global/css.js */ var global_css = function( circular, isClient, removeFromArray ) { var css, update, runloop, styleElement, head, styleSheet, inDom, prefix = '/* Ractive.js component styles */\n', componentsInPage = {}, styles = []; if ( !isClient ) { css = null; } else { circular.push( function() { runloop = circular.runloop; } ); styleElement = document.createElement( 'style' ); styleElement.type = 'text/css'; head = document.getElementsByTagName( 'head' )[ 0 ]; inDom = false; // Internet Exploder won't let you use styleSheet.innerHTML - we have to // use styleSheet.cssText instead styleSheet = styleElement.styleSheet; update = function() { var css; if ( styles.length ) { css = prefix + styles.join( ' ' ); if ( styleSheet ) { styleSheet.cssText = css; } else { styleElement.innerHTML = css; } if ( !inDom ) { head.appendChild( styleElement ); inDom = true; } } else if ( inDom ) { head.removeChild( styleElement ); inDom = false; } }; css = { add: function( Component ) { if ( !Component.css ) { return; } if ( !componentsInPage[ Component._guid ] ) { // we create this counter so that we can in/decrement it as // instances are added and removed. When all components are // removed, the style is too componentsInPage[ Component._guid ] = 0; styles.push( Component.css ); runloop.scheduleTask( update ); } componentsInPage[ Component._guid ] += 1; }, remove: function( Component ) { if ( !Component.css ) { return; } componentsInPage[ Component._guid ] -= 1; if ( !componentsInPage[ Component._guid ] ) { removeFromArray( styles, Component.css ); runloop.scheduleTask( update ); } } }; } return css; }( circular, isClient, removeFromArray ); /* Ractive/prototype/render.js */ var Ractive$render = function( runloop, css, getElement ) { var queues = {}, rendering = {}; return function Ractive$render( target, anchor ) { var this$0 = this; var promise, instances; rendering[ this._guid ] = true; promise = runloop.start( this, true ); if ( this.rendered ) { throw new Error( 'You cannot call ractive.render() on an already rendered instance! Call ractive.unrender() first' ); } target = getElement( target ) || this.el; anchor = getElement( anchor ) || this.anchor; this.el = target; this.anchor = anchor; // Add CSS, if applicable if ( this.constructor.css ) { css.add( this.constructor ); } if ( target ) { if ( !( instances = target.__ractive_instances__ ) ) { target.__ractive_instances__ = [ this ]; } else { instances.push( this ); } if ( anchor ) { target.insertBefore( this.fragment.render(), anchor ); } else { target.appendChild( this.fragment.render() ); } } // Only init once, until we rework lifecycle events if ( !this._hasInited ) { this._hasInited = true; // If this is *isn't* a child of a component that's in the process of rendering, // it should call any `init()` methods at this point if ( !this._parent || !rendering[ this._parent._guid ] ) { init( this ); } else { getChildInitQueue( this._parent ).push( this ); } } rendering[ this._guid ] = false; runloop.end(); this.rendered = true; if ( this.complete ) { promise.then( function() { return this$0.complete(); } ); } return promise; }; function init( instance ) { if ( instance.init ) { instance.init( instance._config.options ); } getChildInitQueue( instance ).forEach( init ); queues[ instance._guid ] = null; } function getChildInitQueue( instance ) { return queues[ instance._guid ] || ( queues[ instance._guid ] = [] ); } }( runloop, global_css, getElement ); /* virtualdom/Fragment/prototype/bubble.js */ var virtualdom_Fragment$bubble = function Fragment$bubble() { this.dirtyValue = this.dirtyArgs = true; if ( this.inited && this.owner.bubble ) { this.owner.bubble(); } }; /* virtualdom/Fragment/prototype/detach.js */ var virtualdom_Fragment$detach = function Fragment$detach() { var docFrag; if ( this.items.length === 1 ) { return this.items[ 0 ].detach(); } docFrag = document.createDocumentFragment(); this.items.forEach( function( item ) { docFrag.appendChild( item.detach() ); } ); return docFrag; }; /* virtualdom/Fragment/prototype/find.js */ var virtualdom_Fragment$find = function Fragment$find( selector ) { var i, len, item, queryResult; if ( this.items ) { len = this.items.length; for ( i = 0; i < len; i += 1 ) { item = this.items[ i ]; if ( item.find && ( queryResult = item.find( selector ) ) ) { return queryResult; } } return null; } }; /* virtualdom/Fragment/prototype/findAll.js */ var virtualdom_Fragment$findAll = function Fragment$findAll( selector, query ) { var i, len, item; if ( this.items ) { len = this.items.length; for ( i = 0; i < len; i += 1 ) { item = this.items[ i ]; if ( item.findAll ) { item.findAll( selector, query ); } } } return query; }; /* virtualdom/Fragment/prototype/findAllComponents.js */ var virtualdom_Fragment$findAllComponents = function Fragment$findAllComponents( selector, query ) { var i, len, item; if ( this.items ) { len = this.items.length; for ( i = 0; i < len; i += 1 ) { item = this.items[ i ]; if ( item.findAllComponents ) { item.findAllComponents( selector, query ); } } } return query; }; /* virtualdom/Fragment/prototype/findComponent.js */ var virtualdom_Fragment$findComponent = function Fragment$findComponent( selector ) { var len, i, item, queryResult; if ( this.items ) { len = this.items.length; for ( i = 0; i < len; i += 1 ) { item = this.items[ i ]; if ( item.findComponent && ( queryResult = item.findComponent( selector ) ) ) { return queryResult; } } return null; } }; /* virtualdom/Fragment/prototype/findNextNode.js */ var virtualdom_Fragment$findNextNode = function Fragment$findNextNode( item ) { var index = item.index, node; if ( this.items[ index + 1 ] ) { node = this.items[ index + 1 ].firstNode(); } else if ( this.owner === this.root ) { if ( !this.owner.component ) { // TODO but something else could have been appended to // this.root.el, no? node = null; } else { node = this.owner.component.findNextNode(); } } else { node = this.owner.findNextNode( this ); } return node; }; /* virtualdom/Fragment/prototype/firstNode.js */ var virtualdom_Fragment$firstNode = function Fragment$firstNode() { if ( this.items && this.items[ 0 ] ) { return this.items[ 0 ].firstNode(); } return null; }; /* virtualdom/Fragment/prototype/getNode.js */ var virtualdom_Fragment$getNode = function Fragment$getNode() { var fragment = this; do { if ( fragment.pElement ) { return fragment.pElement.node; } } while ( fragment = fragment.parent ); return this.root.el; }; /* virtualdom/Fragment/prototype/getValue.js */ var virtualdom_Fragment$getValue = function( parseJSON ) { var empty = {}; return function Fragment$getValue() { var options = arguments[ 0 ]; if ( options === void 0 ) options = empty; var asArgs, values, source, parsed, cachedResult, dirtyFlag, result; asArgs = options.args; cachedResult = asArgs ? 'argsList' : 'value'; dirtyFlag = asArgs ? 'dirtyArgs' : 'dirtyValue'; if ( this[ dirtyFlag ] ) { source = processItems( this.items, values = {}, this.root._guid ); parsed = parseJSON( asArgs ? '[' + source + ']' : source, values ); if ( !parsed ) { result = asArgs ? [ this.toString() ] : this.toString(); } else { result = parsed.value; } this[ cachedResult ] = result; this[ dirtyFlag ] = false; } return this[ cachedResult ]; }; function processItems( items, values, guid, counter ) { counter = counter || 0; return items.map( function( item ) { var placeholderId, wrapped, value; if ( item.text ) { return item.text; } if ( item.fragments ) { return item.fragments.map( function( fragment ) { return processItems( fragment.items, values, guid, counter ); } ).join( '' ); } placeholderId = guid + '-' + counter++; if ( wrapped = item.root.viewmodel.wrapped[ item.keypath ] ) { value = wrapped.value; } else { value = item.getValue(); } values[ placeholderId ] = value; return '${' + placeholderId + '}'; } ).join( '' ); } }( parseJSON ); /* utils/escapeHtml.js */ var escapeHtml = function() { var lessThan = /</g, greaterThan = />/g; return function escapeHtml( str ) { return str.replace( lessThan, '&lt;' ).replace( greaterThan, '&gt;' ); }; }(); /* utils/detachNode.js */ var detachNode = function detachNode( node ) { if ( node && node.parentNode ) { node.parentNode.removeChild( node ); } return node; }; /* virtualdom/items/shared/detach.js */ var detach = function( detachNode ) { return function() { return detachNode( this.node ); }; }( detachNode ); /* virtualdom/items/Text.js */ var Text = function( types, escapeHtml, detach ) { var Text = function( options ) { this.type = types.TEXT; this.text = options.template; }; Text.prototype = { detach: detach, firstNode: function() { return this.node; }, render: function() { if ( !this.node ) { this.node = document.createTextNode( this.text ); } return this.node; }, toString: function( escape ) { return escape ? escapeHtml( this.text ) : this.text; }, unrender: function( shouldDestroy ) { if ( shouldDestroy ) { return this.detach(); } } }; return Text; }( types, escapeHtml, detach ); /* virtualdom/items/shared/unbind.js */ var unbind = function( runloop ) { return function unbind() { if ( !this.keypath ) { // this was on the 'unresolved' list, we need to remove it runloop.removeUnresolved( this ); } else { // this was registered as a dependant this.root.viewmodel.unregister( this.keypath, this ); } if ( this.resolver ) { this.resolver.teardown(); } }; }( runloop ); /* virtualdom/items/shared/Mustache/getValue.js */ var getValue = function Mustache$getValue() { return this.value; }; /* shared/Unresolved.js */ var Unresolved = function( runloop ) { var Unresolved = function( ractive, ref, parentFragment, callback ) { this.root = ractive; this.ref = ref; this.parentFragment = parentFragment; this.resolve = callback; runloop.addUnresolved( this ); }; Unresolved.prototype = { teardown: function() { runloop.removeUnresolved( this ); } }; return Unresolved; }( runloop ); /* virtualdom/items/shared/utils/startsWithKeypath.js */ var startsWithKeypath = function startsWithKeypath( target, keypath ) { return target.substr( 0, keypath.length + 1 ) === keypath + '.'; }; /* virtualdom/items/shared/utils/getNewKeypath.js */ var getNewKeypath = function( startsWithKeypath ) { return function getNewKeypath( targetKeypath, oldKeypath, newKeypath ) { // exact match if ( targetKeypath === oldKeypath ) { return newKeypath; } // partial match based on leading keypath segments if ( startsWithKeypath( targetKeypath, oldKeypath ) ) { return targetKeypath.replace( oldKeypath + '.', newKeypath + '.' ); } }; }( startsWithKeypath ); /* utils/log.js */ var log = function( consolewarn, errors ) { var log = { warn: function( options, passthru ) { if ( !options.debug && !passthru ) { return; } this.logger( getMessage( options ), options.allowDuplicates ); }, error: function( options ) { this.errorOnly( options ); if ( !options.debug ) { this.warn( options, true ); } }, errorOnly: function( options ) { if ( options.debug ) { this.critical( options ); } }, critical: function( options ) { var err = options.err || new Error( getMessage( options ) ); this.thrower( err ); }, logger: consolewarn, thrower: function( err ) { throw err; } }; function getMessage( options ) { var message = errors[ options.message ] || options.message || ''; return interpolate( message, options.args ); } // simple interpolation. probably quicker (and better) out there, // but log is not in golden path of execution, only exceptions function interpolate( message, args ) { return message.replace( /{([^{}]*)}/g, function( a, b ) { return args[ b ]; } ); } return log; }( warn, errors ); /* viewmodel/Computation/diff.js */ var diff = function diff( computation, dependencies, newDependencies ) { var i, keypath; // remove dependencies that are no longer used i = dependencies.length; while ( i-- ) { keypath = dependencies[ i ]; if ( newDependencies.indexOf( keypath ) === -1 ) { computation.viewmodel.unregister( keypath, computation, 'computed' ); } } // create references for any new dependencies i = newDependencies.length; while ( i-- ) { keypath = newDependencies[ i ]; if ( dependencies.indexOf( keypath ) === -1 ) { computation.viewmodel.register( keypath, computation, 'computed' ); } } computation.dependencies = newDependencies.slice(); }; /* virtualdom/items/shared/Evaluator/Evaluator.js */ var Evaluator = function( log, isEqual, defineProperty, diff ) { // TODO this is a red flag... should be treated the same? var Evaluator, cache = {}; Evaluator = function( root, keypath, uniqueString, functionStr, args, priority ) { var evaluator = this, viewmodel = root.viewmodel; evaluator.root = root; evaluator.viewmodel = viewmodel; evaluator.uniqueString = uniqueString; evaluator.keypath = keypath; evaluator.priority = priority; evaluator.fn = getFunctionFromString( functionStr, args.length ); evaluator.explicitDependencies = []; evaluator.dependencies = []; // created by `this.get()` within functions evaluator.argumentGetters = args.map( function( arg ) { var keypath, index; if ( !arg ) { return void 0; } if ( arg.indexRef ) { index = arg.value; return index; } keypath = arg.keypath; evaluator.explicitDependencies.push( keypath ); viewmodel.register( keypath, evaluator, 'computed' ); return function() { var value = viewmodel.get( keypath ); return typeof value === 'function' ? wrap( value, root ) : value; }; } ); }; Evaluator.prototype = { wake: function() { this.awake = true; }, sleep: function() { this.awake = false; }, getValue: function() { var args, value, newImplicitDependencies; args = this.argumentGetters.map( call ); if ( this.updating ) { // Prevent infinite loops caused by e.g. in-place array mutations return; } this.updating = true; this.viewmodel.capture(); try { value = this.fn.apply( null, args ); } catch ( err ) { if ( this.root.debug ) { log.warn( { debug: this.root.debug, message: 'evaluationError', args: { uniqueString: this.uniqueString, err: err.message || err } } ); } value = undefined; } newImplicitDependencies = this.viewmodel.release(); diff( this, this.dependencies, newImplicitDependencies ); this.updating = false; return value; }, update: function() { var value = this.getValue(); if ( !isEqual( value, this.value ) ) { this.value = value; this.root.viewmodel.mark( this.keypath ); } return this; }, // TODO should evaluators ever get torn down? At present, they don't... teardown: function() { var this$0 = this; this.explicitDependencies.concat( this.dependencies ).forEach( function( keypath ) { return this$0.viewmodel.unregister( keypath, this$0, 'computed' ); } ); this.root.viewmodel.evaluators[ this.keypath ] = null; } }; return Evaluator; function getFunctionFromString( str, i ) { var fn, args; str = str.replace( /\$\{([0-9]+)\}/g, '_$1' ); if ( cache[ str ] ) { return cache[ str ]; } args = []; while ( i-- ) { args[ i ] = '_' + i; } fn = new Function( args.join( ',' ), 'return(' + str + ')' ); cache[ str ] = fn; return fn; } function wrap( fn, ractive ) { var wrapped, prop; if ( fn._noWrap ) { return fn; } prop = '__ractive_' + ractive._guid; wrapped = fn[ prop ]; if ( wrapped ) { return wrapped; } else if ( /this/.test( fn.toString() ) ) { defineProperty( fn, prop, { value: fn.bind( ractive ) } ); return fn[ prop ]; } defineProperty( fn, '__ractive_nowrap', { value: fn } ); return fn.__ractive_nowrap; } function call( arg ) { return typeof arg === 'function' ? arg() : arg; } }( log, isEqual, defineProperty, diff ); /* virtualdom/items/shared/Resolvers/ExpressionResolver.js */ var ExpressionResolver = function( removeFromArray, resolveRef, Unresolved, Evaluator, getNewKeypath ) { var ExpressionResolver = function( owner, parentFragment, expression, callback ) { var expressionResolver = this, ractive, indexRefs, args; ractive = owner.root; this.root = ractive; this.callback = callback; this.owner = owner; this.str = expression.s; this.args = args = []; this.unresolved = []; this.pending = 0; indexRefs = parentFragment.indexRefs; // some expressions don't have references. edge case, but, yeah. if ( !expression.r || !expression.r.length ) { this.resolved = this.ready = true; this.bubble(); return; } // Create resolvers for each reference expression.r.forEach( function( reference, i ) { var index, keypath, unresolved; // Is this an index reference? if ( indexRefs && ( index = indexRefs[ reference ] ) !== undefined ) { args[ i ] = { indexRef: reference, value: index }; return; } // Can we resolve it immediately? if ( keypath = resolveRef( ractive, reference, parentFragment ) ) { args[ i ] = { keypath: keypath }; return; } // Couldn't resolve yet args[ i ] = null; expressionResolver.pending += 1; unresolved = new Unresolved( ractive, reference, parentFragment, function( keypath ) { expressionResolver.resolve( i, keypath ); removeFromArray( expressionResolver.unresolved, unresolved ); } ); expressionResolver.unresolved.push( unresolved ); } ); this.ready = true; this.bubble(); }; ExpressionResolver.prototype = { bubble: function() { if ( !this.ready ) { return; } this.uniqueString = getUniqueString( this.str, this.args ); this.keypath = getKeypath( this.uniqueString ); this.createEvaluator(); this.callback( this.keypath ); }, teardown: function() { var unresolved; while ( unresolved = this.unresolved.pop() ) { unresolved.teardown(); } }, resolve: function( index, keypath ) { this.args[ index ] = { keypath: keypath }; this.bubble(); // when all references have been resolved, we can flag the entire expression // as having been resolved this.resolved = !--this.pending; }, createEvaluator: function() { var evaluator = this.root.viewmodel.evaluators[ this.keypath ]; // only if it doesn't exist yet! if ( !evaluator ) { evaluator = new Evaluator( this.root, this.keypath, this.uniqueString, this.str, this.args, this.owner.priority ); this.root.viewmodel.evaluators[ this.keypath ] = evaluator; } evaluator.update(); }, rebind: function( indexRef, newIndex, oldKeypath, newKeypath ) { var changed; this.args.forEach( function( arg ) { var changedKeypath; if ( !arg ) return; if ( arg.keypath && ( changedKeypath = getNewKeypath( arg.keypath, oldKeypath, newKeypath ) ) ) { arg.keypath = changedKeypath; changed = true; } else if ( arg.indexRef && arg.indexRef === indexRef ) { arg.value = newIndex; changed = true; } } ); if ( changed ) { this.bubble(); } } }; return ExpressionResolver; function getUniqueString( str, args ) { // get string that is unique to this expression return str.replace( /\$\{([0-9]+)\}/g, function( match, $1 ) { var arg = args[ $1 ]; if ( !arg ) return 'undefined'; if ( arg.indexRef ) return arg.value; return arg.keypath; } ); } function getKeypath( uniqueString ) { // Sanitize by removing any periods or square brackets. Otherwise // we can't split the keypath into keys! return '${' + uniqueString.replace( /[\.\[\]]/g, '-' ) + '}'; } }( removeFromArray, resolveRef, Unresolved, Evaluator, getNewKeypath ); /* virtualdom/items/shared/Resolvers/ReferenceExpressionResolver/MemberResolver.js */ var MemberResolver = function( types, resolveRef, Unresolved, getNewKeypath, ExpressionResolver ) { var MemberResolver = function( template, resolver, parentFragment ) { var member = this, ref, indexRefs, index, ractive, keypath; member.resolver = resolver; member.root = resolver.root; member.viewmodel = resolver.root.viewmodel; if ( typeof template === 'string' ) { member.value = template; } else if ( template.t === types.REFERENCE ) { ref = member.ref = template.n; // If it's an index reference, our job is simple if ( ( indexRefs = parentFragment.indexRefs ) && ( index = indexRefs[ ref ] ) !== undefined ) { member.indexRef = ref; member.value = index; } else { ractive = resolver.root; // Can we resolve the reference immediately? if ( keypath = resolveRef( ractive, ref, parentFragment ) ) { member.resolve( keypath ); } else { // Couldn't resolve yet member.unresolved = new Unresolved( ractive, ref, parentFragment, function( keypath ) { member.unresolved = null; member.resolve( keypath ); } ); } } } else { new ExpressionResolver( resolver, parentFragment, template, function( keypath ) { member.resolve( keypath ); } ); } }; MemberResolver.prototype = { resolve: function( keypath ) { this.keypath = keypath; this.value = this.viewmodel.get( keypath ); this.bind(); this.resolver.bubble(); }, bind: function() { this.viewmodel.register( this.keypath, this ); }, rebind: function( indexRef, newIndex, oldKeypath, newKeypath ) { var keypath; if ( indexRef && this.indexRef === indexRef ) { if ( newIndex !== this.value ) { this.value = newIndex; return true; } } else if ( this.keypath && ( keypath = getNewKeypath( this.keypath, oldKeypath, newKeypath ) ) ) { this.unbind(); this.keypath = keypath; this.value = this.root.viewmodel.get( keypath ); this.bind(); return true; } }, setValue: function( value ) { this.value = value; this.resolver.bubble(); }, unbind: function() { if ( this.keypath ) { this.root.viewmodel.unregister( this.keypath, this ); } }, teardown: function() { this.unbind(); if ( this.unresolved ) { this.unresolved.teardown(); } }, forceResolution: function() { if ( this.unresolved ) { this.unresolved.teardown(); this.unresolved = null; this.keypath = this.ref; this.value = this.viewmodel.get( this.ref ); this.bind(); } } }; return MemberResolver; }( types, resolveRef, Unresolved, getNewKeypath, ExpressionResolver ); /* virtualdom/items/shared/Resolvers/ReferenceExpressionResolver/ReferenceExpressionResolver.js */ var ReferenceExpressionResolver = function( resolveRef, Unresolved, MemberResolver ) { var ReferenceExpressionResolver = function( mustache, template, callback ) { var this$0 = this; var resolver = this, ractive, ref, keypath, parentFragment; parentFragment = mustache.parentFragment; resolver.root = ractive = mustache.root; resolver.mustache = mustache; resolver.priority = mustache.priority; resolver.ref = ref = template.r; resolver.callback = callback; resolver.unresolved = []; // Find base keypath if ( keypath = resolveRef( ractive, ref, parentFragment ) ) { resolver.base = keypath; } else { resolver.baseResolver = new Unresolved( ractive, ref, parentFragment, function( keypath ) { resolver.base = keypath; resolver.baseResolver = null; resolver.bubble(); } ); } // Find values for members, or mark them as unresolved resolver.members = template.m.map( function( template ) { return new MemberResolver( template, this$0, parentFragment ); } ); resolver.ready = true; resolver.bubble(); }; ReferenceExpressionResolver.prototype = { getKeypath: function() { var values = this.members.map( getValue ); if ( !values.every( isDefined ) || this.baseResolver ) { return; } return this.base + '.' + values.join( '.' ); }, bubble: function() { if ( !this.ready || this.baseResolver ) { return; } this.callback( this.getKeypath() ); }, teardown: function() { this.members.forEach( unbind ); }, rebind: function( indexRef, newIndex, oldKeypath, newKeypath ) { var changed; this.members.forEach( function( members ) { if ( members.rebind( indexRef, newIndex, oldKeypath, newKeypath ) ) { changed = true; } } ); if ( changed ) { this.bubble(); } }, forceResolution: function() { if ( this.baseResolver ) { this.base = this.ref; this.baseResolver.teardown(); this.baseResolver = null; } this.members.forEach( function( m ) { return m.forceResolution(); } ); this.bubble(); } }; function getValue( member ) { return member.value; } function isDefined( value ) { return value != undefined; } function unbind( member ) { member.unbind(); } return ReferenceExpressionResolver; }( resolveRef, Unresolved, MemberResolver ); /* virtualdom/items/shared/Mustache/initialise.js */ var initialise = function( types, runloop, resolveRef, ReferenceExpressionResolver, ExpressionResolver ) { return function Mustache$init( mustache, options ) { var ref, keypath, indexRefs, index, parentFragment, template; parentFragment = options.parentFragment; template = options.template; mustache.root = parentFragment.root; mustache.parentFragment = parentFragment; mustache.pElement = parentFragment.pElement; mustache.template = options.template; mustache.index = options.index || 0; mustache.priority = parentFragment.priority; mustache.isStatic = options.template.s; mustache.type = options.template.t; // if this is a simple mustache, with a reference, we just need to resolve // the reference to a keypath if ( ref = template.r ) { indexRefs = parentFragment.indexRefs; if ( indexRefs && ( index = indexRefs[ ref ] ) !== undefined ) { mustache.indexRef = ref; mustache.setValue( index ); return; } keypath = resolveRef( mustache.root, ref, mustache.parentFragment ); if ( keypath !== undefined ) { mustache.resolve( keypath ); } else { mustache.ref = ref; runloop.addUnresolved( mustache ); } } // if it's an expression, we have a bit more work to do if ( options.template.x ) { mustache.resolver = new ExpressionResolver( mustache, parentFragment, options.template.x, resolveAndRebindChildren ); } if ( options.template.rx ) { mustache.resolver = new ReferenceExpressionResolver( mustache, options.template.rx, resolveAndRebindChildren ); } // Special case - inverted sections if ( mustache.template.n === types.SECTION_UNLESS && !mustache.hasOwnProperty( 'value' ) ) { mustache.setValue( undefined ); } function resolveAndRebindChildren( newKeypath ) { var oldKeypath = mustache.keypath; if ( newKeypath !== oldKeypath ) { mustache.resolve( newKeypath ); if ( oldKeypath !== undefined ) { mustache.fragments && mustache.fragments.forEach( function( f ) { f.rebind( null, null, oldKeypath, newKeypath ); } ); } } } }; }( types, runloop, resolveRef, ReferenceExpressionResolver, ExpressionResolver ); /* virtualdom/items/shared/Mustache/resolve.js */ var resolve = function Mustache$resolve( keypath ) { var wasResolved, value, twowayBinding; // If we resolved previously, we need to unregister if ( this.keypath !== undefined ) { this.root.viewmodel.unregister( this.keypath, this ); wasResolved = true; } this.keypath = keypath; // If the new keypath exists, we need to register // with the viewmodel if ( keypath !== undefined ) { value = this.root.viewmodel.get( keypath ); this.root.viewmodel.register( keypath, this ); } // Either way we need to queue up a render (`value` // will be `undefined` if there's no keypath) this.setValue( value ); // Two-way bindings need to point to their new target keypath if ( wasResolved && ( twowayBinding = this.twowayBinding ) ) { twowayBinding.rebound(); } }; /* virtualdom/items/shared/Mustache/rebind.js */ var rebind = function( getNewKeypath ) { return function Mustache$rebind( indexRef, newIndex, oldKeypath, newKeypath ) { var keypath; // Children first if ( this.fragments ) { this.fragments.forEach( function( f ) { return f.rebind( indexRef, newIndex, oldKeypath, newKeypath ); } ); } // Expression mustache? if ( this.resolver ) { this.resolver.rebind( indexRef, newIndex, oldKeypath, newKeypath ); } // Normal keypath mustache or reference expression? if ( this.keypath ) { // was a new keypath created? if ( keypath = getNewKeypath( this.keypath, oldKeypath, newKeypath ) ) { // resolve it this.resolve( keypath ); } } else if ( indexRef !== undefined && this.indexRef === indexRef ) { this.setValue( newIndex ); } }; }( getNewKeypath ); /* virtualdom/items/shared/Mustache/_Mustache.js */ var Mustache = function( getValue, init, resolve, rebind ) { return { getValue: getValue, init: init, resolve: resolve, rebind: rebind }; }( getValue, initialise, resolve, rebind ); /* virtualdom/items/Interpolator.js */ var Interpolator = function( types, runloop, escapeHtml, detachNode, unbind, Mustache, detach ) { var Interpolator = function( options ) { this.type = types.INTERPOLATOR; Mustache.init( this, options ); }; Interpolator.prototype = { update: function() { this.node.data = this.value == undefined ? '' : this.value; }, resolve: Mustache.resolve, rebind: Mustache.rebind, detach: detach, unbind: unbind, render: function() { if ( !this.node ) { this.node = document.createTextNode( this.value != undefined ? this.value : '' ); } return this.node; }, unrender: function( shouldDestroy ) { if ( shouldDestroy ) { detachNode( this.node ); } }, getValue: Mustache.getValue, // TEMP setValue: function( value ) { var wrapper; // TODO is there a better way to approach this? if ( wrapper = this.root.viewmodel.wrapped[ this.keypath ] ) { value = wrapper.get(); } if ( value !== this.value ) { this.value = value; this.parentFragment.bubble(); if ( this.node ) { runloop.addView( this ); } } }, firstNode: function() { return this.node; }, toString: function( escape ) { var string = this.value != undefined ? '' + this.value : ''; return escape ? escapeHtml( string ) : string; } }; return Interpolator; }( types, runloop, escapeHtml, detachNode, unbind, Mustache, detach ); /* virtualdom/items/Section/prototype/bubble.js */ var virtualdom_items_Section$bubble = function Section$bubble() { this.parentFragment.bubble(); }; /* virtualdom/items/Section/prototype/detach.js */ var virtualdom_items_Section$detach = function Section$detach() { var docFrag; if ( this.fragments.length === 1 ) { return this.fragments[ 0 ].detach(); } docFrag = document.createDocumentFragment(); this.fragments.forEach( function( item ) { docFrag.appendChild( item.detach() ); } ); return docFrag; }; /* virtualdom/items/Section/prototype/find.js */ var virtualdom_items_Section$find = function Section$find( selector ) { var i, len, queryResult; len = this.fragments.length; for ( i = 0; i < len; i += 1 ) { if ( queryResult = this.fragments[ i ].find( selector ) ) { return queryResult; } } return null; }; /* virtualdom/items/Section/prototype/findAll.js */ var virtualdom_items_Section$findAll = function Section$findAll( selector, query ) { var i, len; len = this.fragments.length; for ( i = 0; i < len; i += 1 ) { this.fragments[ i ].findAll( selector, query ); } }; /* virtualdom/items/Section/prototype/findAllComponents.js */ var virtualdom_items_Section$findAllComponents = function Section$findAllComponents( selector, query ) { var i, len; len = this.fragments.length; for ( i = 0; i < len; i += 1 ) { this.fragments[ i ].findAllComponents( selector, query ); } }; /* virtualdom/items/Section/prototype/findComponent.js */ var virtualdom_items_Section$findComponent = function Section$findComponent( selector ) { var i, len, queryResult; len = this.fragments.length; for ( i = 0; i < len; i += 1 ) { if ( queryResult = this.fragments[ i ].findComponent( selector ) ) { return queryResult; } } return null; }; /* virtualdom/items/Section/prototype/findNextNode.js */ var virtualdom_items_Section$findNextNode = function Section$findNextNode( fragment ) { if ( this.fragments[ fragment.index + 1 ] ) { return this.fragments[ fragment.index + 1 ].firstNode(); } return this.parentFragment.findNextNode( this ); }; /* virtualdom/items/Section/prototype/firstNode.js */ var virtualdom_items_Section$firstNode = function Section$firstNode() { var len, i, node; if ( len = this.fragments.length ) { for ( i = 0; i < len; i += 1 ) { if ( node = this.fragments[ i ].firstNode() ) { return node; } } } return this.parentFragment.findNextNode( this ); }; /* virtualdom/items/Section/prototype/merge.js */ var virtualdom_items_Section$merge = function( runloop, circular ) { var Fragment; circular.push( function() { Fragment = circular.Fragment; } ); return function Section$merge( newIndices ) { var section = this, parentFragment, firstChange, i, newLength, reboundFragments, fragmentOptions, fragment, nextNode; if ( this.unbound ) { return; } parentFragment = this.parentFragment; reboundFragments = []; // first, rebind existing fragments newIndices.forEach( function rebindIfNecessary( newIndex, oldIndex ) { var fragment, by, oldKeypath, newKeypath; if ( newIndex === oldIndex ) { reboundFragments[ newIndex ] = section.fragments[ oldIndex ]; return; } fragment = section.fragments[ oldIndex ]; if ( firstChange === undefined ) { firstChange = oldIndex; } // does this fragment need to be torn down? if ( newIndex === -1 ) { section.fragmentsToUnrender.push( fragment ); fragment.unbind(); return; } // Otherwise, it needs to be rebound to a new index by = newIndex - oldIndex; oldKeypath = section.keypath + '.' + oldIndex; newKeypath = section.keypath + '.' + newIndex; fragment.rebind( section.template.i, newIndex, oldKeypath, newKeypath ); reboundFragments[ newIndex ] = fragment; } ); newLength = this.root.get( this.keypath ).length; // If nothing changed with the existing fragments, then we start adding // new fragments at the end... if ( firstChange === undefined ) { // ...unless there are no new fragments to add if ( this.length === newLength ) { return; } firstChange = this.length; } this.length = this.fragments.length = newLength; runloop.addView( this ); // Prepare new fragment options fragmentOptions = { template: this.template.f, root: this.root, owner: this }; if ( this.template.i ) { fragmentOptions.indexRef = this.template.i; } // Add as many new fragments as we need to, or add back existing // (detached) fragments for ( i = firstChange; i < newLength; i += 1 ) { // is this an existing fragment? if ( fragment = reboundFragments[ i ] ) { this.docFrag.appendChild( fragment.detach( false ) ); } else { // Fragment will be created when changes are applied // by the runloop this.fragmentsToCreate.push( i ); } this.fragments[ i ] = fragment; } // reinsert fragment nextNode = parentFragment.findNextNode( this ); this.parentFragment.getNode().insertBefore( this.docFrag, nextNode ); }; }( runloop, circular ); /* virtualdom/items/Section/prototype/render.js */ var virtualdom_items_Section$render = function Section$render() { var docFrag; docFrag = this.docFrag = document.createDocumentFragment(); this.update(); this.rendered = true; return docFrag; }; /* virtualdom/items/Section/prototype/setValue.js */ var virtualdom_items_Section$setValue = function( types, isArray, isObject, runloop, circular ) { var Fragment; circular.push( function() { Fragment = circular.Fragment; } ); return function Section$setValue( value ) { var this$0 = this; var wrapper, fragmentOptions; if ( this.updating ) { // If a child of this section causes a re-evaluation - for example, an // expression refers to a function that mutates the array that this // section depends on - we'll end up with a double rendering bug (see // https://github.com/ractivejs/ractive/issues/748). This prevents it. return; } this.updating = true; // with sections, we need to get the fake value if we have a wrapped object if ( wrapper = this.root.viewmodel.wrapped[ this.keypath ] ) { value = wrapper.get(); } // If any fragments are awaiting creation after a splice, // this is the place to do it if ( this.fragmentsToCreate.length ) { fragmentOptions = { template: this.template.f, root: this.root, pElement: this.pElement, owner: this, indexRef: this.template.i }; this.fragmentsToCreate.forEach( function( index ) { var fragment; fragmentOptions.context = this$0.keypath + '.' + index; fragmentOptions.index = index; fragment = new Fragment( fragmentOptions ); this$0.fragmentsToRender.push( this$0.fragments[ index ] = fragment ); } ); this.fragmentsToCreate.length = 0; } else if ( reevaluateSection( this, value ) ) { this.bubble(); if ( this.rendered ) { runloop.addView( this ); } } this.value = value; this.updating = false; }; function reevaluateSection( section, value ) { var fragmentOptions = { template: section.template.f, root: section.root, pElement: section.parentFragment.pElement, owner: section }; // If we already know the section type, great // TODO can this be optimised? i.e. pick an reevaluateSection function during init // and avoid doing this each time? if ( section.subtype ) { switch ( section.subtype ) { case types.SECTION_IF: return reevaluateConditionalSection( section, value, false, fragmentOptions ); case types.SECTION_UNLESS: return reevaluateConditionalSection( section, value, true, fragmentOptions ); case types.SECTION_WITH: return reevaluateContextSection( section, fragmentOptions ); case types.SECTION_EACH: if ( isObject( value ) ) { return reevaluateListObjectSection( section, value, fragmentOptions ); } } } // Otherwise we need to work out what sort of section we're dealing with section.ordered = !!isArray( value ); // Ordered list section if ( section.ordered ) { return reevaluateListSection( section, value, fragmentOptions ); } // Unordered list, or context if ( isObject( value ) || typeof value === 'function' ) { // Index reference indicates section should be treated as a list if ( section.template.i ) { return reevaluateListObjectSection( section, value, fragmentOptions ); } // Otherwise, object provides context for contents return reevaluateContextSection( section, fragmentOptions ); } // Conditional section return reevaluateConditionalSection( section, value, false, fragmentOptions ); } function reevaluateListSection( section, value, fragmentOptions ) { var i, length, fragment; length = value.length; if ( length === section.length ) { // Nothing to do return false; } // if the array is shorter than it was previously, remove items if ( length < section.length ) { section.fragmentsToUnrender = section.fragments.splice( length, section.length - length ); section.fragmentsToUnrender.forEach( unbind ); } else { if ( length > section.length ) { // add any new ones for ( i = section.length; i < length; i += 1 ) { // append list item to context stack fragmentOptions.context = section.keypath + '.' + i; fragmentOptions.index = i; if ( section.template.i ) { fragmentOptions.indexRef = section.template.i; } fragment = new Fragment( fragmentOptions ); section.fragmentsToRender.push( section.fragments[ i ] = fragment ); } } } section.length = length; return true; } function reevaluateListObjectSection( section, value, fragmentOptions ) { var id, i, hasKey, fragment, changed; hasKey = section.hasKey || ( section.hasKey = {} ); // remove any fragments that should no longer exist i = section.fragments.length; while ( i-- ) { fragment = section.fragments[ i ]; if ( !( fragment.index in value ) ) { changed = true; fragment.unbind(); section.fragmentsToUnrender.push( fragment ); section.fragments.splice( i, 1 ); hasKey[ fragment.index ] = false; } } // add any that haven't been created yet for ( id in value ) { if ( !hasKey[ id ] ) { changed = true; fragmentOptions.context = section.keypath + '.' + id; fragmentOptions.index = id; if ( section.template.i ) { fragmentOptions.indexRef = section.template.i; } fragment = new Fragment( fragmentOptions ); section.fragmentsToRender.push( fragment ); section.fragments.push( fragment ); hasKey[ id ] = true; } } section.length = section.fragments.length; return changed; } function reevaluateContextSection( section, fragmentOptions ) { var fragment; // ...then if it isn't rendered, render it, adding section.keypath to the context stack // (if it is already rendered, then any children dependent on the context stack // will update themselves without any prompting) if ( !section.length ) { // append this section to the context stack fragmentOptions.context = section.keypath; fragmentOptions.index = 0; fragment = new Fragment( fragmentOptions ); section.fragmentsToRender.push( section.fragments[ 0 ] = fragment ); section.length = 1; return true; } } function reevaluateConditionalSection( section, value, inverted, fragmentOptions ) { var doRender, emptyArray, fragment; emptyArray = isArray( value ) && value.length === 0; if ( inverted ) { doRender = emptyArray || !value; } else { doRender = value && !emptyArray; } if ( doRender ) { if ( !section.length ) { // no change to context stack fragmentOptions.index = 0; fragment = new Fragment( fragmentOptions ); section.fragmentsToRender.push( section.fragments[ 0 ] = fragment ); section.length = 1; return true; } if ( section.length > 1 ) { section.fragmentsToUnrender = section.fragments.splice( 1 ); section.fragmentsToUnrender.forEach( unbind ); return true; } } else if ( section.length ) { section.fragmentsToUnrender = section.fragments.splice( 0, section.fragments.length ); section.fragmentsToUnrender.forEach( unbind ); section.length = 0; return true; } } function unbind( fragment ) { fragment.unbind(); } }( types, isArray, isObject, runloop, circular ); /* virtualdom/items/Section/prototype/splice.js */ var virtualdom_items_Section$splice = function( runloop, circular ) { var Fragment; circular.push( function() { Fragment = circular.Fragment; } ); return function Section$splice( spliceSummary ) { var section = this, balance, start, insertStart, insertEnd, spliceArgs; // In rare cases, a section will receive a splice instruction after it has // been unbound (see https://github.com/ractivejs/ractive/issues/967). This // prevents errors arising from those situations if ( this.unbound ) { return; } balance = spliceSummary.balance; if ( !balance ) { // The array length hasn't changed - we don't need to add or remove anything return; } // Register with the runloop, so we can (un)render with the // next batch of DOM changes runloop.addView( section ); start = spliceSummary.rangeStart; section.length += balance; // If more items were removed from the array than added, we tear down // the excess fragments and remove them... if ( balance < 0 ) { section.fragmentsToUnrender = section.fragments.splice( start, -balance ); section.fragmentsToUnrender.forEach( unbind ); // Reassign fragments after the ones we've just removed rebindFragments( section, start, section.length, balance ); // Nothing more to do return; } // ...otherwise we need to add some things to the DOM. insertStart = start + spliceSummary.removed; insertEnd = start + spliceSummary.added; // Make room for the new fragments by doing a splice that simulates // what happened to the data array spliceArgs = [ insertStart, 0 ]; spliceArgs.length += balance; section.fragments.splice.apply( section.fragments, spliceArgs ); // Rebind existing fragments at the end of the array rebindFragments( section, insertEnd, section.length, balance ); // Schedule new fragments to be created section.fragmentsToCreate = range( insertStart, insertEnd ); }; function unbind( fragment ) { fragment.unbind(); } function range( start, end ) { var array = [], i; for ( i = start; i < end; i += 1 ) { array.push( i ); } return array; } function rebindFragments( section, start, end, by ) { var i, fragment, indexRef, oldKeypath, newKeypath; indexRef = section.template.i; for ( i = start; i < end; i += 1 ) { fragment = section.fragments[ i ]; oldKeypath = section.keypath + '.' + ( i - by ); newKeypath = section.keypath + '.' + i; // change the fragment index fragment.index = i; fragment.rebind( indexRef, i, oldKeypath, newKeypath ); } } }( runloop, circular ); /* virtualdom/items/Section/prototype/toString.js */ var virtualdom_items_Section$toString = function Section$toString( escape ) { var str, i, len; str = ''; i = 0; len = this.length; for ( i = 0; i < len; i += 1 ) { str += this.fragments[ i ].toString( escape ); } return str; }; /* virtualdom/items/Section/prototype/unbind.js */ var virtualdom_items_Section$unbind = function( unbind ) { return function Section$unbind() { this.fragments.forEach( unbindFragment ); unbind.call( this ); this.length = 0; this.unbound = true; }; function unbindFragment( fragment ) { fragment.unbind(); } }( unbind ); /* virtualdom/items/Section/prototype/unrender.js */ var virtualdom_items_Section$unrender = function() { return function Section$unrender( shouldDestroy ) { this.fragments.forEach( shouldDestroy ? unrenderAndDestroy : unrender ); }; function unrenderAndDestroy( fragment ) { fragment.unrender( true ); } function unrender( fragment ) { fragment.unrender( false ); } }(); /* virtualdom/items/Section/prototype/update.js */ var virtualdom_items_Section$update = function Section$update() { var fragment, rendered, nextFragment, anchor, target; while ( fragment = this.fragmentsToUnrender.pop() ) { fragment.unrender( true ); } // If we have no new nodes to insert (i.e. the section length stayed the // same, or shrank), we don't need to go any further if ( !this.fragmentsToRender.length ) { return; } if ( this.rendered ) { target = this.parentFragment.getNode(); } // Render new fragments to our docFrag while ( fragment = this.fragmentsToRender.shift() ) { rendered = fragment.render(); this.docFrag.appendChild( rendered ); // If this is an ordered list, and it's already rendered, we may // need to insert content into the appropriate place if ( this.rendered && this.ordered ) { // If the next fragment is already rendered, use it as an anchor... nextFragment = this.fragments[ fragment.index + 1 ]; if ( nextFragment && nextFragment.rendered ) { target.insertBefore( this.docFrag, nextFragment.firstNode() || null ); } } } if ( this.rendered && this.docFrag.childNodes.length ) { anchor = this.parentFragment.findNextNode( this ); target.insertBefore( this.docFrag, anchor ); } }; /* virtualdom/items/Section/_Section.js */ var Section = function( types, Mustache, bubble, detach, find, findAll, findAllComponents, findComponent, findNextNode, firstNode, merge, render, setValue, splice, toString, unbind, unrender, update ) { var Section = function( options ) { this.type = types.SECTION; this.subtype = options.template.n; this.inverted = this.subtype === types.SECTION_UNLESS; this.pElement = options.pElement; this.fragments = []; this.fragmentsToCreate = []; this.fragmentsToRender = []; this.fragmentsToUnrender = []; this.length = 0; // number of times this section is rendered Mustache.init( this, options ); }; Section.prototype = { bubble: bubble, detach: detach, find: find, findAll: findAll, findAllComponents: findAllComponents, findComponent: findComponent, findNextNode: findNextNode, firstNode: firstNode, getValue: Mustache.getValue, merge: merge, rebind: Mustache.rebind, render: render, resolve: Mustache.resolve, setValue: setValue, splice: splice, toString: toString, unbind: unbind, unrender: unrender, update: update }; return Section; }( types, Mustache, virtualdom_items_Section$bubble, virtualdom_items_Section$detach, virtualdom_items_Section$find, virtualdom_items_Section$findAll, virtualdom_items_Section$findAllComponents, virtualdom_items_Section$findComponent, virtualdom_items_Section$findNextNode, virtualdom_items_Section$firstNode, virtualdom_items_Section$merge, virtualdom_items_Section$render, virtualdom_items_Section$setValue, virtualdom_items_Section$splice, virtualdom_items_Section$toString, virtualdom_items_Section$unbind, virtualdom_items_Section$unrender, virtualdom_items_Section$update ); /* virtualdom/items/Triple/prototype/detach.js */ var virtualdom_items_Triple$detach = function Triple$detach() { var len, i; if ( this.docFrag ) { len = this.nodes.length; for ( i = 0; i < len; i += 1 ) { this.docFrag.appendChild( this.nodes[ i ] ); } return this.docFrag; } }; /* virtualdom/items/Triple/prototype/find.js */ var virtualdom_items_Triple$find = function( matches ) { return function Triple$find( selector ) { var i, len, node, queryResult; len = this.nodes.length; for ( i = 0; i < len; i += 1 ) { node = this.nodes[ i ]; if ( node.nodeType !== 1 ) { continue; } if ( matches( node, selector ) ) { return node; } if ( queryResult = node.querySelector( selector ) ) { return queryResult; } } return null; }; }( matches ); /* virtualdom/items/Triple/prototype/findAll.js */ var virtualdom_items_Triple$findAll = function( matches ) { return function Triple$findAll( selector, queryResult ) { var i, len, node, queryAllResult, numNodes, j; len = this.nodes.length; for ( i = 0; i < len; i += 1 ) { node = this.nodes[ i ]; if ( node.nodeType !== 1 ) { continue; } if ( matches( node, selector ) ) { queryResult.push( node ); } if ( queryAllResult = node.querySelectorAll( selector ) ) { numNodes = queryAllResult.length; for ( j = 0; j < numNodes; j += 1 ) { queryResult.push( queryAllResult[ j ] ); } } } }; }( matches ); /* virtualdom/items/Triple/prototype/firstNode.js */ var virtualdom_items_Triple$firstNode = function Triple$firstNode() { if ( this.rendered && this.nodes[ 0 ] ) { return this.nodes[ 0 ]; } return this.parentFragment.findNextNode( this ); }; /* virtualdom/items/Triple/helpers/insertHtml.js */ var insertHtml = function( namespaces, createElement ) { var elementCache = {}, ieBug, ieBlacklist; try { createElement( 'table' ).innerHTML = 'foo'; } catch ( err ) { ieBug = true; ieBlacklist = { TABLE: [ '<table class="x">', '</table>' ], THEAD: [ '<table><thead class="x">', '</thead></table>' ], TBODY: [ '<table><tbody class="x">', '</tbody></table>' ], TR: [ '<table><tr class="x">', '</tr></table>' ], SELECT: [ '<select class="x">', '</select>' ] }; } return function( html, node, docFrag ) { var container, nodes = [], wrapper, selectedOption, child, i; if ( html ) { if ( ieBug && ( wrapper = ieBlacklist[ node.tagName ] ) ) { container = element( 'DIV' ); container.innerHTML = wrapper[ 0 ] + html + wrapper[ 1 ]; container = container.querySelector( '.x' ); if ( container.tagName === 'SELECT' ) { selectedOption = container.options[ container.selectedIndex ]; } } else if ( node.namespaceURI === namespaces.svg ) { container = element( 'DIV' ); container.innerHTML = '<svg class="x">' + html + '</svg>'; container = container.querySelector( '.x' ); } else { container = element( node.tagName ); container.innerHTML = html; } while ( child = container.firstChild ) { nodes.push( child ); docFrag.appendChild( child ); } // This is really annoying. Extracting <option> nodes from the // temporary container <select> causes the remaining ones to // become selected. So now we have to deselect them. IE8, you // amaze me. You really do if ( ieBug && node.tagName === 'SELECT' ) { i = nodes.length; while ( i-- ) { if ( nodes[ i ] !== selectedOption ) { nodes[ i ].selected = false; } } } } return nodes; }; function element( tagName ) { return elementCache[ tagName ] || ( elementCache[ tagName ] = createElement( tagName ) ); } }( namespaces, createElement ); /* utils/toArray.js */ var toArray = function toArray( arrayLike ) { var array = [], i = arrayLike.length; while ( i-- ) { array[ i ] = arrayLike[ i ]; } return array; }; /* virtualdom/items/Triple/helpers/updateSelect.js */ var updateSelect = function( toArray ) { return function updateSelect( parentElement ) { var selectedOptions, option, value; if ( !parentElement || parentElement.name !== 'select' || !parentElement.binding ) { return; } selectedOptions = toArray( parentElement.node.options ).filter( isSelected ); // If one of them had a `selected` attribute, we need to sync // the model to the view if ( parentElement.getAttribute( 'multiple' ) ) { value = selectedOptions.map( function( o ) { return o.value; } ); } else if ( option = selectedOptions[ 0 ] ) { value = option.value; } if ( value !== undefined ) { parentElement.binding.setValue( value ); } parentElement.bubble(); }; function isSelected( option ) { return option.selected; } }( toArray ); /* virtualdom/items/Triple/prototype/render.js */ var virtualdom_items_Triple$render = function( insertHtml, updateSelect ) { return function Triple$render() { if ( this.rendered ) { throw new Error( 'Attempted to render an item that was already rendered' ); } this.docFrag = document.createDocumentFragment(); this.nodes = insertHtml( this.value, this.parentFragment.getNode(), this.docFrag ); // Special case - we're inserting the contents of a <select> updateSelect( this.pElement ); this.rendered = true; return this.docFrag; }; }( insertHtml, updateSelect ); /* virtualdom/items/Triple/prototype/setValue.js */ var virtualdom_items_Triple$setValue = function( runloop ) { return function Triple$setValue( value ) { var wrapper; // TODO is there a better way to approach this? if ( wrapper = this.root.viewmodel.wrapped[ this.keypath ] ) { value = wrapper.get(); } if ( value !== this.value ) { this.value = value; this.parentFragment.bubble(); if ( this.rendered ) { runloop.addView( this ); } } }; }( runloop ); /* virtualdom/items/Triple/prototype/toString.js */ var virtualdom_items_Triple$toString = function Triple$toString() { return this.value != undefined ? this.value : ''; }; /* virtualdom/items/Triple/prototype/unrender.js */ var virtualdom_items_Triple$unrender = function( detachNode ) { return function Triple$unrender( shouldDestroy ) { if ( this.rendered && shouldDestroy ) { this.nodes.forEach( detachNode ); this.rendered = false; } }; }( detachNode ); /* virtualdom/items/Triple/prototype/update.js */ var virtualdom_items_Triple$update = function( insertHtml, updateSelect ) { return function Triple$update() { var node, parentNode; if ( !this.rendered ) { return; } // Remove existing nodes while ( this.nodes && this.nodes.length ) { node = this.nodes.pop(); node.parentNode.removeChild( node ); } // Insert new nodes parentNode = this.parentFragment.getNode(); this.nodes = insertHtml( this.value, parentNode, this.docFrag ); parentNode.insertBefore( this.docFrag, this.parentFragment.findNextNode( this ) ); // Special case - we're inserting the contents of a <select> updateSelect( this.pElement ); }; }( insertHtml, updateSelect ); /* virtualdom/items/Triple/_Triple.js */ var Triple = function( types, Mustache, detach, find, findAll, firstNode, render, setValue, toString, unrender, update, unbind ) { var Triple = function( options ) { this.type = types.TRIPLE; Mustache.init( this, options ); }; Triple.prototype = { detach: detach, find: find, findAll: findAll, firstNode: firstNode, getValue: Mustache.getValue, rebind: Mustache.rebind, render: render, resolve: Mustache.resolve, setValue: setValue, toString: toString, unbind: unbind, unrender: unrender, update: update }; return Triple; }( types, Mustache, virtualdom_items_Triple$detach, virtualdom_items_Triple$find, virtualdom_items_Triple$findAll, virtualdom_items_Triple$firstNode, virtualdom_items_Triple$render, virtualdom_items_Triple$setValue, virtualdom_items_Triple$toString, virtualdom_items_Triple$unrender, virtualdom_items_Triple$update, unbind ); /* virtualdom/items/Element/prototype/bubble.js */ var virtualdom_items_Element$bubble = function() { this.parentFragment.bubble(); }; /* virtualdom/items/Element/prototype/detach.js */ var virtualdom_items_Element$detach = function Element$detach() { var node = this.node, parentNode; if ( node ) { // need to check for parent node - DOM may have been altered // by something other than Ractive! e.g. jQuery UI... if ( parentNode = node.parentNode ) { parentNode.removeChild( node ); } return node; } }; /* virtualdom/items/Element/prototype/find.js */ var virtualdom_items_Element$find = function( matches ) { return function( selector ) { if ( matches( this.node, selector ) ) { return this.node; } if ( this.fragment && this.fragment.find ) { return this.fragment.find( selector ); } }; }( matches ); /* virtualdom/items/Element/prototype/findAll.js */ var virtualdom_items_Element$findAll = function( selector, query ) { // Add this node to the query, if applicable, and register the // query on this element if ( query._test( this, true ) && query.live ) { ( this.liveQueries || ( this.liveQueries = [] ) ).push( query ); } if ( this.fragment ) { this.fragment.findAll( selector, query ); } }; /* virtualdom/items/Element/prototype/findAllComponents.js */ var virtualdom_items_Element$findAllComponents = function( selector, query ) { if ( this.fragment ) { this.fragment.findAllComponents( selector, query ); } }; /* virtualdom/items/Element/prototype/findComponent.js */ var virtualdom_items_Element$findComponent = function( selector ) { if ( this.fragment ) { return this.fragment.findComponent( selector ); } }; /* virtualdom/items/Element/prototype/findNextNode.js */ var virtualdom_items_Element$findNextNode = function Element$findNextNode() { return null; }; /* virtualdom/items/Element/prototype/firstNode.js */ var virtualdom_items_Element$firstNode = function Element$firstNode() { return this.node; }; /* virtualdom/items/Element/prototype/getAttribute.js */ var virtualdom_items_Element$getAttribute = function Element$getAttribute( name ) { if ( !this.attributes || !this.attributes[ name ] ) { return; } return this.attributes[ name ].value; }; /* virtualdom/items/Element/shared/enforceCase.js */ var enforceCase = function() { var svgCamelCaseElements, svgCamelCaseAttributes, createMap, map; svgCamelCaseElements = 'altGlyph altGlyphDef altGlyphItem animateColor animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject glyphRef linearGradient radialGradient textPath vkern'.split( ' ' ); svgCamelCaseAttributes = 'attributeName attributeType baseFrequency baseProfile calcMode clipPathUnits contentScriptType contentStyleType diffuseConstant edgeMode externalResourcesRequired filterRes filterUnits glyphRef gradientTransform gradientUnits kernelMatrix kernelUnitLength keyPoints keySplines keyTimes lengthAdjust limitingConeAngle markerHeight markerUnits markerWidth maskContentUnits maskUnits numOctaves pathLength patternContentUnits patternTransform patternUnits pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits refX refY repeatCount repeatDur requiredExtensions requiredFeatures specularConstant specularExponent spreadMethod startOffset stdDeviation stitchTiles surfaceScale systemLanguage tableValues targetX targetY textLength viewBox viewTarget xChannelSelector yChannelSelector zoomAndPan'.split( ' ' ); createMap = function( items ) { var map = {}, i = items.length; while ( i-- ) { map[ items[ i ].toLowerCase() ] = items[ i ]; } return map; }; map = createMap( svgCamelCaseElements.concat( svgCamelCaseAttributes ) ); return function( elementName ) { var lowerCaseElementName = elementName.toLowerCase(); return map[ lowerCaseElementName ] || lowerCaseElementName; }; }(); /* virtualdom/items/Element/Attribute/prototype/bubble.js */ var virtualdom_items_Element_Attribute$bubble = function( runloop ) { return function Attribute$bubble() { var value = this.fragment.getValue(); // TODO this can register the attribute multiple times (see render test // 'Attribute with nested mustaches') if ( value !== this.value ) { this.value = value; if ( this.name === 'value' && this.node ) { // We need to store the value on the DOM like this so we // can retrieve it later without it being coerced to a string this.node._ractive.value = value; } if ( this.rendered ) { runloop.addView( this ); } } }; }( runloop ); /* virtualdom/items/Element/Attribute/helpers/determineNameAndNamespace.js */ var determineNameAndNamespace = function( namespaces, enforceCase ) { return function( attribute, name ) { var colonIndex, namespacePrefix; // are we dealing with a namespaced attribute, e.g. xlink:href? colonIndex = name.indexOf( ':' ); if ( colonIndex !== -1 ) { // looks like we are, yes... namespacePrefix = name.substr( 0, colonIndex ); // ...unless it's a namespace *declaration*, which we ignore (on the assumption // that only valid namespaces will be used) if ( namespacePrefix !== 'xmlns' ) { name = name.substring( colonIndex + 1 ); attribute.name = enforceCase( name ); attribute.namespace = namespaces[ namespacePrefix.toLowerCase() ]; if ( !attribute.namespace ) { throw 'Unknown namespace ("' + namespacePrefix + '")'; } return; } } // SVG attribute names are case sensitive attribute.name = attribute.element.namespace !== namespaces.html ? enforceCase( name ) : name; }; }( namespaces, enforceCase ); /* virtualdom/items/Element/Attribute/helpers/getInterpolator.js */ var getInterpolator = function( types ) { return function getInterpolator( attribute ) { var items = attribute.fragment.items; if ( items.length !== 1 ) { return; } if ( items[ 0 ].type === types.INTERPOLATOR ) { return items[ 0 ]; } }; }( types ); /* virtualdom/items/Element/Attribute/helpers/determinePropertyName.js */ var determinePropertyName = function( namespaces ) { // the property name equivalents for element attributes, where they differ // from the lowercased attribute name var propertyNames = { 'accept-charset': 'acceptCharset', accesskey: 'accessKey', bgcolor: 'bgColor', 'class': 'className', codebase: 'codeBase', colspan: 'colSpan', contenteditable: 'contentEditable', datetime: 'dateTime', dirname: 'dirName', 'for': 'htmlFor', 'http-equiv': 'httpEquiv', ismap: 'isMap', maxlength: 'maxLength', novalidate: 'noValidate', pubdate: 'pubDate', readonly: 'readOnly', rowspan: 'rowSpan', tabindex: 'tabIndex', usemap: 'useMap' }; return function( attribute, options ) { var propertyName; if ( attribute.pNode && !attribute.namespace && ( !options.pNode.namespaceURI || options.pNode.namespaceURI === namespaces.html ) ) { propertyName = propertyNames[ attribute.name ] || attribute.name; if ( options.pNode[ propertyName ] !== undefined ) { attribute.propertyName = propertyName; } // is attribute a boolean attribute or 'value'? If so we're better off doing e.g. // node.selected = true rather than node.setAttribute( 'selected', '' ) if ( typeof options.pNode[ propertyName ] === 'boolean' || propertyName === 'value' ) { attribute.useProperty = true; } } }; }( namespaces ); /* virtualdom/items/Element/Attribute/prototype/init.js */ var virtualdom_items_Element_Attribute$init = function( types, determineNameAndNamespace, getInterpolator, determinePropertyName, circular ) { var Fragment; circular.push( function() { Fragment = circular.Fragment; } ); return function Attribute$init( options ) { this.type = types.ATTRIBUTE; this.element = options.element; this.root = options.root; determineNameAndNamespace( this, options.name ); // if it's an empty attribute, or just a straight key-value pair, with no // mustache shenanigans, set the attribute accordingly and go home if ( !options.value || typeof options.value === 'string' ) { this.value = options.value || true; return; } // otherwise we need to do some work // share parentFragment with parent element this.parentFragment = this.element.parentFragment; this.fragment = new Fragment( { template: options.value, root: this.root, owner: this } ); this.value = this.fragment.getValue(); // Store a reference to this attribute's interpolator, if its fragment // takes the form `{{foo}}`. This is necessary for two-way binding and // for correctly rendering HTML later this.interpolator = getInterpolator( this ); this.isBindable = !!this.interpolator; // can we establish this attribute's property name equivalent? determinePropertyName( this, options ); // mark as ready this.ready = true; }; }( types, determineNameAndNamespace, getInterpolator, determinePropertyName, circular ); /* virtualdom/items/Element/Attribute/prototype/rebind.js */ var virtualdom_items_Element_Attribute$rebind = function Attribute$rebind( indexRef, newIndex, oldKeypath, newKeypath ) { if ( this.fragment ) { this.fragment.rebind( indexRef, newIndex, oldKeypath, newKeypath ); } }; /* virtualdom/items/Element/Attribute/prototype/render.js */ var virtualdom_items_Element_Attribute$render = function( namespaces ) { // the property name equivalents for element attributes, where they differ // from the lowercased attribute name var propertyNames = { 'accept-charset': 'acceptCharset', 'accesskey': 'accessKey', 'bgcolor': 'bgColor', 'class': 'className', 'codebase': 'codeBase', 'colspan': 'colSpan', 'contenteditable': 'contentEditable', 'datetime': 'dateTime', 'dirname': 'dirName', 'for': 'htmlFor', 'http-equiv': 'httpEquiv', 'ismap': 'isMap', 'maxlength': 'maxLength', 'novalidate': 'noValidate', 'pubdate': 'pubDate', 'readonly': 'readOnly', 'rowspan': 'rowSpan', 'tabindex': 'tabIndex', 'usemap': 'useMap' }; return function Attribute$render( node ) { var propertyName; this.node = node; // should we use direct property access, or setAttribute? if ( !node.namespaceURI || node.namespaceURI === namespaces.html ) { propertyName = propertyNames[ this.name ] || this.name; if ( node[ propertyName ] !== undefined ) { this.propertyName = propertyName; } // is attribute a boolean attribute or 'value'? If so we're better off doing e.g. // node.selected = true rather than node.setAttribute( 'selected', '' ) if ( typeof node[ propertyName ] === 'boolean' || propertyName === 'value' ) { this.useProperty = true; } if ( propertyName === 'value' ) { this.useProperty = true; node._ractive.value = this.value; } } this.rendered = true; this.update(); }; }( namespaces ); /* virtualdom/items/Element/Attribute/prototype/toString.js */ var virtualdom_items_Element_Attribute$toString = function() { return function Attribute$toString() { var name, value, interpolator; name = this.name; value = this.value; // Special case - select values (should not be stringified) if ( name === 'value' && this.element.name === 'select' ) { return; } // Special case - radio names if ( name === 'name' && this.element.name === 'input' && ( interpolator = this.interpolator ) ) { return 'name={{' + ( interpolator.keypath || interpolator.ref ) + '}}'; } // Numbers if ( typeof value === 'number' ) { return name + '="' + value + '"'; } // Strings if ( typeof value === 'string' ) { return name + '="' + escape( value ) + '"'; } // Everything else return value ? name : ''; }; function escape( value ) { return value.replace( /&/g, '&amp;' ).replace( /"/g, '&quot;' ).replace( /'/g, '&#39;' ); } }(); /* virtualdom/items/Element/Attribute/prototype/unbind.js */ var virtualdom_items_Element_Attribute$unbind = function Attribute$unbind() { // ignore non-dynamic attributes if ( this.fragment ) { this.fragment.unbind(); } }; /* virtualdom/items/Element/Attribute/prototype/update/updateSelectValue.js */ var virtualdom_items_Element_Attribute$update_updateSelectValue = function Attribute$updateSelect() { var value = this.value, options, option, optionValue, i; if ( !this.locked ) { this.node._ractive.value = value; options = this.node.options; i = options.length; while ( i-- ) { option = options[ i ]; optionValue = option._ractive ? option._ractive.value : option.value; // options inserted via a triple don't have _ractive if ( optionValue == value ) { // double equals as we may be comparing numbers with strings option.selected = true; break; } } } }; /* virtualdom/items/Element/Attribute/prototype/update/updateMultipleSelectValue.js */ var virtualdom_items_Element_Attribute$update_updateMultipleSelectValue = function( isArray ) { return function Attribute$updateMultipleSelect() { var value = this.value, options, i, option, optionValue; if ( !isArray( value ) ) { value = [ value ]; } options = this.node.options; i = options.length; while ( i-- ) { option = options[ i ]; optionValue = option._ractive ? option._ractive.value : option.value; // options inserted via a triple don't have _ractive option.selected = value.indexOf( optionValue ) !== -1; } }; }( isArray ); /* virtualdom/items/Element/Attribute/prototype/update/updateRadioName.js */ var virtualdom_items_Element_Attribute$update_updateRadioName = function Attribute$updateRadioName() { var node = ( value = this ).node, value = value.value; node.checked = value == node._ractive.value; }; /* virtualdom/items/Element/Attribute/prototype/update/updateRadioValue.js */ var virtualdom_items_Element_Attribute$update_updateRadioValue = function( runloop ) { return function Attribute$updateRadioValue() { var wasChecked, node = this.node, binding, bindings, i; wasChecked = node.checked; node.value = this.element.getAttribute( 'value' ); node.checked = this.element.getAttribute( 'value' ) === this.element.getAttribute( 'name' ); // This is a special case - if the input was checked, and the value // changed so that it's no longer checked, the twoway binding is // most likely out of date. To fix it we have to jump through some // hoops... this is a little kludgy but it works if ( wasChecked && !node.checked && this.element.binding ) { bindings = this.element.binding.siblings; if ( i = bindings.length ) { while ( i-- ) { binding = bindings[ i ]; if ( !binding.element.node ) { // this is the initial render, siblings are still rendering! // we'll come back later... return; } if ( binding.element.node.checked ) { runloop.addViewmodel( binding.root.viewmodel ); return binding.handleChange(); } } runloop.addViewmodel( binding.root.viewmodel ); this.root.viewmodel.set( binding.keypath, undefined ); } } }; }( runloop ); /* virtualdom/items/Element/Attribute/prototype/update/updateCheckboxName.js */ var virtualdom_items_Element_Attribute$update_updateCheckboxName = function( isArray ) { return function Attribute$updateCheckboxName() { var node, value; node = this.node; value = this.value; if ( !isArray( value ) ) { node.checked = value == node._ractive.value; } else { node.checked = value.indexOf( node._ractive.value ) !== -1; } }; }( isArray ); /* virtualdom/items/Element/Attribute/prototype/update/updateClassName.js */ var virtualdom_items_Element_Attribute$update_updateClassName = function Attribute$updateClassName() { var node, value; node = this.node; value = this.value; if ( value === undefined ) { value = ''; } node.className = value; }; /* virtualdom/items/Element/Attribute/prototype/update/updateIdAttribute.js */ var virtualdom_items_Element_Attribute$update_updateIdAttribute = function Attribute$updateIdAttribute() { var node, value; node = this.node; value = this.value; if ( value !== undefined ) { this.root.nodes[ value ] = undefined; } this.root.nodes[ value ] = node; node.id = value; }; /* virtualdom/items/Element/Attribute/prototype/update/updateIEStyleAttribute.js */ var virtualdom_items_Element_Attribute$update_updateIEStyleAttribute = function Attribute$updateIEStyleAttribute() { var node, value; node = this.node; value = this.value; if ( value === undefined ) { value = ''; } node.style.setAttribute( 'cssText', value ); }; /* virtualdom/items/Element/Attribute/prototype/update/updateContentEditableValue.js */ var virtualdom_items_Element_Attribute$update_updateContentEditableValue = function Attribute$updateContentEditableValue() { var node, value; node = this.node; value = this.value; if ( value === undefined ) { value = ''; } if ( !this.locked ) { node.innerHTML = value; } }; /* virtualdom/items/Element/Attribute/prototype/update/updateValue.js */ var virtualdom_items_Element_Attribute$update_updateValue = function Attribute$updateValue() { var node, value; node = this.node; value = this.value; // store actual value, so it doesn't get coerced to a string node._ractive.value = value; // with two-way binding, only update if the change wasn't initiated by the user // otherwise the cursor will often be sent to the wrong place if ( !this.locked ) { node.value = value == undefined ? '' : value; } }; /* virtualdom/items/Element/Attribute/prototype/update/updateBoolean.js */ var virtualdom_items_Element_Attribute$update_updateBoolean = function Attribute$updateBooleanAttribute() { // with two-way binding, only update if the change wasn't initiated by the user // otherwise the cursor will often be sent to the wrong place if ( !this.locked ) { this.node[ this.propertyName ] = this.value; } }; /* virtualdom/items/Element/Attribute/prototype/update/updateEverythingElse.js */ var virtualdom_items_Element_Attribute$update_updateEverythingElse = function Attribute$updateEverythingElse() { var node, name, value; node = this.node; name = this.name; value = this.value; if ( this.namespace ) { node.setAttributeNS( this.namespace, name, value ); } else if ( typeof value === 'string' || typeof value === 'number' ) { node.setAttribute( name, value ); } else { if ( value ) { node.setAttribute( name, '' ); } else { node.removeAttribute( name ); } } }; /* virtualdom/items/Element/Attribute/prototype/update.js */ var virtualdom_items_Element_Attribute$update = function( namespaces, noop, updateSelectValue, updateMultipleSelectValue, updateRadioName, updateRadioValue, updateCheckboxName, updateClassName, updateIdAttribute, updateIEStyleAttribute, updateContentEditableValue, updateValue, updateBoolean, updateEverythingElse ) { // There are a few special cases when it comes to updating attributes. For this reason, // the prototype .update() method points to this method, which waits until the // attribute has finished initialising, then replaces the prototype method with a more // suitable one. That way, we save ourselves doing a bunch of tests on each call return function Attribute$update() { var name, element, node, type, updateMethod; name = this.name; element = this.element; node = this.node; if ( name === 'id' ) { updateMethod = updateIdAttribute; } else if ( name === 'value' ) { // special case - selects if ( element.name === 'select' && name === 'value' ) { updateMethod = node.multiple ? updateMultipleSelectValue : updateSelectValue; } else if ( element.name === 'textarea' ) { updateMethod = updateValue; } else if ( node.getAttribute( 'contenteditable' ) ) { updateMethod = updateContentEditableValue; } else if ( element.name === 'input' ) { type = element.getAttribute( 'type' ); // type='file' value='{{fileList}}'> if ( type === 'file' ) { updateMethod = noop; } else if ( type === 'radio' && element.binding && element.binding.name === 'name' ) { updateMethod = updateRadioValue; } else { updateMethod = updateValue; } } } else if ( this.twoway && name === 'name' ) { if ( node.type === 'radio' ) { updateMethod = updateRadioName; } else if ( node.type === 'checkbox' ) { updateMethod = updateCheckboxName; } } else if ( name === 'style' && node.style.setAttribute ) { updateMethod = updateIEStyleAttribute; } else if ( name === 'class' && ( !node.namespaceURI || node.namespaceURI === namespaces.html ) ) { updateMethod = updateClassName; } else if ( this.useProperty ) { updateMethod = updateBoolean; } if ( !updateMethod ) { updateMethod = updateEverythingElse; } this.update = updateMethod; this.update(); }; }( namespaces, noop, virtualdom_items_Element_Attribute$update_updateSelectValue, virtualdom_items_Element_Attribute$update_updateMultipleSelectValue, virtualdom_items_Element_Attribute$update_updateRadioName, virtualdom_items_Element_Attribute$update_updateRadioValue, virtualdom_items_Element_Attribute$update_updateCheckboxName, virtualdom_items_Element_Attribute$update_updateClassName, virtualdom_items_Element_Attribute$update_updateIdAttribute, virtualdom_items_Element_Attribute$update_updateIEStyleAttribute, virtualdom_items_Element_Attribute$update_updateContentEditableValue, virtualdom_items_Element_Attribute$update_updateValue, virtualdom_items_Element_Attribute$update_updateBoolean, virtualdom_items_Element_Attribute$update_updateEverythingElse ); /* virtualdom/items/Element/Attribute/_Attribute.js */ var Attribute = function( bubble, init, rebind, render, toString, unbind, update ) { var Attribute = function( options ) { this.init( options ); }; Attribute.prototype = { bubble: bubble, init: init, rebind: rebind, render: render, toString: toString, unbind: unbind, update: update }; return Attribute; }( virtualdom_items_Element_Attribute$bubble, virtualdom_items_Element_Attribute$init, virtualdom_items_Element_Attribute$rebind, virtualdom_items_Element_Attribute$render, virtualdom_items_Element_Attribute$toString, virtualdom_items_Element_Attribute$unbind, virtualdom_items_Element_Attribute$update ); /* virtualdom/items/Element/prototype/init/createAttributes.js */ var virtualdom_items_Element$init_createAttributes = function( Attribute ) { return function( element, attributes ) { var name, attribute, result = []; for ( name in attributes ) { if ( attributes.hasOwnProperty( name ) ) { attribute = new Attribute( { element: element, name: name, value: attributes[ name ], root: element.root } ); result.push( result[ name ] = attribute ); } } return result; }; }( Attribute ); /* utils/extend.js */ var extend = function( target ) { var SLICE$0 = Array.prototype.slice; var sources = SLICE$0.call( arguments, 1 ); var prop, source; while ( source = sources.shift() ) { for ( prop in source ) { if ( source.hasOwnProperty( prop ) ) { target[ prop ] = source[ prop ]; } } } return target; }; /* virtualdom/items/Element/Binding/Binding.js */ var Binding = function( runloop, warn, create, extend, removeFromArray ) { var Binding = function( element ) { var interpolator, keypath, value; this.element = element; this.root = element.root; this.attribute = element.attributes[ this.name || 'value' ]; interpolator = this.attribute.interpolator; interpolator.twowayBinding = this; if ( interpolator.keypath && interpolator.keypath.substr === '${' ) { warn( 'Two-way binding does not work with expressions: ' + interpolator.keypath ); return false; } // A mustache may be *ambiguous*. Let's say we were given // `value="{{bar}}"`. If the context was `foo`, and `foo.bar` // *wasn't* `undefined`, the keypath would be `foo.bar`. // Then, any user input would result in `foo.bar` being updated. // // If, however, `foo.bar` *was* undefined, and so was `bar`, we would be // left with an unresolved partial keypath - so we are forced to make an // assumption. That assumption is that the input in question should // be forced to resolve to `bar`, and any user input would affect `bar` // and not `foo.bar`. // // Did that make any sense? No? Oh. Sorry. Well the moral of the story is // be explicit when using two-way data-binding about what keypath you're // updating. Using it in lists is probably a recipe for confusion... if ( !interpolator.keypath ) { if ( interpolator.ref ) { interpolator.resolve( interpolator.ref ); } // If we have a reference expression resolver, we have to force // members to attach themselves to the root if ( interpolator.resolver ) { interpolator.resolver.forceResolution(); } } this.keypath = keypath = interpolator.keypath; // initialise value, if it's undefined if ( this.root.viewmodel.get( keypath ) === undefined && this.getInitialValue ) { value = this.getInitialValue(); if ( value !== undefined ) { this.root.viewmodel.set( keypath, value ); } } }; Binding.prototype = { handleChange: function() { var this$0 = this; runloop.start( this.root ); this.attribute.locked = true; this.root.viewmodel.set( this.keypath, this.getValue() ); runloop.scheduleTask( function() { return this$0.attribute.locked = false; } ); runloop.end(); }, rebound: function() { var bindings, oldKeypath, newKeypath; oldKeypath = this.keypath; newKeypath = this.attribute.interpolator.keypath; // The attribute this binding is linked to has already done the work if ( oldKeypath === newKeypath ) { return; } removeFromArray( this.root._twowayBindings[ oldKeypath ], this ); this.keypath = newKeypath; bindings = this.root._twowayBindings[ newKeypath ] || ( this.root._twowayBindings[ newKeypath ] = [] ); bindings.push( this ); }, unbind: function() {} }; Binding.extend = function( properties ) { var Parent = this, SpecialisedBinding; SpecialisedBinding = function( element ) { Binding.call( this, element ); if ( this.init ) { this.init(); } }; SpecialisedBinding.prototype = create( Parent.prototype ); extend( SpecialisedBinding.prototype, properties ); SpecialisedBinding.extend = Binding.extend; return SpecialisedBinding; }; return Binding; }( runloop, warn, create, extend, removeFromArray ); /* virtualdom/items/Element/Binding/shared/handleDomEvent.js */ var handleDomEvent = function handleChange() { this._ractive.binding.handleChange(); }; /* virtualdom/items/Element/Binding/ContentEditableBinding.js */ var ContentEditableBinding = function( Binding, handleDomEvent ) { var ContentEditableBinding = Binding.extend( { getInitialValue: function() { return this.element.fragment ? this.element.fragment.toString() : ''; }, render: function() { var node = this.element.node; node.addEventListener( 'change', handleDomEvent, false ); if ( !this.root.lazy ) { node.addEventListener( 'input', handleDomEvent, false ); if ( node.attachEvent ) { node.addEventListener( 'keyup', handleDomEvent, false ); } } }, unrender: function() { var node = this.element.node; node.removeEventListener( 'change', handleDomEvent, false ); node.removeEventListener( 'input', handleDomEvent, false ); node.removeEventListener( 'keyup', handleDomEvent, false ); }, getValue: function() { return this.element.node.innerHTML; } } ); return ContentEditableBinding; }( Binding, handleDomEvent ); /* virtualdom/items/Element/Binding/shared/getSiblings.js */ var getSiblings = function() { var sets = {}; return function getSiblings( id, group, keypath ) { var hash = id + group + keypath; return sets[ hash ] || ( sets[ hash ] = [] ); }; }(); /* virtualdom/items/Element/Binding/RadioBinding.js */ var RadioBinding = function( runloop, removeFromArray, Binding, getSiblings, handleDomEvent ) { var RadioBinding = Binding.extend( { name: 'checked', init: function() { this.siblings = getSiblings( this.root._guid, 'radio', this.element.getAttribute( 'name' ) ); this.siblings.push( this ); }, render: function() { var node = this.element.node; node.addEventListener( 'change', handleDomEvent, false ); if ( node.attachEvent ) { node.addEventListener( 'click', handleDomEvent, false ); } }, unrender: function() { var node = this.element.node; node.removeEventListener( 'change', handleDomEvent, false ); node.removeEventListener( 'click', handleDomEvent, false ); }, handleChange: function() { runloop.start( this.root ); this.siblings.forEach( function( binding ) { binding.root.viewmodel.set( binding.keypath, binding.getValue() ); } ); runloop.end(); }, getValue: function() { return this.element.node.checked; }, unbind: function() { removeFromArray( this.siblings, this ); } } ); return RadioBinding; }( runloop, removeFromArray, Binding, getSiblings, handleDomEvent ); /* virtualdom/items/Element/Binding/RadioNameBinding.js */ var RadioNameBinding = function( removeFromArray, Binding, handleDomEvent, getSiblings ) { var RadioNameBinding = Binding.extend( { name: 'name', init: function() { this.siblings = getSiblings( this.root._guid, 'radioname', this.keypath ); this.siblings.push( this ); this.radioName = true; // so that ractive.updateModel() knows what to do with this this.attribute.twoway = true; }, getInitialValue: function() { if ( this.element.getAttribute( 'checked' ) ) { return this.element.getAttribute( 'value' ); } }, render: function() { var node = this.element.node; node.name = '{{' + this.keypath + '}}'; node.checked = this.root.viewmodel.get( this.keypath ) == this.element.getAttribute( 'value' ); node.addEventListener( 'change', handleDomEvent, false ); if ( node.attachEvent ) { node.addEventListener( 'click', handleDomEvent, false ); } }, unrender: function() { var node = this.element.node; node.removeEventListener( 'change', handleDomEvent, false ); node.removeEventListener( 'click', handleDomEvent, false ); }, getValue: function() { var node = this.element.node; return node._ractive ? node._ractive.value : node.value; }, handleChange: function() { // If this <input> is the one that's checked, then the value of its // `name` keypath gets set to its value if ( this.element.node.checked ) { Binding.prototype.handleChange.call( this ); } }, rebound: function( indexRef, newIndex, oldKeypath, newKeypath ) { var node; Binding.prototype.rebound.call( this, indexRef, newIndex, oldKeypath, newKeypath ); if ( node = this.element.node ) { node.name = '{{' + this.keypath + '}}'; } }, unbind: function() { removeFromArray( this.siblings, this ); } } ); return RadioNameBinding; }( removeFromArray, Binding, handleDomEvent, getSiblings ); /* virtualdom/items/Element/Binding/CheckboxNameBinding.js */ var CheckboxNameBinding = function( isArray, removeFromArray, Binding, getSiblings, handleDomEvent ) { var CheckboxNameBinding = Binding.extend( { name: 'name', getInitialValue: function() { // This only gets called once per group (of inputs that // share a name), because it only gets called if there // isn't an initial value. By the same token, we can make // a note of that fact that there was no initial value, // and populate it using any `checked` attributes that // exist (which users should avoid, but which we should // support anyway to avoid breaking expectations) this.noInitialValue = true; return []; }, init: function() { var existingValue, bindingValue, noInitialValue; this.checkboxName = true; // so that ractive.updateModel() knows what to do with this // Each input has a reference to an array containing it and its // siblings, as two-way binding depends on being able to ascertain // the status of all inputs within the group this.siblings = getSiblings( this.root._guid, 'checkboxes', this.keypath ); this.siblings.push( this ); if ( this.noInitialValue ) { this.siblings.noInitialValue = true; } noInitialValue = this.siblings.noInitialValue; existingValue = this.root.viewmodel.get( this.keypath ); bindingValue = this.element.getAttribute( 'value' ); if ( noInitialValue ) { this.isChecked = this.element.getAttribute( 'checked' ); if ( this.isChecked ) { existingValue.push( bindingValue ); } } else { this.isChecked = isArray( existingValue ) ? existingValue.indexOf( bindingValue ) !== -1 : existingValue === bindingValue; } }, unbind: function() { removeFromArray( this.siblings, this ); }, render: function() { var node = this.element.node; node.name = '{{' + this.keypath + '}}'; node.checked = this.isChecked; node.addEventListener( 'change', handleDomEvent, false ); // in case of IE emergency, bind to click event as well if ( node.attachEvent ) { node.addEventListener( 'click', handleDomEvent, false ); } }, unrender: function() { var node = this.element.node; node.removeEventListener( 'change', handleDomEvent, false ); node.removeEventListener( 'click', handleDomEvent, false ); }, changed: function() { var wasChecked = !!this.isChecked; this.isChecked = this.element.node.checked; return this.isChecked === wasChecked; }, handleChange: function() { this.isChecked = this.element.node.checked; Binding.prototype.handleChange.call( this ); }, getValue: function() { return this.siblings.filter( isChecked ).map( getValue ); } } ); function isChecked( binding ) { return binding.isChecked; } function getValue( binding ) { return binding.element.getAttribute( 'value' ); } return CheckboxNameBinding; }( isArray, removeFromArray, Binding, getSiblings, handleDomEvent ); /* virtualdom/items/Element/Binding/CheckboxBinding.js */ var CheckboxBinding = function( Binding, handleDomEvent ) { var CheckboxBinding = Binding.extend( { name: 'checked', render: function() { var node = this.element.node; node.addEventListener( 'change', handleDomEvent, false ); if ( node.attachEvent ) { node.addEventListener( 'click', handleDomEvent, false ); } }, unrender: function() { var node = this.element.node; node.removeEventListener( 'change', handleDomEvent, false ); node.removeEventListener( 'click', handleDomEvent, false ); }, getValue: function() { return this.element.node.checked; } } ); return CheckboxBinding; }( Binding, handleDomEvent ); /* virtualdom/items/Element/Binding/SelectBinding.js */ var SelectBinding = function( runloop, Binding, handleDomEvent ) { var SelectBinding = Binding.extend( { getInitialValue: function() { var options = this.element.options, len, i; i = len = options.length; if ( !len ) { return; } // take the final selected option... while ( i-- ) { if ( options[ i ].getAttribute( 'selected' ) ) { return options[ i ].getAttribute( 'value' ); } } // or the first non-disabled option, if none are selected while ( ++i < len ) { if ( !options[ i ].getAttribute( 'disabled' ) ) { return options[ i ].getAttribute( 'value' ); } } }, render: function() { this.element.node.addEventListener( 'change', handleDomEvent, false ); }, unrender: function() { this.element.node.removeEventListener( 'change', handleDomEvent, false ); }, // TODO this method is an anomaly... is it necessary? setValue: function( value ) { runloop.addViewmodel( this.root.viewmodel ); this.root.viewmodel.set( this.keypath, value ); }, getValue: function() { var options, i, len, option, optionValue; options = this.element.node.options; len = options.length; for ( i = 0; i < len; i += 1 ) { option = options[ i ]; if ( options[ i ].selected ) { optionValue = option._ractive ? option._ractive.value : option.value; return optionValue; } } }, forceUpdate: function() { var this$0 = this; var value = this.getValue(); if ( value !== undefined ) { this.attribute.locked = true; runloop.addViewmodel( this.root.viewmodel ); runloop.scheduleTask( function() { return this$0.attribute.locked = false; } ); this.root.viewmodel.set( this.keypath, value ); } } } ); return SelectBinding; }( runloop, Binding, handleDomEvent ); /* utils/arrayContentsMatch.js */ var arrayContentsMatch = function( isArray ) { return function( a, b ) { var i; if ( !isArray( a ) || !isArray( b ) ) { return false; } if ( a.length !== b.length ) { return false; } i = a.length; while ( i-- ) { if ( a[ i ] !== b[ i ] ) { return false; } } return true; }; }( isArray ); /* virtualdom/items/Element/Binding/MultipleSelectBinding.js */ var MultipleSelectBinding = function( runloop, arrayContentsMatch, SelectBinding, handleDomEvent ) { var MultipleSelectBinding = SelectBinding.extend( { getInitialValue: function() { return this.element.options.filter( function( option ) { return option.getAttribute( 'selected' ); } ).map( function( option ) { return option.getAttribute( 'value' ); } ); }, render: function() { var valueFromModel; this.element.node.addEventListener( 'change', handleDomEvent, false ); valueFromModel = this.root.viewmodel.get( this.keypath ); if ( valueFromModel === undefined ) { // get value from DOM, if possible this.handleChange(); } }, unrender: function() { this.element.node.removeEventListener( 'change', handleDomEvent, false ); }, setValue: function() { throw new Error( 'TODO not implemented yet' ); }, getValue: function() { var selectedValues, options, i, len, option, optionValue; selectedValues = []; options = this.element.node.options; len = options.length; for ( i = 0; i < len; i += 1 ) { option = options[ i ]; if ( option.selected ) { optionValue = option._ractive ? option._ractive.value : option.value; selectedValues.push( optionValue ); } } return selectedValues; }, handleChange: function() { var attribute, previousValue, value; attribute = this.attribute; previousValue = attribute.value; value = this.getValue(); if ( previousValue === undefined || !arrayContentsMatch( value, previousValue ) ) { SelectBinding.prototype.handleChange.call( this ); } return this; }, forceUpdate: function() { var this$0 = this; var value = this.getValue(); if ( value !== undefined ) { this.attribute.locked = true; runloop.addViewmodel( this.root.viewmodel ); runloop.scheduleTask( function() { return this$0.attribute.locked = false; } ); this.root.viewmodel.set( this.keypath, value ); } }, updateModel: function() { if ( this.attribute.value === undefined || !this.attribute.value.length ) { this.root.viewmodel.set( this.keypath, this.initialValue ); } } } ); return MultipleSelectBinding; }( runloop, arrayContentsMatch, SelectBinding, handleDomEvent ); /* virtualdom/items/Element/Binding/FileListBinding.js */ var FileListBinding = function( Binding, handleDomEvent ) { var FileListBinding = Binding.extend( { render: function() { this.element.node.addEventListener( 'change', handleDomEvent, false ); }, unrender: function() { this.element.node.removeEventListener( 'change', handleDomEvent, false ); }, getValue: function() { return this.element.node.files; } } ); return FileListBinding; }( Binding, handleDomEvent ); /* virtualdom/items/Element/Binding/GenericBinding.js */ var GenericBinding = function( Binding, handleDomEvent ) { var GenericBinding, getOptions; getOptions = { evaluateWrapped: true }; GenericBinding = Binding.extend( { getInitialValue: function() { return ''; }, getValue: function() { return this.element.node.value; }, render: function() { var node = this.element.node; node.addEventListener( 'change', handleDomEvent, false ); if ( !this.root.lazy ) { node.addEventListener( 'input', handleDomEvent, false ); if ( node.attachEvent ) { node.addEventListener( 'keyup', handleDomEvent, false ); } } node.addEventListener( 'blur', handleBlur, false ); }, unrender: function() { var node = this.element.node; node.removeEventListener( 'change', handleDomEvent, false ); node.removeEventListener( 'input', handleDomEvent, false ); node.removeEventListener( 'keyup', handleDomEvent, false ); node.removeEventListener( 'blur', handleBlur, false ); } } ); return GenericBinding; function handleBlur() { var value; handleDomEvent.call( this ); value = this._ractive.root.viewmodel.get( this._ractive.binding.keypath, getOptions ); this.value = value == undefined ? '' : value; } }( Binding, handleDomEvent ); /* virtualdom/items/Element/Binding/NumericBinding.js */ var NumericBinding = function( GenericBinding ) { return GenericBinding.extend( { getInitialValue: function() { return undefined; }, getValue: function() { var value = parseFloat( this.element.node.value ); return isNaN( value ) ? undefined : value; } } ); }( GenericBinding ); /* virtualdom/items/Element/prototype/init/createTwowayBinding.js */ var virtualdom_items_Element$init_createTwowayBinding = function( log, ContentEditableBinding, RadioBinding, RadioNameBinding, CheckboxNameBinding, CheckboxBinding, SelectBinding, MultipleSelectBinding, FileListBinding, NumericBinding, GenericBinding ) { return function createTwowayBinding( element ) { var attributes = element.attributes, type, Binding, bindName, bindChecked; // if this is a late binding, and there's already one, it // needs to be torn down if ( element.binding ) { element.binding.teardown(); element.binding = null; } // contenteditable if ( element.getAttribute( 'contenteditable' ) && isBindable( attributes.value ) ) { Binding = ContentEditableBinding; } else if ( element.name === 'input' ) { type = element.getAttribute( 'type' ); if ( type === 'radio' || type === 'checkbox' ) { bindName = isBindable( attributes.name ); bindChecked = isBindable( attributes.checked ); // we can either bind the name attribute, or the checked attribute - not both if ( bindName && bindChecked ) { log.error( { message: 'badRadioInputBinding' } ); } if ( bindName ) { Binding = type === 'radio' ? RadioNameBinding : CheckboxNameBinding; } else if ( bindChecked ) { Binding = type === 'radio' ? RadioBinding : CheckboxBinding; } } else if ( type === 'file' && isBindable( attributes.value ) ) { Binding = FileListBinding; } else if ( isBindable( attributes.value ) ) { Binding = type === 'number' || type === 'range' ? NumericBinding : GenericBinding; } } else if ( element.name === 'select' && isBindable( attributes.value ) ) { Binding = element.getAttribute( 'multiple' ) ? MultipleSelectBinding : SelectBinding; } else if ( element.name === 'textarea' && isBindable( attributes.value ) ) { Binding = GenericBinding; } if ( Binding ) { return new Binding( element ); } }; function isBindable( attribute ) { return attribute && attribute.isBindable; } }( log, ContentEditableBinding, RadioBinding, RadioNameBinding, CheckboxNameBinding, CheckboxBinding, SelectBinding, MultipleSelectBinding, FileListBinding, NumericBinding, GenericBinding ); /* virtualdom/items/Element/EventHandler/prototype/fire.js */ var virtualdom_items_Element_EventHandler$fire = function EventHandler$fire( event ) { this.root.fire( this.action.toString().trim(), event ); }; /* virtualdom/items/Element/EventHandler/prototype/init.js */ var virtualdom_items_Element_EventHandler$init = function( circular ) { var Fragment, getValueOptions = { args: true }; circular.push( function() { Fragment = circular.Fragment; } ); return function EventHandler$init( element, name, template ) { var action; this.element = element; this.root = element.root; this.name = name; this.proxies = []; // Get action ('foo' in 'on-click='foo') action = template.n || template; if ( typeof action !== 'string' ) { action = new Fragment( { template: action, root: this.root, owner: this.element } ); } this.action = action; // Get parameters if ( template.d ) { this.dynamicParams = new Fragment( { template: template.d, root: this.root, owner: this.element } ); this.fire = fireEventWithDynamicParams; } else if ( template.a ) { this.params = template.a; this.fire = fireEventWithParams; } }; function fireEventWithParams( event ) { this.root.fire.apply( this.root, [ this.action.toString().trim(), event ].concat( this.params ) ); } function fireEventWithDynamicParams( event ) { var args = this.dynamicParams.getValue( getValueOptions ); // need to strip [] from ends if a string! if ( typeof args === 'string' ) { args = args.substr( 1, args.length - 2 ); } this.root.fire.apply( this.root, [ this.action.toString().trim(), event ].concat( args ) ); } }( circular ); /* virtualdom/items/Element/EventHandler/prototype/rebind.js */ var virtualdom_items_Element_EventHandler$rebind = function EventHandler$rebind( indexRef, newIndex, oldKeypath, newKeypath ) { if ( typeof this.action !== 'string' ) { this.action.rebind( indexRef, newIndex, oldKeypath, newKeypath ); } if ( this.dynamicParams ) { this.dynamicParams.rebind( indexRef, newIndex, oldKeypath, newKeypath ); } }; /* virtualdom/items/Element/EventHandler/shared/genericHandler.js */ var genericHandler = function genericHandler( event ) { var storage, handler; storage = this._ractive; handler = storage.events[ event.type ]; handler.fire( { node: this, original: event, index: storage.index, keypath: storage.keypath, context: storage.root.get( storage.keypath ) } ); }; /* virtualdom/items/Element/EventHandler/prototype/render.js */ var virtualdom_items_Element_EventHandler$render = function( warn, config, genericHandler ) { var customHandlers = {}; return function EventHandler$render() { var name = this.name, definition; this.node = this.element.node; if ( definition = config.registries.events.find( this.root, name ) ) { this.custom = definition( this.node, getCustomHandler( name ) ); } else { // Looks like we're dealing with a standard DOM event... but let's check if ( !( 'on' + name in this.node ) && !( window && 'on' + name in window ) ) { warn( 'Missing "' + this.name + '" event. You may need to download a plugin via http://docs.ractivejs.org/latest/plugins#events' ); } this.node.addEventListener( name, genericHandler, false ); } // store this on the node itself, so it can be retrieved by a // universal handler this.node._ractive.events[ name ] = this; }; function getCustomHandler( name ) { if ( !customHandlers[ name ] ) { customHandlers[ name ] = function( event ) { var storage = event.node._ractive; event.index = storage.index; event.keypath = storage.keypath; event.context = storage.root.get( storage.keypath ); storage.events[ name ].fire( event ); }; } return customHandlers[ name ]; } }( warn, config, genericHandler ); /* virtualdom/items/Element/EventHandler/prototype/teardown.js */ var virtualdom_items_Element_EventHandler$teardown = function EventHandler$teardown() { // Tear down dynamic name if ( typeof this.action !== 'string' ) { this.action.teardown(); } // Tear down dynamic parameters if ( this.dynamicParams ) { this.dynamicParams.teardown(); } }; /* virtualdom/items/Element/EventHandler/prototype/unrender.js */ var virtualdom_items_Element_EventHandler$unrender = function( genericHandler ) { return function EventHandler$unrender() { if ( this.custom ) { this.custom.teardown(); } else { this.node.removeEventListener( this.name, genericHandler, false ); } }; }( genericHandler ); /* virtualdom/items/Element/EventHandler/_EventHandler.js */ var EventHandler = function( fire, init, rebind, render, teardown, unrender ) { var EventHandler = function( element, name, template ) { this.init( element, name, template ); }; EventHandler.prototype = { fire: fire, init: init, rebind: rebind, render: render, teardown: teardown, unrender: unrender }; return EventHandler; }( virtualdom_items_Element_EventHandler$fire, virtualdom_items_Element_EventHandler$init, virtualdom_items_Element_EventHandler$rebind, virtualdom_items_Element_EventHandler$render, virtualdom_items_Element_EventHandler$teardown, virtualdom_items_Element_EventHandler$unrender ); /* virtualdom/items/Element/prototype/init/createEventHandlers.js */ var virtualdom_items_Element$init_createEventHandlers = function( EventHandler ) { return function( element, template ) { var i, name, names, handler, result = []; for ( name in template ) { if ( template.hasOwnProperty( name ) ) { names = name.split( '-' ); i = names.length; while ( i-- ) { handler = new EventHandler( element, names[ i ], template[ name ] ); result.push( handler ); } } } return result; }; }( EventHandler ); /* virtualdom/items/Element/Decorator/_Decorator.js */ var Decorator = function( log, circular, config ) { var Fragment, getValueOptions, Decorator; circular.push( function() { Fragment = circular.Fragment; } ); getValueOptions = { args: true }; Decorator = function( element, template ) { var decorator = this, ractive, name, fragment; decorator.element = element; decorator.root = ractive = element.root; name = template.n || template; if ( typeof name !== 'string' ) { fragment = new Fragment( { template: name, root: ractive, owner: element } ); name = fragment.toString(); fragment.unbind(); } if ( template.a ) { decorator.params = template.a; } else if ( template.d ) { decorator.fragment = new Fragment( { template: template.d, root: ractive, owner: element } ); decorator.params = decorator.fragment.getValue( getValueOptions ); decorator.fragment.bubble = function() { this.dirtyArgs = this.dirtyValue = true; decorator.params = this.getValue( getValueOptions ); if ( decorator.ready ) { decorator.update(); } }; } decorator.fn = config.registries.decorators.find( ractive, name ); if ( !decorator.fn ) { log.error( { debug: ractive.debug, message: 'missingPlugin', args: { plugin: 'decorator', name: name } } ); } }; Decorator.prototype = { init: function() { var decorator = this, node, result, args; node = decorator.element.node; if ( decorator.params ) { args = [ node ].concat( decorator.params ); result = decorator.fn.apply( decorator.root, args ); } else { result = decorator.fn.call( decorator.root, node ); } if ( !result || !result.teardown ) { throw new Error( 'Decorator definition must return an object with a teardown method' ); } // TODO does this make sense? decorator.actual = result; decorator.ready = true; }, update: function() { if ( this.actual.update ) { this.actual.update.apply( this.root, this.params ); } else { this.actual.teardown( true ); this.init(); } }, teardown: function( updating ) { this.actual.teardown(); if ( !updating && this.fragment ) { this.fragment.unbind(); } } }; return Decorator; }( log, circular, config ); /* virtualdom/items/Element/special/select/sync.js */ var sync = function( toArray ) { return function syncSelect( selectElement ) { var selectNode, selectValue, isMultiple, options, optionWasSelected; selectNode = selectElement.node; if ( !selectNode ) { return; } options = toArray( selectNode.options ); selectValue = selectElement.getAttribute( 'value' ); isMultiple = selectElement.getAttribute( 'multiple' ); // If the <select> has a specified value, that should override // these options if ( selectValue !== undefined ) { options.forEach( function( o ) { var optionValue, shouldSelect; optionValue = o._ractive ? o._ractive.value : o.value; shouldSelect = isMultiple ? valueContains( selectValue, optionValue ) : selectValue == optionValue; if ( shouldSelect ) { optionWasSelected = true; } o.selected = shouldSelect; } ); if ( !optionWasSelected ) { if ( options[ 0 ] ) { options[ 0 ].selected = true; } if ( selectElement.binding ) { selectElement.binding.forceUpdate(); } } } else if ( selectElement.binding ) { selectElement.binding.forceUpdate(); } }; function valueContains( selectValue, optionValue ) { var i = selectValue.length; while ( i-- ) { if ( selectValue[ i ] == optionValue ) { return true; } } } }( toArray ); /* virtualdom/items/Element/special/select/bubble.js */ var bubble = function( runloop, syncSelect ) { return function bubbleSelect() { var this$0 = this; if ( !this.dirty ) { this.dirty = true; runloop.scheduleTask( function() { syncSelect( this$0 ); this$0.dirty = false; } ); } this.parentFragment.bubble(); }; }( runloop, sync ); /* virtualdom/items/Element/special/option/findParentSelect.js */ var findParentSelect = function findParentSelect( element ) { do { if ( element.name === 'select' ) { return element; } } while ( element = element.parent ); }; /* virtualdom/items/Element/special/option/init.js */ var init = function( findParentSelect ) { return function initOption( option, template ) { option.select = findParentSelect( option.parent ); option.select.options.push( option ); // If the value attribute is missing, use the element's content if ( !template.a ) { template.a = {}; } // ...as long as it isn't disabled if ( !template.a.value && !template.a.hasOwnProperty( 'disabled' ) ) { template.a.value = template.f; } // If there is a `selected` attribute, but the <select> // already has a value, delete it if ( 'selected' in template.a && option.select.getAttribute( 'value' ) !== undefined ) { delete template.a.selected; } }; }( findParentSelect ); /* virtualdom/items/Element/prototype/init.js */ var virtualdom_items_Element$init = function( types, enforceCase, createAttributes, createTwowayBinding, createEventHandlers, Decorator, bubbleSelect, initOption, circular ) { var Fragment; circular.push( function() { Fragment = circular.Fragment; } ); return function Element$init( options ) { var parentFragment, template, ractive, binding, bindings; this.type = types.ELEMENT; // stuff we'll need later parentFragment = this.parentFragment = options.parentFragment; template = this.template = options.template; this.parent = options.pElement || parentFragment.pElement; this.root = ractive = parentFragment.root; this.index = options.index; this.name = enforceCase( template.e ); // Special case - <option> elements if ( this.name === 'option' ) { initOption( this, template ); } // Special case - <select> elements if ( this.name === 'select' ) { this.options = []; this.bubble = bubbleSelect; } // create attributes this.attributes = createAttributes( this, template.a ); // append children, if there are any if ( template.f ) { this.fragment = new Fragment( { template: template.f, root: ractive, owner: this, pElement: this } ); } // create twoway binding if ( ractive.twoway && ( binding = createTwowayBinding( this, template.a ) ) ) { this.binding = binding; // register this with the root, so that we can do ractive.updateModel() bindings = this.root._twowayBindings[ binding.keypath ] || ( this.root._twowayBindings[ binding.keypath ] = [] ); bindings.push( binding ); } // create event proxies if ( template.v ) { this.eventHandlers = createEventHandlers( this, template.v ); } // create decorator if ( template.o ) { this.decorator = new Decorator( this, template.o ); } // create transitions this.intro = template.t0 || template.t1; this.outro = template.t0 || template.t2; }; }( types, enforceCase, virtualdom_items_Element$init_createAttributes, virtualdom_items_Element$init_createTwowayBinding, virtualdom_items_Element$init_createEventHandlers, Decorator, bubble, init, circular ); /* virtualdom/items/shared/utils/startsWith.js */ var startsWith = function( startsWithKeypath ) { return function startsWith( target, keypath ) { return target === keypath || startsWithKeypath( target, keypath ); }; }( startsWithKeypath ); /* virtualdom/items/shared/utils/assignNewKeypath.js */ var assignNewKeypath = function( startsWith, getNewKeypath ) { return function assignNewKeypath( target, property, oldKeypath, newKeypath ) { var existingKeypath = target[ property ]; if ( !existingKeypath || startsWith( existingKeypath, newKeypath ) || !startsWith( existingKeypath, oldKeypath ) ) { return; } target[ property ] = getNewKeypath( existingKeypath, oldKeypath, newKeypath ); }; }( startsWith, getNewKeypath ); /* virtualdom/items/Element/prototype/rebind.js */ var virtualdom_items_Element$rebind = function( assignNewKeypath ) { return function Element$rebind( indexRef, newIndex, oldKeypath, newKeypath ) { var i, storage, liveQueries, ractive; if ( this.attributes ) { this.attributes.forEach( rebind ); } if ( this.eventHandlers ) { this.eventHandlers.forEach( rebind ); } // rebind children if ( this.fragment ) { rebind( this.fragment ); } // Update live queries, if necessary if ( liveQueries = this.liveQueries ) { ractive = this.root; i = liveQueries.length; while ( i-- ) { liveQueries[ i ]._makeDirty(); } } if ( this.node && ( storage = this.node._ractive ) ) { // adjust keypath if needed assignNewKeypath( storage, 'keypath', oldKeypath, newKeypath ); if ( indexRef != undefined ) { storage.index[ indexRef ] = newIndex; } } function rebind( thing ) { thing.rebind( indexRef, newIndex, oldKeypath, newKeypath ); } }; }( assignNewKeypath ); /* virtualdom/items/Element/special/img/render.js */ var render = function renderImage( img ) { var width, height, loadHandler; // if this is an <img>, and we're in a crap browser, we may need to prevent it // from overriding width and height when it loads the src if ( ( width = img.getAttribute( 'width' ) ) || ( height = img.getAttribute( 'height' ) ) ) { img.node.addEventListener( 'load', loadHandler = function() { if ( width ) { img.node.width = width.value; } if ( height ) { img.node.height = height.value; } img.node.removeEventListener( 'load', loadHandler, false ); }, false ); } }; /* virtualdom/items/Element/Transition/prototype/init.js */ var virtualdom_items_Element_Transition$init = function( log, config, circular ) { var Fragment, getValueOptions = {}; // TODO what are the options? circular.push( function() { Fragment = circular.Fragment; } ); return function Transition$init( element, template, isIntro ) { var t = this, ractive, name, fragment; t.element = element; t.root = ractive = element.root; t.isIntro = isIntro; name = template.n || template; if ( typeof name !== 'string' ) { fragment = new Fragment( { template: name, root: ractive, owner: element } ); name = fragment.toString(); fragment.unbind(); } t.name = name; if ( template.a ) { t.params = template.a; } else if ( template.d ) { // TODO is there a way to interpret dynamic arguments without all the // 'dependency thrashing'? fragment = new Fragment( { template: template.d, root: ractive, owner: element } ); t.params = fragment.getValue( getValueOptions ); fragment.unbind(); } t._fn = config.registries.transitions.find( ractive, name ); if ( !t._fn ) { log.error( { debug: ractive.debug, message: 'missingPlugin', args: { plugin: 'transition', name: name } } ); return; } }; }( log, config, circular ); /* utils/camelCase.js */ var camelCase = function( hyphenatedStr ) { return hyphenatedStr.replace( /-([a-zA-Z])/g, function( match, $1 ) { return $1.toUpperCase(); } ); }; /* virtualdom/items/Element/Transition/helpers/prefix.js */ var prefix = function( isClient, vendors, createElement, camelCase ) { var prefix, prefixCache, testStyle; if ( !isClient ) { prefix = null; } else { prefixCache = {}; testStyle = createElement( 'div' ).style; prefix = function( prop ) { var i, vendor, capped; prop = camelCase( prop ); if ( !prefixCache[ prop ] ) { if ( testStyle[ prop ] !== undefined ) { prefixCache[ prop ] = prop; } else { // test vendors... capped = prop.charAt( 0 ).toUpperCase() + prop.substring( 1 ); i = vendors.length; while ( i-- ) { vendor = vendors[ i ]; if ( testStyle[ vendor + capped ] !== undefined ) { prefixCache[ prop ] = vendor + capped; break; } } } } return prefixCache[ prop ]; }; } return prefix; }( isClient, vendors, createElement, camelCase ); /* virtualdom/items/Element/Transition/prototype/getStyle.js */ var virtualdom_items_Element_Transition$getStyle = function( legacy, isClient, isArray, prefix ) { var getStyle, getComputedStyle; if ( !isClient ) { getStyle = null; } else { getComputedStyle = window.getComputedStyle || legacy.getComputedStyle; getStyle = function( props ) { var computedStyle, styles, i, prop, value; computedStyle = getComputedStyle( this.node ); if ( typeof props === 'string' ) { value = computedStyle[ prefix( props ) ]; if ( value === '0px' ) { value = 0; } return value; } if ( !isArray( props ) ) { throw new Error( 'Transition$getStyle must be passed a string, or an array of strings representing CSS properties' ); } styles = {}; i = props.length; while ( i-- ) { prop = props[ i ]; value = computedStyle[ prefix( prop ) ]; if ( value === '0px' ) { value = 0; } styles[ prop ] = value; } return styles; }; } return getStyle; }( legacy, isClient, isArray, prefix ); /* virtualdom/items/Element/Transition/prototype/setStyle.js */ var virtualdom_items_Element_Transition$setStyle = function( prefix ) { return function( style, value ) { var prop; if ( typeof style === 'string' ) { this.node.style[ prefix( style ) ] = value; } else { for ( prop in style ) { if ( style.hasOwnProperty( prop ) ) { this.node.style[ prefix( prop ) ] = style[ prop ]; } } } return this; }; }( prefix ); /* shared/Ticker.js */ var Ticker = function( warn, getTime, animations ) { // TODO what happens if a transition is aborted? // TODO use this with Animation to dedupe some code? var Ticker = function( options ) { var easing; this.duration = options.duration; this.step = options.step; this.complete = options.complete; // easing if ( typeof options.easing === 'string' ) { easing = options.root.easing[ options.easing ]; if ( !easing ) { warn( 'Missing easing function ("' + options.easing + '"). You may need to download a plugin from [TODO]' ); easing = linear; } } else if ( typeof options.easing === 'function' ) { easing = options.easing; } else { easing = linear; } this.easing = easing; this.start = getTime(); this.end = this.start + this.duration; this.running = true; animations.add( this ); }; Ticker.prototype = { tick: function( now ) { var elapsed, eased; if ( !this.running ) { return false; } if ( now > this.end ) { if ( this.step ) { this.step( 1 ); } if ( this.complete ) { this.complete( 1 ); } return false; } elapsed = now - this.start; eased = this.easing( elapsed / this.duration ); if ( this.step ) { this.step( eased ); } return true; }, stop: function() { if ( this.abort ) { this.abort(); } this.running = false; } }; return Ticker; function linear( t ) { return t; } }( warn, getTime, animations ); /* virtualdom/items/Element/Transition/helpers/unprefix.js */ var unprefix = function( vendors ) { var unprefixPattern = new RegExp( '^-(?:' + vendors.join( '|' ) + ')-' ); return function( prop ) { return prop.replace( unprefixPattern, '' ); }; }( vendors ); /* virtualdom/items/Element/Transition/helpers/hyphenate.js */ var hyphenate = function( vendors ) { var vendorPattern = new RegExp( '^(?:' + vendors.join( '|' ) + ')([A-Z])' ); return function( str ) { var hyphenated; if ( !str ) { return ''; } if ( vendorPattern.test( str ) ) { str = '-' + str; } hyphenated = str.replace( /[A-Z]/g, function( match ) { return '-' + match.toLowerCase(); } ); return hyphenated; }; }( vendors ); /* virtualdom/items/Element/Transition/prototype/animateStyle/createTransitions.js */ var virtualdom_items_Element_Transition$animateStyle_createTransitions = function( isClient, warn, createElement, camelCase, interpolate, Ticker, prefix, unprefix, hyphenate ) { var createTransitions, testStyle, TRANSITION, TRANSITIONEND, CSS_TRANSITIONS_ENABLED, TRANSITION_DURATION, TRANSITION_PROPERTY, TRANSITION_TIMING_FUNCTION, canUseCssTransitions = {}, cannotUseCssTransitions = {}; if ( !isClient ) { createTransitions = null; } else { testStyle = createElement( 'div' ).style; // determine some facts about our environment ( function() { if ( testStyle.transition !== undefined ) { TRANSITION = 'transition'; TRANSITIONEND = 'transitionend'; CSS_TRANSITIONS_ENABLED = true; } else if ( testStyle.webkitTransition !== undefined ) { TRANSITION = 'webkitTransition'; TRANSITIONEND = 'webkitTransitionEnd'; CSS_TRANSITIONS_ENABLED = true; } else { CSS_TRANSITIONS_ENABLED = false; } }() ); if ( TRANSITION ) { TRANSITION_DURATION = TRANSITION + 'Duration'; TRANSITION_PROPERTY = TRANSITION + 'Property'; TRANSITION_TIMING_FUNCTION = TRANSITION + 'TimingFunction'; } createTransitions = function( t, to, options, changedProperties, resolve ) { // Wait a beat (otherwise the target styles will be applied immediately) // TODO use a fastdom-style mechanism? setTimeout( function() { var hashPrefix, jsTransitionsComplete, cssTransitionsComplete, checkComplete, transitionEndHandler; checkComplete = function() { if ( jsTransitionsComplete && cssTransitionsComplete ) { t.root.fire( t.name + ':end', t.node, t.isIntro ); resolve(); } }; // this is used to keep track of which elements can use CSS to animate // which properties hashPrefix = ( t.node.namespaceURI || '' ) + t.node.tagName; t.node.style[ TRANSITION_PROPERTY ] = changedProperties.map( prefix ).map( hyphenate ).join( ',' ); t.node.style[ TRANSITION_TIMING_FUNCTION ] = hyphenate( options.easing || 'linear' ); t.node.style[ TRANSITION_DURATION ] = options.duration / 1000 + 's'; transitionEndHandler = function( event ) { var index; index = changedProperties.indexOf( camelCase( unprefix( event.propertyName ) ) ); if ( index !== -1 ) { changedProperties.splice( index, 1 ); } if ( changedProperties.length ) { // still transitioning... return; } t.node.removeEventListener( TRANSITIONEND, transitionEndHandler, false ); cssTransitionsComplete = true; checkComplete(); }; t.node.addEventListener( TRANSITIONEND, transitionEndHandler, false ); setTimeout( function() { var i = changedProperties.length, hash, originalValue, index, propertiesToTransitionInJs = [], prop, suffix; while ( i-- ) { prop = changedProperties[ i ]; hash = hashPrefix + prop; if ( CSS_TRANSITIONS_ENABLED && !cannotUseCssTransitions[ hash ] ) { t.node.style[ prefix( prop ) ] = to[ prop ]; // If we're not sure if CSS transitions are supported for // this tag/property combo, find out now if ( !canUseCssTransitions[ hash ] ) { originalValue = t.getStyle( prop ); // if this property is transitionable in this browser, // the current style will be different from the target style canUseCssTransitions[ hash ] = t.getStyle( prop ) != to[ prop ]; cannotUseCssTransitions[ hash ] = !canUseCssTransitions[ hash ]; // Reset, if we're going to use timers after all if ( cannotUseCssTransitions[ hash ] ) { t.node.style[ prefix( prop ) ] = originalValue; } } } if ( !CSS_TRANSITIONS_ENABLED || cannotUseCssTransitions[ hash ] ) { // we need to fall back to timer-based stuff if ( originalValue === undefined ) { originalValue = t.getStyle( prop ); } // need to remove this from changedProperties, otherwise transitionEndHandler // will get confused index = changedProperties.indexOf( prop ); if ( index === -1 ) { warn( 'Something very strange happened with transitions. If you see this message, please let @RactiveJS know. Thanks!' ); } else { changedProperties.splice( index, 1 ); } // TODO Determine whether this property is animatable at all suffix = /[^\d]*$/.exec( to[ prop ] )[ 0 ]; // ...then kick off a timer-based transition propertiesToTransitionInJs.push( { name: prefix( prop ), interpolator: interpolate( parseFloat( originalValue ), parseFloat( to[ prop ] ) ), suffix: suffix } ); } } // javascript transitions if ( propertiesToTransitionInJs.length ) { new Ticker( { root: t.root, duration: options.duration, easing: camelCase( options.easing || '' ), step: function( pos ) { var prop, i; i = propertiesToTransitionInJs.length; while ( i-- ) { prop = propertiesToTransitionInJs[ i ]; t.node.style[ prop.name ] = prop.interpolator( pos ) + prop.suffix; } }, complete: function() { jsTransitionsComplete = true; checkComplete(); } } ); } else { jsTransitionsComplete = true; } if ( !changedProperties.length ) { // We need to cancel the transitionEndHandler, and deal with // the fact that it will never fire t.node.removeEventListener( TRANSITIONEND, transitionEndHandler, false ); cssTransitionsComplete = true; checkComplete(); } }, 0 ); }, options.delay || 0 ); }; } return createTransitions; }( isClient, warn, createElement, camelCase, interpolate, Ticker, prefix, unprefix, hyphenate ); /* virtualdom/items/Element/Transition/prototype/animateStyle/visibility.js */ var virtualdom_items_Element_Transition$animateStyle_visibility = function( vendors ) { var hidden, vendor, prefix, i, visibility; if ( typeof document !== 'undefined' ) { hidden = 'hidden'; visibility = {}; if ( hidden in document ) { prefix = ''; } else { i = vendors.length; while ( i-- ) { vendor = vendors[ i ]; hidden = vendor + 'Hidden'; if ( hidden in document ) { prefix = vendor; } } } if ( prefix !== undefined ) { document.addEventListener( prefix + 'visibilitychange', onChange ); // initialise onChange(); } else { // gah, we're in an old browser if ( 'onfocusout' in document ) { document.addEventListener( 'focusout', onHide ); document.addEventListener( 'focusin', onShow ); } else { window.addEventListener( 'pagehide', onHide ); window.addEventListener( 'blur', onHide ); window.addEventListener( 'pageshow', onShow ); window.addEventListener( 'focus', onShow ); } visibility.hidden = false; } } function onChange() { visibility.hidden = document[ hidden ]; } function onHide() { visibility.hidden = true; } function onShow() { visibility.hidden = false; } return visibility; }( vendors ); /* virtualdom/items/Element/Transition/prototype/animateStyle/_animateStyle.js */ var virtualdom_items_Element_Transition$animateStyle__animateStyle = function( legacy, isClient, warn, Promise, prefix, createTransitions, visibility ) { var animateStyle, getComputedStyle, resolved; if ( !isClient ) { animateStyle = null; } else { getComputedStyle = window.getComputedStyle || legacy.getComputedStyle; animateStyle = function( style, value, options, complete ) { var t = this, to; // Special case - page isn't visible. Don't animate anything, because // that way you'll never get CSS transitionend events if ( visibility.hidden ) { this.setStyle( style, value ); return resolved || ( resolved = Promise.resolve() ); } if ( typeof style === 'string' ) { to = {}; to[ style ] = value; } else { to = style; // shuffle arguments complete = options; options = value; } // As of 0.3.9, transition authors should supply an `option` object with // `duration` and `easing` properties (and optional `delay`), plus a // callback function that gets called after the animation completes // TODO remove this check in a future version if ( !options ) { warn( 'The "' + t.name + '" transition does not supply an options object to `t.animateStyle()`. This will break in a future version of Ractive. For more info see https://github.com/RactiveJS/Ractive/issues/340' ); options = t; complete = t.complete; } var promise = new Promise( function( resolve ) { var propertyNames, changedProperties, computedStyle, current, from, i, prop; // Edge case - if duration is zero, set style synchronously and complete if ( !options.duration ) { t.setStyle( to ); resolve(); return; } // Get a list of the properties we're animating propertyNames = Object.keys( to ); changedProperties = []; // Store the current styles computedStyle = getComputedStyle( t.node ); from = {}; i = propertyNames.length; while ( i-- ) { prop = propertyNames[ i ]; current = computedStyle[ prefix( prop ) ]; if ( current === '0px' ) { current = 0; } // we need to know if we're actually changing anything if ( current != to[ prop ] ) { // use != instead of !==, so we can compare strings with numbers changedProperties.push( prop ); // make the computed style explicit, so we can animate where // e.g. height='auto' t.node.style[ prefix( prop ) ] = current; } } // If we're not actually changing anything, the transitionend event // will never fire! So we complete early if ( !changedProperties.length ) { resolve(); return; } createTransitions( t, to, options, changedProperties, resolve ); } ); // If a callback was supplied, do the honours // TODO remove this check in future if ( complete ) { warn( 't.animateStyle returns a Promise as of 0.4.0. Transition authors should do t.animateStyle(...).then(callback)' ); promise.then( complete ); } return promise; }; } return animateStyle; }( legacy, isClient, warn, Promise, prefix, virtualdom_items_Element_Transition$animateStyle_createTransitions, virtualdom_items_Element_Transition$animateStyle_visibility ); /* utils/fillGaps.js */ var fillGaps = function( target, source ) { var key; for ( key in source ) { if ( source.hasOwnProperty( key ) && !( key in target ) ) { target[ key ] = source[ key ]; } } return target; }; /* virtualdom/items/Element/Transition/prototype/processParams.js */ var virtualdom_items_Element_Transition$processParams = function( fillGaps ) { return function( params, defaults ) { if ( typeof params === 'number' ) { params = { duration: params }; } else if ( typeof params === 'string' ) { if ( params === 'slow' ) { params = { duration: 600 }; } else if ( params === 'fast' ) { params = { duration: 200 }; } else { params = { duration: 400 }; } } else if ( !params ) { params = {}; } return fillGaps( params, defaults ); }; }( fillGaps ); /* virtualdom/items/Element/Transition/prototype/start.js */ var virtualdom_items_Element_Transition$start = function() { return function Transition$start() { var t = this, node, originalStyle; node = t.node = t.element.node; originalStyle = node.getAttribute( 'style' ); // create t.complete() - we don't want this on the prototype, // because we don't want `this` silliness when passing it as // an argument t.complete = function( noReset ) { if ( !noReset && t.isIntro ) { resetStyle( node, originalStyle ); } node._ractive.transition = null; t._manager.remove( t ); }; // If the transition function doesn't exist, abort if ( !t._fn ) { t.complete(); return; } t._fn.apply( t.root, [ t ].concat( t.params ) ); }; function resetStyle( node, style ) { if ( style ) { node.setAttribute( 'style', style ); } else { // Next line is necessary, to remove empty style attribute! // See http://stackoverflow.com/a/7167553 node.getAttribute( 'style' ); node.removeAttribute( 'style' ); } } }(); /* virtualdom/items/Element/Transition/_Transition.js */ var Transition = function( init, getStyle, setStyle, animateStyle, processParams, start, circular ) { var Fragment, Transition; circular.push( function() { Fragment = circular.Fragment; } ); Transition = function( owner, template, isIntro ) { this.init( owner, template, isIntro ); }; Transition.prototype = { init: init, start: start, getStyle: getStyle, setStyle: setStyle, animateStyle: animateStyle, processParams: processParams }; return Transition; }( virtualdom_items_Element_Transition$init, virtualdom_items_Element_Transition$getStyle, virtualdom_items_Element_Transition$setStyle, virtualdom_items_Element_Transition$animateStyle__animateStyle, virtualdom_items_Element_Transition$processParams, virtualdom_items_Element_Transition$start, circular ); /* virtualdom/items/Element/prototype/render.js */ var virtualdom_items_Element$render = function( namespaces, isArray, warn, create, createElement, defineProperty, noop, runloop, getInnerContext, renderImage, Transition ) { var updateCss, updateScript; updateCss = function() { var node = this.node, content = this.fragment.toString( false ); if ( node.styleSheet ) { node.styleSheet.cssText = content; } else { while ( node.hasChildNodes() ) { node.removeChild( node.firstChild ); } node.appendChild( document.createTextNode( content ) ); } }; updateScript = function() { if ( !this.node.type || this.node.type === 'text/javascript' ) { warn( 'Script tag was updated. This does not cause the code to be re-evaluated!' ); } this.node.text = this.fragment.toString( false ); }; return function Element$render() { var this$0 = this; var root = this.root, namespace, node; namespace = getNamespace( this ); node = this.node = createElement( this.name, namespace ); // Is this a top-level node of a component? If so, we may need to add // a data-rvcguid attribute, for CSS encapsulation // NOTE: css no longer copied to instance, so we check constructor.css - // we can enhance to handle instance, but this is more "correct" with current // functionality if ( root.constructor.css && this.parentFragment.getNode() === root.el ) { this.node.setAttribute( 'data-rvcguid', root.constructor._guid ); } // Add _ractive property to the node - we use this object to store stuff // related to proxy events, two-way bindings etc defineProperty( this.node, '_ractive', { value: { proxy: this, keypath: getInnerContext( this.parentFragment ), index: this.parentFragment.indexRefs, events: create( null ), root: root } } ); // Render attributes this.attributes.forEach( function( a ) { return a.render( node ); } ); // Render children if ( this.fragment ) { // Special case - <script> element if ( this.name === 'script' ) { this.bubble = updateScript; this.node.text = this.fragment.toString( false ); // bypass warning initially this.fragment.unrender = noop; } else if ( this.name === 'style' ) { this.bubble = updateCss; this.bubble(); this.fragment.unrender = noop; } else if ( this.binding && this.getAttribute( 'contenteditable' ) ) { this.fragment.unrender = noop; } else { this.node.appendChild( this.fragment.render() ); } } // Add proxy event handlers if ( this.eventHandlers ) { this.eventHandlers.forEach( function( h ) { return h.render(); } ); } // deal with two-way bindings if ( this.binding ) { this.binding.render(); this.node._ractive.binding = this.binding; } // Special case: if this is an <img>, and we're in a crap browser, we may // need to prevent it from overriding width and height when it loads the src if ( this.name === 'img' ) { renderImage( this ); } // apply decorator(s) if ( this.decorator && this.decorator.fn ) { runloop.scheduleTask( function() { this$0.decorator.init(); } ); } // trigger intro transition if ( root.transitionsEnabled && this.intro ) { var transition = new Transition( this, this.intro, true ); runloop.registerTransition( transition ); runloop.scheduleTask( function() { return transition.start(); } ); } if ( this.name === 'option' ) { processOption( this ); } if ( this.node.autofocus ) { // Special case. Some browsers (*cough* Firefix *cough*) have a problem // with dynamically-generated elements having autofocus, and they won't // allow you to programmatically focus the element until it's in the DOM runloop.scheduleTask( function() { return this$0.node.focus(); } ); } updateLiveQueries( this ); return this.node; }; function getNamespace( element ) { var namespace, xmlns, parent; // Use specified namespace... if ( xmlns = element.getAttribute( 'xmlns' ) ) { namespace = xmlns; } else if ( element.name === 'svg' ) { namespace = namespaces.svg; } else if ( parent = element.parent ) { // ...or HTML, if the parent is a <foreignObject> if ( parent.name === 'foreignObject' ) { namespace = namespaces.html; } else { namespace = parent.node.namespaceURI; } } else { namespace = element.root.el.namespaceURI; } return namespace; } function processOption( option ) { var optionValue, selectValue, i; selectValue = option.select.getAttribute( 'value' ); if ( selectValue === undefined ) { return; } optionValue = option.getAttribute( 'value' ); if ( option.select.node.multiple && isArray( selectValue ) ) { i = selectValue.length; while ( i-- ) { if ( optionValue == selectValue[ i ] ) { option.node.selected = true; break; } } } else { option.node.selected = optionValue == selectValue; } } function updateLiveQueries( element ) { var instance, liveQueries, i, selector, query; // Does this need to be added to any live queries? instance = element.root; do { liveQueries = instance._liveQueries; i = liveQueries.length; while ( i-- ) { selector = liveQueries[ i ]; query = liveQueries[ '_' + selector ]; if ( query._test( element ) ) { // keep register of applicable selectors, for when we teardown ( element.liveQueries || ( element.liveQueries = [] ) ).push( query ); } } } while ( instance = instance._parent ); } }( namespaces, isArray, warn, create, createElement, defineProperty, noop, runloop, getInnerContext, render, Transition ); /* virtualdom/items/Element/prototype/toString.js */ var virtualdom_items_Element$toString = function( voidElementNames, isArray ) { return function() { var str, escape; str = '<' + ( this.template.y ? '!DOCTYPE' : this.template.e ); str += this.attributes.map( stringifyAttribute ).join( '' ); // Special case - selected options if ( this.name === 'option' && optionIsSelected( this ) ) { str += ' selected'; } // Special case - two-way radio name bindings if ( this.name === 'input' && inputIsCheckedRadio( this ) ) { str += ' checked'; } str += '>'; if ( this.fragment ) { escape = this.name !== 'script' && this.name !== 'style'; str += this.fragment.toString( escape ); } // add a closing tag if this isn't a void element if ( !voidElementNames.test( this.template.e ) ) { str += '</' + this.template.e + '>'; } return str; }; function optionIsSelected( element ) { var optionValue, selectValue, i; optionValue = element.getAttribute( 'value' ); if ( optionValue === undefined ) { return false; } selectValue = element.select.getAttribute( 'value' ); if ( selectValue == optionValue ) { return true; } if ( element.select.getAttribute( 'multiple' ) && isArray( selectValue ) ) { i = selectValue.length; while ( i-- ) { if ( selectValue[ i ] == optionValue ) { return true; } } } } function inputIsCheckedRadio( element ) { var attributes, typeAttribute, valueAttribute, nameAttribute; attributes = element.attributes; typeAttribute = attributes.type; valueAttribute = attributes.value; nameAttribute = attributes.name; if ( !typeAttribute || typeAttribute.value !== 'radio' || !valueAttribute || !nameAttribute.interpolator ) { return; } if ( valueAttribute.value === nameAttribute.interpolator.value ) { return true; } } function stringifyAttribute( attribute ) { var str = attribute.toString(); return str ? ' ' + str : ''; } }( voidElementNames, isArray ); /* virtualdom/items/Element/special/option/unbind.js */ var virtualdom_items_Element_special_option_unbind = function( removeFromArray ) { return function unbindOption( option ) { removeFromArray( option.select.options, option ); }; }( removeFromArray ); /* virtualdom/items/Element/prototype/unbind.js */ var virtualdom_items_Element$unbind = function( unbindOption ) { return function Element$unbind() { if ( this.fragment ) { this.fragment.unbind(); } if ( this.binding ) { this.binding.unbind(); } // Special case - <option> if ( this.name === 'option' ) { unbindOption( this ); } this.attributes.forEach( unbindAttribute ); }; function unbindAttribute( attribute ) { attribute.unbind(); } }( virtualdom_items_Element_special_option_unbind ); /* virtualdom/items/Element/prototype/unrender.js */ var virtualdom_items_Element$unrender = function( runloop, Transition ) { return function Element$unrender( shouldDestroy ) { var binding, bindings; // Detach as soon as we can if ( this.name === 'option' ) { // <option> elements detach immediately, so that // their parent <select> element syncs correctly, and // since option elements can't have transitions anyway this.detach(); } else if ( shouldDestroy ) { runloop.detachWhenReady( this ); } // Children first. that way, any transitions on child elements will be // handled by the current transitionManager if ( this.fragment ) { this.fragment.unrender( false ); } if ( binding = this.binding ) { this.binding.unrender(); this.node._ractive.binding = null; bindings = this.root._twowayBindings[ binding.keypath ]; bindings.splice( bindings.indexOf( binding ), 1 ); } // Remove event handlers if ( this.eventHandlers ) { this.eventHandlers.forEach( function( h ) { return h.unrender(); } ); } if ( this.decorator ) { this.decorator.teardown(); } // trigger outro transition if necessary if ( this.root.transitionsEnabled && this.outro ) { var transition = new Transition( this, this.outro, false ); runloop.registerTransition( transition ); runloop.scheduleTask( function() { return transition.start(); } ); } // Remove this node from any live queries if ( this.liveQueries ) { removeFromLiveQueries( this ); } }; function removeFromLiveQueries( element ) { var query, selector, i; i = element.liveQueries.length; while ( i-- ) { query = element.liveQueries[ i ]; selector = query.selector; query._remove( element.node ); } } }( runloop, Transition ); /* virtualdom/items/Element/_Element.js */ var Element = function( bubble, detach, find, findAll, findAllComponents, findComponent, findNextNode, firstNode, getAttribute, init, rebind, render, toString, unbind, unrender ) { var Element = function( options ) { this.init( options ); }; Element.prototype = { bubble: bubble, detach: detach, find: find, findAll: findAll, findAllComponents: findAllComponents, findComponent: findComponent, findNextNode: findNextNode, firstNode: firstNode, getAttribute: getAttribute, init: init, rebind: rebind, render: render, toString: toString, unbind: unbind, unrender: unrender }; return Element; }( virtualdom_items_Element$bubble, virtualdom_items_Element$detach, virtualdom_items_Element$find, virtualdom_items_Element$findAll, virtualdom_items_Element$findAllComponents, virtualdom_items_Element$findComponent, virtualdom_items_Element$findNextNode, virtualdom_items_Element$firstNode, virtualdom_items_Element$getAttribute, virtualdom_items_Element$init, virtualdom_items_Element$rebind, virtualdom_items_Element$render, virtualdom_items_Element$toString, virtualdom_items_Element$unbind, virtualdom_items_Element$unrender ); /* virtualdom/items/Partial/deIndent.js */ var deIndent = function() { var empty = /^\s*$/, leadingWhitespace = /^\s*/; return function( str ) { var lines, firstLine, lastLine, minIndent; lines = str.split( '\n' ); // remove first and last line, if they only contain whitespace firstLine = lines[ 0 ]; if ( firstLine !== undefined && empty.test( firstLine ) ) { lines.shift(); } lastLine = lines[ lines.length - 1 ]; if ( lastLine !== undefined && empty.test( lastLine ) ) { lines.pop(); } minIndent = lines.reduce( reducer, null ); if ( minIndent ) { str = lines.map( function( line ) { return line.replace( minIndent, '' ); } ).join( '\n' ); } return str; }; function reducer( previous, line ) { var lineIndent = leadingWhitespace.exec( line )[ 0 ]; if ( previous === null || lineIndent.length < previous.length ) { return lineIndent; } return previous; } }(); /* virtualdom/items/Partial/getPartialDescriptor.js */ var getPartialDescriptor = function( log, config, parser, deIndent ) { return function getPartialDescriptor( ractive, name ) { var partial; // If the partial in instance or view heirarchy instances, great if ( partial = getPartialFromRegistry( ractive, name ) ) { return partial; } // Does it exist on the page as a script tag? partial = parser.fromId( name, { noThrow: true } ); if ( partial ) { // is this necessary? partial = deIndent( partial ); // parse and register to this ractive instance var parsed = parser.parse( partial, parser.getParseOptions( ractive ) ); // register (and return main partial if there are others in the template) return ractive.partials[ name ] = parsed.t; } log.error( { debug: ractive.debug, message: 'noTemplateForPartial', args: { name: name } } ); // No match? Return an empty array return []; }; function getPartialFromRegistry( ractive, name ) { var partials = config.registries.partials; // find first instance in the ractive or view hierarchy that has this partial var instance = partials.findInstance( ractive, name ); if ( !instance ) { return; } var partial = instance.partials[ name ], fn; // partial is a function? if ( typeof partial === 'function' ) { fn = partial.bind( instance ); fn.isOwner = instance.partials.hasOwnProperty( name ); partial = fn( instance.data, parser ); } if ( !partial ) { log.warn( { debug: ractive.debug, message: 'noRegistryFunctionReturn', args: { registry: 'partial', name: name } } ); return; } // If this was added manually to the registry, // but hasn't been parsed, parse it now if ( !parser.isParsed( partial ) ) { // use the parseOptions of the ractive instance on which it was found var parsed = parser.parse( partial, parser.getParseOptions( instance ) ); // Partials cannot contain nested partials! // TODO add a test for this if ( parsed.p ) { log.warn( { debug: ractive.debug, message: 'noNestedPartials', args: { rname: name } } ); } // if fn, use instance to store result, otherwise needs to go // in the correct point in prototype chain on instance or constructor var target = fn ? instance : partials.findOwner( instance, name ); // may be a template with partials, which need to be registered and main template extracted target.partials[ name ] = partial = parsed.t; } // store for reset if ( fn ) { partial._fn = fn; } return partial.v ? partial.t : partial; } }( log, config, parser, deIndent ); /* virtualdom/items/Partial/applyIndent.js */ var applyIndent = function( string, indent ) { var indented; if ( !indent ) { return string; } indented = string.split( '\n' ).map( function( line, notFirstLine ) { return notFirstLine ? indent + line : line; } ).join( '\n' ); return indented; }; /* virtualdom/items/Partial/_Partial.js */ var Partial = function( types, getPartialDescriptor, applyIndent, circular ) { var Partial, Fragment; circular.push( function() { Fragment = circular.Fragment; } ); Partial = function( options ) { var parentFragment = this.parentFragment = options.parentFragment, template; this.type = types.PARTIAL; this.name = options.template.r; this.index = options.index; this.root = parentFragment.root; if ( !options.template.r ) { // TODO support dynamic partial switching throw new Error( 'Partials must have a static reference (no expressions). This may change in a future version of Ractive.' ); } template = getPartialDescriptor( parentFragment.root, options.template.r ); this.fragment = new Fragment( { template: template, root: parentFragment.root, owner: this, pElement: parentFragment.pElement } ); }; Partial.prototype = { bubble: function() { this.parentFragment.bubble(); }, firstNode: function() { return this.fragment.firstNode(); }, findNextNode: function() { return this.parentFragment.findNextNode( this ); }, detach: function() { return this.fragment.detach(); }, render: function() { return this.fragment.render(); }, unrender: function( shouldDestroy ) { this.fragment.unrender( shouldDestroy ); }, rebind: function( indexRef, newIndex, oldKeypath, newKeypath ) { return this.fragment.rebind( indexRef, newIndex, oldKeypath, newKeypath ); }, unbind: function() { this.fragment.unbind(); }, toString: function( toString ) { var string, previousItem, lastLine, match; string = this.fragment.toString( toString ); previousItem = this.parentFragment.items[ this.index - 1 ]; if ( !previousItem || previousItem.type !== types.TEXT ) { return string; } lastLine = previousItem.template.split( '\n' ).pop(); if ( match = /^\s+$/.exec( lastLine ) ) { return applyIndent( string, match[ 0 ] ); } return string; }, find: function( selector ) { return this.fragment.find( selector ); }, findAll: function( selector, query ) { return this.fragment.findAll( selector, query ); }, findComponent: function( selector ) { return this.fragment.findComponent( selector ); }, findAllComponents: function( selector, query ) { return this.fragment.findAllComponents( selector, query ); }, getValue: function() { return this.fragment.getValue(); } }; return Partial; }( types, getPartialDescriptor, applyIndent, circular ); /* virtualdom/items/Component/getComponent.js */ var getComponent = function( config, log, circular ) { var Ractive; circular.push( function() { Ractive = circular.Ractive; } ); // finds the component constructor in the registry or view hierarchy registries return function getComponent( ractive, name ) { var component, instance = config.registries.components.findInstance( ractive, name ); if ( instance ) { component = instance.components[ name ]; // best test we have for not Ractive.extend if ( !component._parent ) { // function option, execute and store for reset var fn = component.bind( instance ); fn.isOwner = instance.components.hasOwnProperty( name ); component = fn( instance.data ); if ( !component ) { log.warn( { debug: ractive.debug, message: 'noRegistryFunctionReturn', args: { registry: 'component', name: name } } ); return; } if ( typeof component === 'string' ) { //allow string lookup component = getComponent( ractive, component ); } component._fn = fn; instance.components[ name ] = component; } } return component; }; }( config, log, circular ); /* virtualdom/items/Component/prototype/detach.js */ var virtualdom_items_Component$detach = function Component$detach() { return this.instance.fragment.detach(); }; /* virtualdom/items/Component/prototype/find.js */ var virtualdom_items_Component$find = function Component$find( selector ) { return this.instance.fragment.find( selector ); }; /* virtualdom/items/Component/prototype/findAll.js */ var virtualdom_items_Component$findAll = function Component$findAll( selector, query ) { return this.instance.fragment.findAll( selector, query ); }; /* virtualdom/items/Component/prototype/findAllComponents.js */ var virtualdom_items_Component$findAllComponents = function Component$findAllComponents( selector, query ) { query._test( this, true ); if ( this.instance.fragment ) { this.instance.fragment.findAllComponents( selector, query ); } }; /* virtualdom/items/Component/prototype/findComponent.js */ var virtualdom_items_Component$findComponent = function Component$findComponent( selector ) { if ( !selector || selector === this.name ) { return this.instance; } if ( this.instance.fragment ) { return this.instance.fragment.findComponent( selector ); } return null; }; /* virtualdom/items/Component/prototype/findNextNode.js */ var virtualdom_items_Component$findNextNode = function Component$findNextNode() { return this.parentFragment.findNextNode( this ); }; /* virtualdom/items/Component/prototype/firstNode.js */ var virtualdom_items_Component$firstNode = function Component$firstNode() { if ( this.rendered ) { return this.instance.fragment.firstNode(); } return null; }; /* virtualdom/items/Component/initialise/createModel/ComponentParameter.js */ var ComponentParameter = function( runloop, circular ) { var Fragment, ComponentParameter; circular.push( function() { Fragment = circular.Fragment; } ); ComponentParameter = function( component, key, value ) { this.parentFragment = component.parentFragment; this.component = component; this.key = key; this.fragment = new Fragment( { template: value, root: component.root, owner: this } ); this.value = this.fragment.getValue(); }; ComponentParameter.prototype = { bubble: function() { if ( !this.dirty ) { this.dirty = true; runloop.addView( this ); } }, update: function() { var value = this.fragment.getValue(); this.component.instance.viewmodel.set( this.key, value ); runloop.addViewmodel( this.component.instance.viewmodel ); this.value = value; this.dirty = false; }, rebind: function( indexRef, newIndex, oldKeypath, newKeypath ) { this.fragment.rebind( indexRef, newIndex, oldKeypath, newKeypath ); }, unbind: function() { this.fragment.unbind(); } }; return ComponentParameter; }( runloop, circular ); /* virtualdom/items/Component/initialise/createModel/_createModel.js */ var createModel = function( types, parseJSON, resolveRef, ComponentParameter ) { return function( component, defaultData, attributes, toBind ) { var data = {}, key, value; // some parameters, e.g. foo="The value is {{bar}}", are 'complex' - in // other words, we need to construct a string fragment to watch // when they change. We store these so they can be torn down later component.complexParameters = []; for ( key in attributes ) { if ( attributes.hasOwnProperty( key ) ) { value = getValue( component, key, attributes[ key ], toBind ); if ( value !== undefined || defaultData[ key ] === undefined ) { data[ key ] = value; } } } return data; }; function getValue( component, key, template, toBind ) { var parameter, parsed, parentInstance, parentFragment, keypath, indexRef; parentInstance = component.root; parentFragment = component.parentFragment; // If this is a static value, great if ( typeof template === 'string' ) { parsed = parseJSON( template ); if ( !parsed ) { return template; } return parsed.value; } // If null, we treat it as a boolean attribute (i.e. true) if ( template === null ) { return true; } // If a regular interpolator, we bind to it if ( template.length === 1 && template[ 0 ].t === types.INTERPOLATOR && template[ 0 ].r ) { // Is it an index reference? if ( parentFragment.indexRefs && parentFragment.indexRefs[ indexRef = template[ 0 ].r ] !== undefined ) { component.indexRefBindings[ indexRef ] = key; return parentFragment.indexRefs[ indexRef ]; } // TODO what about references that resolve late? Should these be considered? keypath = resolveRef( parentInstance, template[ 0 ].r, parentFragment ) || template[ 0 ].r; // We need to set up bindings between parent and child, but // we can't do it yet because the child instance doesn't exist // yet - so we make a note instead toBind.push( { childKeypath: key, parentKeypath: keypath } ); return parentInstance.viewmodel.get( keypath ); } // We have a 'complex parameter' - we need to create a full-blown string // fragment in order to evaluate and observe its value parameter = new ComponentParameter( component, key, template ); component.complexParameters.push( parameter ); return parameter.value; } }( types, parseJSON, resolveRef, ComponentParameter ); /* virtualdom/items/Component/initialise/createInstance.js */ var createInstance = function( component, Component, data, contentDescriptor ) { var instance, parentFragment, partials, root; parentFragment = component.parentFragment; root = component.root; // Make contents available as a {{>content}} partial partials = { content: contentDescriptor || [] }; instance = new Component( { append: true, data: data, partials: partials, magic: root.magic || Component.defaults.magic, modifyArrays: root.modifyArrays, _parent: root, _component: component, // need to inherit runtime parent adaptors adapt: root.adapt } ); return instance; }; /* virtualdom/items/Component/initialise/createBindings.js */ var createBindings = function( createComponentBinding ) { return function createInitialComponentBindings( component, toBind ) { toBind.forEach( function createInitialComponentBinding( pair ) { var childValue, parentValue; createComponentBinding( component, component.root, pair.parentKeypath, pair.childKeypath ); childValue = component.instance.viewmodel.get( pair.childKeypath ); parentValue = component.root.viewmodel.get( pair.parentKeypath ); if ( childValue !== undefined && parentValue === undefined ) { component.root.viewmodel.set( pair.parentKeypath, childValue ); } } ); }; }( createComponentBinding ); /* virtualdom/items/Component/initialise/propagateEvents.js */ var propagateEvents = function( log ) { // TODO how should event arguments be handled? e.g. // <widget on-foo='bar:1,2,3'/> // The event 'bar' will be fired on the parent instance // when 'foo' fires on the child, but the 1,2,3 arguments // will be lost return function( component, eventsDescriptor ) { var eventName; for ( eventName in eventsDescriptor ) { if ( eventsDescriptor.hasOwnProperty( eventName ) ) { propagateEvent( component.instance, component.root, eventName, eventsDescriptor[ eventName ] ); } } }; function propagateEvent( childInstance, parentInstance, eventName, proxyEventName ) { if ( typeof proxyEventName !== 'string' ) { log.error( { debug: parentInstance.debug, message: 'noComponentEventArguments' } ); } childInstance.on( eventName, function() { var args = Array.prototype.slice.call( arguments ); args.unshift( proxyEventName ); parentInstance.fire.apply( parentInstance, args ); } ); } }( log ); /* virtualdom/items/Component/initialise/updateLiveQueries.js */ var updateLiveQueries = function( component ) { var ancestor, query; // If there's a live query for this component type, add it ancestor = component.root; while ( ancestor ) { if ( query = ancestor._liveComponentQueries[ '_' + component.name ] ) { query.push( component.instance ); } ancestor = ancestor._parent; } }; /* virtualdom/items/Component/prototype/init.js */ var virtualdom_items_Component$init = function( types, warn, createModel, createInstance, createBindings, propagateEvents, updateLiveQueries ) { return function Component$init( options, Component ) { var parentFragment, root, data, toBind; parentFragment = this.parentFragment = options.parentFragment; root = parentFragment.root; this.root = root; this.type = types.COMPONENT; this.name = options.template.e; this.index = options.index; this.indexRefBindings = {}; this.bindings = []; if ( !Component ) { throw new Error( 'Component "' + this.name + '" not found' ); } // First, we need to create a model for the component - e.g. if we // encounter <widget foo='bar'/> then we need to create a widget // with `data: { foo: 'bar' }`. // // This may involve setting up some bindings, but we can't do it // yet so we take some notes instead toBind = []; data = createModel( this, Component.defaults.data || {}, options.template.a, toBind ); createInstance( this, Component, data, options.template.f ); createBindings( this, toBind ); propagateEvents( this, options.template.v ); // intro, outro and decorator directives have no effect if ( options.template.t1 || options.template.t2 || options.template.o ) { warn( 'The "intro", "outro" and "decorator" directives have no effect on components' ); } updateLiveQueries( this ); }; }( types, warn, createModel, createInstance, createBindings, propagateEvents, updateLiveQueries ); /* virtualdom/items/Component/prototype/rebind.js */ var virtualdom_items_Component$rebind = function( runloop, getNewKeypath ) { return function Component$rebind( indexRef, newIndex, oldKeypath, newKeypath ) { var childInstance = this.instance, parentInstance = childInstance._parent, indexRefAlias, query; this.bindings.forEach( function( binding ) { var updated; if ( binding.root !== parentInstance ) { return; } if ( updated = getNewKeypath( binding.keypath, oldKeypath, newKeypath ) ) { binding.rebind( updated ); } } ); this.complexParameters.forEach( function( parameter ) { parameter.rebind( indexRef, newIndex, oldKeypath, newKeypath ); } ); if ( indexRefAlias = this.indexRefBindings[ indexRef ] ) { runloop.addViewmodel( childInstance.viewmodel ); childInstance.viewmodel.set( indexRefAlias, newIndex ); } if ( query = this.root._liveComponentQueries[ '_' + this.name ] ) { query._makeDirty(); } }; }( runloop, getNewKeypath ); /* virtualdom/items/Component/prototype/render.js */ var virtualdom_items_Component$render = function Component$render() { var instance = this.instance; instance.render( this.parentFragment.getNode() ); this.rendered = true; return instance.detach(); }; /* virtualdom/items/Component/prototype/toString.js */ var virtualdom_items_Component$toString = function Component$toString() { return this.instance.fragment.toString(); }; /* virtualdom/items/Component/prototype/unbind.js */ var virtualdom_items_Component$unbind = function() { return function Component$unbind() { this.complexParameters.forEach( unbind ); this.bindings.forEach( unbind ); removeFromLiveComponentQueries( this ); this.instance.fragment.unbind(); }; function unbind( thing ) { thing.unbind(); } function removeFromLiveComponentQueries( component ) { var instance, query; instance = component.root; do { if ( query = instance._liveComponentQueries[ '_' + component.name ] ) { query._remove( component ); } } while ( instance = instance._parent ); } }(); /* virtualdom/items/Component/prototype/unrender.js */ var virtualdom_items_Component$unrender = function Component$unrender( shouldDestroy ) { this.instance.fire( 'teardown' ); this.shouldDestroy = shouldDestroy; this.instance.unrender(); }; /* virtualdom/items/Component/_Component.js */ var Component = function( detach, find, findAll, findAllComponents, findComponent, findNextNode, firstNode, init, rebind, render, toString, unbind, unrender ) { var Component = function( options, Constructor ) { this.init( options, Constructor ); }; Component.prototype = { detach: detach, find: find, findAll: findAll, findAllComponents: findAllComponents, findComponent: findComponent, findNextNode: findNextNode, firstNode: firstNode, init: init, rebind: rebind, render: render, toString: toString, unbind: unbind, unrender: unrender }; return Component; }( virtualdom_items_Component$detach, virtualdom_items_Component$find, virtualdom_items_Component$findAll, virtualdom_items_Component$findAllComponents, virtualdom_items_Component$findComponent, virtualdom_items_Component$findNextNode, virtualdom_items_Component$firstNode, virtualdom_items_Component$init, virtualdom_items_Component$rebind, virtualdom_items_Component$render, virtualdom_items_Component$toString, virtualdom_items_Component$unbind, virtualdom_items_Component$unrender ); /* virtualdom/items/Comment.js */ var Comment = function( types, detach ) { var Comment = function( options ) { this.type = types.COMMENT; this.value = options.template.c; }; Comment.prototype = { detach: detach, firstNode: function() { return this.node; }, render: function() { if ( !this.node ) { this.node = document.createComment( this.value ); } return this.node; }, toString: function() { return '<!--' + this.value + '-->'; }, unrender: function( shouldDestroy ) { if ( shouldDestroy ) { this.node.parentNode.removeChild( this.node ); } } }; return Comment; }( types, detach ); /* virtualdom/Fragment/prototype/init/createItem.js */ var virtualdom_Fragment$init_createItem = function( types, Text, Interpolator, Section, Triple, Element, Partial, getComponent, Component, Comment ) { return function createItem( options ) { if ( typeof options.template === 'string' ) { return new Text( options ); } switch ( options.template.t ) { case types.INTERPOLATOR: return new Interpolator( options ); case types.SECTION: return new Section( options ); case types.TRIPLE: return new Triple( options ); case types.ELEMENT: var constructor; if ( constructor = getComponent( options.parentFragment.root, options.template.e ) ) { return new Component( options, constructor ); } return new Element( options ); case types.PARTIAL: return new Partial( options ); case types.COMMENT: return new Comment( options ); default: throw new Error( 'Something very strange happened. Please file an issue at https://github.com/ractivejs/ractive/issues. Thanks!' ); } }; }( types, Text, Interpolator, Section, Triple, Element, Partial, getComponent, Component, Comment ); /* virtualdom/Fragment/prototype/init.js */ var virtualdom_Fragment$init = function( types, create, createItem ) { return function Fragment$init( options ) { var this$0 = this; var parentFragment, parentRefs, ref; // The item that owns this fragment - an element, section, partial, or attribute this.owner = options.owner; parentFragment = this.parent = this.owner.parentFragment; // inherited properties this.root = options.root; this.pElement = options.pElement; this.context = options.context; // If parent item is a section, this may not be the only fragment // that belongs to it - we need to make a note of the index if ( this.owner.type === types.SECTION ) { this.index = options.index; } // index references (the 'i' in {{#section:i}}...{{/section}}) need to cascade // down the tree if ( parentFragment ) { parentRefs = parentFragment.indexRefs; if ( parentRefs ) { this.indexRefs = create( null ); // avoids need for hasOwnProperty for ( ref in parentRefs ) { this.indexRefs[ ref ] = parentRefs[ ref ]; } } } // inherit priority this.priority = parentFragment ? parentFragment.priority + 1 : 1; if ( options.indexRef ) { if ( !this.indexRefs ) { this.indexRefs = {}; } this.indexRefs[ options.indexRef ] = options.index; } // Time to create this fragment's child items // TEMP should this be happening? if ( typeof options.template === 'string' ) { options.template = [ options.template ]; } else if ( !options.template ) { options.template = []; } this.items = options.template.map( function( template, i ) { return createItem( { parentFragment: this$0, pElement: options.pElement, template: template, index: i } ); } ); this.value = this.argsList = null; this.dirtyArgs = this.dirtyValue = true; this.inited = true; }; }( types, create, virtualdom_Fragment$init_createItem ); /* virtualdom/Fragment/prototype/rebind.js */ var virtualdom_Fragment$rebind = function( assignNewKeypath ) { return function Fragment$rebind( indexRef, newIndex, oldKeypath, newKeypath ) { // assign new context keypath if needed assignNewKeypath( this, 'context', oldKeypath, newKeypath ); if ( this.indexRefs && this.indexRefs[ indexRef ] !== undefined ) { this.indexRefs[ indexRef ] = newIndex; } this.items.forEach( function( item ) { if ( item.rebind ) { item.rebind( indexRef, newIndex, oldKeypath, newKeypath ); } } ); }; }( assignNewKeypath ); /* virtualdom/Fragment/prototype/render.js */ var virtualdom_Fragment$render = function Fragment$render() { var result; if ( this.items.length === 1 ) { result = this.items[ 0 ].render(); } else { result = document.createDocumentFragment(); this.items.forEach( function( item ) { result.appendChild( item.render() ); } ); } this.rendered = true; return result; }; /* virtualdom/Fragment/prototype/toString.js */ var virtualdom_Fragment$toString = function Fragment$toString( escape ) { if ( !this.items ) { return ''; } return this.items.map( function( item ) { return item.toString( escape ); } ).join( '' ); }; /* virtualdom/Fragment/prototype/unbind.js */ var virtualdom_Fragment$unbind = function() { return function Fragment$unbind() { this.items.forEach( unbindItem ); }; function unbindItem( item ) { if ( item.unbind ) { item.unbind(); } } }(); /* virtualdom/Fragment/prototype/unrender.js */ var virtualdom_Fragment$unrender = function Fragment$unrender( shouldDestroy ) { if ( !this.rendered ) { throw new Error( 'Attempted to unrender a fragment that was not rendered' ); } this.items.forEach( function( i ) { return i.unrender( shouldDestroy ); } ); }; /* virtualdom/Fragment.js */ var Fragment = function( bubble, detach, find, findAll, findAllComponents, findComponent, findNextNode, firstNode, getNode, getValue, init, rebind, render, toString, unbind, unrender, circular ) { var Fragment = function( options ) { this.init( options ); }; Fragment.prototype = { bubble: bubble, detach: detach, find: find, findAll: findAll, findAllComponents: findAllComponents, findComponent: findComponent, findNextNode: findNextNode, firstNode: firstNode, getNode: getNode, getValue: getValue, init: init, rebind: rebind, render: render, toString: toString, unbind: unbind, unrender: unrender }; circular.Fragment = Fragment; return Fragment; }( virtualdom_Fragment$bubble, virtualdom_Fragment$detach, virtualdom_Fragment$find, virtualdom_Fragment$findAll, virtualdom_Fragment$findAllComponents, virtualdom_Fragment$findComponent, virtualdom_Fragment$findNextNode, virtualdom_Fragment$firstNode, virtualdom_Fragment$getNode, virtualdom_Fragment$getValue, virtualdom_Fragment$init, virtualdom_Fragment$rebind, virtualdom_Fragment$render, virtualdom_Fragment$toString, virtualdom_Fragment$unbind, virtualdom_Fragment$unrender, circular ); /* Ractive/prototype/reset.js */ var Ractive$reset = function( runloop, Fragment, config ) { var shouldRerender = [ 'template', 'partials', 'components', 'decorators', 'events' ]; return function Ractive$reset( data, callback ) { var promise, wrapper, changes, i, rerender; if ( typeof data === 'function' && !callback ) { callback = data; data = {}; } else { data = data || {}; } if ( typeof data !== 'object' ) { throw new Error( 'The reset method takes either no arguments, or an object containing new data' ); } // If the root object is wrapped, try and use the wrapper's reset value if ( ( wrapper = this.viewmodel.wrapped[ '' ] ) && wrapper.reset ) { if ( wrapper.reset( data ) === false ) { // reset was rejected, we need to replace the object this.data = data; } } else { this.data = data; } // reset config items and track if need to rerender changes = config.reset( this ); i = changes.length; while ( i-- ) { if ( shouldRerender.indexOf( changes[ i ] ) > -1 ) { rerender = true; break; } } if ( rerender ) { var component; this.viewmodel.mark( '' ); // Is this is a component, we need to set the `shouldDestroy` // flag, otherwise it will assume by default that a parent node // will be detached, and therefore it doesn't need to bother // detaching its own nodes if ( component = this.component ) { component.shouldDestroy = true; } this.unrender(); if ( component ) { component.shouldDestroy = false; } // If the template changed, we need to destroy the parallel DOM // TODO if we're here, presumably it did? if ( this.fragment.template !== this.template ) { this.fragment.unbind(); this.fragment = new Fragment( { template: this.template, root: this, owner: this } ); } promise = this.render( this.el, this.anchor ); } else { promise = runloop.start( this, true ); this.viewmodel.mark( '' ); runloop.end(); } this.fire( 'reset', data ); if ( callback ) { promise.then( callback ); } return promise; }; }( runloop, Fragment, config ); /* Ractive/prototype/resetTemplate.js */ var Ractive$resetTemplate = function( config, Fragment ) { // TODO should resetTemplate be asynchronous? i.e. should it be a case // of outro, update template, intro? I reckon probably not, since that // could be achieved with unrender-resetTemplate-render. Also, it should // conceptually be similar to resetPartial, which couldn't be async return function Ractive$resetTemplate( template ) { var transitionsEnabled, component; config.template.init( null, this, { template: template } ); transitionsEnabled = this.transitionsEnabled; this.transitionsEnabled = false; // Is this is a component, we need to set the `shouldDestroy` // flag, otherwise it will assume by default that a parent node // will be detached, and therefore it doesn't need to bother // detaching its own nodes if ( component = this.component ) { component.shouldDestroy = true; } this.unrender(); if ( component ) { component.shouldDestroy = false; } // remove existing fragment and create new one this.fragment.unbind(); this.fragment = new Fragment( { template: this.template, root: this, owner: this } ); this.render( this.el, this.anchor ); this.transitionsEnabled = transitionsEnabled; }; }( config, Fragment ); /* Ractive/prototype/reverse.js */ var Ractive$reverse = function( makeArrayMethod ) { return makeArrayMethod( 'reverse' ); }( Ractive$shared_makeArrayMethod ); /* Ractive/prototype/set.js */ var Ractive$set = function( runloop, isObject, normaliseKeypath, getMatchingKeypaths ) { var wildcard = /\*/; return function Ractive$set( keypath, value, callback ) { var this$0 = this; var map, promise; promise = runloop.start( this, true ); // Set multiple keypaths in one go if ( isObject( keypath ) ) { map = keypath; callback = value; for ( keypath in map ) { if ( map.hasOwnProperty( keypath ) ) { value = map[ keypath ]; keypath = normaliseKeypath( keypath ); this.viewmodel.set( keypath, value ); } } } else { keypath = normaliseKeypath( keypath ); if ( wildcard.test( keypath ) ) { getMatchingKeypaths( this, keypath ).forEach( function( keypath ) { this$0.viewmodel.set( keypath, value ); } ); } else { this.viewmodel.set( keypath, value ); } } runloop.end(); if ( callback ) { promise.then( callback.bind( this ) ); } return promise; }; }( runloop, isObject, normaliseKeypath, getMatchingKeypaths ); /* Ractive/prototype/shift.js */ var Ractive$shift = function( makeArrayMethod ) { return makeArrayMethod( 'shift' ); }( Ractive$shared_makeArrayMethod ); /* Ractive/prototype/sort.js */ var Ractive$sort = function( makeArrayMethod ) { return makeArrayMethod( 'sort' ); }( Ractive$shared_makeArrayMethod ); /* Ractive/prototype/splice.js */ var Ractive$splice = function( makeArrayMethod ) { return makeArrayMethod( 'splice' ); }( Ractive$shared_makeArrayMethod ); /* Ractive/prototype/subtract.js */ var Ractive$subtract = function( add ) { return function Ractive$subtract( keypath, d ) { return add( this, keypath, d === undefined ? -1 : -d ); }; }( Ractive$shared_add ); /* Ractive/prototype/teardown.js */ var Ractive$teardown = function( Promise ) { // Teardown. This goes through the root fragment and all its children, removing observers // and generally cleaning up after itself return function Ractive$teardown( callback ) { var promise; this.fire( 'teardown' ); this.fragment.unbind(); this.viewmodel.teardown(); promise = this.rendered ? this.unrender() : Promise.resolve(); if ( callback ) { // TODO deprecate this? promise.then( callback.bind( this ) ); } return promise; }; }( Promise ); /* Ractive/prototype/toggle.js */ var Ractive$toggle = function( log ) { return function Ractive$toggle( keypath, callback ) { var value; if ( typeof keypath !== 'string' ) { log.errorOnly( { debug: this.debug, messsage: 'badArguments', arg: { arguments: keypath } } ); } value = this.get( keypath ); return this.set( keypath, !value, callback ); }; }( log ); /* Ractive/prototype/toHTML.js */ var Ractive$toHTML = function Ractive$toHTML() { return this.fragment.toString( true ); }; /* Ractive/prototype/unrender.js */ var Ractive$unrender = function( removeFromArray, runloop, css ) { return function Ractive$unrender() { var this$0 = this; var promise, shouldDestroy; if ( !this.rendered ) { throw new Error( 'ractive.unrender() was called on a Ractive instance that was not rendered' ); } promise = runloop.start( this, true ); // If this is a component, and the component isn't marked for destruction, // don't detach nodes from the DOM unnecessarily shouldDestroy = !this.component || this.component.shouldDestroy; shouldDestroy = shouldDestroy || this.shouldDestroy; if ( this.constructor.css ) { promise.then( function() { css.remove( this$0.constructor ); } ); } // Cancel any animations in progress while ( this._animations[ 0 ] ) { this._animations[ 0 ].stop(); } this.fragment.unrender( shouldDestroy ); this.rendered = false; removeFromArray( this.el.__ractive_instances__, this ); runloop.end(); return promise; }; }( removeFromArray, runloop, global_css ); /* Ractive/prototype/unshift.js */ var Ractive$unshift = function( makeArrayMethod ) { return makeArrayMethod( 'unshift' ); }( Ractive$shared_makeArrayMethod ); /* Ractive/prototype/update.js */ var Ractive$update = function( runloop ) { return function Ractive$update( keypath, callback ) { var promise; if ( typeof keypath === 'function' ) { callback = keypath; keypath = ''; } else { keypath = keypath || ''; } promise = runloop.start( this, true ); this.viewmodel.mark( keypath ); runloop.end(); this.fire( 'update', keypath ); if ( callback ) { promise.then( callback.bind( this ) ); } return promise; }; }( runloop ); /* Ractive/prototype/updateModel.js */ var Ractive$updateModel = function( arrayContentsMatch, isEqual ) { return function Ractive$updateModel( keypath, cascade ) { var values; if ( typeof keypath !== 'string' ) { keypath = ''; cascade = true; } consolidateChangedValues( this, keypath, values = {}, cascade ); return this.set( values ); }; function consolidateChangedValues( ractive, keypath, values, cascade ) { var bindings, childDeps, i, binding, oldValue, newValue, checkboxGroups = []; bindings = ractive._twowayBindings[ keypath ]; if ( bindings && ( i = bindings.length ) ) { while ( i-- ) { binding = bindings[ i ]; // special case - radio name bindings if ( binding.radioName && !binding.element.node.checked ) { continue; } // special case - checkbox name bindings come in groups, so // we want to get the value once at most if ( binding.checkboxName ) { if ( !checkboxGroups[ binding.keypath ] && !binding.changed() ) { checkboxGroups.push( binding.keypath ); checkboxGroups[ binding.keypath ] = binding; } continue; } oldValue = binding.attribute.value; newValue = binding.getValue(); if ( arrayContentsMatch( oldValue, newValue ) ) { continue; } if ( !isEqual( oldValue, newValue ) ) { values[ keypath ] = newValue; } } } // Handle groups of `<input type='checkbox' name='{{foo}}' ...>` if ( checkboxGroups.length ) { checkboxGroups.forEach( function( keypath ) { var binding, oldValue, newValue; binding = checkboxGroups[ keypath ]; // one to represent the entire group oldValue = binding.attribute.value; newValue = binding.getValue(); if ( !arrayContentsMatch( oldValue, newValue ) ) { values[ keypath ] = newValue; } } ); } if ( !cascade ) { return; } // cascade childDeps = ractive.viewmodel.depsMap[ 'default' ][ keypath ]; if ( childDeps ) { i = childDeps.length; while ( i-- ) { consolidateChangedValues( ractive, childDeps[ i ], values, cascade ); } } } }( arrayContentsMatch, isEqual ); /* Ractive/prototype.js */ var prototype = function( add, animate, detach, find, findAll, findAllComponents, findComponent, fire, get, insert, merge, observe, off, on, pop, push, render, reset, resetTemplate, reverse, set, shift, sort, splice, subtract, teardown, toggle, toHTML, unrender, unshift, update, updateModel ) { return { add: add, animate: animate, detach: detach, find: find, findAll: findAll, findAllComponents: findAllComponents, findComponent: findComponent, fire: fire, get: get, insert: insert, merge: merge, observe: observe, off: off, on: on, pop: pop, push: push, render: render, reset: reset, resetTemplate: resetTemplate, reverse: reverse, set: set, shift: shift, sort: sort, splice: splice, subtract: subtract, teardown: teardown, toggle: toggle, toHTML: toHTML, unrender: unrender, unshift: unshift, update: update, updateModel: updateModel }; }( Ractive$add, Ractive$animate, Ractive$detach, Ractive$find, Ractive$findAll, Ractive$findAllComponents, Ractive$findComponent, Ractive$fire, Ractive$get, Ractive$insert, Ractive$merge, Ractive$observe, Ractive$off, Ractive$on, Ractive$pop, Ractive$push, Ractive$render, Ractive$reset, Ractive$resetTemplate, Ractive$reverse, Ractive$set, Ractive$shift, Ractive$sort, Ractive$splice, Ractive$subtract, Ractive$teardown, Ractive$toggle, Ractive$toHTML, Ractive$unrender, Ractive$unshift, Ractive$update, Ractive$updateModel ); /* utils/getGuid.js */ var getGuid = function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace( /[xy]/g, function( c ) { var r, v; r = Math.random() * 16 | 0; v = c == 'x' ? r : r & 3 | 8; return v.toString( 16 ); } ); }; /* utils/getNextNumber.js */ var getNextNumber = function() { var i = 0; return function() { return 'r-' + i++; }; }(); /* viewmodel/prototype/get/arrayAdaptor/processWrapper.js */ var viewmodel$get_arrayAdaptor_processWrapper = function( wrapper, array, methodName, spliceSummary ) { var root = wrapper.root, keypath = wrapper.keypath; // If this is a sort or reverse, we just do root.set()... // TODO use merge logic? if ( methodName === 'sort' || methodName === 'reverse' ) { root.viewmodel.set( keypath, array ); return; } if ( !spliceSummary ) { // (presumably we tried to pop from an array of zero length. // in which case there's nothing to do) return; } root.viewmodel.splice( keypath, spliceSummary ); }; /* viewmodel/prototype/get/arrayAdaptor/patch.js */ var viewmodel$get_arrayAdaptor_patch = function( runloop, defineProperty, getSpliceEquivalent, summariseSpliceOperation, processWrapper ) { var patchedArrayProto = [], mutatorMethods = [ 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift' ], testObj, patchArrayMethods, unpatchArrayMethods; mutatorMethods.forEach( function( methodName ) { var method = function() { var spliceEquivalent, spliceSummary, result, wrapper, i; // push, pop, shift and unshift can all be represented as a splice operation. // this makes life easier later spliceEquivalent = getSpliceEquivalent( this, methodName, Array.prototype.slice.call( arguments ) ); spliceSummary = summariseSpliceOperation( this, spliceEquivalent ); // apply the underlying method result = Array.prototype[ methodName ].apply( this, arguments ); // trigger changes this._ractive.setting = true; i = this._ractive.wrappers.length; while ( i-- ) { wrapper = this._ractive.wrappers[ i ]; runloop.start( wrapper.root ); processWrapper( wrapper, this, methodName, spliceSummary ); runloop.end(); } this._ractive.setting = false; return result; }; defineProperty( patchedArrayProto, methodName, { value: method } ); } ); // can we use prototype chain injection? // http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/#wrappers_prototype_chain_injection testObj = {}; if ( testObj.__proto__ ) { // yes, we can patchArrayMethods = function( array ) { array.__proto__ = patchedArrayProto; }; unpatchArrayMethods = function( array ) { array.__proto__ = Array.prototype; }; } else { // no, we can't patchArrayMethods = function( array ) { var i, methodName; i = mutatorMethods.length; while ( i-- ) { methodName = mutatorMethods[ i ]; defineProperty( array, methodName, { value: patchedArrayProto[ methodName ], configurable: true } ); } }; unpatchArrayMethods = function( array ) { var i; i = mutatorMethods.length; while ( i-- ) { delete array[ mutatorMethods[ i ] ]; } }; } patchArrayMethods.unpatch = unpatchArrayMethods; return patchArrayMethods; }( runloop, defineProperty, getSpliceEquivalent, summariseSpliceOperation, viewmodel$get_arrayAdaptor_processWrapper ); /* viewmodel/prototype/get/arrayAdaptor.js */ var viewmodel$get_arrayAdaptor = function( defineProperty, isArray, patch ) { var arrayAdaptor, // helpers ArrayWrapper, errorMessage; arrayAdaptor = { filter: function( object ) { // wrap the array if a) b) it's an array, and b) either it hasn't been wrapped already, // or the array didn't trigger the get() itself return isArray( object ) && ( !object._ractive || !object._ractive.setting ); }, wrap: function( ractive, array, keypath ) { return new ArrayWrapper( ractive, array, keypath ); } }; ArrayWrapper = function( ractive, array, keypath ) { this.root = ractive; this.value = array; this.keypath = keypath; // if this array hasn't already been ractified, ractify it if ( !array._ractive ) { // define a non-enumerable _ractive property to store the wrappers defineProperty( array, '_ractive', { value: { wrappers: [], instances: [], setting: false }, configurable: true } ); patch( array ); } // store the ractive instance, so we can handle transitions later if ( !array._ractive.instances[ ractive._guid ] ) { array._ractive.instances[ ractive._guid ] = 0; array._ractive.instances.push( ractive ); } array._ractive.instances[ ractive._guid ] += 1; array._ractive.wrappers.push( this ); }; ArrayWrapper.prototype = { get: function() { return this.value; }, teardown: function() { var array, storage, wrappers, instances, index; array = this.value; storage = array._ractive; wrappers = storage.wrappers; instances = storage.instances; // if teardown() was invoked because we're clearing the cache as a result of // a change that the array itself triggered, we can save ourselves the teardown // and immediate setup if ( storage.setting ) { return false; } index = wrappers.indexOf( this ); if ( index === -1 ) { throw new Error( errorMessage ); } wrappers.splice( index, 1 ); // if nothing else depends on this array, we can revert it to its // natural state if ( !wrappers.length ) { delete array._ractive; patch.unpatch( this.value ); } else { // remove ractive instance if possible instances[ this.root._guid ] -= 1; if ( !instances[ this.root._guid ] ) { index = instances.indexOf( this.root ); if ( index === -1 ) { throw new Error( errorMessage ); } instances.splice( index, 1 ); } } } }; errorMessage = 'Something went wrong in a rather interesting way'; return arrayAdaptor; }( defineProperty, isArray, viewmodel$get_arrayAdaptor_patch ); /* viewmodel/prototype/get/magicArrayAdaptor.js */ var viewmodel$get_magicArrayAdaptor = function( magicAdaptor, arrayAdaptor ) { var magicArrayAdaptor, MagicArrayWrapper; if ( magicAdaptor ) { magicArrayAdaptor = { filter: function( object, keypath, ractive ) { return magicAdaptor.filter( object, keypath, ractive ) && arrayAdaptor.filter( object ); }, wrap: function( ractive, array, keypath ) { return new MagicArrayWrapper( ractive, array, keypath ); } }; MagicArrayWrapper = function( ractive, array, keypath ) { this.value = array; this.magic = true; this.magicWrapper = magicAdaptor.wrap( ractive, array, keypath ); this.arrayWrapper = arrayAdaptor.wrap( ractive, array, keypath ); }; MagicArrayWrapper.prototype = { get: function() { return this.value; }, teardown: function() { this.arrayWrapper.teardown(); this.magicWrapper.teardown(); }, reset: function( value ) { return this.magicWrapper.reset( value ); } }; } return magicArrayAdaptor; }( viewmodel$get_magicAdaptor, viewmodel$get_arrayAdaptor ); /* viewmodel/prototype/adapt.js */ var viewmodel$adapt = function( config, arrayAdaptor, magicAdaptor, magicArrayAdaptor ) { var prefixers = {}; return function Viewmodel$adapt( keypath, value ) { var ractive = this.ractive, len, i, adaptor, wrapped; // Do we have an adaptor for this value? len = ractive.adapt.length; for ( i = 0; i < len; i += 1 ) { adaptor = ractive.adapt[ i ]; // Adaptors can be specified as e.g. [ 'Backbone.Model', 'Backbone.Collection' ] - // we need to get the actual adaptor if that's the case if ( typeof adaptor === 'string' ) { var found = config.registries.adaptors.find( ractive, adaptor ); if ( !found ) { throw new Error( 'Missing adaptor "' + adaptor + '"' ); } adaptor = ractive.adapt[ i ] = found; } if ( adaptor.filter( value, keypath, ractive ) ) { wrapped = this.wrapped[ keypath ] = adaptor.wrap( ractive, value, keypath, getPrefixer( keypath ) ); wrapped.value = value; return value; } } if ( ractive.magic ) { if ( magicArrayAdaptor.filter( value, keypath, ractive ) ) { this.wrapped[ keypath ] = magicArrayAdaptor.wrap( ractive, value, keypath ); } else if ( magicAdaptor.filter( value, keypath, ractive ) ) { this.wrapped[ keypath ] = magicAdaptor.wrap( ractive, value, keypath ); } } else if ( ractive.modifyArrays && arrayAdaptor.filter( value, keypath, ractive ) ) { this.wrapped[ keypath ] = arrayAdaptor.wrap( ractive, value, keypath ); } return value; }; function prefixKeypath( obj, prefix ) { var prefixed = {}, key; if ( !prefix ) { return obj; } prefix += '.'; for ( key in obj ) { if ( obj.hasOwnProperty( key ) ) { prefixed[ prefix + key ] = obj[ key ]; } } return prefixed; } function getPrefixer( rootKeypath ) { var rootDot; if ( !prefixers[ rootKeypath ] ) { rootDot = rootKeypath ? rootKeypath + '.' : ''; prefixers[ rootKeypath ] = function( relativeKeypath, value ) { var obj; if ( typeof relativeKeypath === 'string' ) { obj = {}; obj[ rootDot + relativeKeypath ] = value; return obj; } if ( typeof relativeKeypath === 'object' ) { // 'relativeKeypath' is in fact a hash, not a keypath return rootDot ? prefixKeypath( relativeKeypath, rootKeypath ) : relativeKeypath; } }; } return prefixers[ rootKeypath ]; } }( config, viewmodel$get_arrayAdaptor, viewmodel$get_magicAdaptor, viewmodel$get_magicArrayAdaptor ); /* viewmodel/helpers/getUpstreamChanges.js */ var getUpstreamChanges = function getUpstreamChanges( changes ) { var upstreamChanges = [ '' ], i, keypath, keys, upstreamKeypath; i = changes.length; while ( i-- ) { keypath = changes[ i ]; keys = keypath.split( '.' ); while ( keys.length > 1 ) { keys.pop(); upstreamKeypath = keys.join( '.' ); if ( upstreamChanges.indexOf( upstreamKeypath ) === -1 ) { upstreamChanges.push( upstreamKeypath ); } } } return upstreamChanges; }; /* viewmodel/prototype/applyChanges/getPotentialWildcardMatches.js */ var viewmodel$applyChanges_getPotentialWildcardMatches = function() { var starMaps = {}; // This function takes a keypath such as 'foo.bar.baz', and returns // all the variants of that keypath that include a wildcard in place // of a key, such as 'foo.bar.*', 'foo.*.baz', 'foo.*.*' and so on. // These are then checked against the dependants map (ractive.viewmodel.depsMap) // to see if any pattern observers are downstream of one or more of // these wildcard keypaths (e.g. 'foo.bar.*.status') return function getPotentialWildcardMatches( keypath ) { var keys, starMap, mapper, result; keys = keypath.split( '.' ); starMap = getStarMap( keys.length ); mapper = function( star, i ) { return star ? '*' : keys[ i ]; }; result = starMap.map( function( mask ) { return mask.map( mapper ).join( '.' ); } ); return result; }; // This function returns all the possible true/false combinations for // a given number - e.g. for two, the possible combinations are // [ true, true ], [ true, false ], [ false, true ], [ false, false ]. // It does so by getting all the binary values between 0 and e.g. 11 function getStarMap( length ) { var ones = '', max, binary, starMap, mapper, i; if ( !starMaps[ length ] ) { starMap = []; while ( ones.length < length ) { ones += 1; } max = parseInt( ones, 2 ); mapper = function( digit ) { return digit === '1'; }; for ( i = 0; i <= max; i += 1 ) { binary = i.toString( 2 ); while ( binary.length < length ) { binary = '0' + binary; } starMap[ i ] = Array.prototype.map.call( binary, mapper ); } starMaps[ length ] = starMap; } return starMaps[ length ]; } }(); /* viewmodel/prototype/applyChanges/notifyPatternObservers.js */ var viewmodel$applyChanges_notifyPatternObservers = function( getPotentialWildcardMatches ) { var lastKey = /[^\.]+$/; return notifyPatternObservers; function notifyPatternObservers( viewmodel, keypath, onlyDirect ) { var potentialWildcardMatches; updateMatchingPatternObservers( viewmodel, keypath ); if ( onlyDirect ) { return; } potentialWildcardMatches = getPotentialWildcardMatches( keypath ); potentialWildcardMatches.forEach( function( upstreamPattern ) { cascade( viewmodel, upstreamPattern, keypath ); } ); } function cascade( viewmodel, upstreamPattern, keypath ) { var group, map, actualChildKeypath; group = viewmodel.depsMap.patternObservers; map = group[ upstreamPattern ]; if ( map ) { map.forEach( function( childKeypath ) { var key = lastKey.exec( childKeypath )[ 0 ]; // 'baz' actualChildKeypath = keypath ? keypath + '.' + key : key; // 'foo.bar.baz' updateMatchingPatternObservers( viewmodel, actualChildKeypath ); cascade( viewmodel, childKeypath, actualChildKeypath ); } ); } } function updateMatchingPatternObservers( viewmodel, keypath ) { viewmodel.patternObservers.forEach( function( observer ) { if ( observer.regex.test( keypath ) ) { observer.update( keypath ); } } ); } }( viewmodel$applyChanges_getPotentialWildcardMatches ); /* viewmodel/prototype/applyChanges.js */ var viewmodel$applyChanges = function( getUpstreamChanges, notifyPatternObservers ) { var dependantGroups = [ 'observers', 'default' ]; return function Viewmodel$applyChanges() { var this$0 = this; var self = this, changes, upstreamChanges, allChanges = [], computations, addComputations, cascade, hash = {}; if ( !this.changes.length ) { // TODO we end up here on initial render. Perhaps we shouldn't? return; } addComputations = function( keypath ) { var newComputations; if ( newComputations = self.deps.computed[ keypath ] ) { addNewItems( computations, newComputations ); } }; cascade = function( keypath ) { var map; addComputations( keypath ); if ( map = self.depsMap.computed[ keypath ] ) { map.forEach( cascade ); } }; // Find computations and evaluators that are invalidated by // these changes. If they have changed, add them to the // list of changes. Lather, rinse and repeat until the // system is settled do { changes = this.changes; addNewItems( allChanges, changes ); this.changes = []; computations = []; upstreamChanges = getUpstreamChanges( changes ); upstreamChanges.forEach( addComputations ); changes.forEach( cascade ); computations.forEach( updateComputation ); } while ( this.changes.length ); upstreamChanges = getUpstreamChanges( allChanges ); // Pattern observers are a weird special case if ( this.patternObservers.length ) { upstreamChanges.forEach( function( keypath ) { return notifyPatternObservers( this$0, keypath, true ); } ); allChanges.forEach( function( keypath ) { return notifyPatternObservers( this$0, keypath ); } ); } dependantGroups.forEach( function( group ) { if ( !this$0.deps[ group ] ) { return; } upstreamChanges.forEach( function( keypath ) { return notifyUpstreamDependants( this$0, keypath, group ); } ); notifyAllDependants( this$0, allChanges, group ); } ); // Return a hash of keypaths to updated values allChanges.forEach( function( keypath ) { hash[ keypath ] = this$0.get( keypath ); } ); this.implicitChanges = {}; return hash; }; function updateComputation( computation ) { computation.update(); } function notifyUpstreamDependants( viewmodel, keypath, groupName ) { var dependants, value; if ( dependants = findDependants( viewmodel, keypath, groupName ) ) { value = viewmodel.get( keypath ); dependants.forEach( function( d ) { return d.setValue( value ); } ); } } function notifyAllDependants( viewmodel, keypaths, groupName ) { var queue = []; addKeypaths( keypaths ); queue.forEach( dispatch ); function addKeypaths( keypaths ) { keypaths.forEach( addKeypath ); keypaths.forEach( cascade ); } function addKeypath( keypath ) { var deps = findDependants( viewmodel, keypath, groupName ); if ( deps ) { queue.push( { keypath: keypath, deps: deps } ); } } function cascade( keypath ) { var childDeps; if ( childDeps = viewmodel.depsMap[ groupName ][ keypath ] ) { addKeypaths( childDeps ); } } function dispatch( set ) { var value = viewmodel.get( set.keypath ); set.deps.forEach( function( d ) { return d.setValue( value ); } ); } } function findDependants( viewmodel, keypath, groupName ) { var group = viewmodel.deps[ groupName ]; return group ? group[ keypath ] : null; } function addNewItems( arr, items ) { items.forEach( function( item ) { if ( arr.indexOf( item ) === -1 ) { arr.push( item ); } } ); } }( getUpstreamChanges, viewmodel$applyChanges_notifyPatternObservers ); /* viewmodel/prototype/capture.js */ var viewmodel$capture = function Viewmodel$capture() { this.capturing = true; this.captured = []; }; /* viewmodel/prototype/clearCache.js */ var viewmodel$clearCache = function Viewmodel$clearCache( keypath, dontTeardownWrapper ) { var cacheMap, wrapper, computation; if ( !dontTeardownWrapper ) { // Is there a wrapped property at this keypath? if ( wrapper = this.wrapped[ keypath ] ) { // Did we unwrap it? if ( wrapper.teardown() !== false ) { this.wrapped[ keypath ] = null; } } } if ( computation = this.computations[ keypath ] ) { computation.compute(); } this.cache[ keypath ] = undefined; if ( cacheMap = this.cacheMap[ keypath ] ) { while ( cacheMap.length ) { this.clearCache( cacheMap.pop() ); } } }; /* viewmodel/prototype/get/FAILED_LOOKUP.js */ var viewmodel$get_FAILED_LOOKUP = { FAILED_LOOKUP: true }; /* viewmodel/prototype/get/UnresolvedImplicitDependency.js */ var viewmodel$get_UnresolvedImplicitDependency = function( removeFromArray, runloop ) { var empty = {}; var UnresolvedImplicitDependency = function( viewmodel, keypath ) { this.viewmodel = viewmodel; this.root = viewmodel.ractive; // TODO eliminate this this.ref = keypath; this.parentFragment = empty; viewmodel.unresolvedImplicitDependencies[ keypath ] = true; viewmodel.unresolvedImplicitDependencies.push( this ); runloop.addUnresolved( this ); }; UnresolvedImplicitDependency.prototype = { resolve: function() { this.viewmodel.mark( this.ref ); this.viewmodel.unresolvedImplicitDependencies[ this.ref ] = false; removeFromArray( this.viewmodel.unresolvedImplicitDependencies, this ); }, teardown: function() { runloop.removeUnresolved( this ); } }; return UnresolvedImplicitDependency; }( removeFromArray, runloop ); /* viewmodel/prototype/get.js */ var viewmodel$get = function( FAILED_LOOKUP, UnresolvedImplicitDependency ) { var empty = {}; return function Viewmodel$get( keypath ) { var options = arguments[ 1 ]; if ( options === void 0 ) options = empty; var ractive = this.ractive, cache = this.cache, value, computation, wrapped, evaluator; if ( cache[ keypath ] === undefined ) { // Is this a computed property? if ( computation = this.computations[ keypath ] ) { value = computation.value; } else if ( wrapped = this.wrapped[ keypath ] ) { value = wrapped.value; } else if ( !keypath ) { this.adapt( '', ractive.data ); value = ractive.data; } else if ( evaluator = this.evaluators[ keypath ] ) { value = evaluator.value; } else { value = retrieve( this, keypath ); } cache[ keypath ] = value; } else { value = cache[ keypath ]; } if ( options.evaluateWrapped && ( wrapped = this.wrapped[ keypath ] ) ) { value = wrapped.get(); } // capture the keypath, if we're inside a computation or evaluator if ( options.capture && this.capturing && this.captured.indexOf( keypath ) === -1 ) { this.captured.push( keypath ); // if we couldn't resolve the keypath, we need to make it as a failed // lookup, so that the evaluator updates correctly once we CAN // resolve the keypath if ( value === FAILED_LOOKUP && this.unresolvedImplicitDependencies[ keypath ] !== true ) { new UnresolvedImplicitDependency( this, keypath ); } } return value === FAILED_LOOKUP ? void 0 : value; }; function retrieve( viewmodel, keypath ) { var keys, key, parentKeypath, parentValue, cacheMap, value, wrapped; keys = keypath.split( '.' ); key = keys.pop(); parentKeypath = keys.join( '.' ); parentValue = viewmodel.get( parentKeypath ); if ( wrapped = viewmodel.wrapped[ parentKeypath ] ) { parentValue = wrapped.get(); } if ( parentValue === null || parentValue === undefined ) { return; } // update cache map if ( !( cacheMap = viewmodel.cacheMap[ parentKeypath ] ) ) { viewmodel.cacheMap[ parentKeypath ] = [ keypath ]; } else { if ( cacheMap.indexOf( keypath ) === -1 ) { cacheMap.push( keypath ); } } // If this property doesn't exist, we return a sentinel value // so that we know to query parent scope (if such there be) if ( typeof parentValue === 'object' && !( key in parentValue ) ) { return viewmodel.cache[ keypath ] = FAILED_LOOKUP; } value = parentValue[ key ]; // Do we have an adaptor for this value? viewmodel.adapt( keypath, value, false ); // Update cache viewmodel.cache[ keypath ] = value; return value; } }( viewmodel$get_FAILED_LOOKUP, viewmodel$get_UnresolvedImplicitDependency ); /* viewmodel/prototype/mark.js */ var viewmodel$mark = function Viewmodel$mark( keypath, isImplicitChange ) { // implicit changes (i.e. `foo.length` on `ractive.push('foo',42)`) // should not be picked up by pattern observers if ( isImplicitChange ) { this.implicitChanges[ keypath ] = true; } if ( this.changes.indexOf( keypath ) === -1 ) { this.changes.push( keypath ); this.clearCache( keypath ); } }; /* viewmodel/prototype/merge/mapOldToNewIndex.js */ var viewmodel$merge_mapOldToNewIndex = function( oldArray, newArray ) { var usedIndices, firstUnusedIndex, newIndices, changed; usedIndices = {}; firstUnusedIndex = 0; newIndices = oldArray.map( function( item, i ) { var index, start, len; start = firstUnusedIndex; len = newArray.length; do { index = newArray.indexOf( item, start ); if ( index === -1 ) { changed = true; return -1; } start = index + 1; } while ( usedIndices[ index ] && start < len ); // keep track of the first unused index, so we don't search // the whole of newArray for each item in oldArray unnecessarily if ( index === firstUnusedIndex ) { firstUnusedIndex += 1; } if ( index !== i ) { changed = true; } usedIndices[ index ] = true; return index; } ); newIndices.unchanged = !changed; return newIndices; }; /* viewmodel/prototype/merge.js */ var viewmodel$merge = function( types, warn, mapOldToNewIndex ) { var comparators = {}; return function Viewmodel$merge( keypath, currentArray, array, options ) { var this$0 = this; var oldArray, newArray, comparator, newIndices, dependants; this.mark( keypath ); if ( options && options.compare ) { comparator = getComparatorFunction( options.compare ); try { oldArray = currentArray.map( comparator ); newArray = array.map( comparator ); } catch ( err ) { // fallback to an identity check - worst case scenario we have // to do more DOM manipulation than we thought... // ...unless we're in debug mode of course if ( this.debug ) { throw err; } else { warn( 'Merge operation: comparison failed. Falling back to identity checking' ); } oldArray = currentArray; newArray = array; } } else { oldArray = currentArray; newArray = array; } // find new indices for members of oldArray newIndices = mapOldToNewIndex( oldArray, newArray ); // Indices that are being removed should be marked as dirty newIndices.forEach( function( newIndex, oldIndex ) { if ( newIndex === -1 ) { this$0.mark( keypath + '.' + oldIndex ); } } ); // Update the model // TODO allow existing array to be updated in place, rather than replaced? this.set( keypath, array, true ); if ( dependants = this.deps[ 'default' ][ keypath ] ) { dependants.filter( canMerge ).forEach( function( dependant ) { return dependant.merge( newIndices ); } ); } if ( currentArray.length !== array.length ) { this.mark( keypath + '.length', true ); } }; function canMerge( dependant ) { return typeof dependant.merge === 'function' && ( !dependant.subtype || dependant.subtype === types.SECTION_EACH ); } function stringify( item ) { return JSON.stringify( item ); } function getComparatorFunction( comparator ) { // If `compare` is `true`, we use JSON.stringify to compare // objects that are the same shape, but non-identical - i.e. // { foo: 'bar' } !== { foo: 'bar' } if ( comparator === true ) { return stringify; } if ( typeof comparator === 'string' ) { if ( !comparators[ comparator ] ) { comparators[ comparator ] = function( item ) { return item[ comparator ]; }; } return comparators[ comparator ]; } if ( typeof comparator === 'function' ) { return comparator; } throw new Error( 'The `compare` option must be a function, or a string representing an identifying field (or `true` to use JSON.stringify)' ); } }( types, warn, viewmodel$merge_mapOldToNewIndex ); /* viewmodel/prototype/register.js */ var viewmodel$register = function() { return function Viewmodel$register( keypath, dependant ) { var group = arguments[ 2 ]; if ( group === void 0 ) group = 'default'; var depsByKeypath, deps, evaluator; if ( dependant.isStatic ) { return; } depsByKeypath = this.deps[ group ] || ( this.deps[ group ] = {} ); deps = depsByKeypath[ keypath ] || ( depsByKeypath[ keypath ] = [] ); deps.push( dependant ); if ( !keypath ) { return; } if ( evaluator = this.evaluators[ keypath ] ) { if ( !evaluator.dependants ) { evaluator.wake(); } evaluator.dependants += 1; } updateDependantsMap( this, keypath, group ); }; function updateDependantsMap( viewmodel, keypath, group ) { var keys, parentKeypath, map, parent; // update dependants map keys = keypath.split( '.' ); while ( keys.length ) { keys.pop(); parentKeypath = keys.join( '.' ); map = viewmodel.depsMap[ group ] || ( viewmodel.depsMap[ group ] = {} ); parent = map[ parentKeypath ] || ( map[ parentKeypath ] = [] ); if ( parent[ keypath ] === undefined ) { parent[ keypath ] = 0; parent.push( keypath ); } parent[ keypath ] += 1; keypath = parentKeypath; } } }(); /* viewmodel/prototype/release.js */ var viewmodel$release = function Viewmodel$release() { this.capturing = false; return this.captured; }; /* viewmodel/prototype/set.js */ var viewmodel$set = function( isEqual, createBranch ) { return function Viewmodel$set( keypath, value, silent ) { var keys, lastKey, parentKeypath, parentValue, computation, wrapper, evaluator, dontTeardownWrapper; if ( isEqual( this.cache[ keypath ], value ) ) { return; } computation = this.computations[ keypath ]; wrapper = this.wrapped[ keypath ]; evaluator = this.evaluators[ keypath ]; if ( computation && !computation.setting ) { computation.set( value ); } // If we have a wrapper with a `reset()` method, we try and use it. If the // `reset()` method returns false, the wrapper should be torn down, and // (most likely) a new one should be created later if ( wrapper && wrapper.reset ) { dontTeardownWrapper = wrapper.reset( value ) !== false; if ( dontTeardownWrapper ) { value = wrapper.get(); } } // Update evaluator value. This may be from the evaluator itself, or // it may be from the wrapper that wraps an evaluator's result - it // doesn't matter if ( evaluator ) { evaluator.value = value; } if ( !computation && !evaluator && !dontTeardownWrapper ) { keys = keypath.split( '.' ); lastKey = keys.pop(); parentKeypath = keys.join( '.' ); wrapper = this.wrapped[ parentKeypath ]; if ( wrapper && wrapper.set ) { wrapper.set( lastKey, value ); } else { parentValue = wrapper ? wrapper.get() : this.get( parentKeypath ); if ( !parentValue ) { parentValue = createBranch( lastKey ); this.set( parentKeypath, parentValue, true ); } parentValue[ lastKey ] = value; } } if ( !silent ) { this.mark( keypath ); } else { // We're setting a parent of the original target keypath (i.e. // creating a fresh branch) - we need to clear the cache, but // not mark it as a change this.clearCache( keypath ); } }; }( isEqual, createBranch ); /* viewmodel/prototype/splice.js */ var viewmodel$splice = function( types ) { return function Viewmodel$splice( keypath, spliceSummary ) { var viewmodel = this, i, dependants; // Mark changed keypaths for ( i = spliceSummary.rangeStart; i < spliceSummary.rangeEnd; i += 1 ) { viewmodel.mark( keypath + '.' + i ); } if ( spliceSummary.balance ) { viewmodel.mark( keypath + '.length', true ); } // Trigger splice operations if ( dependants = viewmodel.deps[ 'default' ][ keypath ] ) { dependants.filter( canSplice ).forEach( function( dependant ) { return dependant.splice( spliceSummary ); } ); } }; function canSplice( dependant ) { return dependant.type === types.SECTION && ( !dependant.subtype || dependant.subtype === types.SECTION_EACH ) && dependant.rendered; } }( types ); /* viewmodel/prototype/teardown.js */ var viewmodel$teardown = function Viewmodel$teardown() { var this$0 = this; var unresolvedImplicitDependency; // Clear entire cache - this has the desired side-effect // of unwrapping adapted values (e.g. arrays) Object.keys( this.cache ).forEach( function( keypath ) { return this$0.clearCache( keypath ); } ); // Teardown any failed lookups - we don't need them to resolve any more while ( unresolvedImplicitDependency = this.unresolvedImplicitDependencies.pop() ) { unresolvedImplicitDependency.teardown(); } }; /* viewmodel/prototype/unregister.js */ var viewmodel$unregister = function() { return function Viewmodel$unregister( keypath, dependant ) { var group = arguments[ 2 ]; if ( group === void 0 ) group = 'default'; var deps, index, evaluator; if ( dependant.isStatic ) { return; } deps = this.deps[ group ][ keypath ]; index = deps.indexOf( dependant ); if ( index === -1 ) { throw new Error( 'Attempted to remove a dependant that was no longer registered! This should not happen. If you are seeing this bug in development please raise an issue at https://github.com/RactiveJS/Ractive/issues - thanks' ); } deps.splice( index, 1 ); if ( !keypath ) { return; } if ( evaluator = this.evaluators[ keypath ] ) { evaluator.dependants -= 1; if ( !evaluator.dependants ) { evaluator.sleep(); } } updateDependantsMap( this, keypath, group ); }; function updateDependantsMap( viewmodel, keypath, group ) { var keys, parentKeypath, map, parent; // update dependants map keys = keypath.split( '.' ); while ( keys.length ) { keys.pop(); parentKeypath = keys.join( '.' ); map = viewmodel.depsMap[ group ]; parent = map[ parentKeypath ]; parent[ keypath ] -= 1; if ( !parent[ keypath ] ) { // remove from parent deps map parent.splice( parent.indexOf( keypath ), 1 ); parent[ keypath ] = undefined; } keypath = parentKeypath; } } }(); /* viewmodel/Computation/getComputationSignature.js */ var getComputationSignature = function() { var pattern = /\$\{([^\}]+)\}/g; return function( signature ) { if ( typeof signature === 'function' ) { return { get: signature }; } if ( typeof signature === 'string' ) { return { get: createFunctionFromString( signature ) }; } if ( typeof signature === 'object' && typeof signature.get === 'string' ) { signature = { get: createFunctionFromString( signature.get ), set: signature.set }; } return signature; }; function createFunctionFromString( signature ) { var functionBody = 'var __ractive=this;return(' + signature.replace( pattern, function( match, keypath ) { return '__ractive.get("' + keypath + '")'; } ) + ')'; return new Function( functionBody ); } }(); /* viewmodel/Computation/Computation.js */ var Computation = function( log, isEqual, diff ) { var Computation = function( ractive, key, signature ) { this.ractive = ractive; this.viewmodel = ractive.viewmodel; this.key = key; this.getter = signature.get; this.setter = signature.set; this.dependencies = []; this.update(); }; Computation.prototype = { set: function( value ) { if ( this.setting ) { this.value = value; return; } if ( !this.setter ) { throw new Error( 'Computed properties without setters are read-only. (This may change in a future version of Ractive!)' ); } this.setter.call( this.ractive, value ); }, // returns `false` if the computation errors compute: function() { var ractive, errored, newDependencies; ractive = this.ractive; ractive.viewmodel.capture(); try { this.value = this.getter.call( ractive ); } catch ( err ) { log.warn( { debug: ractive.debug, message: 'failedComputation', args: { key: this.key, err: err.message || err } } ); errored = true; } newDependencies = ractive.viewmodel.release(); diff( this, this.dependencies, newDependencies ); return errored ? false : true; }, update: function() { var oldValue = this.value; if ( this.compute() && !isEqual( this.value, oldValue ) ) { this.ractive.viewmodel.mark( this.key ); } } }; return Computation; }( log, isEqual, diff ); /* viewmodel/Computation/createComputations.js */ var createComputations = function( getComputationSignature, Computation ) { return function createComputations( ractive, computed ) { var key, signature; for ( key in computed ) { signature = getComputationSignature( computed[ key ] ); ractive.viewmodel.computations[ key ] = new Computation( ractive, key, signature ); } }; }( getComputationSignature, Computation ); /* viewmodel/adaptConfig.js */ var adaptConfig = function() { // should this be combined with prototype/adapt.js? var configure = { lookup: function( target, adaptors ) { var i, adapt = target.adapt; if ( !adapt || !adapt.length ) { return adapt; } if ( adaptors && Object.keys( adaptors ).length && ( i = adapt.length ) ) { while ( i-- ) { var adaptor = adapt[ i ]; if ( typeof adaptor === 'string' ) { adapt[ i ] = adaptors[ adaptor ] || adaptor; } } } return adapt; }, combine: function( parent, adapt ) { // normalize 'Foo' to [ 'Foo' ] parent = arrayIfString( parent ); adapt = arrayIfString( adapt ); // no parent? return adapt if ( !parent || !parent.length ) { return adapt; } // no adapt? return 'copy' of parent if ( !adapt || !adapt.length ) { return parent.slice(); } // add parent adaptors to options parent.forEach( function( a ) { // don't put in duplicates if ( adapt.indexOf( a ) === -1 ) { adapt.push( a ); } } ); return adapt; } }; function arrayIfString( adapt ) { if ( typeof adapt === 'string' ) { adapt = [ adapt ]; } return adapt; } return configure; }(); /* viewmodel/Viewmodel.js */ var Viewmodel = function( create, adapt, applyChanges, capture, clearCache, get, mark, merge, register, release, set, splice, teardown, unregister, createComputations, adaptConfig ) { // TODO: fix our ES6 modules so we can have multiple exports // then this magic check can be reused by magicAdaptor var noMagic; try { Object.defineProperty( {}, 'test', { value: 0 } ); } catch ( err ) { noMagic = true; } var Viewmodel = function( ractive ) { this.ractive = ractive; // TODO eventually, we shouldn't need this reference Viewmodel.extend( ractive.constructor, ractive ); //this.ractive.data this.cache = {}; // we need to be able to use hasOwnProperty, so can't inherit from null this.cacheMap = create( null ); this.deps = { computed: {}, 'default': {} }; this.depsMap = { computed: {}, 'default': {} }; this.patternObservers = []; this.wrapped = create( null ); // TODO these are conceptually very similar. Can they be merged somehow? this.evaluators = create( null ); this.computations = create( null ); this.captured = null; this.unresolvedImplicitDependencies = []; this.changes = []; this.implicitChanges = {}; }; Viewmodel.extend = function( Parent, instance ) { if ( instance.magic && noMagic ) { throw new Error( 'Getters and setters (magic mode) are not supported in this browser' ); } instance.adapt = adaptConfig.combine( Parent.prototype.adapt, instance.adapt ) || []; instance.adapt = adaptConfig.lookup( instance, instance.adaptors ); }; Viewmodel.prototype = { adapt: adapt, applyChanges: applyChanges, capture: capture, clearCache: clearCache, get: get, mark: mark, merge: merge, register: register, release: release, set: set, splice: splice, teardown: teardown, unregister: unregister, // createComputations, in the computations, may call back through get or set // of ractive. So, for now, we delay creation of computed from constructor. // on option would be to have the Computed class be lazy about using .update() compute: function() { createComputations( this.ractive, this.ractive.computed ); } }; return Viewmodel; }( create, viewmodel$adapt, viewmodel$applyChanges, viewmodel$capture, viewmodel$clearCache, viewmodel$get, viewmodel$mark, viewmodel$merge, viewmodel$register, viewmodel$release, viewmodel$set, viewmodel$splice, viewmodel$teardown, viewmodel$unregister, createComputations, adaptConfig ); /* Ractive/initialise.js */ var Ractive_initialise = function( config, create, getElement, getNextNumber, Viewmodel, Fragment ) { return function initialiseRactiveInstance( ractive ) { var options = arguments[ 1 ]; if ( options === void 0 ) options = {}; initialiseProperties( ractive, options ); // init config from Parent and options config.init( ractive.constructor, ractive, options ); // TEMPORARY. This is so we can implement Viewmodel gradually ractive.viewmodel = new Viewmodel( ractive ); // hacky circular problem until we get this sorted out // if viewmodel immediately processes computed properties, // they may call ractive.get, which calls ractive.viewmodel, // which hasn't been set till line above finishes. ractive.viewmodel.compute(); // Render our *root fragment* if ( ractive.template ) { ractive.fragment = new Fragment( { template: ractive.template, root: ractive, owner: ractive } ); } ractive.viewmodel.applyChanges(); // render automatically ( if `el` is specified ) tryRender( ractive ); }; function tryRender( ractive ) { var el; if ( el = getElement( ractive.el ) ) { var wasEnabled = ractive.transitionsEnabled; // Temporarily disable transitions, if `noIntro` flag is set if ( ractive.noIntro ) { ractive.transitionsEnabled = false; } // If the target contains content, and `append` is falsy, clear it if ( el && !ractive.append ) { // Tear down any existing instances on this element if ( el.__ractive_instances__ ) { try { el.__ractive_instances__.splice( 0, el.__ractive_instances__.length ).forEach( function( r ) { return r.teardown(); } ); } catch ( err ) {} } el.innerHTML = ''; } ractive.render( el, ractive.append ); // reset transitionsEnabled ractive.transitionsEnabled = wasEnabled; } } function initialiseProperties( ractive, options ) { // Generate a unique identifier, for places where you'd use a weak map if it // existed ractive._guid = getNextNumber(); // events ractive._subs = create( null ); // storage for item configuration from instantiation to reset, // like dynamic functions or original values ractive._config = {}; // two-way bindings ractive._twowayBindings = create( null ); // animations (so we can stop any in progress at teardown) ractive._animations = []; // nodes registry ractive.nodes = {}; // live queries ractive._liveQueries = []; ractive._liveComponentQueries = []; // If this is a component, store a reference to the parent if ( options._parent && options._component ) { ractive._parent = options._parent; ractive.component = options._component; // And store a reference to the instance on the component options._component.instance = ractive; } } }( config, create, getElement, getNextNumber, Viewmodel, Fragment ); /* extend/initChildInstance.js */ var initChildInstance = function( initialise ) { // The Child constructor contains the default init options for this class return function initChildInstance( child, Child, options ) { if ( child.beforeInit ) { child.beforeInit( options ); } initialise( child, options ); }; }( Ractive_initialise ); /* extend/childOptions.js */ var childOptions = function( wrapPrototype, wrap, config, circular ) { var Ractive, // would be nice to not have these here, // they get added during initialise, so for now we have // to make sure not to try and extend them. // Possibly, we could re-order and not add till later // in process. blacklisted = { '_parent': true, '_component': true }, childOptions = { toPrototype: toPrototype, toOptions: toOptions }, registries = config.registries; config.keys.forEach( function( key ) { return blacklisted[ key ] = true; } ); circular.push( function() { Ractive = circular.Ractive; } ); return childOptions; function toPrototype( parent, proto, options ) { for ( var key in options ) { if ( !( key in blacklisted ) && options.hasOwnProperty( key ) ) { var member = options[ key ]; // if this is a method that overwrites a method, wrap it: if ( typeof member === 'function' ) { member = wrapPrototype( parent, key, member ); } proto[ key ] = member; } } } function toOptions( Child ) { if ( !( Child.prototype instanceof Ractive ) ) { return Child; } var options = {}; while ( Child ) { registries.forEach( function( r ) { addRegistry( r.useDefaults ? Child.prototype : Child, options, r.name ); } ); Object.keys( Child.prototype ).forEach( function( key ) { if ( key === 'computed' ) { return; } var value = Child.prototype[ key ]; if ( !( key in options ) ) { options[ key ] = value._method ? value._method : value; } else if ( typeof options[ key ] === 'function' && typeof value === 'function' && options[ key ]._method ) { var result, needsSuper = value._method; if ( needsSuper ) { value = value._method; } // rewrap bound directly to parent fn result = wrap( options[ key ]._method, value ); if ( needsSuper ) { result._method = result; } options[ key ] = result; } } ); if ( Child._parent !== Ractive ) { Child = Child._parent; } else { Child = false; } } return options; } function addRegistry( target, options, name ) { var registry, keys = Object.keys( target[ name ] ); if ( !keys.length ) { return; } if ( !( registry = options[ name ] ) ) { registry = options[ name ] = {}; } keys.filter( function( key ) { return !( key in registry ); } ).forEach( function( key ) { return registry[ key ] = target[ name ][ key ]; } ); } }( wrapPrototypeMethod, wrapMethod, config, circular ); /* extend/_extend.js */ var Ractive_extend = function( create, defineProperties, getGuid, config, initChildInstance, Viewmodel, childOptions ) { return function extend() { var options = arguments[ 0 ]; if ( options === void 0 ) options = {}; var Parent = this, Child, proto, staticProperties; // if we're extending with another Ractive instance, inherit its // prototype methods and default options as well options = childOptions.toOptions( options ); // create Child constructor Child = function( options ) { initChildInstance( this, Child, options ); }; proto = create( Parent.prototype ); proto.constructor = Child; staticProperties = { // each component needs a guid, for managing CSS etc _guid: { value: getGuid() }, // alias prototype as defaults defaults: { value: proto }, // extendable extend: { value: extend, writable: true, configurable: true }, // Parent - for IE8, can't use Object.getPrototypeOf _parent: { value: Parent } }; defineProperties( Child, staticProperties ); // extend configuration config.extend( Parent, proto, options ); Viewmodel.extend( Parent, proto ); // and any other properties or methods on options... childOptions.toPrototype( Parent.prototype, proto, options ); Child.prototype = proto; return Child; }; }( create, defineProperties, getGuid, config, initChildInstance, Viewmodel, childOptions ); /* Ractive.js */ var Ractive = function( defaults, easing, interpolators, svg, magic, defineProperties, proto, Promise, extendObj, extend, parse, initialise, circular ) { var Ractive, properties; // Main Ractive required object Ractive = function( options ) { initialise( this, options ); }; // Ractive properties properties = { // static methods: extend: { value: extend }, parse: { value: parse }, // Namespaced constructors Promise: { value: Promise }, // support svg: { value: svg }, magic: { value: magic }, // version VERSION: { value: '0.5.5' }, // Plugins adaptors: { writable: true, value: {} }, components: { writable: true, value: {} }, decorators: { writable: true, value: {} }, easing: { writable: true, value: easing }, events: { writable: true, value: {} }, interpolators: { writable: true, value: interpolators }, partials: { writable: true, value: {} }, transitions: { writable: true, value: {} } }; // Ractive properties defineProperties( Ractive, properties ); Ractive.prototype = extendObj( proto, defaults ); Ractive.prototype.constructor = Ractive; // alias prototype as defaults Ractive.defaults = Ractive.prototype; // Certain modules have circular dependencies. If we were bundling a // module loader, e.g. almond.js, this wouldn't be a problem, but we're // not - we're using amdclean as part of the build process. Because of // this, we need to wait until all modules have loaded before those // circular dependencies can be required. circular.Ractive = Ractive; while ( circular.length ) { circular.pop()(); } // Ractive.js makes liberal use of things like Array.prototype.indexOf. In // older browsers, these are made available via a shim - here, we do a quick // pre-flight check to make sure that either a) we're not in a shit browser, // or b) we're using a Ractive-legacy.js build var FUNCTION = 'function'; if ( typeof Date.now !== FUNCTION || typeof String.prototype.trim !== FUNCTION || typeof Object.keys !== FUNCTION || typeof Array.prototype.indexOf !== FUNCTION || typeof Array.prototype.forEach !== FUNCTION || typeof Array.prototype.map !== FUNCTION || typeof Array.prototype.filter !== FUNCTION || typeof window !== 'undefined' && typeof window.addEventListener !== FUNCTION ) { throw new Error( 'It looks like you\'re attempting to use Ractive.js in an older browser. You\'ll need to use one of the \'legacy builds\' in order to continue - see http://docs.ractivejs.org/latest/legacy-builds for more information.' ); } return Ractive; }( options, easing, interpolators, svg, magic, defineProperties, prototype, Promise, extend, Ractive_extend, parse, Ractive_initialise, circular ); // export as Common JS module... if ( typeof module !== "undefined" && module.exports ) { module.exports = Ractive; } // ... or as AMD module else if ( typeof define === "function" && define.amd ) { define( function() { return Ractive; } ); } // ... or as browser global global.Ractive = Ractive; Ractive.noConflict = function() { global.Ractive = noConflict; return Ractive; }; }( typeof window !== 'undefined' ? window : this ) );
version https://git-lfs.github.com/spec/v1 oid sha256:7fc456b6be440886b9cc38c33cf2f6bd265d0b4fe0354392830570537f83a252 size 907
import { Component } from 'react' export default class extends Component { state = { input: '', message: null } componentDidMount () { // start listening the channel message global.ipcRenderer.on('message', this.handleMessage) } componentWillUnmount () { // stop listening the channel message global.ipcRenderer.removeListener('message', this.handleMessage) } handleMessage = (event, message) => { // receive a message from the main process and save it in the local state this.setState({ message }) } handleChange = event => { this.setState({ input: event.target.value }) } handleSubmit = event => { event.preventDefault() global.ipcRenderer.send('message', this.state.input) this.setState({ message: null }) } render () { return ( <div> <h1>Hello Electron!</h1> {this.state.message && <p>{this.state.message}</p>} <form onSubmit={this.handleSubmit}> <input type='text' onChange={this.handleChange} /> </form> <style jsx>{` h1 { color: red; font-size: 50px; } `}</style> </div> ) } }
define([], function() { 'use strict'; return [ '$scope', '$location', 'Rest', 'getRequestStat', 'gettext', 'getCreateRequest', function($scope, $location, Rest, getRequestStat, gettext, getCreateRequest) { $scope.setPageTitle(gettext('Requests')); var users = Rest.admin.users.getResource(); setTimeout(function() { // wait for search initialization $scope.search = $location.search(); $scope.$apply(); }, 1000); $scope.popover = { selectuser: { search: '' } }; /** * A search in the users popover * @param {string} newValue * @param {string} oldValue */ $scope.$watch('popover.selectuser.search', function(newValue) { if (newValue && newValue.length > 0) { $scope.popover.selectuser.users = users.query({ name: newValue, isAccount:true }); } else { $scope.popover.selectuser.users = []; } }); /** * Select a user account in the create request popover, open a modal * with spoof informations and available actions * * @param {Object} user */ $scope.popoverSelect = getCreateRequest($scope); $scope.departments = Rest.admin.departments.getResource().query(); $scope.getViewUrl = function(request) { if (request.absence.distribution.length > 0) { return '/admin/requests/absences/'+request._id; } if (request.workperiod_recover.length > 0) { return '/admin/requests/workperiod-recovers/'+request._id; } if (request.time_saving_deposit.length > 0) { return '/admin/requests/time-saving-deposits/'+request._id; } }; $scope.getStat = getRequestStat; }]; });
Package.describe({ name: 'ishwerdas:user-form-creator', version: '0.0.1', // Brief, one-line summary of the package. summary: '', // URL to the Git repository containing the source code for this package. git: '', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2.1'); api.use('ecmascript'); api.addFiles('user-form-creator.js'); }); Package.onTest(function(api) { api.use('ecmascript'); api.use('tinytest'); api.use('ishwerdas:user-form-creator'); api.addFiles('user-form-creator-tests.js'); });
import { assert } from './debug'; import isEnabled from './features'; import { _getPath as getPath } from './property_get'; import { propertyWillChange, propertyDidChange } from './property_events'; import EmberError from './error'; import { isPath, hasThis as pathHasThis } from './path_cache'; import { peekMeta } from './meta'; import { toString } from './utils'; /** Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the property is not defined but the object implements the `setUnknownProperty` method then that will be invoked as well. @method set @for Ember @param {Object} obj The object to modify. @param {String} keyName The property key to set @param {Object} value The value to set @return {Object} the passed value. @public */ export function set(obj, keyName, value, tolerant) { assert( `Set must be called with three or four arguments; an object, a property key, a value and tolerant true/false`, arguments.length === 3 || arguments.length === 4 ); assert(`Cannot call set with '${keyName}' on an undefined object.`, obj && typeof obj === 'object' || typeof obj === 'function'); assert(`The key provided to set must be a string, you passed ${keyName}`, typeof keyName === 'string'); assert(`'this' in paths is not supported`, !pathHasThis(keyName)); assert(`calling set on destroyed object: ${toString(obj)}.${keyName} = ${toString(value)}`, !obj.isDestroyed); if (isPath(keyName)) { return setPath(obj, keyName, value, tolerant); } let meta = peekMeta(obj); let possibleDesc = obj[keyName]; let desc, currentValue; if (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) { desc = possibleDesc; } else { currentValue = possibleDesc; } if (desc) { /* computed property */ desc.set(obj, keyName, value); } else if (obj.setUnknownProperty && currentValue === undefined && !(keyName in obj)) { /* unknown property */ assert('setUnknownProperty must be a function', typeof obj.setUnknownProperty === 'function'); obj.setUnknownProperty(keyName, value); } else if (currentValue === value) { /* no change */ return value; } else { propertyWillChange(obj, keyName); if (isEnabled('mandatory-setter')) { setWithMandatorySetter(meta, obj, keyName, value); } else { obj[keyName] = value; } propertyDidChange(obj, keyName); } return value; } if (isEnabled('mandatory-setter')) { var setWithMandatorySetter = function(meta, obj, keyName, value) { if (meta && meta.peekWatching(keyName) > 0) { makeEnumerable(obj, keyName); meta.writeValue(obj, keyName, value); } else { obj[keyName] = value; } }; var makeEnumerable = function(obj, key) { let desc = Object.getOwnPropertyDescriptor(obj, key); if (desc && desc.set && desc.set.isMandatorySetter) { desc.enumerable = true; Object.defineProperty(obj, key, desc); } }; } function setPath(root, path, value, tolerant) { // get the last part of the path let keyName = path.slice(path.lastIndexOf('.') + 1); // get the first part of the part path = (path === keyName) ? keyName : path.slice(0, path.length - (keyName.length + 1)); // unless the path is this, look up the first part to // get the root if (path !== 'this') { root = getPath(root, path); } if (!keyName || keyName.length === 0) { throw new EmberError('Property set failed: You passed an empty path'); } if (!root) { if (tolerant) { return; } else { throw new EmberError('Property set failed: object in path "' + path + '" could not be found or was destroyed.'); } } return set(root, keyName, value); } /** Error-tolerant form of `Ember.set`. Will not blow up if any part of the chain is `undefined`, `null`, or destroyed. This is primarily used when syncing bindings, which may try to update after an object has been destroyed. @method trySet @for Ember @param {Object} root The object to modify. @param {String} path The property path to set @param {Object} value The value to set @public */ export function trySet(root, path, value) { return set(root, path, value, true); }
const paramPattern = /:(\w+)(?:!(\w+))?/g; const typePattern = type => { switch (type) { case 'any': return '.+'; case 'number': return '-?\\d+'; default: return '[^/]+'; } }; const convert = type => { switch (type) { case 'number': return value => Number(value); default: return value => value; } }; function route(pattern) { const parameterNames = []; const conversions = []; const rxPattern = pattern.replace(paramPattern, (match, parameterName, type) => { parameterNames.push(parameterName); conversions.push(convert(type)); return `(${typePattern(type)})`; }); const rx = new RegExp(`^${rxPattern}$`); return function(url) { const match = url.match(rx); if (!match) { return; } const [, ...captures] = match; const mapped = captures.filter(value => value != undefined).map((value, i) => ({ [parameterNames[i]]: conversions[i](value), })); return Object.assign({}, ...mapped); }; } module.exports = route;
const createPromise = () => new Promise((resolve, reject) => { console.log('2 --> Promise created') setTimeout(() => resolve('babies'), 900) }) const createdPromise = new Promise((resolve, reject) => { console.log('7 --> Promise created') setTimeout(() => resolve('babies'), 900) }) setTimeout(() => { createdPromise .then(console.log) }, 1000) // createPromise() // .then(() => createdPromise) // .then(() => { // console.log('All done!') // }) // .catch(console.error)
var searchData= [ ['phi',['phi',['../class_wave_gen.html#a44097e6c7d06256be4d9866e8563e040',1,'WaveGen']]], ['phiincrement',['phiIncrement',['../class_wave_gen.html#a38a93ed92f9da20fa1f4477a863286f8',1,'WaveGen']]], ['polyblep',['polyBlep',['../class_wave_gen.html#ac27146def7ca149aca0ec7373a6d773d',1,'WaveGen']]] ];
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides a filter for list bindings sap.ui.define(['jquery.sap.global', 'sap/ui/base/Object', './FilterOperator', 'sap/ui/Device'], function(jQuery, BaseObject, FilterOperator, Device) { "use strict"; /** * Constructor for Filter * You can either pass an object with the filter parameters or use the function arguments * * Using object: * new sap.ui.model.Filter({ * path: "...", * operator: "...", * value1: "...", * value2: "..." * }) * * OR: * new sap.ui.model.Filter({ * path: "...", * test: function(oValue) { * } * }) * * OR: * new sap.ui.model.Filter({ * filters: [...], * and: true|false * }) * * You can only pass sPath, sOperator and their values OR sPath, fnTest OR aFilters and bAnd. You will get an error if you define an invalid combination of filters parameters. * * Using arguments: * new sap.ui.model.Filter(sPath, sOperator, oValue1, oValue2); * OR * new sap.ui.model.Filter(sPath, fnTest); * OR * new sap.ui.model.Filter(aFilters, bAnd); * * aFilters is an array of other instances of sap.ui.model.Filter. If bAnd is set all filters within the filter will be ANDed else they will be ORed. * * @class * Filter for the list binding * * @param {object} oFilterInfo the filter info object * @param {string} oFilterInfo.path the binding path for this filter * @param {function} oFilterInfo.test function which is used to filter the items which should return a boolean value to indicate whether the current item is preserved * @param {sap.ui.model.FilterOperator} oFilterInfo.operator operator used for the filter * @param {object} oFilterInfo.value1 first value to use for filter * @param {object} [oFilterInfo.value2=null] second value to use for filter * @param {array} oFilterInfo.filters array of filters on which logical conjunction is applied * @param {boolean} oFilterInfo.and indicates whether an "and" logical conjunction is applied on the filters. If it's set to false, an "or" conjunction is applied * @public * @alias sap.ui.model.Filter */ var Filter = BaseObject.extend("sap.ui.model.Filter", /** @lends sap.ui.model.Filter.prototype */ { constructor : function(sPath, sOperator, oValue1, oValue2){ //There are two different ways of specifying a filter //If can be passed in only one object or defined with parameters if (typeof sPath === "object" && !jQuery.isArray(sPath)) { var oFilterData = sPath; this.sPath = oFilterData.path; this.sOperator = oFilterData.operator; this.oValue1 = oFilterData.value1; this.oValue2 = oFilterData.value2; this.aFilters = oFilterData.filters || oFilterData.aFilters; this.bAnd = oFilterData.and || oFilterData.bAnd; this.fnTest = oFilterData.test; } else { //If parameters are used we have to check whether a regular or a multi filter is specified if (jQuery.isArray(sPath)) { this.aFilters = sPath; } else { this.sPath = sPath; } if (jQuery.type(sOperator) === "boolean") { this.bAnd = sOperator; } else if (jQuery.type(sOperator) === "function" ) { this.fnTest = sOperator; } else { this.sOperator = sOperator; } this.oValue1 = oValue1; this.oValue2 = oValue2; } // apply normalize polyfill to non mobile browsers when it is a string filter if (!String.prototype.normalize && typeof this.oValue1 == "string" && !Device.browser.mobile) { jQuery.sap.require("jquery.sap.unicode"); } if (jQuery.isArray(this.aFilters) && !this.sPath && !this.sOperator && !this.oValue1 && !this.oValue2) { this._bMultiFilter = true; jQuery.each(this.aFilters, function(iIndex, oFilter) { if (!(oFilter instanceof Filter)) { jQuery.sap.log.error("Filter in Aggregation of Multi filter has to be instance of sap.ui.model.Filter"); } }); } else if (!this.aFilters && this.sPath !== undefined && ((this.sOperator && this.oValue1 !== undefined) || this.fnTest)) { this._bMultiFilter = false; } else { jQuery.sap.log.error("Wrong parameters defined for filter."); } } }); return Filter; });
Chartmander.components.label = function (data, title) { var label = new Chartmander.components.element(); label.label(data.label).value(data.value); // for old axis label.startAt = function (val) { label.savePosition(0, val); return label; }; label.startAtY = function (val) { label.savePosition(0, val); return label; }; label.startAtX = function (val) { label.savePosition(val, 0); return label; }; return label; };
// All symbols in the Vertical Forms block as per Unicode v9.0.0: [ '\uFE10', '\uFE11', '\uFE12', '\uFE13', '\uFE14', '\uFE15', '\uFE16', '\uFE17', '\uFE18', '\uFE19', '\uFE1A', '\uFE1B', '\uFE1C', '\uFE1D', '\uFE1E', '\uFE1F' ];
import container from '../dependencies/container'; class ConfirmDialog { show(fn) { return this.constructor.show(fn); } setContent(title, message) { return this.constructor.setContent(title, message); } static show(fn) { return this.$provider.show(fn); } static setContent(title, message) { return this.$provider.setContent(title, message); } } container.mapType('ConfirmDialog', ConfirmDialog, '$ConfirmDialogProvider');
"use strict"; var world_laby = document.getElementById("world_labyrinth"); /* Mini-Game: Labyrinth A group of people are in a maze, the input defines which walls are open or closed A crystal is in some cell, the people try to reach it When someone reach the crystal, it moves to another cell */ var Cell = function (x0, y0) { this.x0 = x0; this.y0 = y0; this.active = false; }; Cell.prototype.draw = function(ctx) { ctx.save(); if (this.active) { // cell ctx.beginPath(); ctx.fillStyle = this.active ? "SlateGray" : "white"; ctx.rect(this.x0, this.y0, world_laby.tW, world_laby.tH); ctx.fill(); } ctx.restore(); }; Cell.prototype.drawShadow = function(ctx) { ctx.save(); if (this.active) { var shadowDepth = 3; ctx.beginPath(); ctx.fillStyle = "black"; ctx.rect(this.x0 + shadowDepth, this.y0 + shadowDepth, world_laby.tW, world_laby.tH ); ctx.fill(); } ctx.restore(); } Cell.prototype.isInside = function(x, y) { return x >= this.x0 && x <= this.x0 + world_laby.tW && y >= this.y0 && y <= this.y0 + world_laby.tH; }; var Guy = function(x, y) { this.x = x; this.y = y; this.radius = Math.round(world_laby.height / 30 * Math.random()); this.maxSpeed = Math.round(10 * Math.random()) + 30; this.speed = 0; this.acc = 30; // px/s/s }; Guy.snapDistance = 3; //px Guy.prototype.update = function(dt) { var target = world_laby.crystal; var dx = target.x - this.x; var dy = target.y - this.y; // var angl = Math.atan2(dy, dx); var dist = Math.sqrt(dx * dx + dy * dy); if (dist <= Guy.snapDistance) { this.x = target.x; this.y = target.y; } else { var speedX = this.speed * (dx / dist); var speedY = this.speed * (dy / dist); // if (this.speed != 0) {console.log(this.speed, speedX, speedY);} this.x += dt / 1000 * speedX; this.y += dt / 1000 * speedY; } this.speed += dt / 1000 * this.acc; this.speed = Math.min(this.speed, this.maxSpeed); // random movement this.x += Math.round(2 * (Math.random() - 0.5)); this.y += Math.round(2 * (Math.random() - 0.5)); // collision with cells for (var h = 0; h < world_laby.cells.length; h++) { for (var w = 0; w < world_laby.cells[0].length; w++) { var cell = world_laby.cells[h][w]; if (cell.active && cell.isInside(this.x, this.y)) { this.speed = 0; // snap to closest wall var distUP = this.y - cell.y0; var distDOWN = cell.y0 + world_laby.tH - this.y; var distLEFT = this.x - cell.x0; var distRIGHT = cell.x0 + world_laby.tW - this.x; var distMIN = Math.min(distUP, distDOWN, distLEFT, distRIGHT); if (distUP >= 0 && distMIN === distUP) { this.y = cell.y0; } else if (distDOWN >= 0 && distMIN === distDOWN) { this.y = cell.y0 + world_laby.tH; } else if (distLEFT >= 0 && distMIN === distLEFT) { this.x = cell.x0; } else if (distRIGHT >= 0 && distMIN === distRIGHT) { this.x = cell.x0 + world_laby.tW; } } } } // collision with other guys for (var g = 0; g < world_laby.people.length; g++) { var otherGuy = world_laby.people[g]; if (otherGuy != this) { var dx = this.x - otherGuy.x; var dy = this.y - otherGuy.y; var dist = Math.sqrt(dx * dx + dy * dy); if (dist <= this.radius + otherGuy.radius) if (this.radius < otherGuy.radius) { otherGuy.push(this); } else { this.push(otherGuy); } } } // world_laby limits this.x = Math.max(0, this.x); this.y = Math.max(0, this.y); this.x = Math.min(this.x, world_laby.width); this.y = Math.min(this.y, world_laby.height); }; Guy.prototype.push = function(otherGuy) { var dx = otherGuy.x - this.x; var dy = otherGuy.y - this.y; var dist = Math.sqrt(dx * dx + dy * dy); if (dist <= 0.01) { otherGuy.x -= 10; dist = 10; } dx /= dist; dy /= dist; var newDist = this.radius + otherGuy.radius; otherGuy.x = this.x + dx * newDist; otherGuy.y = this.y + dx * newDist; }; Guy.prototype.draw = function(ctx) { ctx.save(); ctx.beginPath(); ctx.beginPath(); ctx.fillStyle = "green"; ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI); ctx.fill(); ctx.restore(); }; var Crystal = function() { this.findCell(); this.size = world_laby.tH / 3; }; Crystal.blinkTime = 0.25; //s Crystal.prototype.findCell = function() { var cellY = Math.round((world_laby.cells.length - 1) * Math.random()); var cellX = Math.round((world_laby.cells[0].length - 1) * Math.random()); var x = (cellX + 0.5) * world_laby.tW; var y = (cellY + 0.5) * world_laby.tH; this.x = x; this.y = y; world_laby.blink = Crystal.blinkTime; }; Crystal.prototype.update = function(dt) { for (var g = 0; g < world_laby.people.length; g++) { var guy = world_laby.people[g]; var dx = this.x - guy.x; var dy = this.y - guy.y; var squared_dist = dx * dx + dy * dy; if (squared_dist < this.size * this.size) { this.findCell(); } } }; Crystal.prototype.draw = function(ctx) { ctx.save(); ctx.fillStyle = "DarkMagenta"; ctx.beginPath(); ctx.rect(this.x - this.size / 2, this.y - this.size / 2, this.size, this.size); ctx.fill(); ctx.restore(); }; world_laby.init = function(inputs) { world_laby.tH = world_laby.height / inputs.length; // tile Height world_laby.tW = world_laby.width / inputs[0].length; // tile Width world_laby.cells = []; for (var h = 0; h < inputs.length; h++) { world_laby.cells.push([]); for (var w = 0; w < inputs[h].length; w++) { var cell = new Cell(w * world_laby.tW, h * world_laby.tH); cell.active = inputs[h][w].checked; world_laby.cells[h].push(cell); } } world_laby.people = []; var populationCount = 10; for (var g = 0; g < populationCount; g++) { world_laby.people.push(new Guy( world_laby.width / 2 - world_laby.tW / 2 + Math.round((world_laby.tW - 1) * Math.random()), world_laby.height / 2 - world_laby.tH / 2 + Math.round((world_laby.tH - 1) * Math.random()) )); } world_laby.crystal = new Crystal(); world_laby.blink = 0; }; world_laby.update = function(dt, inputs) { for (var h = 0; h < inputs.length; h++) { for (var w = 0; w < inputs[h].length; w++) { world_laby.cells[h][w].active = inputs[h][w].checked; } } for (var g = 0; g < world_laby.people.length; g++) { world_laby.people[g].update(dt); } world_laby.crystal.update(dt); if (world_laby.blink > 0) { world_laby.blink -= dt / 1000; } }; world_laby.draw = function() { var ctx = world_laby.getContext("2d"); ctx.imageSmoothingEnabled = false; ctx.beginPath(); ctx.fillStyle = "white"; ctx.rect(0, 0, world_laby.width, world_laby.height); ctx.fill(); if (world_laby.blink > 0) { ctx.beginPath(); ctx.fillStyle = "DarkMagenta"; ctx.globalAlpha = world_laby.blink / Crystal.blinkTime; ctx.rect(0, 0, world_laby.width, world_laby.height); ctx.fill(); ctx.globalAlpha = 1; } // draw all cells shadow for (var h = 0; h < world_laby.cells.length; h++) { for (var w = 0; w < world_laby.cells[h].length; w++) { world_laby.cells[h][w].drawShadow(ctx); } } // draw people for (var g = 0; g < world_laby.people.length; g++) { world_laby.people[g].draw(ctx); } // draw all cells for (var h = 0; h < world_laby.cells.length; h++) { for (var w = 0; w < world_laby.cells[h].length; w++) { world_laby.cells[h][w].draw(ctx); } } world_laby.crystal.draw(ctx); };
import {log} from 'gulp-util'; import {exec} from 'child_process'; import promisify from 'es6-promisify'; import gulp from 'gulp'; import {infoForUpdatedPackages, publishPackages} from './helpers/publish-helper'; import runSequence from 'run-sequence'; const execPromise = promisify(exec); gulp.task('set-styleguide-env-to-production', () => process.env.STYLEGUIDE_ENV = 'production'); gulp.task('release-push-git-verify', async () => { const currentSha = await execPromise('git rev-parse HEAD'); const masterSha = await execPromise('git rev-parse master'); if (currentSha !== masterSha) { log('Error: You must be on master.'); process.exit(1); } try { await execPromise('git diff --quiet && git diff --cached --quiet'); } catch (e) { log('Error: You have uncommitted changes.'); process.exit(2); } return execPromise('git fetch origin'); }); gulp.task('release-push-production-styleguide-verify', () => // Verifies that we're logged in - will prevent future steps if not execPromise('cf target -o pivotal -s pivotal-ui') .catch(() => { log('Error: could not set the org and space. Are you logged in to cf?'); process.exit(3); }) ); gulp.task('release-push-npm-publish', ['css-build', 'react-build'], () => { return gulp.src('dist/{css,react}/*/package.json') .pipe(infoForUpdatedPackages()) .pipe(publishPackages()); }); gulp.task('release-push-git', async () => { const {version} = require('../package.json'); log(`Cutting tag v${version}`); await execPromise(`git tag v${version}`); log('Pushing to origin/master'); await execPromise('git push origin master'); log('Pushing new tag'); return await execPromise(`git push origin v${version}`); }); gulp.task('release-push-production-styleguide', (done) => { const deployProcess = exec('cf push'); deployProcess.stdout.pipe(process.stdout); deployProcess.stderr.pipe(process.stderr); deployProcess.on('exit', (code) => { if (code) { process.exit(code); } done(); }); }); gulp.task('release-push', (done) => runSequence( 'set-styleguide-env-to-production', ['release-push-git-verify', 'release-push-production-styleguide-verify'], 'release-push-npm-publish', 'monolith', ['release-push-git', 'release-push-production-styleguide'], done ));
(function (window, angular, _) { /* global VK */ 'use strict'; angular.module('vk') .constant('API_VERSION', '5.35') .factory('VKAPI', ['$q', '$window', 'API_VERSION', 'APP_ID', VKService]); var APPENDED = false; function appendScript() { if (APPENDED === false) { var el = document.createElement("script"); el.type = "text/javascript"; el.src = "//vk.com/js/api/openapi.js"; el.async = true; document.getElementById("vk_api_transport").appendChild(el); } APPENDED = true; } function VKService($q, $window, API_VERSION, APP_ID) { var defer = $q.defer(); var versionOptions = { v: API_VERSION }; var SESSION; var INJECTED = false; var USER; $window.vkAsyncInit = function () { VK.init({apiId: APP_ID}); methods.access = VK.access; methods.apiCall = VK.Api.call; //_.debounce(VK.Api.call, 300); setTimeout(function () { INJECTED = true; defer.resolve(INJECTED); }, 0); }; var methods = { access: null, session: SESSION, /** * @returns {Promise} */ getUser: function () { return $q(function (resolve, reject) { if (USER) { resolve(USER); } else { reject(false); } }); }, user: function() { return USER; }, userFullName: function () { return USER.first_name + ' ' + USER.last_name; }, /** * @returns {Promise} */ apiUsersGetCurrent: function () { return methods.api('users.get', { user_ids: SESSION.mid }).then(function (data) { USER = data[0]; return USER; }); }, /** * @returns {Promise} */ apiUsersGet: function(ids) { return methods.api('users.get', { user_ids: ids }); }, /** * @returns {Promise} */ getLoginStatus: function () { return $q(function (resolve, reject) { VK.Auth.getLoginStatus(function (data) { SESSION = data.session; if (SESSION !== null && data.status !== 'not_authorized') { methods.apiUsersGetCurrent().then(function () { resolve(USER); }, reject); } else { reject(data); } }); }); }, /** * @returns {Boolean} */ isGuest: function () { return typeof USER === 'undefined'; }, /** * @param {Number} access code * @returns {Promise} */ login: function (access) { return $q(function (resolve, reject) { VK.Auth.login(function (data) { if (data.status === "connected") { SESSION = data.session; methods.apiUsersGetCurrent().then(function () { resolve(data.session); }); } else { reject(data.error); } }, access); }); }, /** * @returns {Promise} */ logout: function () { return $q(function (resolve, reject) { VK.Auth.logout(function (data) { resolve(data); }); }); }, /** * @returns {Promise} */ api: function (method, settings) { var params = angular.extend(versionOptions, { offset: 0 //count: MAX_COUNT }, settings); /** * Inject 'next' function to paginate * @param res * @returns {*} */ function injectNext(res) { var count = res.count, len = res.items && res.items.length, nextOffset; if (count && len && (params.offset + len < count)) { nextOffset = params.offset + len; if (nextOffset) { params.offset = nextOffset; res.next = apiCall.bind(null, method, params); } } return res; } function apiCall(method, params) { return $q(function (resolve, reject) { methods.apiCall(method, params, function (data) { if (data.response) { resolve(data.response); } else { console.error(method + ':' + data.error.error_msg, params); reject(data.error); } }); }); } return apiCall(method, params); }, /** * @returns {Promise} */ inject: function () { setTimeout(function () { appendScript(); }, 0); return defer.promise; } }; return methods; } })(window, angular, _);
var mongoose = require('../../lib/mongodb'); const tools=require('../../lib/tools'); var OrdExpress={ id: {type: Number, required: true, unique: true},//主键 orderId:{type:Number,required:true,unique:false},//订单号 expNo:{type:String,required:true,unique:true,default:''},//快递单号 status:{type:Number,required:true,default:-1,enum:[-1,0,1,2,3,4,5,6,7,8,9,10]},//-1 待查询 0 查询异常 1 暂无记录 2 在途中 3 派送中 4 已签收 5 用户拒签 6 疑难件 7 无效单 8 超时单 9 签收失败 10 退回 expSpellName:{type:String,default:''},//快递公司简拼 expName:{type:String,default:''},//快递公司名 path:[{time:String,context:String}],//查询内容 update:{type:Date,default:tools.getNow()}//最后一次查询时间 } var ordExpressSchema=new mongoose.Schema(OrdExpress,{id:false}); var OrdExpressModel=mongoose.model('OrdExpressModel',ordExpressSchema,'ord_express'); module.exports=OrdExpressModel;
var r; reportCompare( "x", (r = /[\x]+/.exec("x")) && r[0], "Section 1" );
import { connect } from 'react-redux'; import Renderer from './renderer'; import * as UIActions from '../../../../actions/ui'; import * as EdgeActions from '../../../../actions/edges'; import * as NodeActions from '../../../../actions/nodes'; function mapStateToProps(state, ownProps) { return { node: ownProps.node, selectedNode: state.ui.selectedNode }; } function mapDispatchToProps(dispatch, ownProps) { return { removeNode: () => { dispatch(NodeActions.removeNode(ownProps.node.id)); } }; } export default connect(mapStateToProps, mapDispatchToProps)(Renderer);
define([ 'app', 'framework', './view' ], function(App, Framework, Views) { var Widget = Framework.BaseWidget.extend({ initialize: function(options) { return new Views.CardsView(options); } }); return Widget; });
import { Mongo } from 'meteor/mongo'; export const Tasks = new Mongo.Collection('playlist');
var lobFactory = require('../lib/index.js'); var Lob = new lobFactory('test_0dc8d51e0acffcb1880e0f19c79b2f5b0cc'); var chai = require('chai'); var expect = chai.expect; /* jshint camelcase: false */ describe('Verification', function () { it('should have correct defaults', function (done) { var addressLine1 = '220 William T Morrissey Boulevard'; var addressCity = 'Boston'; var addressState = 'MA'; var addressZip = '02125'; Lob.verification.verify({ address_line1: addressLine1, address_city: addressCity, address_state: addressState, address_zip: addressZip }, function (err, res) { expect(res).to.have.property('address'); expect(res.address).to.have.property('address_line1'); expect(res.address.address_line1).to.eql('220 WILLIAM T MORRISSEY BLVD'); expect(res.address).to.have.property('address_line2'); expect(res.address.address_line2).to.eql(''); expect(res.address).to.have.property('address_city'); expect(res.address.address_city).to.eql('BOSTON'); expect(res.address).to.have.property('address_state'); expect(res.address.address_state).to.eql('MA'); expect(res.address).to.have.property('address_zip'); expect(res.address.address_zip).to.eql('02125-3314'); expect(res.address).to.have.property('address_country'); expect(res.address.address_country).to.eql('US'); return done(); }); }); it('should error when invalid address is provided', function (done) { var addressLine1 = '123 Test Street'; var addressCity = 'Boston'; var addressState = 'MA'; var addressZip = '02125'; Lob.verification.verify({ address_line1: addressLine1, address_city: addressCity, address_state: addressState, address_zip: addressZip }, function (err) { expect(err).to.be.instanceof(Array); return done(); }); }); it('should warn when semi-valid address is provided', function (done) { var addressLine1 = '325 Berry St'; var addressCity = 'San Francisco'; var addressState = 'CA'; var addressZip = '94158'; Lob.verification.verify({ address_line1: addressLine1, address_city: addressCity, address_state: addressState, address_zip: addressZip }, function (err, res) { expect(res).to.have.property('address'); expect(res.address).to.have.property('address_line1'); expect(res.address.address_line1).to.eql('325 BERRY ST'); expect(res.address).to.have.property('address_line2'); expect(res.address.address_line2).to.eql(''); expect(res.address).to.have.property('address_city'); expect(res.address.address_city).to.eql('SAN FRANCISCO'); expect(res.address).to.have.property('address_state'); expect(res.address.address_state).to.eql('CA'); expect(res.address).to.have.property('address_zip'); expect(res.address.address_zip).to.eql('94158-1553'); expect(res.address).to.have.property('address_country'); expect(res.address.address_country).to.eql('US'); expect(res).to.have.property('message'); return done(); }); }); }); /* jshint camelcase: true */
var _ = require('lodash'), chalk = require('chalk'), path = require('path'), Promise = require('bluebird'), NotFoundError = require('./not-found-error'), BadRequestError = require('./bad-request-error'), InternalServerError = require('./internal-server-error'), NoPermissionError = require('./no-permission-error'), MethodNotAllowedError = require('./method-not-allowed-error'), RequestEntityTooLargeError = require('./request-too-large-error'), UnauthorizedError = require('./unauthorized-error'), ValidationError = require('./validation-error'), UnsupportedMediaTypeError = require('./unsupported-media-type-error'), EmailError = require('./email-error'), DataImportError = require('./data-import-error'), TooManyRequestsError = require('./too-many-requests-error'), config, errors, userErrorTemplateExists = false; function getConfigModule() { if (!config) { config = require('../config'); } return config; } function isValidErrorStatus(status) { return _.isNumber(status) && status >= 400 && status < 600; } function getStatusCode(error) { if (error.statusCode) { return error.statusCode; } if (error.status && isValidErrorStatus(error.status)) { error.statusCode = error.status; return error.statusCode; } if (error.code && isValidErrorStatus(error.code)) { error.statusCode = error.code; return error.statusCode; } error.statusCode = 500; return error.statusCode; } /** * Basic error handling helpers */ errors = { throwError: function (err) { if (!err) { err = new Error('errors.errors.anErrorOccurred'); } if (_.isString(err)) { throw new Error(err); } throw err; }, // ## Reject Error // Used to pass through promise errors when we want to handle them at a later time rejectError: function (err) { return Promise.reject(err); }, logInfo: function (component, info) { if ((process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'staging' || process.env.NODE_ENV === 'production')) { console.info(chalk.cyan(component + ':', info)); } }, logWarn: function (warn, context, help) { if ((process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'staging' || process.env.NODE_ENV === 'production')) { warn = warn || 'errors.errors.noMessageSupplied'; var msgs = [chalk.yellow('errors.errors.warning', warn), '\n']; if (context) { msgs.push(chalk.white(context), '\n'); } if (help) { msgs.push(chalk.green(help)); } // add a new line msgs.push('\n'); console.log.apply(console, msgs); } }, logError: function (err, context, help) { var self = this, origArgs = _.toArray(arguments).slice(1), stack, msgs; if (_.isArray(err)) { _.each(err, function (e) { var newArgs = [e].concat(origArgs); errors.logError.apply(self, newArgs); }); return; } stack = err ? err.stack : null; if (!_.isString(err)) { if (_.isObject(err) && _.isString(err.message)) { err = err.message; } else { err = 'errors.errors.unknownErrorOccurred'; } } if (err.indexOf('SQLITE_READONLY') !== -1) { context = 'errors.errors.databaseIsReadOnly'; help = 'errors.errors.checkDatabase'; } if ((process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'staging' || process.env.NODE_ENV === 'production')) { msgs = [chalk.red('errors.errors.error', err), '\n']; if (context) { msgs.push(chalk.white(context), '\n'); } if (help) { msgs.push(chalk.green(help)); } // add a new line msgs.push('\n'); if (stack) { msgs.push(stack, '\n'); } console.error.apply(console, msgs); } }, logErrorAndExit: function (err, context, help) { this.logError(err, context, help); process.exit(0); }, logAndThrowError: function (err, context, help) { this.logError(err, context, help); this.throwError(err, context, help); }, logAndRejectError: function (err, context, help) { this.logError(err, context, help); return this.rejectError(err, context, help); }, logErrorWithRedirect: function (msg, context, help, redirectTo, req, res) { var self = this; return function () { self.logError(msg, context, help); if (_.isFunction(res.redirect)) { res.redirect(redirectTo); } }; }, /** * @param {Array} error * @return {{errors: Array, statusCode: number}} */ formatHttpErrors: function formatHttpErrors(error) { var statusCode = 500, errors = []; if (!_.isArray(error)) { error = [].concat(error); } _.each(error, function each(errorItem) { var errorContent = {}; statusCode = getStatusCode(errorItem); errorContent.message = _.isString(errorItem) ? errorItem : (_.isObject(errorItem) ? errorItem.message : 'errors.errors.unknownApiError'); errorContent.errorType = errorItem.errorType || 'InternalServerError'; errors.push(errorContent); }); return {errors: errors, statusCode: statusCode}; }, formatAndRejectAPIError: function (error, permsMessage) { if (!error) { return this.rejectError( new this.NoPermissionError(permsMessage || 'errors.errors.notEnoughPermission') ); } if (_.isString(error)) { return this.rejectError(new this.NoPermissionError(error)); } if (error.errorType) { return this.rejectError(error); } // handle database errors if (error.code && (error.errno || error.detail)) { error.db_error_code = error.code; error.errorType = 'DatabaseError'; error.statusCode = 500; return this.rejectError(error); } return this.rejectError(new this.InternalServerError(error)); }, handleAPIError: function errorHandler(err, req, res, next) { var httpErrors = this.formatHttpErrors(err); this.logError(err); // Send a properly formatted HTTP response containing the errors res.status(httpErrors.statusCode).json({errors: httpErrors.errors}); }, renderErrorPage: function (statusCode, err, req, res, next) { console.log("errorCode" + statusCode +"....." +err); }, error404: function (req, res, next) { var message = 'errors.errors.pageNotFound'; // do not cache 404 error res.set({'Cache-Control': 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'}); if (req.method === 'GET') { this.renderErrorPage(404, message, req, res, next); } else { res.status(404).send(message); } }, error500: function (err, req, res, next) { var statusCode = getStatusCode(err), returnErrors = []; // 500 errors should never be cached res.set({'Cache-Control': 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'}); if (statusCode === 404) { return this.error404(req, res, next); } if (req.method === 'GET') { if (!err || !(err instanceof Error)) { next(); } errors.renderErrorPage(statusCode, err, req, res, next); } else { if (!_.isArray(err)) { err = [].concat(err); } _.each(err, function (errorItem) { var errorContent = {}; errorContent.message = _.isString(errorItem) ? errorItem : (_.isObject(errorItem) ? errorItem.message : 'errors.errors.unknownError'); errorContent.errorType = errorItem.errorType || 'InternalServerError'; returnErrors.push(errorContent); }); res.status(statusCode).json({errors: returnErrors}); } } }; _.forEach([ 'logWarn', 'logInfo', 'rejectError', 'throwError', 'logError', 'logAndThrowError', 'logAndRejectError', 'logErrorAndExit', 'logErrorWithRedirect', 'handleAPIError', 'formatAndRejectAPIError', 'formatHttpErrors', 'renderErrorPage', 'error404', 'error500' ], function (funcName) { errors[funcName] = errors[funcName].bind(errors); }); module.exports = errors; module.exports.NotFoundError = NotFoundError; module.exports.BadRequestError = BadRequestError; module.exports.InternalServerError = InternalServerError; module.exports.NoPermissionError = NoPermissionError; module.exports.UnauthorizedError = UnauthorizedError; module.exports.ValidationError = ValidationError; module.exports.RequestEntityTooLargeError = RequestEntityTooLargeError; module.exports.UnsupportedMediaTypeError = UnsupportedMediaTypeError; module.exports.EmailError = EmailError; module.exports.DataImportError = DataImportError; module.exports.MethodNotAllowedError = MethodNotAllowedError; module.exports.TooManyRequestsError = TooManyRequestsError;
"use strict"; var Http = require("http"); var Async = require("./../node_modules/asyncjs"); var options = { host: "localhost", port: 8000, method: "REPORT", path: "/" }; Async.range(1, 1000) .each(function(num) { var req = Http.request(options, function(res) { if (res.statusCode != 207) return next("Invalid status code! " + res.statusCode); console.log("[" + num + "] status: " + res.statusCode); //console.log("[" + num + "] headers: " + JSON.stringify(res.headers)); res.setEncoding("utf8"); res.on("data", function(chunk) { console.log("[" + num + "] body: " + chunk); }); res.on("end", function() { //next(); }); }); req.on("error", function(e) { console.log("problem with request: " + e.message); }); // write data to request body req.write('<?xml version="1.0" encoding="utf-8" ?>\n'); req.write('<D:filelist xmlns:D="DAV:"></D:filelist>'); req.end(); }) .end(function(err) { console.log("DONE"); });
var profile = (function () { return { resourceTags: { test: function (filename, mid) { return /tests/.test(filename); }, amd: function (filename, mid) { return /TerraArcGIS\.js$/.test(filename) && !/tests/.test(filename); } } }; })();
import CharacterT19 from './CharacterT19' export default CharacterT19
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Web Client * Copyright (C) 2007, 2008, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ /** * Creates a new calendar item edit view. * @constructor * @class * This is the main screen for creating/editing an appointment. It provides * inputs for the various appointment details. * * @author Parag Shah * * @param {DwtControl} parent some container * @param {Hash} attendees attendees/locations/equipment * @param {Object} dateInfo a hash of date info * @param {ZmController} controller the compose controller for this view * * @extends ZmCalItemEditView * * @private */ ZmApptEditView = function(parent, attendees, controller, dateInfo) { ZmCalItemEditView.call(this, parent, attendees, controller, dateInfo, null, "ZmApptEditView"); // cache so we dont keep calling appCtxt this.GROUP_CALENDAR_ENABLED = appCtxt.get(ZmSetting.GROUP_CALENDAR_ENABLED); this._attTypes = []; if (this.GROUP_CALENDAR_ENABLED) { this._attTypes.push(ZmCalBaseItem.PERSON); } this._attTypes.push(ZmCalBaseItem.LOCATION); if (appCtxt.get(ZmSetting.GAL_ENABLED) && this.GROUP_CALENDAR_ENABLED) { this._attTypes.push(ZmCalBaseItem.EQUIPMENT); } this._locationTextMap = {}; this._attendeePicker = {}; this._pickerButton = {}; this._useAcAddrBubbles = appCtxt.get(ZmSetting.USE_ADDR_BUBBLES); //used to preserve original attendees while forwarding appt this._fwdApptOrigAttendees = []; this._attendeesHashMap = {}; // Store Appt form values. this._apptFormValue = {}; this._showAsValueChanged = false; this._locationExceptions = null; this._alteredLocations = null; this._enableResolveDialog = true; this._locationConflict = false; this._locationStatusMode = ZmApptEditView.LOCATION_STATUS_NONE; var app = appCtxt.getApp(ZmApp.CALENDAR); // Each ApptEditView must now have its own copy of the FreeBusyCache. The cache will // now hold FreeBusy info that is unique to an appointment, in that the Server provides // Free busy info that excludes the current appointment. So the cache information cannot // be shared across appointments. //this._fbCache = app.getFreeBusyCache(); AjxDispatcher.require("CalendarCore"); this._fbCache = new ZmFreeBusyCache(app); this._customRecurDialogCallback = this._recurChangeForLocationConflict.bind(this); }; ZmApptEditView.prototype = new ZmCalItemEditView; ZmApptEditView.prototype.constructor = ZmApptEditView; // Consts ZmApptEditView.PRIVACY_OPTION_PUBLIC = "PUB"; ZmApptEditView.PRIVACY_OPTION_PRIVATE = "PRI"; ZmApptEditView.PRIVACY_OPTIONS = [ { label: ZmMsg._public, value: "PUB", selected: true }, { label: ZmMsg._private, value: "PRI" } // { label: ZmMsg.confidential, value: "CON" } // see bug #21205 ]; ZmApptEditView.BAD = "_bad_addrs_"; ZmApptEditView.REMINDER_MAX_VALUE = {}; ZmApptEditView.REMINDER_MAX_VALUE[ZmCalItem.REMINDER_UNIT_DAYS] = 14; ZmApptEditView.REMINDER_MAX_VALUE[ZmCalItem.REMINDER_UNIT_MINUTES] = 20160; ZmApptEditView.REMINDER_MAX_VALUE[ZmCalItem.REMINDER_UNIT_HOURS] = 336; ZmApptEditView.REMINDER_MAX_VALUE[ZmCalItem.REMINDER_UNIT_WEEKS] = 2; ZmApptEditView.TIMEZONE_TYPE = "TZ_TYPE"; ZmApptEditView.START_TIMEZONE = 1; ZmApptEditView.END_TIMEZONE = 2; ZmApptEditView.LOCATION_STATUS_UNDEFINED = -1; ZmApptEditView.LOCATION_STATUS_NONE = 0; ZmApptEditView.LOCATION_STATUS_VALIDATING = 1; ZmApptEditView.LOCATION_STATUS_CONFLICT = 2; ZmApptEditView.LOCATION_STATUS_RESOLVED = 3; // Public Methods ZmApptEditView.prototype.toString = function() { return "ZmApptEditView"; }; ZmApptEditView.prototype.isLocationConflictEnabled = function() { return ((this._mode != ZmCalItem.MODE_EDIT_SINGLE_INSTANCE) && !this._isForward && !this._isProposeTime && this.getRepeatType() != "NON"); } ZmApptEditView.prototype.getFreeBusyCache = function() { return this._fbCache; } ZmLocationAppt = function() { }; ZmLocationRecurrence = function() { }; ZmApptEditView.prototype.show = function() { ZmCalItemEditView.prototype.show.call(this); this._setAttendees(); if (this.parent.setLocationConflictCallback) { var appt = this.parent.getAppt(); this.initializeLocationConflictCheck(appt); } Dwt.setVisible(this._attendeeStatus, false); Dwt.setVisible(this._suggestTime, !this._isForward); Dwt.setVisible(this._suggestLocation, !this._isForward && !this._isProposeTime); this._scheduleAssistant.close(); if(!this.GROUP_CALENDAR_ENABLED) { this.setSchedulerVisibility(false); } if(!appCtxt.get(ZmSetting.GAL_ENABLED) && this._useAcAddrBubbles){ Dwt.setSize(this._attInputField[ZmCalBaseItem.LOCATION]._input, "100%"); } //bug:48189 Hide schedule tab for non-ZCS acct if (appCtxt.isOffline) { var currAcct = appCtxt.getActiveAccount(); this.setSchedulerVisibility(currAcct.isZimbraAccount && !currAcct.isMain); } this._editViewInitialized = true; if(this._expandInlineScheduler) { this._pickAttendeesInfo(ZmCalBaseItem.PERSON); this._pickAttendeesInfo(ZmCalBaseItem.LOCATION); } }; ZmApptEditView.prototype.initializeLocationConflictCheck = function(appt) { // Create a 'Location-only' clone of the appt, for use with the // resource conflict calls ZmLocationAppt.prototype = appt; ZmLocationRecurrence.prototype = appt.getRecurrence(); this._locationConflictAppt = new ZmLocationAppt(); this._locationConflictAppt._recurrence = new ZmLocationRecurrence(); this._locationConflictAppt._attendees[ZmCalBaseItem.LOCATION] = appt._attendees[ZmCalBaseItem.LOCATION]; this._locationConflictAppt._attendees[ZmCalBaseItem.PERSON] = []; this._locationConflictAppt._attendees[ZmCalBaseItem.EQUIPMENT]= []; this._processLocationCallback = this.processLocationConflicts.bind(this); this._noLocationCallback = this.setLocationStatus.bind(this, ZmApptEditView.LOCATION_STATUS_NONE); this.parent.setLocationConflictCallback(this.updatedLocationsConflictChecker.bind(this)); this._getRecurrenceSearchResponseCallback = this._getExceptionSearchResponse.bind(this, this._locationConflictAppt); this._getRecurrenceSearchErrorCallback = this._getExceptionSearchError.bind(this, this._locationConflictAppt); if (!this._pendingLocationRequest && this._scheduleAssistant && this._scheduleAssistant.isInitialized()) { // Trigger an initial location check - the appt may have been saved // with a location that has conflicts. Only do it if no pending // request and the assistant is initialized (location preferences // are loaded). If !initialized, the locationConflictChecker will // be run when preferences are loaded. this.locationConflictChecker(); } } ZmApptEditView.prototype.cancelLocationRequest = function() { if (this._pendingLocationRequest) { appCtxt.getRequestMgr().cancelRequest(this._pendingLocationRequest, null, true); this._pendingLocationRequest = null; } } ZmApptEditView.prototype.locationConflictChecker = function() { // Cancel any pending requests this.cancelLocationRequest(); if (this.isLocationConflictEnabled() && this._locationConflictAppt.hasAttendeeForType(ZmCalBaseItem.LOCATION)) { // Send a request to the server to get location conflicts // DISABLED until Bug 56464 completed - server side CreateAppointment/ModifyAppointment // SOAP API changes. When done, add code in ZmCalItemComposeController to add the // altered locations as a list of exceptions to the SOAP call. //if (this._apptExceptionList) { // this._runLocationConflictChecker(); //} else { // // Get the existing exceptions, then runLocationConflictChecker // this._doExceptionSearchRequest(); //} // Once bug 56464 completed, remove the following and enable the disabled code above this._runLocationConflictChecker(); } else { if (this._noLocationCallback) { // Restore the 'Suggest Location' line to its default this._noLocationCallback.run(); } } } ZmApptEditView.prototype.updatedLocationsConflictChecker = function(locations){ // Update locations in the appt clone, then run the conflict checker this._locationConflictAppt.setAttendees(locations.getArray(), ZmCalBaseItem.LOCATION); this.locationConflictChecker(); } ZmApptEditView.prototype.getNumLocationConflictRecurrence = function() { var numRecurrence = ZmTimeSuggestionPrefDialog.DEFAULT_NUM_RECURRENCE; if (this._scheduleAssistant) { numRecurrence = this._scheduleAssistant.getLocationConflictNumRecurrence(); } return numRecurrence; } ZmApptEditView.prototype._runLocationConflictChecker = function() { var numRecurrence = this.getNumLocationConflictRecurrence(); var locationCallback = this._controller.getCheckResourceConflicts( this._locationConflictAppt, numRecurrence, this._processLocationCallback, false); this.setLocationStatus(ZmApptEditView.LOCATION_STATUS_VALIDATING); this._pendingLocationRequest = locationCallback.run(); } ZmApptEditView.prototype._doExceptionSearchRequest = function() { var numRecurrence = this.getNumLocationConflictRecurrence(); var startDate = new Date(this._calItem.startDate); var endTime = ZmApptComposeController.getCheckResourceConflictEndTime( this._locationConflictAppt, startDate, numRecurrence); var jsonObj = {SearchRequest:{_jsns:"urn:zimbraMail"}}; var request = jsonObj.SearchRequest; request.sortBy = "dateasc"; request.limit = numRecurrence.toString(); // AjxEnv.DEFAULT_LOCALE is set to the browser's locale setting in the case // when the user's (or their COS) locale is not set. request.locale = { _content: AjxEnv.DEFAULT_LOCALE }; request.calExpandInstStart = startDate.getTime(); request.calExpandInstEnd = endTime; request.types = ZmSearch.TYPE[ZmItem.APPT]; request.query = {_content:'item:"' + this._calItem.id.toString() + '"'}; var accountName = appCtxt.multiAccounts ? appCtxt.accountList.mainAccount.name : null; var params = { jsonObj: jsonObj, asyncMode: true, callback: this._getExceptionSearchResponse.bind(this), errorCallback: this._getExceptionSearchError.bind(this), noBusyOverlay: true, accountName: accountName }; appCtxt.getAppController().sendRequest(params); } ZmApptEditView.prototype._getExceptionSearchResponse = function(result) { if (!result) { return; } var resp; var appt; try { resp = result.getResponse(); } catch (ex) { return; } // See ZmApptCache.prototype.processSearchResponse var rawAppts = resp.SearchResponse.appt; this._apptExceptionList = new ZmApptList(); this._apptExceptionList.loadFromSummaryJs(rawAppts); this._apptExceptionLookup = {}; this._locationExceptions = {} for (var i = 0; i < this._apptExceptionList.size(); i++) { appt = this._apptExceptionList.get(i); this._apptExceptionLookup[appt.startDate.getTime()] = appt; if (appt.isException) { // Found an exception, store its location info, using its start date as the key var location = appt._attendees[ZmCalBaseItem.LOCATION]; if (!location || (location.length == 0)) { location = this.getAttendeesFromString(ZmCalBaseItem.LOCATION, appt.location, false); location = location.getArray(); } this._locationExceptions[appt.startDate.getTime()] = location; } } this._enableResolveDialog = true; // Now find the conflicts this._runLocationConflictChecker(); }; ZmApptEditView.prototype._getExceptionSearchError = function(ex) { // Disallow use of the resolve dialog if can't read the exceptions this._enableResolveDialog = false; } // Callback executed when the CheckResourceConflictRequest completes. // Store the conflict instances (if any) and update the status field ZmApptEditView.prototype.processLocationConflicts = function(inst) { this._inst = inst; var len = inst ? inst.length : 0, locationStatus = ZmApptEditView.LOCATION_STATUS_NONE; for (var i = 0; i < len; i++) { if (this._inst[i].usr) { // Conflict exists for this instance if (this._locationExceptions && this._locationExceptions[this._inst[i].s]) { // Assume that an existing exception (either persisted to the DB, or set via // the current use of the resolve dialog) means that the instance conflict is resolved locationStatus = ZmApptEditView.LOCATION_STATUS_RESOLVED; } else { // No exception for the instance, using default location which has a conflict locationStatus = ZmApptEditView.LOCATION_STATUS_CONFLICT; break; } } } this.setLocationStatus(locationStatus); } ZmApptEditView.prototype.setLocationStatus = function(locationStatus, currentLocationConflict) { var className = ""; var statusMessage = ""; var linkMessage = ""; var msgVisible = false; var linkVisible = false; var statusText = ""; if (locationStatus != ZmApptEditView.LOCATION_STATUS_UNDEFINED) { this._locationStatusMode = locationStatus; } if (currentLocationConflict !== undefined) { this._locationConflict = currentLocationConflict; } // Manage the location suggestion line beneath the location field. switch (this._locationStatusMode) { case ZmApptEditView.LOCATION_STATUS_NONE: // No recurrence conflicts or nothing to check - display based on current conflict flag if (this._locationConflict) { statusMessage = AjxImg.getImageHtml("Warning_12", "display:inline-block;padding-right:4px;") + ZmMsg.locationCurrentConflicts; className = "ZmLocationStatusConflict"; msgVisible = true; } else { msgVisible = false; } break; case ZmApptEditView.LOCATION_STATUS_VALIDATING: // The conflict resource check is in progress, show a busy spinner className = "ZmLocationStatusValidating"; // Don't incorporate currentConflict flag - just show validating; It will update upon completion statusMessage = AjxImg.getImageHtml("Wait_16", "display:inline-block;padding-right:4px;") + ZmMsg.validateLocation; msgVisible = true; linkVisible = false; break; case ZmApptEditView.LOCATION_STATUS_CONFLICT: // Unresolved recurrence conflicts - show the 'Resolve Conflicts' link className = "ZmLocationStatusConflict"; statusText = this._locationConflict ? ZmMsg.locationCurrentAndRecurrenceConflicts : ZmMsg.locationRecurrenceConflicts; statusMessage = AjxImg.getImageHtml("Warning_12", "display:inline-block;padding-right:4px;") + statusText; linkMessage = ZmMsg.resolveConflicts; msgVisible = true; linkVisible = true; break; case ZmApptEditView.LOCATION_STATUS_RESOLVED: // Resolved conflicts - show the 'View Resolutions' link className = "ZmLocationStatusResolved"; statusMessage = this._locationConflict ? ZmMsg.locationRecurrenceResolvedButCurrentConflict : ZmMsg.locationRecurrenceConflictsResolved; linkMessage = ZmMsg.viewResolutions; msgVisible = true; linkVisible = true; break; default: break; } Dwt.setVisible(this._locationStatus, msgVisible); if (!this._enableResolveDialog) { // Unable to read the exeptions, prevent the use of the resolve dialog linkVisible = false; } // NOTE: Once CreateAppt/ModifyAppt SOAP API changes are completed (Bug 56464), enable // the display of the resolve links and the use of the resolve dialog // *** NOT DONE *** linkVisible = false; Dwt.setVisible(this._locationStatusAction, linkVisible); Dwt.setInnerHtml(this._locationStatus, statusMessage); Dwt.setInnerHtml(this._locationStatusAction, linkMessage); this._locationStatus.className = className; } ZmApptEditView.prototype.blur = function(useException) { if (this._activeInputField) { this._handleAttendeeField(this._activeInputField, useException); // bug: 15251 - to avoid race condition, active field will anyway be // cleared by onblur handler for input field this._activeInputField = null; } }; ZmApptEditView.prototype.cleanup = function() { ZmCalItemEditView.prototype.cleanup.call(this); if (this.GROUP_CALENDAR_ENABLED) { this._attendeesInputField.clear(); this._optAttendeesInputField.clear(); this._forwardToField.clear(); this._adjustAddrHeight(this._attendeesInputField.getInputElement()); this._adjustAddrHeight(this._optAttendeesInputField.getInputElement()); } this._attInputField[ZmCalBaseItem.LOCATION].clear(); this._locationTextMap = {}; if (this._resourcesContainer) { this.showResourceField(false); this._resourceInputField.clear(); } this._allDayCheckbox.checked = false; this._showTimeFields(true); this._isKnownLocation = false; // reset autocomplete lists if (this._acContactsList) { this._acContactsList.reset(); this._acContactsList.show(false); } if (this._acLocationsList) { this._acLocationsList.reset(); this._acLocationsList.show(false); } if (this._useAcAddrBubbles && this.GROUP_CALENDAR_ENABLED) { for (var attType in this._attInputField) { this._attInputField[attType].clear(); } } this._attendeesHashMap = {}; this._showAsValueChanged = false; Dwt.setVisible(this._attendeeStatus, false); this.setLocationStatus(ZmApptEditView.LOCATION_STATUS_NONE, false); //Default Persona this.setIdentity(); if(this._scheduleAssistant) this._scheduleAssistant.cleanup(); this._apptExceptionList = null; this._locationExceptions = null; this._alteredLocations = null; }; // Acceptable hack needed to prevent cursor from bleeding thru higher z-index'd views ZmApptEditView.prototype.enableInputs = function(bEnableInputs) { ZmCalItemEditView.prototype.enableInputs.call(this, bEnableInputs); if (this.GROUP_CALENDAR_ENABLED) { var bEnableAttendees = bEnableInputs; if (appCtxt.isOffline && bEnableAttendees && this._calItem && this._calItem.getFolder().getAccount().isMain) { bEnableAttendees = false; } this._attendeesInputField.setEnabled(bEnableAttendees); this._optAttendeesInputField.setEnabled(bEnableAttendees); this._locationInputField.setEnabled(bEnableAttendees); //this was a small bug - the text field of that was not disabled! this.enablePickers(bEnableAttendees); }else { //bug 57083 - disabling group calendar should disable attendee pickers this.enablePickers(false); } this._attInputField[ZmCalBaseItem.LOCATION].setEnabled(bEnableInputs); }; ZmApptEditView.prototype.isOrganizer = function() { return Boolean(this._isOrganizer); }; ZmApptEditView.prototype.enablePickers = function(bEnablePicker) { for (var t = 0; t < this._attTypes.length; t++) { var type = this._attTypes[t]; if(this._pickerButton[type]) this._pickerButton[type].setEnabled(bEnablePicker); } if(this._pickerButton[ZmCalBaseItem.OPTIONAL_PERSON]) this._pickerButton[ZmCalBaseItem.OPTIONAL_PERSON].setEnabled(bEnablePicker); }; ZmApptEditView.prototype.isValid = function() { var errorMsg = []; // check for required subject var subj = AjxStringUtil.trim(this._subjectField.getValue()); //bug: 49990 subject can be empty while proposing new time if ((subj && subj.length) || this._isProposeTime) { var allDay = this._allDayCheckbox.checked; if (!ZmTimeInput.validStartEnd(this._startDateField, this._endDateField, (allDay ? null : this._startTimeSelect), (allDay ? null : this._endTimeSelect))) { errorMsg.push(ZmMsg.errorInvalidDates); } } else { errorMsg.push(ZmMsg.errorMissingSubject); } if (this._reminderSelectInput) { var reminderString = this._reminderSelectInput.getValue(); var reminderInfo = ZmCalendarApp.parseReminderString(reminderString); if (reminderInfo.reminderValue > ZmApptEditView.REMINDER_MAX_VALUE[reminderInfo.reminderUnits]) { errorMsg.push(ZmMsg.errorInvalidReminderValue); } } if (errorMsg.length > 0) { throw errorMsg.join("<br>"); } return true; }; // called by schedule tab view when user changes start date field ZmApptEditView.prototype.updateDateField = function(newStartDate, newEndDate) { var oldTimeInfo = this._getDateTimeText(); this._startDateField.value = newStartDate; this._endDateField.value = newEndDate; this._dateTimeChangeForLocationConflict(oldTimeInfo); }; ZmApptEditView.prototype.updateAllDayField = function(isAllDay) { var oldAllDay = this._allDayCheckbox.checked; this._allDayCheckbox.checked = isAllDay; this._showTimeFields(!isAllDay); if (oldAllDay != isAllDay) { var durationInfo = this.getDurationInfo(); this._locationConflictAppt.startDate = new Date(durationInfo.startTime); this._locationConflictAppt.endDate = new Date(durationInfo.endTime); this._locationConflictAppt.allDayEvent = isAllDay ? "1" : "0"; this.locationConflictChecker(); } }; ZmApptEditView.prototype.toggleAllDayField = function() { this.updateAllDayField(!this._allDayCheckbox.checked); }; ZmApptEditView.prototype.updateShowAsField = function(isAllDay) { if(!this._showAsValueChanged) { if(isAllDay) { this._showAsSelect.setSelectedValue("F"); } else { this._showAsSelect.setSelectedValue("B"); } } }; ZmApptEditView.prototype.setShowAsFlag = function(flag) { this._showAsValueChanged = flag; }; ZmApptEditView.prototype.updateTimeField = function(dateInfo) { this._startTimeSelect.setValue(dateInfo.startTimeStr); this._endTimeSelect.setValue(dateInfo.endTimeStr); }; ZmApptEditView.prototype.setDate = function(startDate, endDate, ignoreTimeUpdate) { var oldTimeInfo = this._getDateTimeText(); this._startDateField.value = AjxDateUtil.simpleComputeDateStr(startDate); this._endDateField.value = AjxDateUtil.simpleComputeDateStr(endDate); if(!ignoreTimeUpdate) { this._startTimeSelect.set(startDate); this._endTimeSelect.set(endDate); } if(this._schedulerOpened) { this._scheduleView.handleTimeChange(); } appCtxt.notifyZimlets("onEditAppt_updateTime", [this, {startDate:startDate, endDate:endDate}]);//notify Zimlets this._dateTimeChangeForLocationConflict(oldTimeInfo); }; // ?? Not used - and not setting this._dateInfo. If used, // need to check change in timezone in caller and then update location conflict ZmApptEditView.prototype.updateTimezone = function(dateInfo) { this._tzoneSelectStart.setSelectedValue(dateInfo.timezone); this._tzoneSelectEnd.setSelectedValue(dateInfo.timezone); this.handleTimezoneOverflow(); }; ZmApptEditView.prototype.updateLocation = function(location, locationStr) { this._updateAttendeeFieldValues(ZmCalBaseItem.LOCATION, [location]); locationStr = locationStr || location.getAttendeeText(ZmCalBaseItem.LOCATION); this.setApptLocation(locationStr); }; // Private / protected methods ZmApptEditView.prototype._initTzSelect = function() { var options = AjxTimezone.getAbbreviatedZoneChoices(); if (options.length != this._tzCount) { this._tzCount = options.length; this._tzoneSelectStart.clearOptions(); this._tzoneSelectEnd.clearOptions(); for (var i = 0; i < options.length; i++) { this._tzoneSelectStart.addOption(options[i]); this._tzoneSelectEnd.addOption(options[i]); } } }; ZmApptEditView.prototype._addTabGroupMembers = function(tabGroup) { tabGroup.addMember(this._subjectField.getInputElement()); if(this.GROUP_CALENDAR_ENABLED) { tabGroup.addMember(this._attInputField[ZmCalBaseItem.PERSON].getInputElement()); tabGroup.addMember(this._attInputField[ZmCalBaseItem.OPTIONAL_PERSON].getInputElement()); } tabGroup.addMember(this._attInputField[ZmCalBaseItem.LOCATION].getInputElement()); if(this.GROUP_CALENDAR_ENABLED && appCtxt.get(ZmSetting.GAL_ENABLED)) { tabGroup.addMember(this._attInputField[ZmCalBaseItem.EQUIPMENT].getInputElement()); } tabGroup.addMember(this._startDateField); tabGroup.addMember(this._startTimeSelect.getInputField()); tabGroup.addMember(this._endDateField); tabGroup.addMember(this._endTimeSelect.getInputField()); tabGroup.addMember(this._allDayCheckbox); tabGroup.addMember(this._showAsSelect); tabGroup.addMember(this._folderSelect); if(this._repeatSelect) tabGroup.addMember(this._repeatSelect); tabGroup.addMember(this._reminderSelectInput); var bodyFieldId = this._notesHtmlEditor.getBodyFieldId(); tabGroup.addMember(document.getElementById(bodyFieldId)); }; ZmApptEditView.prototype._finishReset = function() { ZmCalItemEditView.prototype._finishReset.call(this); this._apptFormValue = {}; this._apptFormValue[ZmApptEditView.CHANGES_SIGNIFICANT] = this._getFormValue(ZmApptEditView.CHANGES_SIGNIFICANT); this._apptFormValue[ZmApptEditView.CHANGES_INSIGNIFICANT] = this._getFormValue(ZmApptEditView.CHANGES_INSIGNIFICANT); this._apptFormValue[ZmApptEditView.CHANGES_LOCAL] = this._getFormValue(ZmApptEditView.CHANGES_LOCAL); this._apptFormValue[ZmApptEditView.CHANGES_TIME_RECURRENCE] = this._getFormValue(ZmApptEditView.CHANGES_TIME_RECURRENCE); var newMode = (this._mode == ZmCalItem.MODE_NEW); // save the original form data in its initialized state this._origFormValueMinusAttendees = newMode ? "" : this._formValue(true); if (this._hasReminderSupport) { this._origFormValueMinusReminder = newMode ? "" : this._formValue(false, true); this._origReminderValue = this._reminderSelectInput.getValue(); } this._keyInfoValue = newMode ? "" : this._keyValue(); }; /** * Checks if location/time/recurrence only are changed. * * @return {Boolean} <code>true</code> if location/time/recurrence only are changed */ ZmApptEditView.prototype.isKeyInfoChanged = function() { var formValue = this._keyInfoValue; return (this._keyValue() != formValue); }; ZmApptEditView.prototype._getClone = function() { if (!this._calItem) { return null; } return ZmAppt.quickClone(this._calItem); }; ZmApptEditView.prototype.getDurationInfo = function() { var startDate = AjxDateUtil.simpleParseDateStr(this._startDateField.value); var endDate = AjxDateUtil.simpleParseDateStr(this._endDateField.value); if (!this._allDayCheckbox.checked) { startDate = this._startTimeSelect.getValue(startDate); endDate = this._endTimeSelect.getValue(endDate); } var durationInfo = {}; durationInfo.startTime = startDate.getTime(); durationInfo.endTime = endDate.getTime(); durationInfo.duration = durationInfo.endTime - durationInfo.startTime; return durationInfo; }; ZmApptEditView.prototype.getDuration = function() { var startDate = AjxDateUtil.simpleParseDateStr(this._startDateField.value); var endDate = AjxDateUtil.simpleParseDateStr(this._endDateField.value); var duration = AjxDateUtil.MSEC_PER_DAY; if (!this._allDayCheckbox.checked) { startDate = this._startTimeSelect.getValue(startDate); endDate = this._endTimeSelect.getValue(endDate); duration = endDate.getTime() - startDate.getTime(); } return duration; }; ZmApptEditView.prototype._populateForSave = function(calItem) { if (!calItem) { return null; } ZmCalItemEditView.prototype._populateForSave.call(this, calItem); //Handle Persona's var identity = this.getIdentity(); if(identity){ calItem.identity = identity; calItem.sentBy = (identity && identity.getField(ZmIdentity.SEND_FROM_ADDRESS)); } calItem.freeBusy = this._showAsSelect.getValue(); calItem.privacy = this._privateCheckbox.checked ? ZmApptEditView.PRIVACY_OPTION_PRIVATE : ZmApptEditView.PRIVACY_OPTION_PUBLIC; // set the start date by aggregating start date/time fields var startDate = AjxDateUtil.simpleParseDateStr(this._startDateField.value); var endDate = AjxDateUtil.simpleParseDateStr(this._endDateField.value); if (this._allDayCheckbox.checked) { calItem.setAllDayEvent(true); if(AjxDateUtil.isDayShifted(startDate)) { AjxDateUtil.rollToNextDay(startDate); AjxDateUtil.rollToNextDay(endDate); } } else { calItem.setAllDayEvent(false); startDate = this._startTimeSelect.getValue(startDate); endDate = this._endTimeSelect.getValue(endDate); } calItem.setStartDate(startDate, true); calItem.setEndDate(endDate, true); if (Dwt.getVisibility(this._tzoneSelectStartElement)) { calItem.timezone = this._tzoneSelectStart.getValue(); if (Dwt.getVisibility(this._tzoneSelectEndElement)) { calItem.setEndTimezone(this._tzoneSelectEnd.getValue()); }else { calItem.setEndTimezone(this._tzoneSelectStart.getValue()); } } // set attendees for (var t = 0; t < this._attTypes.length; t++) { var type = this._attTypes[t]; calItem.setAttendees(this._attendees[type].getArray(), type); } var calLoc = AjxStringUtil.trim(this._attInputField[ZmCalBaseItem.LOCATION].getValue()); //bug 44858, trimming ';' so that ;; does not appears in outlook, calItem.location = AjxStringUtil.trim(calLoc, false, ';'); // set any recurrence rules LAST this._getRecurrence(calItem); calItem.isForward = this._isForward; calItem.isProposeTime = this._isProposeTime; if(this._isForward) { var addrs = this._collectForwardAddrs(); var a = {}; if (addrs[AjxEmailAddress.TO] && addrs[AjxEmailAddress.TO].good) { a[AjxEmailAddress.TO] = addrs[AjxEmailAddress.TO].good.getArray(); } calItem.setForwardAddress(a[AjxEmailAddress.TO]); } // Only used for the save calItem.alteredLocations = this._alteredLocations; return calItem; }; ZmApptEditView.prototype.getRsvp = function() { return this.GROUP_CALENDAR_ENABLED ? this._controller.getRequestResponses() : false; }; ZmApptEditView.prototype.updateToolbarOps = function(){ this._controller.updateToolbarOps((this.isAttendeesEmpty() || !this.isOrganizer()) ? ZmCalItemComposeController.APPT_MODE : ZmCalItemComposeController.MEETING_MODE, this._calItem); }; ZmApptEditView.prototype.isAttendeesEmpty = function() { if(!this.GROUP_CALENDAR_ENABLED) return true; var locations = this._attendees[ZmCalBaseItem.LOCATION]; //non-resource location labels also contributes to empty attendee var isLocationResource =(locations && locations.size() > 0); var isAttendeesNotEmpty = AjxStringUtil.trim(this._attendeesInputField.getValue()) || AjxStringUtil.trim(this._optAttendeesInputField.getValue()) || (this._resourceInputField ? AjxStringUtil.trim(this._resourceInputField.getValue()) : "") || isLocationResource; return !isAttendeesNotEmpty; }; ZmApptEditView.prototype._populateForEdit = function(calItem, mode) { ZmCalItemEditView.prototype._populateForEdit.call(this, calItem, mode); var enableTimeSelection = !this._isForward; var enableApptDetails = !this._isForward && !this._isProposeTime; this._showAsSelect.setSelectedValue(calItem.freeBusy); this._showAsSelect.setEnabled(enableApptDetails); // reset the date/time values based on current time var sd = new Date(calItem.startDate.getTime()); var ed = new Date(calItem.endDate.getTime()); var isNew = (mode == ZmCalItem.MODE_NEW || mode == ZmCalItem.MODE_NEW_FROM_QUICKADD); var isAllDayAppt = calItem.isAllDayEvent(); if (isAllDayAppt) { this._allDayCheckbox.checked = true; this._showTimeFields(false); this.updateShowAsField(true); this._showAsSelect.setSelectedValue(calItem.freeBusy); this._showAsSelect.setEnabled(enableApptDetails); // set time anyway to current time and default duration (in case user changes mind) var now = AjxDateUtil.roundTimeMins(new Date(), 30); this._startTimeSelect.set(now); now.setTime(now.getTime() + ZmCalViewController.DEFAULT_APPOINTMENT_DURATION); this._endTimeSelect.set(now); // bug 9969: HACK - remove the all day durtion for display if (!isNew && !calItem.draftUpdated && ed.getHours() == 0 && ed.getMinutes() == 0 && ed.getSeconds() == 0 && sd.getTime() != ed.getTime()) { ed.setHours(-12); } } else { this._showTimeFields(true); this._startTimeSelect.set(calItem.startDate); this._endTimeSelect.set(calItem.endDate); } this._startDateField.value = AjxDateUtil.simpleComputeDateStr(sd); this._endDateField.value = AjxDateUtil.simpleComputeDateStr(ed); this._initTzSelect(); this._resetTimezoneSelect(calItem, isAllDayAppt); //need to capture initial time set while composing/editing appt ZmApptViewHelper.getDateInfo(this, this._dateInfo); this._startTimeSelect.setEnabled(enableTimeSelection); this._endTimeSelect.setEnabled(enableTimeSelection); this._startDateButton.setEnabled(enableTimeSelection); this._endDateButton.setEnabled(enableTimeSelection); this._fwdApptOrigAttendees = []; //editing an appt should exclude the original appt time for FB calculation this._fbExcludeInfo = {}; var showScheduleView = false; // attendees var attendees = calItem.getAttendees(ZmCalBaseItem.PERSON); if (attendees && attendees.length) { if (this.GROUP_CALENDAR_ENABLED) { var people = calItem.getAttendees(ZmCalBaseItem.PERSON); var reqAttendees = ZmApptViewHelper.filterAttendeesByRole(people, ZmCalItem.ROLE_REQUIRED); this._setAddresses(this._attendeesInputField, reqAttendees, ZmCalBaseItem.PERSON); var optAttendees = ZmApptViewHelper.filterAttendeesByRole(people, ZmCalItem.ROLE_OPTIONAL); this._setAddresses(this._optAttendeesInputField, optAttendees, ZmCalBaseItem.PERSON); if (optAttendees.length) { this._toggleOptionalAttendees(true); } } if(this._isForward) { this._attInputField[ZmCalBaseItem.FORWARD] = this._forwardToField; } this._attendees[ZmCalBaseItem.PERSON] = AjxVector.fromArray(attendees); for(var a=0;a<attendees.length;a++){ this._attendeesHashMap[attendees[a].getEmail()+"-"+ZmCalBaseItem.PERSON]=attendees[a]; if(!isNew) this.addFreeBusyExcludeInfo(attendees[a].getEmail(), calItem.startDate.getTime(), calItem.endDate.getTime()); } this._attInputField[ZmCalBaseItem.PERSON] = this._attendeesInputField; this._fwdApptOrigAttendees = []; showScheduleView = true; } else { if (this.GROUP_CALENDAR_ENABLED) { this._attendeesInputField.clear(); this._optAttendeesInputField.clear(); } this._attendees[ZmCalBaseItem.PERSON] = new AjxVector(); } // set the location attendee(s) var locations = calItem.getAttendees(ZmCalBaseItem.LOCATION); if (!locations || !locations.length) { locations = this.getAttendeesFromString(ZmCalBaseItem.LOCATION, calItem.getLocation(), false); if (locations) { locations = locations.getArray(); } } if (locations && locations.length) { this.updateAttendeesCache(ZmCalBaseItem.LOCATION, locations); this._attendees[ZmCalBaseItem.LOCATION] = AjxVector.fromArray(locations); var locStr = ZmApptViewHelper.getAttendeesString(locations, ZmCalBaseItem.LOCATION); this._setAddresses(this._attInputField[ZmCalBaseItem.LOCATION], locStr); showScheduleView = true; }else{ // set the location *label* this._attInputField[ZmCalBaseItem.LOCATION].setValue(calItem.getLocation()); } // set the equipment attendee(s) var equipment = calItem.getAttendees(ZmCalBaseItem.EQUIPMENT); if (equipment && equipment.length) { this._toggleResourcesField(true); this._attendees[ZmCalBaseItem.EQUIPMENT] = AjxVector.fromArray(equipment); this.updateAttendeesCache(ZmCalBaseItem.EQUIPMENT, equipment); var equipStr = ZmApptViewHelper.getAttendeesString(equipment, ZmCalBaseItem.EQUIPMENT); this._setAddresses(this._attInputField[ZmCalBaseItem.EQUIPMENT], equipStr); showScheduleView = true; } // privacy var isRemote = calItem.isShared(); var cal = isRemote ? appCtxt.getById(calItem.folderId) : null; var isPrivacyEnabled = ((!isRemote || (cal && cal.hasPrivateAccess())) && enableApptDetails); var defaultPrivacyOption = (appCtxt.get(ZmSetting.CAL_APPT_VISIBILITY) == ZmSetting.CAL_VISIBILITY_PRIV); this._privateCheckbox.checked = (calItem.privacy == ZmApptEditView.PRIVACY_OPTION_PRIVATE); this._privateCheckbox.disabled = !isPrivacyEnabled; if (this.GROUP_CALENDAR_ENABLED) { this._controller.setRequestResponses((attendees && attendees.length) ? calItem.shouldRsvp() : true); this._isOrganizer = calItem.isOrganizer(); //this._attInputField[ZmCalBaseItem.PERSON].setEnabled(calItem.isOrganizer() || this._isForward); //todo: disable notification for attendee if(this._organizerData) { this._organizerData.innerHTML = calItem.getOrganizer() || ""; } this._calItemOrganizer = calItem.getOrganizer() || ""; if(!isNew) this.addFreeBusyExcludeInfo(this.getOrganizerEmail(), calItem.startDate.getTime(), calItem.endDate.getTime()); //enable forward field/picker if its not propose time view this._setAddresses(this._forwardToField, this._isProposeTime ? calItem.getOrganizer() : ""); this._forwardToField.setEnabled(!this._isProposeTime); this._forwardPicker.setEnabled(!this._isProposeTime); for (var t = 0; t < this._attTypes.length; t++) { var type = this._attTypes[t]; if(this._pickerButton[type]) this._pickerButton[type].setEnabled(enableApptDetails); } if(this._pickerButton[ZmCalBaseItem.OPTIONAL_PERSON]) this._pickerButton[ZmCalBaseItem.OPTIONAL_PERSON].setEnabled(enableApptDetails); } this._folderSelect.setEnabled(enableApptDetails); if (this._reminderSelect) { this._reminderSelect.setEnabled(enableTimeSelection); } this._allDayCheckbox.disabled = !enableTimeSelection; if(calItem.isAcceptingProposal) this._isDirty = true; //Persona's [ Should select Persona as combination of both DisplayName, FromAddress ] if(calItem.identity){ this.setIdentity(calItem.identity); }else{ var sentBy = calItem.sentBy; sentBy = sentBy || (calItem.organizer != calItem.getFolder().getOwner() ? calItem.organizer : null); if(sentBy){ var ic = appCtxt.getIdentityCollection(); if (ic) { this.setIdentity(ic.getIdentityBySendAddress(sentBy)); } } } this.setApptMessage(this._getMeetingStatusMsg(calItem)); this.updateToolbarOps(); if(this._isProposeTime) { this._controller.setRequestResponses(false); } else if (this._isForward) { this._controller.setRequestResponses(calItem.rsvp); this._controller.setRequestResponsesEnabled(false); } else { this._controller.setRequestResponses(calItem && calItem.hasAttendees() ? calItem.shouldRsvp() : true); } showScheduleView = showScheduleView && !this._isForward; if(this._controller.isSave() && showScheduleView){ this._toggleInlineScheduler(true); }else{ this._schedulerOpened = null; this._closeScheduler(); } this._expandInlineScheduler = (showScheduleView && !isNew); }; ZmApptEditView.prototype.getFreeBusyExcludeInfo = function(emailAddr){ return this._fbExcludeInfo ? this._fbExcludeInfo[emailAddr] : null; }; ZmApptEditView.prototype.excludeLocationFBSlots = function(locations, startTime, endTime){ for(var i=0; i < locations.length; i++){ var location = locations[i]; if(!location) continue; this.addFreeBusyExcludeInfo(location.getEmail(), startTime, endTime); } }; ZmApptEditView.prototype.addFreeBusyExcludeInfo = function(emailAddr, startTime, endTime){ if(!this._fbExcludeInfo) this._fbExcludeInfo = {}; // DISABLE client side exclude info usage. Now using the GetFreeBusyInfo // call with ExcludeId, where the server performs the exclusion of the // current appt. // //this._fbExcludeInfo[emailAddr] = { // s: startTime, // e: endTime //}; }; ZmApptEditView.prototype._getMeetingStatusMsg = function(calItem){ var statusMsg = null; if(!this.isAttendeesEmpty() && calItem.isDraft){ if(calItem.inviteNeverSent){ statusMsg = ZmMsg.inviteNotSent; }else{ statusMsg = ZmMsg.updatedInviteNotSent; } } return statusMsg; }; ZmApptEditView.prototype.setApptMessage = function(msg, icon){ if(msg){ Dwt.setVisible(this._inviteMsgContainer, true); this._inviteMsg.innerHTML = msg; }else{ Dwt.setVisible(this._inviteMsgContainer, false); } }; ZmApptEditView.prototype.getCalItemOrganizer = function() { var folderId = this._folderSelect.getValue(); var organizer = new ZmContact(null); organizer.initFromEmail(this._calItemOrganizer, true); return organizer; }; ZmApptEditView.prototype._createHTML = function() { // cache these Id's since we use them more than once this._allDayCheckboxId = this._htmlElId + "_allDayCheckbox"; this._repeatDescId = this._htmlElId + "_repeatDesc"; this._startTimeAtLblId = this._htmlElId + "_startTimeAtLbl"; this._endTimeAtLblId = this._htmlElId + "_endTimeAtLbl"; this._isAppt = true; var subs = { id: this._htmlElId, height: (this.parent.getSize().y - 30), currDate: (AjxDateUtil.simpleComputeDateStr(new Date())), isGalEnabled: appCtxt.get(ZmSetting.GAL_ENABLED), isAppt: true, isGroupCalEnabled: this.GROUP_CALENDAR_ENABLED }; this.getHtmlElement().innerHTML = AjxTemplate.expand("calendar.Appointment#ComposeView", subs); }; ZmApptEditView.prototype._createWidgets = function(width) { ZmCalItemEditView.prototype._createWidgets.call(this, width); this._attInputField = {}; if (this.GROUP_CALENDAR_ENABLED) { var params = { bubbleRemovedCallback: new AjxCallback(this, this._handleRemovedAttendees) }; this._attendeesInputField = this._createInputField("_person", ZmCalBaseItem.PERSON, { bubbleRemovedCallback: new AjxCallback(this, this._handleRemovedAttendees, [ZmCalBaseItem.PERSON]) }); this._optAttendeesInputField = this._createInputField("_optional", ZmCalBaseItem.OPTIONAL_PERSON, { bubbleRemovedCallback: new AjxCallback(this, this._handleRemovedAttendees, [ZmCalBaseItem.OPTIONAL_PERSON]) }); //add Resources Field if (appCtxt.get(ZmSetting.GAL_ENABLED)) { this._resourceInputField = this._createInputField("_resourcesData", ZmCalBaseItem.EQUIPMENT, {strictMode:false}); } } // add location input field this._locationInputField = this._createInputField("_location", ZmCalBaseItem.LOCATION, {strictMode:false}); this._mainTableId = this._htmlElId + "_table"; this._mainTable = document.getElementById(this._mainTableId); var edvId = AjxCore.assignId(this); this._schButtonId = this._htmlElId + "_scheduleButton"; this._showOptionalId = this._htmlElId + "_show_optional"; this._showResourcesId = this._htmlElId + "_show_resources"; this._showOptional = document.getElementById(this._showOptionalId); this._showResources = document.getElementById(this._showResourcesId); this._schButton = document.getElementById(this._schButtonId); this._schButton._editViewId = edvId; this._schImage = document.getElementById(this._htmlElId + "_scheduleImage"); this._schImage._editViewId = edvId; Dwt.setHandler(this._schButton, DwtEvent.ONCLICK, ZmCalItemEditView._onClick); Dwt.setHandler(this._schImage, DwtEvent.ONCLICK, ZmCalItemEditView._onClick); this._resourcesContainer = document.getElementById(this._htmlElId + "_resourcesContainer"); this._resourcesData = document.getElementById(this._htmlElId + "_resourcesData"); this._schedulerContainer = document.getElementById(this._htmlElId + "_scheduler"); this._suggestions = document.getElementById(this._htmlElId + "_suggestions"); Dwt.setVisible(this._suggestions, false); this._attendeeStatusId = this._htmlElId + "_attendee_status"; this._attendeeStatus = document.getElementById(this._attendeeStatusId); Dwt.setVisible(this._attendeeStatus, false); this._suggestTimeId = this._htmlElId + "_suggest_time"; this._suggestTime = document.getElementById(this._suggestTimeId); Dwt.setVisible(this._suggestTime, !this._isForward); this._suggestLocationId = this._htmlElId + "_suggest_location"; this._suggestLocation = document.getElementById(this._suggestLocationId); Dwt.setVisible(this._suggestLocation, !this._isForward && !this._isProposeTime); this._locationStatusId = this._htmlElId + "_location_status"; this._locationStatus = document.getElementById(this._locationStatusId); Dwt.setVisible(this._locationStatus, false); this._locationStatusMode = ZmApptEditView.LOCATION_STATUS_NONE; this._locationStatusActionId = this._htmlElId + "_location_status_action"; this._locationStatusAction = document.getElementById(this._locationStatusActionId); Dwt.setVisible(this._locationStatusAction, false); this._notesContainerId = this._htmlElId + "_notes_container"; this._notesContainer = document.getElementById(this._notesContainerId); this._schedulerOptions = document.getElementById(this._htmlElId + "_scheduler_option"); // show-as DwtSelect this._showAsSelect = new DwtSelect({parent:this, parentElement: (this._htmlElId + "_showAsSelect")}); for (var i = 0; i < ZmApptViewHelper.SHOWAS_OPTIONS.length; i++) { var option = ZmApptViewHelper.SHOWAS_OPTIONS[i]; this._showAsSelect.addOption(option.label, option.selected, option.value, "showAs" + option.value); } this._showAsSelect.addChangeListener(new AjxListener(this, this.setShowAsFlag, [true])); this._folderSelect.addChangeListener(new AjxListener(this, this._folderListener)); this._privateCheckbox = document.getElementById(this._htmlElId + "_privateCheckbox"); // time ZmTimeSelect var timeSelectListener = new AjxListener(this, this._timeChangeListener); this._startTimeSelect = new ZmTimeInput(this, ZmTimeInput.START); this._startTimeSelect.reparentHtmlElement(this._htmlElId + "_startTimeSelect"); this._startTimeSelect.addChangeListener(timeSelectListener); this._endTimeSelect = new ZmTimeInput(this, ZmTimeInput.END); this._endTimeSelect.reparentHtmlElement(this._htmlElId + "_endTimeSelect"); this._endTimeSelect.addChangeListener(timeSelectListener); if (this.GROUP_CALENDAR_ENABLED) { // create without saving in this._attInputField (will overwrite attendee input) this._forwardToField = this._createInputField("_to_control",ZmCalBaseItem.FORWARD); } // timezone DwtSelect var timezoneListener = new AjxListener(this, this._timezoneListener); this._tzoneSelectStartElement = document.getElementById(this._htmlElId + "_tzoneSelectStart"); this._tzoneSelectStart = new DwtSelect({parent:this, parentElement:this._tzoneSelectStartElement, layout:DwtMenu.LAYOUT_SCROLL, maxRows:7}); this._tzoneSelectStart.addChangeListener(timezoneListener); this._tzoneSelectStart.setData(ZmApptEditView.TIMEZONE_TYPE, ZmApptEditView.START_TIMEZONE); this._tzoneSelectStart.dynamicButtonWidth(); this._tzoneSelectEndElement = document.getElementById(this._htmlElId + "_tzoneSelectEnd"); this._tzoneSelectEnd = new DwtSelect({parent:this, parentElement:this._tzoneSelectEndElement, layout:DwtMenu.LAYOUT_SCROLL, maxRows:7}); this._tzoneSelectEnd.addChangeListener(timezoneListener); this._tzoneSelectEnd.setData(ZmApptEditView.TIMEZONE_TYPE, ZmApptEditView.END_TIMEZONE); this._tzoneSelectEnd.dynamicButtonWidth(); // NOTE: tzone select is initialized later // init auto-complete widget if contacts app enabled if (appCtxt.get(ZmSetting.CONTACTS_ENABLED)) { this._initAutocomplete(); } this._organizerOptions = document.getElementById(this._htmlElId + "_organizer_options"); this._organizerData = document.getElementById(this._htmlElId + "_organizer"); this._optionalAttendeesContainer = document.getElementById(this._htmlElId + "_optionalContainer"); this._maxPickerWidth = 0; var isPickerEnabled = (appCtxt.get(ZmSetting.CONTACTS_ENABLED) || appCtxt.get(ZmSetting.GAL_ENABLED) || appCtxt.multiAccounts); if (isPickerEnabled) { this._createContactPicker(this._htmlElId + "_picker", new AjxListener(this, this._addressButtonListener), ZmCalBaseItem.PERSON, true); this._createContactPicker(this._htmlElId + "_req_att_picker", new AjxListener(this, this._attendeesButtonListener, ZmCalBaseItem.PERSON), ZmCalBaseItem.PERSON); this._createContactPicker(this._htmlElId + "_opt_att_picker", new AjxListener(this, this._attendeesButtonListener, ZmCalBaseItem.OPTIONAL_PERSON), ZmCalBaseItem.OPTIONAL_PERSON); this._createContactPicker(this._htmlElId + "_loc_picker", new AjxListener(this, this._locationButtonListener, ZmCalBaseItem.LOCATION), ZmCalBaseItem.LOCATION); this._createContactPicker(this._htmlElId + "_res_btn", new AjxListener(this, this._locationButtonListener, ZmCalBaseItem.EQUIPMENT), ZmCalBaseItem.EQUIPMENT); } //Personas //TODO: Remove size check once we add identityCollection change listener. if (appCtxt.get(ZmSetting.IDENTITIES_ENABLED) && !appCtxt.multiAccounts){ var identityOptions = this._getIdentityOptions(); this.identitySelect = new DwtSelect({parent:this, options:identityOptions, parentElement: (this._htmlElId + "_identity")}); this.identitySelect.setToolTipContent(ZmMsg.chooseIdentity); } this._setIdentityVisible(); this.updateToolbarOps(); if (this._resourcesContainer) { Dwt.setVisible(this._resourcesContainer, false); } if(this.GROUP_CALENDAR_ENABLED) { Dwt.setVisible(this._optionalAttendeesContainer, false); Dwt.setVisible(this._optAttendeesInputField.getInputElement(), false); if(this._resourceInputField) { Dwt.setVisible(this._resourceInputField.getInputElement(), false); } } this._inviteMsgContainer = document.getElementById(this._htmlElId + "_invitemsg_container"); this._inviteMsg = document.getElementById(this._htmlElId + "_invitemsg"); }; ZmApptEditView.prototype._createInputField = function(idTag, attType, params) { params = params || {}; var height = AjxEnv.isSafari && !AjxEnv.isSafariNightly ? "52px;" : "21px"; var overflow = AjxEnv.isSafari && !AjxEnv.isSafariNightly ? false : true; var inputId = this.parent._htmlElId + idTag + "_input"; var cellId = this._htmlElId + idTag; var input; if (this._useAcAddrBubbles) { var aifParams = { autocompleteListView: this._acAddrSelectList, inputId: inputId, bubbleRemovedCallback: params.bubbleRemovedCallback, type: attType, strictMode: params.strictMode } var input = this._attInputField[attType] = new ZmAddressInputField(aifParams); input.reparentHtmlElement(cellId); } else { var params = { parent: this, parentElement: cellId, inputId: inputId }; if (idTag == '_person' || idTag == '_optional' || idTag == '_to_control') { params.forceMultiRow = true; } input = this._attInputField[attType] = new DwtInputField(params); } var inputEl = input.getInputElement(); Dwt.setSize(inputEl, "100%", height); inputEl._attType = attType; return input; }; ZmApptEditView.prototype._createContactPicker = function(pickerId, listener, addrType, isForwardPicker) { var pickerEl = document.getElementById(pickerId); if (pickerEl) { var buttonId = Dwt.getNextId(); var button = new DwtButton({parent:this, id:buttonId, className: "ZButton ZPicker"}); if(isForwardPicker) { this._forwardPicker = button; }else { this._pickerButton[addrType] = button; } button.setText(pickerEl.innerHTML); button.replaceElement(pickerEl); button.addSelectionListener(listener); button.addrType = addrType; var btnWidth = button.getSize().x; if(btnWidth > this._maxPickerWidth) this._maxPickerWidth = btnWidth; } }; ZmApptEditView.prototype._onSuggestionClose = function() { // Make the trigger links visible and resize now that the suggestion panel is hidden Dwt.setVisible(this._suggestTime, !this._isForward); Dwt.setVisible(this._suggestLocation, !this._isForward && !this._isProposeTime); this.resize(); } ZmApptEditView.prototype._showTimeSuggestions = function() { // Display the time suggestion panel. Dwt.setVisible(this._suggestions, true); Dwt.setVisible(this._suggestTime, false); Dwt.setVisible(this._suggestLocation, !this._isProposeTime); this._scheduleAssistant.show(true); // Resize horizontally this._resizeNotes(); this._scheduleAssistant.suggestAction(true, false); }; ZmApptEditView.prototype._showLocationSuggestions = function() { // Display the location suggestion panel Dwt.setVisible(this._suggestions, true); Dwt.setVisible(this._suggestLocation, false); Dwt.setVisible(this._suggestTime, true); this._scheduleAssistant.show(false); // Resize horizontally this._resizeNotes(); this._scheduleAssistant.suggestAction(true, false); }; ZmApptEditView.prototype._showLocationStatusAction = function() { if (!this._resolveLocationDialog) { this._resolveLocationDialog = new ZmResolveLocationConflictDialog( this._controller, this, this._locationConflictOKCallback.bind(this), this._scheduleAssistant); } else { this._resolveLocationDialog.cleanup(); } this._resolveLocationDialog.popup(this._calItem, this._inst, this._locationExceptions); }; // Invoked from 'OK' button of location conflict resolve dialog ZmApptEditView.prototype._locationConflictOKCallback = function(locationExceptions, alteredLocations) { this._locationExceptions = locationExceptions; this._alteredLocations = alteredLocations; this.locationConflictChecker(); }; ZmApptEditView.prototype._toggleOptionalAttendees = function(forceShow) { this._optionalAttendeesShown = ! this._optionalAttendeesShown || forceShow; this._showOptional.innerHTML = this._optionalAttendeesShown ? ZmMsg.hideOptional : ZmMsg.showOptional; Dwt.setVisible(this._optionalAttendeesContainer, Boolean(this._optionalAttendeesShown)) var inputEl = this._attInputField[ZmCalBaseItem.OPTIONAL_PERSON].getInputElement(); Dwt.setVisible(inputEl, Boolean(this._optionalAttendeesShown)); }; ZmApptEditView.prototype._toggleResourcesField = function(forceShow) { this._resourcesShown = ! this._resourcesShown || forceShow; this.showResourceField(this._resourcesShown); var inputEl = this._attInputField[ZmCalBaseItem.EQUIPMENT].getInputElement(); Dwt.setVisible(inputEl, Boolean(this._resourcesShown)); }; ZmApptEditView.prototype.showResourceField = function(show){ this._showResources.innerHTML = show ? ZmMsg.hideEquipment : ZmMsg.showEquipment; Dwt.setVisible(this._resourcesContainer, Boolean(show)) }; ZmApptEditView.prototype.showOptional = function() { this._toggleOptionalAttendees(true); }; ZmApptEditView.prototype._closeScheduler = function() { this._schButton.innerHTML = ZmMsg.show; this._schImage.className = "ImgSelectPullDownArrow"; if(this._scheduleView) { this._scheduleView.setVisible(false); this.autoSize(); } }; ZmApptEditView.prototype._toggleInlineScheduler = function(forceShow) { if(this._schedulerOpened && !forceShow) { this._schedulerOpened = false; this._closeScheduler(); return; } this._schedulerOpened = true; this._schButton.innerHTML = ZmMsg.hide; this._schImage.className = "ImgSelectPullUpArrow"; var scheduleView = this.getScheduleView(); //todo: scheduler auto complete Dwt.setVisible(this._schedulerContainer, true); scheduleView.setVisible(true); scheduleView.resetPagelessMode(false); scheduleView.showMe(); this.autoSize(); }; ZmApptEditView.prototype.getScheduleView = function() { if(!this._scheduleView) { var appt = this.parent.getAppt(); this._scheduleView = new ZmFreeBusySchedulerView(this, this._attendees, this._controller, this._dateInfo, appt, this.showConflicts.bind(this)); this._scheduleView.reparentHtmlElement(this._schedulerContainer); var closeCallback = this._onSuggestionClose.bind(this); this._scheduleAssistant = new ZmScheduleAssistantView(this, this._controller, this, closeCallback); this._scheduleAssistant.reparentHtmlElement(this._suggestions); AjxTimedAction.scheduleAction(new AjxTimedAction(this, this.loadPreference), 300); } return this._scheduleView; }; ZmApptEditView.prototype._resetAttendeeCount = function() { for (var i = 0; i < ZmFreeBusySchedulerView.FREEBUSY_NUM_CELLS; i++) { this._allAttendees[i] = 0; delete this._allAttendeesStatus[i]; } }; //TODO: // 1. Organizer/From is always Persona - Done // 2. Remote Cals - sentBy is Persona - Done // 3. Appt. Summary body needs Persona details - Needs Action // 4. No Persona's Case - Done ZmApptEditView.prototype.setIdentity = function(identity){ if (this.identitySelect) { identity = identity || appCtxt.getIdentityCollection().defaultIdentity; this.identitySelect.setSelectedValue(identity.id); } }; ZmApptEditView.prototype.getIdentity = function() { if (this.identitySelect) { var collection = appCtxt.getIdentityCollection(); var val = this.identitySelect.getValue(); var identity = collection.getById(val); return identity ? identity : collection.defaultIdentity; } }; ZmApptEditView.prototype._setIdentityVisible = function() { if (!appCtxt.get(ZmSetting.IDENTITIES_ENABLED)) return; var div = document.getElementById(this._htmlElId + "_identityContainer"); if (!div) return; var visible = this.identitySelect ? this.identitySelect.getOptionCount() > 1 : false; Dwt.setVisible(div, visible); }; ZmApptEditView.prototype._getIdentityOptions = function() { var options = []; var identityCollection = appCtxt.getIdentityCollection(); var identities = identityCollection.getIdentities(); var defaultIdentity = identityCollection.defaultIdentity; for (var i = 0, count = identities.length; i < count; i++) { var identity = identities[i]; options.push(new DwtSelectOptionData(identity.id, this._getIdentityText(identity), (identity.id == defaultIdentity.id))); } return options; }; ZmApptEditView.prototype._getIdentityText = function(identity, account) { var name = identity.name; if (identity.isDefault && name == ZmIdentity.DEFAULT_NAME) { name = account ? account.getDisplayName() : ZmMsg.accountDefault; } // default replacement parameters var defaultIdentity = appCtxt.getIdentityCollection().defaultIdentity; var params = [ name, (identity.sendFromDisplay || ''), identity.sendFromAddress, ZmMsg.accountDefault, appCtxt.get(ZmSetting.DISPLAY_NAME), defaultIdentity.sendFromAddress ]; // get appropriate pattern var pattern; if (identity.isDefault) { pattern = ZmMsg.identityTextPrimary; } else if (identity.isFromDataSource) { var ds = appCtxt.getDataSourceCollection().getById(identity.id); params[1] = ds.userName || ''; params[2] = ds.getEmail(); var provider = ZmDataSource.getProviderForAccount(ds); pattern = (provider && ZmMsg["identityText-"+provider.id]) || ZmMsg.identityTextExternal; } else { pattern = ZmMsg.identityTextPersona; } // format text return AjxMessageFormat.format(pattern, params); }; ZmApptEditView.prototype._addressButtonListener = function(ev) { var obj = ev ? DwtControl.getTargetControl(ev) : null; this._forwardToField.setEnabled(false); if (!this._contactPicker) { AjxDispatcher.require("ContactsCore"); var buttonInfo = [ { id: AjxEmailAddress.TO, label: ZmMsg.toLabel } ]; this._contactPicker = new ZmContactPicker(buttonInfo); this._contactPicker.registerCallback(DwtDialog.OK_BUTTON, this._contactPickerOkCallback, this); this._contactPicker.registerCallback(DwtDialog.CANCEL_BUTTON, this._contactPickerCancelCallback, this); } var addrList = {}; var addrs = !this._useAcAddrBubbles && this._collectForwardAddrs(); var type = AjxEmailAddress.TO; addrList[type] = this._useAcAddrBubbles ? this._forwardToField.getAddresses(true) : addrs[type] && addrs[type].good.getArray(); var str = (this._forwardToField.getValue() && !(addrList[type] && addrList[type].length)) ? this._forwardToField.getValue() : ""; this._contactPicker.popup(type, addrList, str); }; ZmApptEditView.prototype._attendeesButtonListener = function(addrType, ev) { var obj = ev ? DwtControl.getTargetControl(ev) : null; var inputObj = this._attInputField[addrType]; inputObj.setEnabled(false); var contactPicker = this._attendeePicker[addrType]; if (!contactPicker) { AjxDispatcher.require("ContactsCore"); var buttonInfo = [ { id: AjxEmailAddress.TO, label: ZmMsg.toLabel } ]; contactPicker = this._attendeePicker[addrType] = new ZmContactPicker(buttonInfo); contactPicker.registerCallback(DwtDialog.OK_BUTTON, this._attendeePickerOkCallback, this, [addrType]); contactPicker.registerCallback(DwtDialog.CANCEL_BUTTON, this._attendeePickerCancelCallback, this, [addrType]); } var addrList = {}; var addrs = !this._useAcAddrBubbles && this._collectAddrs(inputObj.getValue()); var type = AjxEmailAddress.TO; addrList[type] = this._useAcAddrBubbles ? this._attInputField[addrType].getAddresses(true) : addrs[type] && addrs[type].good.getArray(); var str = (inputObj.getValue() && !(addrList[type] && addrList[type].length)) ? inputObj.getValue() : ""; contactPicker.popup(type, addrList, str); }; ZmApptEditView.prototype._locationButtonListener = function(addrType, ev) { var obj = ev ? DwtControl.getTargetControl(ev) : null; var inputObj = this._attInputField[addrType]; if(inputObj) inputObj.setEnabled(false); var locationPicker = this.getAttendeePicker(addrType); locationPicker.popup(); }; ZmApptEditView.prototype.getAttendeePicker = function(addrType) { var attendeePicker = this._attendeePicker[addrType]; if (!attendeePicker) { attendeePicker = this._attendeePicker[addrType] = new ZmAttendeePicker(this, this._attendees, this._controller, addrType, this._dateInfo); attendeePicker.registerCallback(DwtDialog.OK_BUTTON, this._locationPickerOkCallback, this, [addrType]); attendeePicker.registerCallback(DwtDialog.CANCEL_BUTTON, this._attendeePickerCancelCallback, this, [addrType]); attendeePicker.initialize(this._calItem, this._mode, this._isDirty, this._apptComposeMode); } return attendeePicker; }; // Transfers addresses from the contact picker to the appt compose view. ZmApptEditView.prototype._attendeePickerOkCallback = function(addrType, addrs) { this._attInputField[addrType].setEnabled(true); var vec = (addrs instanceof AjxVector) ? addrs : addrs[AjxEmailAddress.TO]; this._setAddresses(this._attInputField[addrType], vec); this._activeInputField = addrType; this._handleAttendeeField(addrType); this._attendeePicker[addrType].popdown(); }; /** * One-stop shop for setting address field content. The input may be either a DwtInputField or a * ZmAddressInputField. The address(es) passed in may be a string, an array, or an AjxVector. The * latter two types may have a member type of string, AjxEmailAddress, or ZmContact/ZmResource. * * @param addrInput * @param addrs * @param type * @param shortForm * * @private */ ZmApptEditView.prototype._setAddresses = function(addrInput, addrs, type, shortForm) { // non-person attendees are shown in short form by default shortForm = (shortForm || (type && type != ZmCalBaseItem.PERSON)); // if we get a string with multiple email addresses, split it if (typeof addrs == "string" && (addrs.indexOf(ZmAppt.ATTENDEES_SEPARATOR) != -1)) { var result = AjxEmailAddress.parseEmailString(addrs, type); addrs = result.good; } // make sure we have an array to deal with addrs = (addrs instanceof AjxVector) ? addrs.getArray() : (typeof addrs == "string") ? [addrs] : addrs; if (this._useAcAddrBubbles) { addrInput.clear(); if (addrs && addrs.length) { var len = addrs.length; for (var i = 0; i < len; i++) { var addr = addrs[i]; if (addr) { var addrStr, email, match; if (typeof addr == "string") { addrStr = addr; } else if (addr.isAjxEmailAddress) { addrStr = addr.toString(shortForm); match = {isDL: addr.isGroup && addr.canExpand, email: addrStr}; } else if (addr instanceof ZmContact) { email = addr.getEmail(true); //bug: 57858 - give preference to lookup email address if its present //bug:60427 to show display name format the lookupemail addrStr = addr.getLookupEmail() ? (new AjxEmailAddress(addr.getLookupEmail(),null,addr.getFullNameForDisplay())).toString() : ZmApptViewHelper.getAttendeesText(addr, type); match = {isDL: addr.isGroup && addr.canExpand, email: addrStr}; } addrInput.addBubble({address:addrStr, match:match, skipNotify:true}); } } } } else { var list = []; if (addrs && addrs.length) { for (var i = 0, len = addrs.length; i < len; i++) { var addr = addrs[i]; if (addr) { if (typeof addr == "string") { list.push(addr); } else if (addr.isAjxEmailAddress) { list.push(addr.toString(shortForm)); } else if (addr instanceof ZmContact) { var email = addr.getEmail(true); list.push(email.toString(shortForm)); } } } } var addrStr = (list.length > 0) ? list.join(AjxEmailAddress.SEPARATOR) + AjxEmailAddress.SEPARATOR : ""; addrInput.setValue(addrStr || ""); } }; // Transfers addresses from the location/resource picker to the appt compose view. ZmApptEditView.prototype._locationPickerOkCallback = function(addrType, attendees) { this.parent.updateAttendees(attendees, addrType); if(this._attInputField[addrType]) { this._attInputField[addrType].setEnabled(true); this._activeInputField = addrType; } if(addrType == ZmCalBaseItem.LOCATION || addrType == ZmCalBaseItem.EQUIPMENT) { this.updateAttendeesCache(addrType, this._attendees[addrType].getArray()); var attendeeStr = ZmApptViewHelper.getAttendeesString(this._attendees[addrType].getArray(), addrType); this.setAttendeesField(addrType, attendeeStr); } this._attendeePicker[addrType].popdown(); }; // Updates the local cache with attendee objects ZmApptEditView.prototype.updateAttendeesCache = function(addrType, attendees){ if (!(attendees && attendees.length)) return ""; var a = []; for (var i = 0; i < attendees.length; i++) { var attendee = attendees[i]; var addr = attendee.getLookupEmail() || attendee.getEmail(); var key = addr + "-" + addrType; this._attendeesHashMap[key] = attendee; } }; ZmApptEditView.prototype.setAttendeesField = function(addrType, attendees){ this._setAddresses(this._attInputField[addrType], attendees); this._handleAttendeeField(addrType); }; ZmApptEditView.prototype._attendeePickerCancelCallback = function(addrType) { if(this._attInputField[addrType]) { this._handleAttendeeField(addrType); this._attInputField[addrType].setEnabled(true); } }; // Transfers addresses from the contact picker to the appt compose view. ZmApptEditView.prototype._contactPickerOkCallback = function(addrs) { this._forwardToField.setEnabled(true); var vec = (addrs instanceof AjxVector) ? addrs : addrs[AjxEmailAddress.TO]; this._setAddresses(this._forwardToField, vec); this._activeInputField = ZmCalBaseItem.PERSON; this._handleAttendeeField(ZmCalBaseItem.PERSON); //this._contactPicker.removePopdownListener(this._controller._dialogPopdownListener); this._contactPicker.popdown(); }; ZmApptEditView.prototype._contactPickerCancelCallback = function() { this._handleAttendeeField(ZmCalBaseItem.PERSON); this._forwardToField.setEnabled(true); }; ZmApptEditView.prototype.getForwardAddress = function() { return this._collectForwardAddrs(); }; // Grab the good addresses out of the forward to field ZmApptEditView.prototype._collectForwardAddrs = function() { return this._collectAddrs(this._forwardToField.getValue()); }; // Grab the good addresses out of the forward to field ZmApptEditView.prototype._collectAddrs = function(addrStr) { var addrs = {}; addrs[ZmApptEditView.BAD] = new AjxVector(); var val = AjxStringUtil.trim(addrStr); if (val.length == 0) return addrs; var result = AjxEmailAddress.parseEmailString(val, AjxEmailAddress.TO, false); if (result.all.size() == 0) return addrs; addrs.gotAddress = true; addrs[AjxEmailAddress.TO] = result; if (result.bad.size()) { addrs[ZmApptEditView.BAD].addList(result.bad); addrs.badType = AjxEmailAddress.TO; } return addrs; }; ZmApptEditView.prototype.initialize = function(calItem, mode, isDirty, apptComposeMode) { this._fbCache.clearCache(); this._editViewInitialized = false; this._isForward = (apptComposeMode == ZmApptComposeView.FORWARD); this._isProposeTime = (apptComposeMode == ZmApptComposeView.PROPOSE_TIME); this._apptComposeMode = apptComposeMode; ZmCalItemEditView.prototype.initialize.call(this, calItem, mode, isDirty, apptComposeMode); var scheduleView = this.getScheduleView(); scheduleView.initialize(calItem, mode, isDirty, apptComposeMode); }; ZmApptEditView.prototype.isSuggestionsNeeded = function() { if (appCtxt.isOffline) { var ac = window["appCtxt"].getAppController(); return !this._isForward && this.GROUP_CALENDAR_ENABLED && ac._isPrismOnline && ac._isUserOnline; } else { return !this._isForward && this.GROUP_CALENDAR_ENABLED; } }; ZmApptEditView.prototype.getCalendarAccount = function() { var cal = appCtxt.getById(this._folderSelect.getValue()); return cal && cal.getAccount(); }; ZmApptEditView.prototype._folderListener = function() { var calId = this._folderSelect.getValue(); var cal = appCtxt.getById(calId); // bug: 48189 - Hide schedule tab for non-ZCS acct if (appCtxt.isOffline) { var currAcct = cal.getAccount(); appCtxt.accountList.setActiveAccount(currAcct); this.setSchedulerVisibility(currAcct.isZimbraAccount && !currAcct.isMain); } var acct = appCtxt.getActiveAccount(); var id = String(cal.id); var isRemote = (id.indexOf(":") != -1) && (id.indexOf(acct.id) != 0); var isEnabled = !isRemote || cal.hasPrivateAccess(); this._privateCheckbox.disabled = !isEnabled; if(this._schedulerOpened) { var organizer = this._isProposeTime ? this.getCalItemOrganizer() : this.getOrganizer(); this._scheduleView.update(this._dateInfo, organizer, this._attendees); this._scheduleView.updateFreeBusy(); } if (appCtxt.isOffline) { this._calItem.setFolderId(calId); this.enableInputs(true); //enableInputs enables or disables the attendees/location/etc inputs based on the selected folder (calendar) - if it's local it will be disabled, and if remote - enabled. } }; ZmApptEditView.prototype.setSchedulerVisibility = function(visible) { Dwt.setVisible(this._schedulerOptions, visible); Dwt.setVisible(this._schedulerContainer, visible); }; ZmApptEditView.prototype._resetFolderSelect = function(calItem, mode) { ZmCalItemEditView.prototype._resetFolderSelect.call(this, calItem, mode); this._resetAutocompleteListView(appCtxt.getById(calItem.folderId)); }; ZmApptEditView.prototype._resetAttendeesField = function(enabled) { var attField = this._attInputField[ZmCalBaseItem.PERSON]; if (attField) { attField.setEnabled(enabled); this._adjustAddrHeight(attField.getInputElement()); } attField = this._attInputField[ZmCalBaseItem.OPTIONAL_PERSON]; if (attField) { attField.setEnabled(enabled); this._adjustAddrHeight(attField.getInputElement()); } }; ZmApptEditView.prototype._folderPickerCallback = function(dlg, folder) { ZmCalItemEditView.prototype._folderPickerCallback.call(this, dlg, folder); this._resetAutocompleteListView(folder); if (appCtxt.isOffline) { this._resetAttendeesField(!folder.getAccount().isMain); } }; ZmApptEditView.prototype._resetAutocompleteListView = function(folder) { if (appCtxt.multiAccounts && this._acContactsList) { this._acContactsList.setActiveAccount(folder.getAccount()); } }; ZmApptEditView.prototype._initAutocomplete = function() { var acCallback = this._autocompleteCallback.bind(this); var keyPressCallback = this._onAttendeesChange.bind(this); this._acList = {}; var params = { dataClass: appCtxt.getAutocompleter(), matchValue: ZmAutocomplete.AC_VALUE_FULL, compCallback: acCallback, keyPressCallback: keyPressCallback, options: {addrBubbles:this._useAcAddrBubbles} }; // autocomplete for attendees (required and optional) and forward recipients if (appCtxt.get(ZmSetting.CONTACTS_ENABLED) && this.GROUP_CALENDAR_ENABLED) { params.contextId = [this._controller.getCurrentViewId(), ZmCalBaseItem.PERSON].join("-"); var aclv = this._acContactsList = new ZmAutocompleteListView(params); this._setAutocompleteHandler(aclv, ZmCalBaseItem.PERSON); this._setAutocompleteHandler(aclv, ZmCalBaseItem.OPTIONAL_PERSON); if (this._forwardToField) { this._setAutocompleteHandler(aclv, ZmCalBaseItem.FORWARD, this._forwardToField); } } if (appCtxt.get(ZmSetting.GAL_ENABLED)) { // autocomplete for locations params.keyUpCallback = this._handleLocationChange.bind(this); //params.matchValue = ZmAutocomplete.AC_VALUE_NAME; params.options = {addrBubbles: this._useAcAddrBubbles, type: ZmAutocomplete.AC_TYPE_LOCATION}; if (AjxEnv.isIE) { params.keyDownCallback = this._resetKnownLocation.bind(this); } params.contextId = [this._controller.getCurrentViewId(), ZmCalBaseItem.LOCATION].join("-"); var aclv = this._acLocationsList = new ZmAutocompleteListView(params); this._setAutocompleteHandler(aclv, ZmCalBaseItem.LOCATION); } if (appCtxt.get(ZmSetting.GAL_ENABLED) && this.GROUP_CALENDAR_ENABLED) { // autocomplete for locations var app = appCtxt.getApp(ZmApp.CALENDAR); params.keyUpCallback = this._handleResourceChange.bind(this); //params.matchValue = ZmAutocomplete.AC_VALUE_NAME; params.options = {addrBubbles: this._useAcAddrBubbles, type:ZmAutocomplete.AC_TYPE_EQUIPMENT}; params.contextId = [this._controller.getCurrentViewId(), ZmCalBaseItem.EQUIPMENT].join("-"); var aclv = this._acResourcesList = new ZmAutocompleteListView(params); this._setAutocompleteHandler(aclv, ZmCalBaseItem.EQUIPMENT); } }; ZmApptEditView.prototype._handleResourceChange = function(event, aclv, result) { var val = this._attInputField[ZmCalBaseItem.EQUIPMENT].getValue(); if (val == "") { this.parent.updateAttendees([], ZmCalBaseItem.EQUIPMENT); this._isKnownResource = false; } }; ZmApptEditView.prototype._setAutocompleteHandler = function(aclv, attType, input) { input = input || this._attInputField[attType]; var aifId = null; if (this._useAcAddrBubbles) { aifId = input._htmlElId; input.setAutocompleteListView(aclv); } aclv.handle(input.getInputElement(), aifId); this._acList[attType] = aclv; }; ZmApptEditView.prototype._handleLocationChange = function(event, aclv, result) { var val = this._attInputField[ZmCalBaseItem.LOCATION].getValue(); if (val == "") { this.parent.updateAttendees([], ZmCalBaseItem.LOCATION); this._isKnownLocation = false; } }; ZmApptEditView.prototype._autocompleteCallback = function(text, el, match) { if (!match) { DBG.println(AjxDebug.DBG1, "ZmApptEditView: match empty in autocomplete callback; text: " + text); return; } var attendee = match.item; var type = el && el._attType; if (attendee) { if (type == ZmCalBaseItem.FORWARD) { DBG.println("forward auto complete match : " + match) return; } if (type == ZmCalBaseItem.LOCATION || type == ZmCalBaseItem.EQUIPMENT) { var name = ZmApptViewHelper.getAttendeesText(attendee); if(name) { this._locationTextMap[name] = attendee; } var locations = text.split(/[\n,;]/); var newAttendees = []; for(var i = 0; i < locations.length; i++) { var l = AjxStringUtil.trim(locations[i]); if(this._locationTextMap[l]) { newAttendees.push(this._locationTextMap[l]); } } attendee = newAttendees; } //controller tracks both optional & required attendees in common var if (type == ZmCalBaseItem.OPTIONAL_PERSON) { this.setAttendeesRole(attendee, ZmCalItem.ROLE_OPTIONAL); type = ZmCalBaseItem.PERSON; } this.parent.updateAttendees(attendee, type, (type == ZmCalBaseItem.LOCATION || type == ZmCalBaseItem.EQUIPMENT )?ZmApptComposeView.MODE_REPLACE : ZmApptComposeView.MODE_ADD); if (type == ZmCalBaseItem.LOCATION) { this._isKnownLocation = true; }else if(type == ZmCalBaseItem.EQUIPMENT){ this._isKnownResource = true; } this._updateScheduler(type, attendee); }else if(match.email){ if((type == ZmCalBaseItem.PERSON || type == ZmCalBaseItem.OPTIONAL_PERSON) && this._scheduleAssistant) { var attendees = this.getAttendeesFromString(ZmCalBaseItem.PERSON, this._attInputField[ZmCalBaseItem.PERSON].getValue()); this.setAttendeesRole(attendees, (type == ZmCalBaseItem.OPTIONAL_PERSON) ? ZmCalItem.ROLE_OPTIONAL : ZmCalItem.ROLE_REQUIRED); if (type == ZmCalBaseItem.OPTIONAL_PERSON) { type = ZmCalBaseItem.PERSON; } this.parent.updateAttendees(attendees, type, (type == ZmCalBaseItem.LOCATION )?ZmApptComposeView.MODE_REPLACE : ZmApptComposeView.MODE_ADD); this._updateScheduler(type, attendees); } } this.updateToolbarOps(); }; ZmApptEditView.prototype._handleRemovedAttendees = function(addrType) { this._activeInputField = addrType; this.handleAttendeeChange(); }; ZmApptEditView.prototype._addEventHandlers = function() { var edvId = AjxCore.assignId(this); // add event listeners where necessary Dwt.setHandler(this._allDayCheckbox, DwtEvent.ONCLICK, ZmCalItemEditView._onClick); Dwt.setHandler(this._repeatDescField, DwtEvent.ONCLICK, ZmCalItemEditView._onClick); if(this._showOptional) Dwt.setHandler(this._showOptional, DwtEvent.ONCLICK, ZmCalItemEditView._onClick); if(this._showResources) Dwt.setHandler(this._showResources, DwtEvent.ONCLICK, ZmCalItemEditView._onClick); Dwt.setHandler(this._repeatDescField, DwtEvent.ONMOUSEOVER, ZmCalItemEditView._onMouseOver); Dwt.setHandler(this._repeatDescField, DwtEvent.ONMOUSEOUT, ZmCalItemEditView._onMouseOut); Dwt.setHandler(this._startDateField, DwtEvent.ONCHANGE, ZmCalItemEditView._onChange); Dwt.setHandler(this._endDateField, DwtEvent.ONCHANGE, ZmCalItemEditView._onChange); Dwt.setHandler(this._startDateField, DwtEvent.ONFOCUS, ZmCalItemEditView._onFocus); Dwt.setHandler(this._endDateField, DwtEvent.ONFOCUS, ZmCalItemEditView._onFocus); if (this.GROUP_CALENDAR_ENABLED) { Dwt.setHandler(this._suggestTime, DwtEvent.ONCLICK, ZmCalItemEditView._onClick); } Dwt.setHandler(this._suggestLocation, DwtEvent.ONCLICK, ZmCalItemEditView._onClick); Dwt.setHandler(this._locationStatusAction, DwtEvent.ONCLICK, ZmCalItemEditView._onClick); this._allDayCheckbox._editViewId = this._repeatDescField._editViewId = edvId; this._startDateField._editViewId = this._endDateField._editViewId = edvId; if(this._showOptional) this._showOptional._editViewId = edvId; if(this._showResources) this._showResources._editViewId = edvId; if (this.GROUP_CALENDAR_ENABLED) { this._suggestTime._editViewId = edvId; } this._suggestLocation._editViewId = edvId; this._locationStatusAction._editViewId = edvId; var inputFields = [this._attendeesInputField, this._optAttendeesInputField, this._locationInputField, this._forwardToField, this._resourceInputField]; for (var i = 0; i < inputFields.length; i++) { if(!inputFields[i]) continue; var inputEl = inputFields[i].getInputElement(); inputEl._editViewId = edvId; inputEl.onfocus = AjxCallback.simpleClosure(this._handleOnFocus, this, inputEl); inputEl.onblur = AjxCallback.simpleClosure(this._handleOnBlur, this, inputEl); inputEl.onkeyup = AjxCallback.simpleClosure(this._onAttendeesChange, this); } if (this._subjectField) { var inputEl = this._subjectField.getInputElement(); inputEl.onblur = AjxCallback.simpleClosure(this._handleSubjectOnBlur, this, inputEl); inputEl.onfocus = AjxCallback.simpleClosure(this._handleSubjectOnFocus, this, inputEl); } }; // cache all input fields so we dont waste time traversing DOM each time ZmApptEditView.prototype._cacheFields = function() { ZmCalItemEditView.prototype._cacheFields.call(this); this._allDayCheckbox = document.getElementById(this._allDayCheckboxId); }; ZmApptEditView.prototype._resetTimezoneSelect = function(calItem, isAllDayAppt) { this._tzoneSelectStart.setSelectedValue(calItem.timezone); this._tzoneSelectEnd.setSelectedValue(calItem.endTimezone || calItem.timezone); this.handleTimezoneOverflow(); }; ZmApptEditView.prototype._setTimezoneVisible = function(dateInfo) { var showTimezones = appCtxt.get(ZmSetting.CAL_SHOW_TIMEZONE) || dateInfo.timezone != AjxTimezone.getServerId(AjxTimezone.DEFAULT); var showStartTimezone = showTimezones && !dateInfo.isAllDay; var showEndTimezone = showStartTimezone && this._repeatSelect && this._repeatSelect.getValue()=="NON"; if (this._tzoneSelectStartElement) { Dwt.setVisible(this._tzoneSelectStartElement, showStartTimezone); Dwt.setVisibility(this._tzoneSelectStartElement, showStartTimezone); } if (this._tzoneSelectEndElement) { Dwt.setVisible(this._tzoneSelectEndElement, showEndTimezone); Dwt.setVisibility(this._tzoneSelectEndElement, showEndTimezone); } }; ZmApptEditView.prototype._showTimeFields = function(show) { Dwt.setVisibility(this._startTimeSelect.getHtmlElement(), show); Dwt.setVisibility(this._endTimeSelect.getHtmlElement(), show); this._setTimezoneVisible(this._dateInfo); }; ZmApptEditView.CHANGES_LOCAL = 1; ZmApptEditView.CHANGES_SIGNIFICANT = 2; ZmApptEditView.CHANGES_INSIGNIFICANT = 3; ZmApptEditView.CHANGES_TIME_RECURRENCE = 4; ZmApptEditView.prototype._getFormValue = function(type, attribs){ var vals = []; attribs = attribs || {}; switch(type){ case ZmApptEditView.CHANGES_LOCAL: vals.push(this._folderSelect.getValue()); // Folder vals.push(this._showAsSelect.getValue()); // Busy Status if(!attribs.excludeReminder){ // Reminder vals.push(this._reminderSelectInput.getValue()); vals.push(this._reminderEmailCheckbox.isSelected()); vals.push(this._reminderDeviceEmailCheckbox.isSelected()); } break; case ZmApptEditView.CHANGES_SIGNIFICANT: vals = this._getTimeAndRecurrenceChanges(); if (!attribs.excludeAttendees) { //Attendees vals.push(ZmApptViewHelper.getAttendeesString(this._attendees[ZmCalBaseItem.PERSON].getArray(), ZmCalBaseItem.PERSON, false, true)); } if(!attribs.excludeLocation) { vals.push(ZmApptViewHelper.getAttendeesString(this._attendees[ZmCalBaseItem.LOCATION].getArray(), ZmCalBaseItem.LOCATION, false, true)); //location can even be a normal label text vals.push(this._locationInputField.getValue()); } if(!attribs.excludeEquipment) { vals.push(ZmApptViewHelper.getAttendeesString(this._attendees[ZmCalBaseItem.EQUIPMENT].getArray(), ZmCalBaseItem.EQUIPMENT, false, true)); } if(this._isForward && !attribs.excludeAttendees) { vals.push(this._forwardToField.getValue()); //ForwardTo } if(this.identitySelect){ vals.push(this.getIdentity().id); //Identity Select } break; case ZmApptEditView.CHANGES_INSIGNIFICANT: vals.push(this._subjectField.getValue()); vals.push(this._notesHtmlEditor.getContent()); vals.push(this._privateCheckbox.checked ? ZmApptEditView.PRIVACY_OPTION_PRIVATE : ZmApptEditView.PRIVACY_OPTION_PUBLIC); //TODO: Attachments, Priority break; case ZmApptEditView.CHANGES_TIME_RECURRENCE: vals = this._getTimeAndRecurrenceChanges(); break; } vals = vals.join("|").replace(/\|+/, "|"); return vals; }; ZmApptEditView.prototype._getTimeAndRecurrenceChanges = function(){ var vals = []; var startDate = AjxDateUtil.simpleParseDateStr(this._startDateField.value); var endDate = AjxDateUtil.simpleParseDateStr(this._endDateField.value); startDate = this._startTimeSelect.getValue(startDate); endDate = this._endTimeSelect.getValue(endDate); vals.push( AjxDateUtil.getServerDateTime(startDate), // Start DateTime AjxDateUtil.getServerDateTime(endDate) // End DateTime ); if (Dwt.getDisplay(this._tzoneSelectStart.getHtmlElement()) != Dwt.DISPLAY_NONE) { vals.push(this._tzoneSelectStart.getValue()); // Start timezone vals.push(this._tzoneSelectEnd.getValue()); // End timezone } vals.push("" + this._allDayCheckbox.checked); // All Day Appt. //TODO: Detailed Recurrence, Repeat support vals.push(this._repeatSelect.getValue()); //Recurrence return vals; } // Returns a string representing the form content ZmApptEditView.prototype._formValue = function(excludeAttendees, excludeReminder) { var attribs = { excludeAttendees: excludeAttendees, excludeReminder: excludeReminder }; var sigFormValue = this._getFormValue(ZmApptEditView.CHANGES_SIGNIFICANT, attribs); var insigFormValue = this._getFormValue(ZmApptEditView.CHANGES_INSIGNIFICANT, attribs); var localFormValue = this._getFormValue(ZmApptEditView.CHANGES_LOCAL, attribs); var formVals = []; formVals.push(sigFormValue, insigFormValue, localFormValue); formVals = formVals.join('|').replace(/\|+/, "|"); return formVals; }; ZmApptEditView.prototype.checkIsDirty = function(type, attribs){ return (this._apptFormValue[type] != this._getFormValue(type, attribs)) }; ZmApptEditView.prototype._keyValue = function() { return this._getFormValue(ZmApptEditView.CHANGES_SIGNIFICANT, {excludeAttendees: true, excludeEquipment: true}); }; // Listeners ZmApptEditView.prototype._getDateTimeText = function() { return this._dateInfo.startDate + "-" + this._dateInfo.startTimeStr + "_" + this._dateInfo.endDate + "_" + this._dateInfo.endTimeStr; } ZmApptEditView.prototype._timeChangeListener = function(ev, id) { ZmTimeInput.adjustStartEnd(ev, this._startTimeSelect, this._endTimeSelect, this._startDateField, this._endDateField, this._dateInfo, id); var oldTimeInfo = this._getDateTimeText(); ZmApptViewHelper.getDateInfo(this, this._dateInfo); var newTimeInfo = this._getDateTimeText(); if (oldTimeInfo != newTimeInfo) { this._dateInfo.isTimeModified = true; if(this._schedulerOpened) { this._scheduleView._timeChangeListener(ev, id); } if(this._scheduleAssistant) this._scheduleAssistant.updateTime(true, true); var durationInfo = this.getDurationInfo(); this._locationConflictAppt.startDate = new Date(durationInfo.startTime); this._locationConflictAppt.endDate = new Date(durationInfo.endTime); this.locationConflictChecker(); } }; ZmApptEditView.prototype._recurChangeForLocationConflict = function() { this._getRecurrence(this._locationConflictAppt); this.locationConflictChecker(); } ZmApptEditView.prototype._dateTimeChangeForLocationConflict = function(oldTimeInfo) { var newTimeInfo = this._getDateTimeText(); if (oldTimeInfo != newTimeInfo) { var durationInfo = this.getDurationInfo(); this._locationConflictAppt.startDate = new Date(durationInfo.startTime); this._locationConflictAppt.endDate = new Date(durationInfo.endTime); this.locationConflictChecker(); } } ZmApptEditView.prototype._dateCalSelectionListener = function(ev) { var oldTimeInfo = this._getDateTimeText(); ZmCalItemEditView.prototype._dateCalSelectionListener.call(this, ev); if(this._schedulerOpened) { ZmApptViewHelper.getDateInfo(this, this._dateInfo); this._scheduleView._updateFreeBusy(); } if(this._scheduleAssistant) this._scheduleAssistant.updateTime(true, true); this._dateTimeChangeForLocationConflict(oldTimeInfo); }; ZmApptEditView.prototype.handleTimezoneOverflow = function() { var timezoneTxt = this._tzoneSelectStart.getText(); var limit = AjxEnv.isIE ? 25 : 30; if(timezoneTxt.length > limit) { var newTimezoneTxt = timezoneTxt.substring(0, limit) + '...'; this._tzoneSelectStart.setText(newTimezoneTxt); } var option = this._tzoneSelectStart.getSelectedOption(); this._tzoneSelectStart.setToolTipContent(option ? option.getDisplayValue() : timezoneTxt); timezoneTxt = this._tzoneSelectEnd.getText(); if(timezoneTxt.length > limit) { var newTimezoneTxt = timezoneTxt.substring(0, limit) + '...'; this._tzoneSelectEnd.setText(newTimezoneTxt); } option = this._tzoneSelectEnd.getSelectedOption(); this._tzoneSelectEnd.setToolTipContent(option ? option.getDisplayValue() : timezoneTxt); }; ZmApptEditView.prototype._timezoneListener = function(ev) { var oldTZ = this._dateInfo.timezone; var dwtSelect = ev.item.parent.parent; var type = dwtSelect ? dwtSelect.getData(ZmApptEditView.TIMEZONE_TYPE) : ZmApptEditView.START_TIMEZONE; //bug: 55256 - Changing start timezone should auto-change end timezone if(type == ZmApptEditView.START_TIMEZONE) { var tzValue = dwtSelect.getValue(); this._tzoneSelectEnd.setSelectedValue(tzValue); } this.handleTimezoneOverflow(); ZmApptViewHelper.getDateInfo(this, this._dateInfo); if(this._schedulerOpened) { //this._controller.getApp().getFreeBusyCache().clearCache(); this._scheduleView._timeChangeListener(ev, id); } if (oldTZ != this._dateInfo.timezone) { this._locationConflictAppt.timezone = this._dateInfo.timezone; this.locationConflictChecker(); } }; ZmApptEditView.prototype._repeatChangeListener = function(ev) { ZmCalItemEditView.prototype._repeatChangeListener.call(this, ev); this._setTimezoneVisible(this._dateInfo); var newSelectVal = ev._args.newValue; if (newSelectVal != "CUS") { // CUS (Custom) launches a dialog. Otherwise act upon the change here this._locationConflictAppt.setRecurType(newSelectVal); this.locationConflictChecker(); } }; /** * Sets the values of the attendees input fields to reflect the current lists of * attendees. */ ZmApptEditView.prototype._setAttendees = function() { for (var t = 0; t < this._attTypes.length; t++) { var type = this._attTypes[t]; var attendees = this._attendees[type].getArray(); var numAttendees = attendees.length; var addrInput = this._attInputField[type]; var curVal = AjxStringUtil.trim(this._attInputField[type].getValue()); if (type == ZmCalBaseItem.PERSON) { var reqAttendees = ZmApptViewHelper.filterAttendeesByRole(attendees, ZmCalItem.ROLE_REQUIRED); var optAttendees = ZmApptViewHelper.filterAttendeesByRole(attendees, ZmCalItem.ROLE_OPTIONAL); //bug: 62008 - always compute all the required/optional arrays before setting them to avoid race condition //_setAddress is a costly operation which will trigger focus listeners and change the state of attendees this._setAddresses(addrInput, reqAttendees, type); this._setAddresses(this._attInputField[ZmCalBaseItem.OPTIONAL_PERSON], optAttendees, type); } else if (type == ZmCalBaseItem.LOCATION) { if (!curVal || numAttendees || this._isKnownLocation) { this._setAddresses(addrInput, attendees, type); this._isKnownLocation = true; } } else if (type == ZmCalBaseItem.EQUIPMENT) { if (!curVal || numAttendees) { if (numAttendees) { this._toggleResourcesField(true); } this._setAddresses(addrInput, attendees, type); } } } }; ZmApptEditView.prototype.removeAttendees = function(attendees, type) { attendees = (attendees instanceof AjxVector) ? attendees.getArray() : (attendees instanceof Array) ? attendees : [attendees]; for (var i = 0; i < attendees.length; i++) { var attendee = attendees[i]; var idx = -1; if (attendee instanceof ZmContact) { idx = this._attendees[type].indexOfLike(attendee, attendee.getAttendeeKey); if (idx !== -1) { this._attendees[type].removeAt(idx); } } else { this._attendees[type].remove(attendee); } } }; ZmApptEditView.prototype.setApptLocation = function(val) { this._setAddresses(this._attInputField[ZmCalBaseItem.LOCATION], val); }; ZmApptEditView.prototype.getAttendees = function(type) { return this.getAttendeesFromString(type, this._attInputField[type].getValue()); }; ZmApptEditView.prototype.getMode = function(type) { return this._mode; }; ZmApptEditView.prototype.getRequiredAttendeeEmails = function() { var attendees = []; var inputField = this._attInputField[ZmCalBaseItem.PERSON]; if(!inputField) { return attendees; } // input field can be null if zimbraFeatureGroupCalendarEnabled is FALSE var requiredEmails = inputField.getValue(); var items = AjxEmailAddress.split(requiredEmails); for (var i = 0; i < items.length; i++) { var item = AjxStringUtil.trim(items[i]); if (!item) { continue; } var contact = AjxEmailAddress.parse(item); if (!contact) { continue; } var email = contact.getAddress(); if(email instanceof Array) email = email[0]; attendees.push(email) } return attendees; }; ZmApptEditView.prototype.getOrganizerEmail = function() { var organizer = this.getOrganizer(); var email = organizer.getEmail(); if (email instanceof Array) { email = email[0]; } return email; }; ZmApptEditView.prototype._handleAttendeeField = function(type, useException) { if (!this._activeInputField || !this.GROUP_CALENDAR_ENABLED) { return; } if (type != ZmCalBaseItem.LOCATION) { this._controller.clearInvalidAttendees(); } return this._pickAttendeesInfo(type, useException); }; ZmApptEditView.prototype._pickAttendeesInfo = function(type, useException) { var attendees = new AjxVector(); if(type == ZmCalBaseItem.OPTIONAL_PERSON || type == ZmCalBaseItem.PERSON || type == ZmCalBaseItem.FORWARD) { attendees = this.getAttendeesFromString(ZmCalBaseItem.PERSON, this._attInputField[ZmCalBaseItem.PERSON].getValue()); this.setAttendeesRole(attendees, ZmCalItem.ROLE_REQUIRED); var optionalAttendees = this.getAttendeesFromString(ZmCalBaseItem.PERSON, this._attInputField[ZmCalBaseItem.OPTIONAL_PERSON].getValue(), true); this.setAttendeesRole(optionalAttendees, ZmCalItem.ROLE_OPTIONAL); var forwardAttendees = this.getAttendeesFromString(ZmCalBaseItem.PERSON, this._attInputField[ZmCalBaseItem.FORWARD].getValue(), false); this.setAttendeesRole(forwardAttendees, ZmCalItem.ROLE_REQUIRED); //merge optional & required attendees to update parent controller attendees.addList(optionalAttendees); attendees.addList(forwardAttendees); type = ZmCalBaseItem.PERSON; }else { var value = this._attInputField[type].getValue(); attendees = this.getAttendeesFromString(type, value); } return this._updateAttendeeFieldValues(type, attendees); }; ZmApptEditView.prototype.setAttendeesRole = function(attendees, role) { var personalAttendees = (attendees instanceof AjxVector) ? attendees.getArray() : (attendees instanceof Array) ? attendees : [attendees]; for (var i = 0; i < personalAttendees.length; i++) { var attendee = personalAttendees[i]; if(attendee) attendee.setParticipantRole(role); } }; ZmApptEditView.prototype.resetParticipantStatus = function() { if (this.isOrganizer() && this.isKeyInfoChanged()) { var personalAttendees = this._attendees[ZmCalBaseItem.PERSON].getArray(); for (var i = 0; i < personalAttendees.length; i++) { var attendee = personalAttendees[i]; if(attendee) attendee.setParticipantStatus(ZmCalBaseItem.PSTATUS_NEEDS_ACTION); } } }; ZmApptEditView.prototype.getAttendeesFromString = function(type, value, markAsOptional) { var attendees = new AjxVector(); var items = AjxEmailAddress.split(value); for (var i = 0; i < items.length; i++) { var item = AjxStringUtil.trim(items[i]); if (!item) { continue; } var contact = AjxEmailAddress.parse(item); if (!contact) { if(type != ZmCalBaseItem.LOCATION) this._controller.addInvalidAttendee(item); continue; } var addr = contact.getAddress(); var key = addr + "-" + type; if(!this._attendeesHashMap[key]) { this._attendeesHashMap[key] = ZmApptViewHelper.getAttendeeFromItem(item, type); } var attendee = this._attendeesHashMap[key]; if (attendee) { if(markAsOptional) attendee.setParticipantRole(ZmCalItem.ROLE_OPTIONAL); attendees.add(attendee); } else if (type != ZmCalBaseItem.LOCATION) { this._controller.addInvalidAttendee(item); } } return attendees; }; ZmApptEditView.prototype._updateAttendeeFieldValues = function(type, attendees) { // *always* force replace of attendees list with what we've found this.parent.updateAttendees(attendees, type); this._updateScheduler(type, attendees); appCtxt.notifyZimlets("onEditAppt_updateAttendees", [this]);//notify Zimlets }; ZmApptEditView.prototype._updateScheduler = function(type, attendees) { // *always* force replace of attendees list with what we've found attendees = (attendees instanceof AjxVector) ? attendees.getArray() : (attendees instanceof Array) ? attendees : [attendees]; if (appCtxt.isOffline && !appCtxt.isZDOnline()) { return; } //avoid duplicate freebusy request by updating the view in sequence if(type == ZmCalBaseItem.PERSON) { this._scheduleView.setUpdateCallback(new AjxCallback(this, this.updateScheduleAssistant, [attendees, type])) } var organizer = this._isProposeTime ? this.getCalItemOrganizer() : this.getOrganizer(); if(this._schedulerOpened) { this._scheduleView.update(this._dateInfo, organizer, this._attendees); this.autoSize(); }else { if(this._schedulerOpened == null && attendees.length > 0 && !this._isForward) { this._toggleInlineScheduler(true); }else { // Update the schedule view even if it won't be visible - it generates // Free/Busy info for other components this._scheduleView.showMe(); this._scheduleView.update(this._dateInfo, organizer, this._attendees); this.updateScheduleAssistant(attendees, type) } }; this.updateToolbarOps(); }; ZmApptEditView.prototype.updateScheduleAssistant = function(attendees, type) { if(this._scheduleAssistant && type == ZmCalBaseItem.PERSON) this._scheduleAssistant.updateAttendees(attendees); }; ZmApptEditView.prototype._getAttendeeByName = function(type, name) { if(!this._attendees[type]) { return null; } var a = this._attendees[type].getArray(); for (var i = 0; i < a.length; i++) { if (a[i].getFullName() == name) { return a[i]; } } return null; }; ZmApptEditView.prototype._getAttendeeByItem = function(item, type) { if(!this._attendees[type]) { return null; } var attendees = this._attendees[type].getArray(); for (var i = 0; i < attendees.length; i++) { var value = (type == ZmCalBaseItem.PERSON) ? attendees[i].getEmail() : attendees[i].getFullName(); if (item == value) { return attendees[i]; } } return null; }; // Callbacks ZmApptEditView.prototype._emailValidator = function(value) { // first parse the value string based on separator var attendees = AjxStringUtil.trim(value); if (attendees.length > 0) { var addrs = AjxEmailAddress.parseEmailString(attendees); if (addrs.bad.size() > 0) { throw ZmMsg.errorInvalidEmail2; } } return value; }; ZmApptEditView.prototype._handleOnClick = function(el) { if (el.id == this._allDayCheckboxId) { var edv = AjxCore.objectWithId(el._editViewId); ZmApptViewHelper.getDateInfo(edv, edv._dateInfo); this._showTimeFields(!el.checked); this.updateShowAsField(el.checked); if (el.checked && this._reminderSelect) { this._reminderSelect.setSelectedValue(1080); } this._scheduleView.handleTimeChange(); if(this._scheduleAssistant) this._scheduleAssistant.updateTime(true, true); var durationInfo = this.getDurationInfo(); this._locationConflictAppt.startDate = new Date(durationInfo.startTime); this._locationConflictAppt.endDate = new Date(durationInfo.startTime + AjxDateUtil.MSEC_PER_DAY); this._locationConflictAppt.allDayEvent = el.checked ? "1" : "0"; this.locationConflictChecker(); } else if(el.id == this._schButtonId || el.id == this._htmlElId + "_scheduleImage") { this._toggleInlineScheduler(); } else if(el.id == this._showOptionalId) { this._toggleOptionalAttendees(); }else if(el.id == this._showResourcesId){ this._toggleResourcesField(); }else if(el.id == this._suggestTimeId){ this._showTimeSuggestions(); }else if(el.id == this._suggestLocationId){ this._showLocationSuggestions(); }else if(el.id == this._locationStatusActionId){ this._showLocationStatusAction(); }else{ ZmCalItemEditView.prototype._handleOnClick.call(this, el); } }; ZmApptEditView.prototype._handleOnFocus = function(inputEl) { if(!this._editViewInitialized) return; this._activeInputField = inputEl._attType; this.setFocusMember(inputEl); }; ZmApptEditView.prototype.setFocusMember = function(member) { var kbMgr = appCtxt.getKeyboardMgr(); var tabGroup = kbMgr.getCurrentTabGroup(); if (tabGroup) { tabGroup.setFocusMember(member); } }; ZmApptEditView.prototype._handleOnBlur = function(inputEl) { if(!this._editViewInitialized) return; this._handleAttendeeField(inputEl._attType); this._activeInputField = null; }; ZmApptEditView.prototype._handleSubjectOnBlur = function(inputEl) { var subject = AjxStringUtil.trim(this._subjectField.getValue()); if(subject) { var buttonText = subject.substr(0, ZmAppViewMgr.TAB_BUTTON_MAX_TEXT); appCtxt.getAppViewMgr().setTabTitle(this._controller.getCurrentViewId(), buttonText); } }; ZmApptEditView.prototype._handleSubjectOnFocus = function(inputEl) { this.setFocusMember(inputEl); }; ZmApptEditView.prototype._resetKnownLocation = function() { this._isKnownLocation = false; }; ZmApptEditView._switchTab = function(type) { var appCtxt = window.parentAppCtxt || window.appCtxt; var tabView = appCtxt.getApp(ZmApp.CALENDAR).getApptComposeController().getTabView(); var key = (type == ZmCalBaseItem.LOCATION) ? tabView._tabKeys[ZmApptComposeView.TAB_LOCATIONS] : tabView._tabKeys[ZmApptComposeView.TAB_EQUIPMENT]; tabView.switchToTab(key); }; ZmApptEditView._showNotificationWarning = function(ev) { ev = ev || window.event; var el = DwtUiEvent.getTarget(ev); if (el && !el.checked) { var dialog = appCtxt.getMsgDialog(); dialog.setMessage(ZmMsg.sendNotificationMailWarning, DwtMessageDialog.WARNING_STYLE); dialog.popup(); } }; ZmApptEditView.prototype._resizeNotes = function() { var bodyFieldId = this._notesHtmlEditor.getBodyFieldId(); if (this._bodyFieldId != bodyFieldId) { this._bodyFieldId = bodyFieldId; this._bodyField = document.getElementById(this._bodyFieldId); } var node = this.getHtmlElement(); if (node && node.parentNode) node.style.height = node.parentNode.style.height; var size = this.getSize(); // Size x by the containing table (excluding the suggestion panel) var mainTableSize = Dwt.getSize(this._mainTable); if (mainTableSize.x <= 0 || size.y <= 0) { return; } var topDiv = document.getElementById(this._htmlElId + "_top"); var topDivSize = Dwt.getSize(topDiv); var topSizeHeight = this._getComponentsHeight(true); var notesEditorHeight = (this._notesHtmlEditor && this._notesHtmlEditor.getHtmlElement()) ? this._notesHtmlEditor.getHtmlElement().clientHeight:0; var rowHeight = (size.y - topSizeHeight) + notesEditorHeight ; var rowWidth = mainTableSize.x; if(AjxEnv.isIE) rowHeight = rowHeight - 10; else { var adj = (appCtxt.isTinyMCEEnabled()) ? 12 : 38; rowHeight = rowHeight + adj; } if(rowHeight < 350){ rowHeight = 350; } if( appCtxt.isTinyMCEEnabled() ) { this._notesHtmlEditor.setSize(rowWidth-5, rowHeight); }else { this._notesHtmlEditor.setSize(rowWidth-10, rowHeight-25); } }; ZmApptEditView.prototype._getComponentsHeight = function(excludeNotes) { var components = [this._topContainer, document.getElementById(this._htmlElId + "_scheduler_option")]; if(!excludeNotes) components.push(this._notesContainer); var compSize; var compHeight= 10; //message label height for(var i=0; i<components.length; i++) { compSize= Dwt.getSize(components[i]); compHeight += compSize.y; } if(this._schedulerOpened) compHeight += this._scheduleView.getSize().y; return compHeight; }; ZmApptEditView.prototype.autoSize = function() { var size = Dwt.getSize(this.getHtmlElement()); mainTableSize = Dwt.getSize(this._mainTable); this.resize(mainTableSize.x, size.y); }; ZmApptEditView.prototype.resize = function(newWidth, newHeight) { if (!this._rendered) { return; } if (newHeight) { this.setSize(Dwt.DEFAULT, newHeight); } this._resizeNotes(); //this._scheduleAssistant.resizeTimeSuggestions(); //If scrollbar handle it // Sizing based on the internal table now. Scrolling bar will be external and accounted for already var size = Dwt.getSize(this.getHtmlElement()); var mainTableSize = Dwt.getSize(this._mainTable); var compHeight= this._getComponentsHeight(); if(compHeight > ( size.y + 5 )) { Dwt.setSize(this.getHtmlElement().firstChild, size.x-15); this._notesHtmlEditor.setSize(mainTableSize.x - 10); if(!this._scrollHandled){ Dwt.setScrollStyle(this.getHtmlElement(), Dwt.SCROLL_Y); this._scrollHandled = true; } }else{ if(this._scrollHandled){ Dwt.setScrollStyle(this.getHtmlElement(), Dwt.CLIP); Dwt.setSize(this.getHtmlElement().firstChild, size.x); this._notesHtmlEditor.setSize(mainTableSize.x - 10); } this._scrollHandled = false; } }; ZmApptEditView.prototype._initAttachContainer = function() { this._attachmentRow = document.getElementById(this._htmlElId + "_attachment_container"); this._attachmentRow.style.display=""; var cell = this._attachmentRow.insertCell(-1); cell.colSpan = 5; this._uploadFormId = Dwt.getNextId(); this._attachDivId = Dwt.getNextId(); var subs = { uploadFormId: this._uploadFormId, attachDivId: this._attachDivId, url: appCtxt.get(ZmSetting.CSFE_UPLOAD_URI)+"&fmt=extended" }; cell.innerHTML = AjxTemplate.expand("calendar.Appointment#AttachContainer", subs); }; // if user presses space or semicolon, add attendee ZmApptEditView.prototype._onAttendeesChange = function(ev) { var el = DwtUiEvent.getTarget(ev); // forward recipient is not an attendee var key = DwtKeyEvent.getCharCode(ev); var _nodeName = el.nodeName; if (_nodeName && _nodeName.toLowerCase() === "textarea") { this._adjustAddrHeight(el); } if (appCtxt.get(ZmSetting.CONTACTS_ENABLED) ){ ZmAutocompleteListView.onKeyUp(ev); } if (key == 32 || key == 59 || key == 186) { this.handleAttendeeChange(); }else { this.updateToolbarOps(); } if (el._attType == ZmCalBaseItem.LOCATION) { this._resetKnownLocation(); } }; ZmApptEditView.prototype.handleAttendeeChange = function(ev) { if (this._schedActionId) { AjxTimedAction.cancelAction(this._schedActionId); } this._schedActionId = AjxTimedAction.scheduleAction(new AjxTimedAction(this, this._handleAttendeeField, ZmCalBaseItem.PERSON), 300); }; ZmApptEditView.prototype._adjustAddrHeight = function(textarea) { if (this._useAcAddrBubbles || !textarea) { return; } if (textarea.value.length == 0) { textarea.style.height = "21px"; if (AjxEnv.isIE) { // for IE use overflow-y textarea.style.overflowY = "hidden"; } else { textarea.style.overflow = "hidden"; } return; } var sh = textarea.scrollHeight; if (sh > textarea.clientHeight) { var taHeight = parseInt(textarea.style.height) || 0; if (taHeight <= 65) { if (sh >= 65) { sh = 65; if (AjxEnv.isIE) textarea.style.overflowY = "scroll"; else textarea.style.overflow = "auto"; } textarea.style.height = sh + 13; } else { if (AjxEnv.isIE) { // for IE use overflow-y textarea.style.overflowY = "scroll"; } else { textarea.style.overflow = "auto"; } textarea.scrollTop = sh; } } }; ZmApptEditView.prototype.loadPreference = function() { var prefDlg = appCtxt.getSuggestionPreferenceDialog(); prefDlg.setCallback(new AjxCallback(this, this._prefChangeListener)); // Trigger an initial location check - the appt may have been saved // with a location that has conflicts. Need to do from here, so that // the user's numRecurrence preference is loaded var locationConflictCheckCallback = this.locationConflictChecker.bind(this); prefDlg.getSearchPreference(appCtxt.getActiveAccount(), locationConflictCheckCallback); }; ZmApptEditView.prototype._prefChangeListener = function() { // Preference Dialog is only displayed when the suggestions panel is visible - so update suggestions this._scheduleAssistant.clearResources(); this._scheduleAssistant.suggestAction(true); var newNumRecurrence = this.getNumLocationConflictRecurrence(); if (newNumRecurrence != this._scheduleAssistant.numRecurrence) { // Trigger Location Conflict test if enabled this.locationConflictChecker(); } }; // Show/Hide the conflict warning beneath the attendee and location input fields, and // color any attendee or location that conflicts with the current appointment time. If // the appointment is recurring, the conflict status and coloration only apply for the // current instance of the series. ZmApptEditView.prototype.showConflicts = function() { var conflictColor = "#F08080"; var color, isFree, type, addressElId, addressEl; var attendeeConflict = false; var locationConflict = false; var conflictEmails = this._scheduleView.getConflicts(); var orgEmail = this.getOrganizerEmail(); for (var email in conflictEmails) { type = this.parent.getAttendeeType(email); if ((type == ZmCalBaseItem.PERSON) || (type == ZmCalBaseItem.LOCATION)) { isFree = orgEmail == email ? true : conflictEmails[email]; if (!isFree) { // Record attendee or location conflict if (type == ZmCalBaseItem.PERSON) { attendeeConflict = true } else { locationConflict = true; } } if (!this._useAcAddrBubbles) { continue; } // Color the address bubble or reset to default color = isFree ? "" : conflictColor; addressElId = this._attInputField[type].getAddressBubble(email); if (addressElId) { addressEl = document.getElementById(addressElId); if (addressEl) { addressEl.style.backgroundColor = color; } } } } Dwt.setVisible(this._attendeeStatus, attendeeConflict); this.setLocationStatus(ZmApptEditView.LOCATION_STATUS_UNDEFINED, locationConflict); }
/** Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests. This guide is running against Jasmine version <span class="version">FILLED IN AT RUNTIME</span>. */ /** ## Standalone Distribution The [releases page](https://github.com/pivotal/jasmine/releases) has links to download the standalone distribution, which contains everything you need to start running Jasmine. After downloading a particular version and unzipping, opening `SpecRunner.html` will run the included specs. You'll note that both the source files and their respective specs are linked in the `<head>` of the `SpecRunner.html`. To start using Jasmine, replace the source/spec files with your own. */ /** ## Suites: `describe` Your Tests A test suite begins with a call to the global Jasmine function `describe` with two parameters: a string and a function. The string is a name or title for a spec suite - usually what is being tested. The function is a block of code that implements the suite. ## Specs Specs are defined by calling the global Jasmine function `it`, which, like `describe` takes a string and a function. The string is the title of the spec and the function is the spec, or test. A spec contains one or more expectations that test the state of the code. An expectation in Jasmine is an assertion that is either true or false. A spec with all true expectations is a passing spec. A spec with one or more false expectations is a failing spec. */ describe("A suite", function() { it("contains spec with an expectation", function() { expect(true).toBe(true); }); }); /** ### It's Just Functions Since `describe` and `it` blocks are functions, they can contain any executable code necessary to implement the test. JavaScript scoping rules apply, so variables declared in a `describe` are available to any `it` block inside the suite. */ describe("A suite is just a function", function() { var a; it("and so is a spec", function() { a = true; expect(a).toBe(true); }); }); /** ## Expectations Expectations are built with the function `expect` which takes a value, called the actual. It is chained with a Matcher function, which takes the expected value. */ describe("The 'toBe' matcher compares with ===", function() { /** ### Matchers Each matcher implements a boolean comparison between the actual value and the expected value. It is responsible for reporting to Jasmine if the expectation is true or false. Jasmine will then pass or fail the spec. */ it("and has a positive case", function() { expect(true).toBe(true); }); /** Any matcher can evaluate to a negative assertion by chaining the call to `expect` with a `not` before calling the matcher. */ it("and can have a negative case", function() { expect(false).not.toBe(true); }); }); /** ### Included Matchers Jasmine has a rich set of matchers included. Each is used here - all expectations and specs pass. There is also the ability to write [custom matchers](custom_matcher.html) for when a project's domain calls for specific assertions that are not included below. */ describe("Included matchers:", function() { it("The 'toBe' matcher compares with ===", function() { var a = 12; var b = a; expect(a).toBe(b); expect(a).not.toBe(null); }); describe("The 'toEqual' matcher", function() { it("works for simple literals and variables", function() { var a = 12; expect(a).toEqual(12); }); it("should work for objects", function() { var foo = { a: 12, b: 34 }; var bar = { a: 12, b: 34 }; expect(foo).toEqual(bar); }); }); it("The 'toMatch' matcher is for regular expressions", function() { var message = "foo bar baz"; expect(message).toMatch(/bar/); expect(message).toMatch("bar"); expect(message).not.toMatch(/quux/); }); it("The 'toBeDefined' matcher compares against `undefined`", function() { var a = { foo: "foo" }; expect(a.foo).toBeDefined(); expect(a.bar).not.toBeDefined(); }); it("The `toBeUndefined` matcher compares against `undefined`", function() { var a = { foo: "foo" }; expect(a.foo).not.toBeUndefined(); expect(a.bar).toBeUndefined(); }); it("The 'toBeNull' matcher compares against null", function() { var a = null; var foo = "foo"; expect(null).toBeNull(); expect(a).toBeNull(); expect(foo).not.toBeNull(); }); it("The 'toBeTruthy' matcher is for boolean casting testing", function() { var a, foo = "foo"; expect(foo).toBeTruthy(); expect(a).not.toBeTruthy(); }); it("The 'toBeFalsy' matcher is for boolean casting testing", function() { var a, foo = "foo"; expect(a).toBeFalsy(); expect(foo).not.toBeFalsy(); }); it("The 'toContain' matcher is for finding an item in an Array", function() { var a = ["foo", "bar", "baz"]; expect(a).toContain("bar"); expect(a).not.toContain("quux"); }); it("The 'toBeLessThan' matcher is for mathematical comparisons", function() { var pi = 3.1415926, e = 2.78; expect(e).toBeLessThan(pi); expect(pi).not.toBeLessThan(e); }); it("The 'toBeGreaterThan' matcher is for mathematical comparisons", function() { var pi = 3.1415926, e = 2.78; expect(pi).toBeGreaterThan(e); expect(e).not.toBeGreaterThan(pi); }); it("The 'toBeCloseTo' matcher is for precision math comparison", function() { var pi = 3.1415926, e = 2.78; expect(pi).not.toBeCloseTo(e, 2); expect(pi).toBeCloseTo(e, 0); }); it("The 'toThrow' matcher is for testing if a function throws an exception", function() { var foo = function() { return 1 + 2; }; var bar = function() { return a + 1; }; expect(foo).not.toThrow(); expect(bar).toThrow(); }); it("The 'toThrowError' matcher is for testing a specific thrown exception", function() { var foo = function() { throw new TypeError("foo bar baz"); }; expect(foo).toThrowError("foo bar baz"); expect(foo).toThrowError(/bar/); expect(foo).toThrowError(TypeError); expect(foo).toThrowError(TypeError, "foo bar baz"); }); }); /** ## Grouping Related Specs with `describe` The `describe` function is for grouping related specs. The string parameter is for naming the collection of specs, and will be concatenated with specs to make a spec's full name. This aids in finding specs in a large suite. If you name them well, your specs read as full sentences in traditional [BDD][bdd] style. [bdd]: http://en.wikipedia.org/wiki/Behavior-driven_development */ describe("A spec", function() { it("is just a function, so it can contain any code", function() { var foo = 0; foo += 1; expect(foo).toEqual(1); }); it("can have more than one expectation", function() { var foo = 0; foo += 1; expect(foo).toEqual(1); expect(true).toEqual(true); }); }); /** ### Setup and Teardown To help a test suite DRY up any duplicated setup and teardown code, Jasmine provides the global `beforeEach`, `afterEach`, `beforeAll`, and `afterAll` functions. */ /** As the name implies, the `beforeEach` function is called once before each spec in the `describe` is run, and the `afterEach` function is called once after each spec. * * Here is the same set of specs written a little differently. The variable under test is defined at the top-level scope -- the `describe` block -- and initialization code is moved into a `beforeEach` function. The `afterEach` function resets the variable before continuing. */ describe("A spec using beforeEach and afterEach", function() { var foo = 0; beforeEach(function() { foo += 1; }); afterEach(function() { foo = 0; }); it("is just a function, so it can contain any code", function() { expect(foo).toEqual(1); }); it("can have more than one expectation", function() { expect(foo).toEqual(1); expect(true).toEqual(true); }); }); /** The `beforeAll` function is called only once before all the specs in `describe` are run, and the `afterAll` function is called after all specs finish. These functions can be used to speed up test suites with expensive setup and teardown. * * * However, be careful using `beforeAll` and `afterAll`! Since they are not reset between specs, it is easy to accidentally leak state between your specs so that they erroneously pass or fail. */ describe("A spec using beforeAll and afterAll", function() { var foo; beforeAll(function() { foo = 1; }); afterAll(function() { foo = 0; }); it("sets the initial value of foo before specs run", function() { expect(foo).toEqual(1); foo += 1; }); it("does not reset foo between specs", function() { expect(foo).toEqual(2); }); }); /** ### The `this` keyword Another way to share variables between a `beforeEach`, `it`, and `afterEach` is through the `this` keyword. Each spec's `beforeEach`/`it`/`afterEach` has the `this` as the same empty object that is set back to empty for the next spec's `beforeEach`/`it`/`afterEach`. */ describe("A spec", function() { beforeEach(function() { this.foo = 0; }); it("can use the `this` to share state", function() { expect(this.foo).toEqual(0); this.bar = "test pollution?"; }); it("prevents test pollution by having an empty `this` created for the next spec", function() { expect(this.foo).toEqual(0); expect(this.bar).toBe(undefined); }); }); /** ### Nesting `describe` Blocks Calls to `describe` can be nested, with specs defined at any level. This allows a suite to be composed as a tree of functions. Before a spec is executed, Jasmine walks down the tree executing each `beforeEach` function in order. After the spec is executed, Jasmine walks through the `afterEach` functions similarly. */ describe("A spec", function() { var foo; beforeEach(function() { foo = 0; foo += 1; }); afterEach(function() { foo = 0; }); it("is just a function, so it can contain any code", function() { expect(foo).toEqual(1); }); it("can have more than one expectation", function() { expect(foo).toEqual(1); expect(true).toEqual(true); }); describe("nested inside a second describe", function() { var bar; beforeEach(function() { bar = 1; }); it("can reference both scopes as needed", function() { expect(foo).toEqual(bar); }); }); }); /** ## Disabling Suites Suites and specs can be disabled with the `xdescribe` and `xit` functions, respectively. These suites and any specs inside them are skipped when run and thus their results will not appear in the results. */ xdescribe("A spec", function() { var foo; beforeEach(function() { foo = 0; foo += 1; }); it("is just a function, so it can contain any code", function() { expect(foo).toEqual(1); }); }); /** ## Pending Specs Pending specs do not run, but their names will show up in the results as `pending`. */ describe("Pending specs", function() { /** Any spec declared with `xit` is marked as pending. */ xit("can be declared 'xit'", function() { expect(true).toBe(false); }); /** Any spec declared without a function body will also be marked pending in results. */ it("can be declared with 'it' but without a function"); /** And if you call the function `pending` anywhere in the spec body, no matter the expectations, the spec will be marked pending. * A string passed to `pending` will be treated as a reason and displayed when the suite finishes. */ it("can be declared by calling 'pending' in the spec body", function() { expect(true).toBe(false); pending('this is why it is pending'); }); }); /** ## Spies Jasmine has test double functions called spies. A spy can stub any function and tracks calls to it and all arguments. A spy only exists in the `describe` or `it` block it is defined, and will be removed after each spec. There are special matchers for interacting with spies. __This syntax has changed for Jasmine 2.0.__ The `toHaveBeenCalled` matcher will return true if the spy was called. The `toHaveBeenCalledWith` matcher will return true if the argument list matches any of the recorded calls to the spy. */ describe("A spy", function() { var foo, bar = null; beforeEach(function() { foo = { setBar: function(value) { bar = value; } }; spyOn(foo, 'setBar'); foo.setBar(123); foo.setBar(456, 'another param'); }); it("tracks that the spy was called", function() { expect(foo.setBar).toHaveBeenCalled(); }); it("tracks all the arguments of its calls", function() { expect(foo.setBar).toHaveBeenCalledWith(123); expect(foo.setBar).toHaveBeenCalledWith(456, 'another param'); }); it("stops all execution on a function", function() { expect(bar).toBeNull(); }); }); /** ### Spies: `and.callThrough` By chaining the spy with `and.callThrough`, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ describe("A spy, when configured to call through", function() { var foo, bar, fetchedBar; beforeEach(function() { foo = { setBar: function(value) { bar = value; }, getBar: function() { return bar; } }; spyOn(foo, 'getBar').and.callThrough(); foo.setBar(123); fetchedBar = foo.getBar(); }); it("tracks that the spy was called", function() { expect(foo.getBar).toHaveBeenCalled(); }); it("should not effect other functions", function() { expect(bar).toEqual(123); }); it("when called returns the requested value", function() { expect(fetchedBar).toEqual(123); }); }); /** ### Spies: `and.returnValue` By chaining the spy with `and.returnValue`, all calls to the function will return a specific value. */ describe("A spy, when configured to fake a return value", function() { var foo, bar, fetchedBar; beforeEach(function() { foo = { setBar: function(value) { bar = value; }, getBar: function() { return bar; } }; spyOn(foo, "getBar").and.returnValue(745); foo.setBar(123); fetchedBar = foo.getBar(); }); it("tracks that the spy was called", function() { expect(foo.getBar).toHaveBeenCalled(); }); it("should not effect other functions", function() { expect(bar).toEqual(123); }); it("when called returns the requested value", function() { expect(fetchedBar).toEqual(745); }); }); /** ### Spies: `and.callFake` By chaining the spy with `and.callFake`, all calls to the spy will delegate to the supplied function. */ describe("A spy, when configured with an alternate implementation", function() { var foo, bar, fetchedBar; beforeEach(function() { foo = { setBar: function(value) { bar = value; }, getBar: function() { return bar; } }; spyOn(foo, "getBar").and.callFake(function() { return 1001; }); foo.setBar(123); fetchedBar = foo.getBar(); }); it("tracks that the spy was called", function() { expect(foo.getBar).toHaveBeenCalled(); }); it("should not effect other functions", function() { expect(bar).toEqual(123); }); it("when called returns the requested value", function() { expect(fetchedBar).toEqual(1001); }); }); /** ### Spies: `and.throwError` By chaining the spy with `and.throwError`, all calls to the spy will `throw` the specified value as an error. */ describe("A spy, when configured to throw an error", function() { var foo, bar; beforeEach(function() { foo = { setBar: function(value) { bar = value; } }; spyOn(foo, "setBar").and.throwError("quux"); }); it("throws the value", function() { expect(function() { foo.setBar(123) }).toThrowError("quux"); }); }); /** ### Spies: `and.stub` When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with `and.stub`. */ describe("A spy", function() { var foo, bar = null; beforeEach(function() { foo = { setBar: function(value) { bar = value; } }; spyOn(foo, 'setBar').and.callThrough(); }); it("can call through and then stub in the same spec", function() { foo.setBar(123); expect(bar).toEqual(123); foo.setBar.and.stub(); bar = null; foo.setBar(123); expect(bar).toBe(null); }); }); /** ### Other tracking properties Every call to a spy is tracked and exposed on the `calls` property. */ describe("A spy", function() { var foo, bar = null; beforeEach(function() { foo = { setBar: function(value) { bar = value; } }; spyOn(foo, 'setBar'); }); /** * `.calls.any()`: returns `false` if the spy has not been called at all, and then `true` once at least one call happens. */ it("tracks if it was called at all", function() { expect(foo.setBar.calls.any()).toEqual(false); foo.setBar(); expect(foo.setBar.calls.any()).toEqual(true); }); /** * `.calls.count()`: returns the number of times the spy was called */ it("tracks the number of times it was called", function() { expect(foo.setBar.calls.count()).toEqual(0); foo.setBar(); foo.setBar(); expect(foo.setBar.calls.count()).toEqual(2); }); /** * `.calls.argsFor(index)`: returns the arguments passed to call number `index` */ it("tracks the arguments of each call", function() { foo.setBar(123); foo.setBar(456, "baz"); expect(foo.setBar.calls.argsFor(0)).toEqual([123]); expect(foo.setBar.calls.argsFor(1)).toEqual([456, "baz"]); }); /** * `.calls.allArgs()`: returns the arguments to all calls */ it("tracks the arguments of all calls", function() { foo.setBar(123); foo.setBar(456, "baz"); expect(foo.setBar.calls.allArgs()).toEqual([[123],[456, "baz"]]); }); /** * `.calls.all()`: returns the context (the `this`) and arguments passed all calls */ it("can provide the context and arguments to all calls", function() { foo.setBar(123); expect(foo.setBar.calls.all()).toEqual([{object: foo, args: [123], returnValue: undefined}]); }); /** * `.calls.mostRecent()`: returns the context (the `this`) and arguments for the most recent call */ it("has a shortcut to the most recent call", function() { foo.setBar(123); foo.setBar(456, "baz"); expect(foo.setBar.calls.mostRecent()).toEqual({object: foo, args: [456, "baz"], returnValue: undefined}); }); /** * `.calls.first()`: returns the context (the `this`) and arguments for the first call */ it("has a shortcut to the first call", function() { foo.setBar(123); foo.setBar(456, "baz"); expect(foo.setBar.calls.first()).toEqual({object: foo, args: [123], returnValue: undefined}); }); /** * When inspecting the return from `all()`, `mostRecent()` and `first()`, the `object` property is set to the value of `this` when the spy was called. */ it("tracks the context", function() { var spy = jasmine.createSpy('spy'); var baz = { fn: spy }; var quux = { fn: spy }; baz.fn(123); quux.fn(456); expect(spy.calls.first().object).toBe(baz); expect(spy.calls.mostRecent().object).toBe(quux); }); /** * `.calls.reset()`: clears all tracking for a spy */ it("can be reset", function() { foo.setBar(123); foo.setBar(456, "baz"); expect(foo.setBar.calls.any()).toBe(true); foo.setBar.calls.reset(); expect(foo.setBar.calls.any()).toBe(false); }); }); /** ### Spies: `createSpy` When there is not a function to spy on, `jasmine.createSpy` can create a "bare" spy. This spy acts as any other spy - tracking calls, arguments, etc. But there is no implementation behind it. Spies are JavaScript objects and can be used as such. */ describe("A spy, when created manually", function() { var whatAmI; beforeEach(function() { whatAmI = jasmine.createSpy('whatAmI'); whatAmI("I", "am", "a", "spy"); }); it("is named, which helps in error reporting", function() { expect(whatAmI.and.identity()).toEqual('whatAmI'); }); it("tracks that the spy was called", function() { expect(whatAmI).toHaveBeenCalled(); }); it("tracks its number of calls", function() { expect(whatAmI.calls.count()).toEqual(1); }); it("tracks all the arguments of its calls", function() { expect(whatAmI).toHaveBeenCalledWith("I", "am", "a", "spy"); }); it("allows access to the most recent call", function() { expect(whatAmI.calls.mostRecent().args[0]).toEqual("I"); }); }); /** ### Spies: `createSpyObj` In order to create a mock with multiple spies, use `jasmine.createSpyObj` and pass an array of strings. It returns an object that has a property for each string that is a spy. */ describe("Multiple spies, when created manually", function() { var tape; beforeEach(function() { tape = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']); tape.play(); tape.pause(); tape.rewind(0); }); it("creates spies for each requested function", function() { expect(tape.play).toBeDefined(); expect(tape.pause).toBeDefined(); expect(tape.stop).toBeDefined(); expect(tape.rewind).toBeDefined(); }); it("tracks that the spies were called", function() { expect(tape.play).toHaveBeenCalled(); expect(tape.pause).toHaveBeenCalled(); expect(tape.rewind).toHaveBeenCalled(); expect(tape.stop).not.toHaveBeenCalled(); }); it("tracks all the arguments of its calls", function() { expect(tape.rewind).toHaveBeenCalledWith(0); }); }); /** ## Matching Anything with `jasmine.any` `jasmine.any` takes a constructor or "class" name as an expected value. It returns `true` if the constructor matches the constructor of the actual value. */ describe("jasmine.any", function() { it("matches any value", function() { expect({}).toEqual(jasmine.any(Object)); expect(12).toEqual(jasmine.any(Number)); }); describe("when used with a spy", function() { it("is useful for comparing arguments", function() { var foo = jasmine.createSpy('foo'); foo(12, function() { return true; }); expect(foo).toHaveBeenCalledWith(jasmine.any(Number), jasmine.any(Function)); }); }); }); /** ## Matching existence with `jasmine.anything` `jasmine.anything` returns `true` if the actual value is not `null` or `undefined`. */ describe("jasmine.anything", function() { it("matches anything", function() { expect(1).toEqual(jasmine.anything()); }); describe("when used with a spy", function() { it("is useful when the argument can be ignored", function() { var foo = jasmine.createSpy('foo'); foo(12, function() { return false; }); expect(foo).toHaveBeenCalledWith(12, jasmine.anything()); }); }); }); /** ## Partial Matching with `jasmine.objectContaining` `jasmine.objectContaining` is for those times when an expectation only cares about certain key/value pairs in the actual. */ describe("jasmine.objectContaining", function() { var foo; beforeEach(function() { foo = { a: 1, b: 2, bar: "baz" }; }); it("matches objects with the expect key/value pairs", function() { expect(foo).toEqual(jasmine.objectContaining({ bar: "baz" })); expect(foo).not.toEqual(jasmine.objectContaining({ c: 37 })); }); describe("when used with a spy", function() { it("is useful for comparing arguments", function() { var callback = jasmine.createSpy('callback'); callback({ bar: "baz" }); expect(callback).toHaveBeenCalledWith(jasmine.objectContaining({ bar: "baz" })); expect(callback).not.toHaveBeenCalledWith(jasmine.objectContaining({ c: 37 })); }); }); }); /** ## Partial Array Matching with `jasmine.arrayContaining` `jasmine.arrayContaining` is for those times when an expectation only cares about some of the values in an array. */ describe("jasmine.arrayContaining", function() { var foo; beforeEach(function() { foo = [1, 2, 3, 4]; }); it("matches arrays with some of the values", function() { expect(foo).toEqual(jasmine.arrayContaining([3, 1])); expect(foo).not.toEqual(jasmine.arrayContaining([6])); }); describe("when used with a spy", function() { it("is useful when comparing arguments", function() { var callback = jasmine.createSpy('callback'); callback([1, 2, 3, 4]); expect(callback).toHaveBeenCalledWith(jasmine.arrayContaining([4, 2, 3])); expect(callback).not.toHaveBeenCalledWith(jasmine.arrayContaining([5, 2])); }); }); }); /** ## String Matching with `jasmine.stringMatching` `jasmine.stringMatching` is for when you don't want to match a string in a larger object exactly, or match a portion of a string in a spy expectation. */ describe('jasmine.stringMatching', function() { it("matches as a regexp", function() { expect({foo: 'bar'}).toEqual({foo: jasmine.stringMatching(/^bar$/)}); expect({foo: 'foobarbaz'}).toEqual({foo: jasmine.stringMatching('bar')}); }); describe("when used with a spy", function() { it("is useful for comparing arguments", function() { var callback = jasmine.createSpy('callback'); callback('foobarbaz'); expect(callback).toHaveBeenCalledWith(jasmine.stringMatching('bar')); expect(callback).not.toHaveBeenCalledWith(jasmine.stringMatching(/^bar$/)); }); }); }); /** ## Custom asymmetric equality tester When you need to check that something meets a certain criteria, without being strictly equal, you can also specify a custom asymmetric equality tester simply by providing an object that has an `asymmetricMatch` function. */ describe("custom asymmetry", function() { var tester = { asymmetricMatch: function(actual) { var secondValue = actual.split(',')[1]; return secondValue === 'bar'; } }; it("dives in deep", function() { expect("foo,bar,baz,quux").toEqual(tester); }); describe("when used with a spy", function() { it("is useful for comparing arguments", function() { var callback = jasmine.createSpy('callback'); callback('foo,bar,baz'); expect(callback).toHaveBeenCalledWith(tester); }); }); }); /** ## Jasmine Clock __This syntax has changed for Jasmine 2.0.__ The Jasmine Clock is available for testing time dependent code. */ describe("Manually ticking the Jasmine Clock", function() { var timerCallback; /** It is installed with a call to `jasmine.clock().install` in a spec or suite that needs to manipulate time. */ beforeEach(function() { timerCallback = jasmine.createSpy("timerCallback"); jasmine.clock().install(); }); /** Be sure to uninstall the clock after you are done to restore the original functions. */ afterEach(function() { jasmine.clock().uninstall(); }); /** ### Mocking the JavaScript Timeout Functions You can make `setTimeout` or `setInterval` synchronous executing the registered functions only once the clock is ticked forward in time. To execute registered functions, move time forward via the `jasmine.clock().tick` function, which takes a number of milliseconds. */ it("causes a timeout to be called synchronously", function() { setTimeout(function() { timerCallback(); }, 100); expect(timerCallback).not.toHaveBeenCalled(); jasmine.clock().tick(101); expect(timerCallback).toHaveBeenCalled(); }); it("causes an interval to be called synchronously", function() { setInterval(function() { timerCallback(); }, 100); expect(timerCallback).not.toHaveBeenCalled(); jasmine.clock().tick(101); expect(timerCallback.calls.count()).toEqual(1); jasmine.clock().tick(50); expect(timerCallback.calls.count()).toEqual(1); jasmine.clock().tick(50); expect(timerCallback.calls.count()).toEqual(2); }); /** ### Mocking the Date The Jasmine Clock can also be used to mock the current date. */ describe("Mocking the Date object", function(){ it("mocks the Date object and sets it to a given time", function() { var baseTime = new Date(2013, 9, 23); // If you do not provide a base time to `mockDate` it will use the current date. jasmine.clock().mockDate(baseTime); jasmine.clock().tick(50); expect(new Date().getTime()).toEqual(baseTime.getTime() + 50); }); }); }); /** ## Asynchronous Support __This syntax has changed for Jasmine 2.0.__ Jasmine also has support for running specs that require testing asynchronous operations. */ describe("Asynchronous specs", function() { var value; /** Calls to `beforeAll`, `afterAll`, `beforeEach`, `afterEach`, and `it` can take an optional single argument that should be called when the async work is complete. */ beforeEach(function(done) { setTimeout(function() { value = 0; done(); }, 1); }); /** This spec will not start until the `done` function is called in the call to `beforeEach` above. And this spec will not complete until its `done` is called. */ it("should support async execution of test preparation and expectations", function(done) { value++; expect(value).toBeGreaterThan(0); done(); }); /** By default jasmine will wait for 5 seconds for an asynchronous spec to finish before causing a timeout failure. If specific specs should fail faster or need more time this can be adjusted by passing a timeout value to `it`, etc. If the entire suite should have a different timeout, `jasmine.DEFAULT_TIMEOUT_INTERVAL` can be set globally, outside of any given `describe`. */ describe("long asynchronous specs", function() { beforeEach(function(done) { done(); }, 1000); it("takes a long time", function(done) { setTimeout(function() { done(); }, 9000); }, 10000); afterEach(function(done) { done(); }, 1000); }); }); // ## Downloads // // * The Standalone Release (available on the [releases page](https://github.com/pivotal/jasmine/releases)) is for simple, browser page, or console projects // * The [Jasmine Ruby Gem](http://github.com/pivotal/jasmine-gem) is for Rails, Ruby, or Ruby-friendly development // * [Other Environments](http://github.com/pivotal/jasmine/wiki) are supported as well // // ## Support // // * [Mailing list](http://groups.google.com/group/jasmine-js) at Google Groups - a great first stop to ask questions, propose features, or discuss pull requests // * [Report Issues](http://github.com/pivotal/jasmine/issues) at Github // * The [Backlog](http://www.pivotaltracker.com/projects/10606) lives at [Pivotal Tracker](http://www.pivotaltracker.com/) // * Follow [@JasmineBDD](http://twitter.com/jasminebdd) on Twitter // // ## Thanks // // _Running documentation inspired by [@mjackson](http://twitter.com/mjackson) and the 2012 [Fluent](http://fluentconf.com) Summit._
'use strict'; module.exports = function(grunt) { // Load the plugin that provides the "uglify" task. require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ clean: ['public'], copy: { main: { files: [ {expand: true, cwd: 'app/', src: ['**', '!**/*.jade', '!**/*.scss'], dest: 'public/', filter: 'isFile'} ] } }, jade: { compile: { options: { pretty: true }, files: [{expand: true, cwd: 'app/', src: ['**/*.jade', '!**/_*.jade'], dest: 'public/', ext: '.html'}] } }, sass: { options: { sourceMap: true }, dist: { files: { 'public/css/main.css': 'app/styles/main.scss' } } }, watch: { bower: { files: ['bower.json'], tasks: ['wiredep'] }, other: { files: ['app/**', '!app/**/*.jade', '!app/**/*.{sass,scss}'], tasks: ['copy'] }, jade: { files: ['app/**/*.jade'], tasks: ['jade'] }, sass: { files: ['app/styles/{,*/}*.{scss,sass}'], tasks: ['sass'] }, }, wiredep: { build: { src: ['public/**/*.html'] } }, autoprefixer: { options: { // Task-specific options go here. browsers: ['last 2 versions', 'ie 8', 'ie 9'], }, your_target: { // Target-specific file lists and/or options go here. }, single_file: { options: { // Target-specific options go here. }, src: 'public/css/main.css', dest: 'public/css/main.css' }, }, }); // Default task(s). grunt.registerTask('default', []); grunt.registerTask('build', ['clean', 'copy', 'jade', 'sass', 'wiredep']); grunt.registerTask('serve', ['build', 'watch']); grunt.registerTask('filter', ['autoprefixer']); };
version https://git-lfs.github.com/spec/v1 oid sha256:94e084030707f97baa42036ed63e49a447a6802c5fc3f01387dae1776f8f85bf size 134617
require('babel-register'); if (!process.env.NODE_ENV) { process.env.NODE_ENV = 'development'; } /* eslint-disable global-require */ if (process.env.NODE_ENV === 'development') { module.exports = require('./development'); } else { module.exports = require('./production'); } /* eslint-enable global-require */
createRuntime(__filename).then(runtime => { let exports = runtime.requireMock(runtime.__mockRootPath, "ManuallyMocked"); exports.setModuleStateValue("test value"); exports = runtime.requireMock(runtime.__mockRootPath, "ManuallyMocked"); expect(exports.getModuleStateValue()).toBe("test value"); });
// Copyright Joyent, Inc. and other Node contributors. // // 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. // Note: In 0.8 and before, crypto functions all defaulted to using // binary-encoded strings rather than buffers. exports.DEFAULT_ENCODING = 'buffer'; try { var binding = process.binding('crypto'); var randomBytes = binding.randomBytes; var pseudoRandomBytes = binding.pseudoRandomBytes; var getCiphers = binding.getCiphers; var getHashes = binding.getHashes; } catch (e) { throw new Error('node.js not compiled with openssl crypto support.'); } var constants = require('constants'); var stream = require('stream'); var util = require('util'); var DH_GENERATOR = 2; // This is here because many functions accepted binary strings without // any explicit encoding in older versions of node, and we don't want // to break them unnecessarily. function toBuf(str, encoding) { encoding = encoding || 'binary'; if (util.isString(str)) { if (encoding === 'buffer') encoding = 'binary'; str = new Buffer(str, encoding); } return str; } exports._toBuf = toBuf; var assert = require('assert'); var StringDecoder = require('string_decoder').StringDecoder; function LazyTransform(options) { this._options = options; } util.inherits(LazyTransform, stream.Transform); [ '_readableState', '_writableState', '_transformState' ].forEach(function(prop, i, props) { Object.defineProperty(LazyTransform.prototype, prop, { get: function() { stream.Transform.call(this, this._options); this._writableState.decodeStrings = false; this._writableState.defaultEncoding = 'binary'; return this[prop]; }, set: function(val) { Object.defineProperty(this, prop, { value: val, enumerable: true, configurable: true, writable: true }); }, configurable: true, enumerable: true }); }); exports.createHash = exports.Hash = Hash; function Hash(algorithm, options) { if (!(this instanceof Hash)) return new Hash(algorithm, options); this._handle = new binding.Hash(algorithm); LazyTransform.call(this, options); } util.inherits(Hash, LazyTransform); Hash.prototype._transform = function(chunk, encoding, callback) { this._handle.update(chunk, encoding); callback(); }; Hash.prototype._flush = function(callback) { var encoding = this._readableState.encoding || 'buffer'; this.push(this._handle.digest(encoding), encoding); callback(); }; Hash.prototype.update = function(data, encoding) { encoding = encoding || exports.DEFAULT_ENCODING; if (encoding === 'buffer' && util.isString(data)) encoding = 'binary'; this._handle.update(data, encoding); return this; }; Hash.prototype.digest = function(outputEncoding) { outputEncoding = outputEncoding || exports.DEFAULT_ENCODING; return this._handle.digest(outputEncoding); }; exports.createHmac = exports.Hmac = Hmac; function Hmac(hmac, key, options) { if (!(this instanceof Hmac)) return new Hmac(hmac, key, options); this._handle = new binding.Hmac(); this._handle.init(hmac, toBuf(key)); LazyTransform.call(this, options); } util.inherits(Hmac, LazyTransform); Hmac.prototype.update = Hash.prototype.update; Hmac.prototype.digest = Hash.prototype.digest; Hmac.prototype._flush = Hash.prototype._flush; Hmac.prototype._transform = Hash.prototype._transform; function getDecoder(decoder, encoding) { if (encoding === 'utf-8') encoding = 'utf8'; // Normalize encoding. decoder = decoder || new StringDecoder(encoding); assert(decoder.encoding === encoding, 'Cannot change encoding'); return decoder; } exports.createCipher = exports.Cipher = Cipher; function Cipher(cipher, password, options) { if (!(this instanceof Cipher)) return new Cipher(cipher, password, options); this._handle = new binding.CipherBase(true); this._handle.init(cipher, toBuf(password)); this._decoder = null; LazyTransform.call(this, options); } util.inherits(Cipher, LazyTransform); Cipher.prototype._transform = function(chunk, encoding, callback) { this.push(this._handle.update(chunk, encoding)); callback(); }; Cipher.prototype._flush = function(callback) { try { this.push(this._handle.final()); } catch (e) { callback(e); return; } callback(); }; Cipher.prototype.update = function(data, inputEncoding, outputEncoding) { inputEncoding = inputEncoding || exports.DEFAULT_ENCODING; outputEncoding = outputEncoding || exports.DEFAULT_ENCODING; var ret = this._handle.update(data, inputEncoding); if (outputEncoding && outputEncoding !== 'buffer') { this._decoder = getDecoder(this._decoder, outputEncoding); ret = this._decoder.write(ret); } return ret; }; Cipher.prototype.final = function(outputEncoding) { outputEncoding = outputEncoding || exports.DEFAULT_ENCODING; var ret = this._handle.final(); if (outputEncoding && outputEncoding !== 'buffer') { this._decoder = getDecoder(this._decoder, outputEncoding); ret = this._decoder.end(ret); } return ret; }; Cipher.prototype.setAutoPadding = function(ap) { this._handle.setAutoPadding(ap); return this; }; exports.createCipheriv = exports.Cipheriv = Cipheriv; function Cipheriv(cipher, key, iv, options) { if (!(this instanceof Cipheriv)) return new Cipheriv(cipher, key, iv, options); this._handle = new binding.CipherBase(true); this._handle.initiv(cipher, toBuf(key), toBuf(iv)); this._decoder = null; LazyTransform.call(this, options); } util.inherits(Cipheriv, LazyTransform); Cipheriv.prototype._transform = Cipher.prototype._transform; Cipheriv.prototype._flush = Cipher.prototype._flush; Cipheriv.prototype.update = Cipher.prototype.update; Cipheriv.prototype.final = Cipher.prototype.final; Cipheriv.prototype.setAutoPadding = Cipher.prototype.setAutoPadding; Cipheriv.prototype.getAuthTag = function() { return this._handle.getAuthTag(); }; Cipheriv.prototype.setAuthTag = function(tagbuf) { this._handle.setAuthTag(tagbuf); }; Cipheriv.prototype.setAAD = function(aadbuf) { this._handle.setAAD(aadbuf); }; exports.createDecipher = exports.Decipher = Decipher; function Decipher(cipher, password, options) { if (!(this instanceof Decipher)) return new Decipher(cipher, password, options); this._handle = new binding.CipherBase(false); this._handle.init(cipher, toBuf(password)); this._decoder = null; LazyTransform.call(this, options); } util.inherits(Decipher, LazyTransform); Decipher.prototype._transform = Cipher.prototype._transform; Decipher.prototype._flush = Cipher.prototype._flush; Decipher.prototype.update = Cipher.prototype.update; Decipher.prototype.final = Cipher.prototype.final; Decipher.prototype.finaltol = Cipher.prototype.final; Decipher.prototype.setAutoPadding = Cipher.prototype.setAutoPadding; exports.createDecipheriv = exports.Decipheriv = Decipheriv; function Decipheriv(cipher, key, iv, options) { if (!(this instanceof Decipheriv)) return new Decipheriv(cipher, key, iv, options); this._handle = new binding.CipherBase(false); this._handle.initiv(cipher, toBuf(key), toBuf(iv)); this._decoder = null; LazyTransform.call(this, options); } util.inherits(Decipheriv, LazyTransform); Decipheriv.prototype._transform = Cipher.prototype._transform; Decipheriv.prototype._flush = Cipher.prototype._flush; Decipheriv.prototype.update = Cipher.prototype.update; Decipheriv.prototype.final = Cipher.prototype.final; Decipheriv.prototype.finaltol = Cipher.prototype.final; Decipheriv.prototype.setAutoPadding = Cipher.prototype.setAutoPadding; Decipheriv.prototype.getAuthTag = Cipheriv.prototype.getAuthTag; Decipheriv.prototype.setAuthTag = Cipheriv.prototype.setAuthTag; Decipheriv.prototype.setAAD = Cipheriv.prototype.setAAD; exports.createSign = exports.Sign = Sign; function Sign(algorithm, options) { if (!(this instanceof Sign)) return new Sign(algorithm, options); this._handle = new binding.Sign(); this._handle.init(algorithm); stream.Writable.call(this, options); } util.inherits(Sign, stream.Writable); Sign.prototype._write = function(chunk, encoding, callback) { this._handle.update(chunk, encoding); callback(); }; Sign.prototype.update = Hash.prototype.update; Sign.prototype.sign = function(options, encoding) { if (!options) throw new Error('No key provided to sign'); var key = options.key || options; var passphrase = options.passphrase || null; var ret = this._handle.sign(toBuf(key), null, passphrase); encoding = encoding || exports.DEFAULT_ENCODING; if (encoding && encoding !== 'buffer') ret = ret.toString(encoding); return ret; }; exports.createVerify = exports.Verify = Verify; function Verify(algorithm, options) { if (!(this instanceof Verify)) return new Verify(algorithm, options); this._handle = new binding.Verify; this._handle.init(algorithm); stream.Writable.call(this, options); } util.inherits(Verify, stream.Writable); Verify.prototype._write = Sign.prototype._write; Verify.prototype.update = Sign.prototype.update; Verify.prototype.verify = function(object, signature, sigEncoding) { sigEncoding = sigEncoding || exports.DEFAULT_ENCODING; return this._handle.verify(toBuf(object), toBuf(signature, sigEncoding)); }; exports.createDiffieHellman = exports.DiffieHellman = DiffieHellman; function DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) { if (!(this instanceof DiffieHellman)) return new DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding); if (keyEncoding) { if (typeof keyEncoding !== 'string' || (!Buffer.isEncoding(keyEncoding) && keyEncoding !== 'buffer')) { genEncoding = generator; generator = keyEncoding; keyEncoding = false; } } keyEncoding = keyEncoding || exports.DEFAULT_ENCODING; genEncoding = genEncoding || exports.DEFAULT_ENCODING; if (typeof sizeOrKey !== 'number') sizeOrKey = toBuf(sizeOrKey, keyEncoding); if (!generator) generator = DH_GENERATOR; else if (typeof generator !== 'number') generator = toBuf(generator, genEncoding); this._handle = new binding.DiffieHellman(sizeOrKey, generator); Object.defineProperty(this, 'verifyError', { enumerable: true, value: this._handle.verifyError, writable: false }); } exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = DiffieHellmanGroup; function DiffieHellmanGroup(name) { if (!(this instanceof DiffieHellmanGroup)) return new DiffieHellmanGroup(name); this._handle = new binding.DiffieHellmanGroup(name); Object.defineProperty(this, 'verifyError', { enumerable: true, value: this._handle.verifyError, writable: false }); } DiffieHellmanGroup.prototype.generateKeys = DiffieHellman.prototype.generateKeys = dhGenerateKeys; function dhGenerateKeys(encoding) { var keys = this._handle.generateKeys(); encoding = encoding || exports.DEFAULT_ENCODING; if (encoding && encoding !== 'buffer') keys = keys.toString(encoding); return keys; } DiffieHellmanGroup.prototype.computeSecret = DiffieHellman.prototype.computeSecret = dhComputeSecret; function dhComputeSecret(key, inEnc, outEnc) { inEnc = inEnc || exports.DEFAULT_ENCODING; outEnc = outEnc || exports.DEFAULT_ENCODING; var ret = this._handle.computeSecret(toBuf(key, inEnc)); if (outEnc && outEnc !== 'buffer') ret = ret.toString(outEnc); return ret; } DiffieHellmanGroup.prototype.getPrime = DiffieHellman.prototype.getPrime = dhGetPrime; function dhGetPrime(encoding) { var prime = this._handle.getPrime(); encoding = encoding || exports.DEFAULT_ENCODING; if (encoding && encoding !== 'buffer') prime = prime.toString(encoding); return prime; } DiffieHellmanGroup.prototype.getGenerator = DiffieHellman.prototype.getGenerator = dhGetGenerator; function dhGetGenerator(encoding) { var generator = this._handle.getGenerator(); encoding = encoding || exports.DEFAULT_ENCODING; if (encoding && encoding !== 'buffer') generator = generator.toString(encoding); return generator; } DiffieHellmanGroup.prototype.getPublicKey = DiffieHellman.prototype.getPublicKey = dhGetPublicKey; function dhGetPublicKey(encoding) { var key = this._handle.getPublicKey(); encoding = encoding || exports.DEFAULT_ENCODING; if (encoding && encoding !== 'buffer') key = key.toString(encoding); return key; } DiffieHellmanGroup.prototype.getPrivateKey = DiffieHellman.prototype.getPrivateKey = dhGetPrivateKey; function dhGetPrivateKey(encoding) { var key = this._handle.getPrivateKey(); encoding = encoding || exports.DEFAULT_ENCODING; if (encoding && encoding !== 'buffer') key = key.toString(encoding); return key; } DiffieHellman.prototype.setPublicKey = function(key, encoding) { encoding = encoding || exports.DEFAULT_ENCODING; this._handle.setPublicKey(toBuf(key, encoding)); return this; }; DiffieHellman.prototype.setPrivateKey = function(key, encoding) { encoding = encoding || exports.DEFAULT_ENCODING; this._handle.setPrivateKey(toBuf(key, encoding)); return this; }; exports.pbkdf2 = function(password, salt, iterations, keylen, digest, callback) { if (util.isFunction(digest)) { callback = digest; digest = undefined; } if (!util.isFunction(callback)) throw new Error('No callback provided to pbkdf2'); return pbkdf2(password, salt, iterations, keylen, digest, callback); }; exports.pbkdf2Sync = function(password, salt, iterations, keylen, digest) { return pbkdf2(password, salt, iterations, keylen, digest); }; function pbkdf2(password, salt, iterations, keylen, digest, callback) { password = toBuf(password); salt = toBuf(salt); if (exports.DEFAULT_ENCODING === 'buffer') return binding.PBKDF2(password, salt, iterations, keylen, digest, callback); // at this point, we need to handle encodings. var encoding = exports.DEFAULT_ENCODING; if (callback) { function next(er, ret) { if (ret) ret = ret.toString(encoding); callback(er, ret); } binding.PBKDF2(password, salt, iterations, keylen, digest, next); } else { var ret = binding.PBKDF2(password, salt, iterations, keylen, digest); return ret.toString(encoding); } } exports.Certificate = Certificate; function Certificate() { if (!(this instanceof Certificate)) return new Certificate(); this._handle = new binding.Certificate(); } Certificate.prototype.verifySpkac = function(object) { return this._handle.verifySpkac(object); }; Certificate.prototype.exportPublicKey = function(object, encoding) { return this._handle.exportPublicKey(toBuf(object, encoding)); }; Certificate.prototype.exportChallenge = function(object, encoding) { return this._handle.exportChallenge(toBuf(object, encoding)); }; exports.setEngine = function setEngine(id, flags) { if (!util.isString(id)) throw new TypeError('id should be a string'); if (flags && !util.isNumber(flags)) throw new TypeError('flags should be a number, if present'); flags = flags >>> 0; // Use provided engine for everything by default if (flags === 0) flags = constants.ENGINE_METHOD_ALL; return binding.setEngine(id, flags); }; exports.randomBytes = randomBytes; exports.pseudoRandomBytes = pseudoRandomBytes; exports.rng = randomBytes; exports.prng = pseudoRandomBytes; exports.getCiphers = function() { return filterDuplicates(getCiphers.call(null, arguments)); }; exports.getHashes = function() { return filterDuplicates(getHashes.call(null, arguments)); }; function filterDuplicates(names) { // Drop all-caps names in favor of their lowercase aliases, // for example, 'sha1' instead of 'SHA1'. var ctx = {}; names.forEach(function(name) { var key = name; if (/^[0-9A-Z\-]+$/.test(key)) key = key.toLowerCase(); if (!ctx.hasOwnProperty(key) || ctx[key] < name) ctx[key] = name; }); return Object.getOwnPropertyNames(ctx).map(function(key) { return ctx[key]; }).sort(); } // Legacy API exports.__defineGetter__('createCredentials', util.deprecate(function() { return require('tls').createSecureContext; }, 'createCredentials() is deprecated, use tls.createSecureContext instead')); exports.__defineGetter__('Credentials', util.deprecate(function() { return require('tls').SecureContext; }, 'Credentials is deprecated, use tls.createSecureContext instead'));
var synthUI = function() { var synthContext = new webkitAudioContext(); var noteFreqs = [261.63, 293.66, 329.63, 349.23, 392.00]; var keyboardKeys = ['a', 's', 'd', 'f', 'g']; var notes = {}; for (var i = 0; i < keyboardKeys.length; i++) { notes[noteFreqs[i]] = {}; notes[noteFreqs[i]].key = keyboardKeys[i]; notes[noteFreqs[i]].pressed = false; notes[noteFreqs[i]].idx = i + 1; } var oscillators = {}; var playNote = function(freq) { var oscillator, noteIndex; if (notes[freq].pressed || oscillators[freq]) { // oscillator.stop(0); return; } else { console.log("playing a note"); noteIndex = notes[freq].idx; oscillator = synthContext.createOscillator(); gainNode = synthContext.createGainNode(); oscillator.type = 'triangle'; oscillator.connect(gainNode); oscillator.frequency.value = freq || 261.63; gainNode.connect(synthContext.destination); oscillator.start(0); d3.selectAll("circle").filter(":nth-child(" + noteIndex + ")").classed("playing", true) setTimeout(3000, function() { oscillator.stop(0); }) notes[freq].pressed = true; oscillators[freq] = oscillator; console.log(oscillators); } } var endNote = function(freq) { if (oscillators[freq]) { var oscillator = oscillators[freq]; var noteIndex = notes[freq].idx; oscillator.stop(0); oscillator.disconnect(); oscillators[freq] = null; notes[freq].pressed = false; d3.selectAll("circle").filter(":nth-child(" + noteIndex + ")").classed("playing", false); } } // d3.selectAll("circle").filter(":nth-child(3)").classed("playing", true) // d3.selectAll("circle").filter(":nth-child(3)").classed("playing", false) //play one note on keypress //stop on keyup // KeyboardJS.on('a', function() { // _.once(function(){ // console.log('you pressed a!'); // playNote(); // })(); // }, function() { // console.log('you released a!'); // endNote(); // }); var setKeyCtrl = function(key, index) { var freq = noteFreqs[index]; KeyboardJS.on(key, function() { _.once(function(){ console.log('you pressed' + key); playNote(freq); })(); }, function() { console.log('you released' + key); endNote(freq); }); } _.each(keyboardKeys, setKeyCtrl); var synthkeys = [], oscillator, gainNode, boardWidth = 400, boardHeight = 400; for (var i = 0; i < 5; i++){ synthkeys.push({"cx": 20*i + 10, "cy": 10*i + 10, 'r': 10, 'note': keyboardKeys[i], 'playing' : false }); }; d3.select(".synth") .append("svg") .attr("width", boardWidth) .attr("height", boardHeight) .append('g') .selectAll('circle') .data(synthkeys) .enter().append("circle").attr("class", "synthkey") .attr("r", function(d){return d.r;}) .attr("cx", function(d){return d["cx"];}) .attr("cy", function(d){return d["cy"];}) .attr("note", function(d){return d["note"];}); }(); var drumUI = function () { console.log("drumdrumdrum"); var sine1 = T("sin", {freq:140, mul:0.9}); var sine2 = T("sin", {freq:220, mul:0.5}); d3.select(".drum") .append("svg") .attr("width", 200) .attr("height", 200) .append('g') .selectAll('circle') .enter().append("circle").attr("class", "drum") .attr("r", 40) .attr("cx", 100) .attr("cy", 100) var playDrum = function() { T("perc", {r:500}, sine1, sine2).on("ended", function() { this.pause(); }).bang().play(); } KeyboardJS.on('x', playDrum); }
var map = L.map('map').setView([33.9, -68.2], 3); L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' + '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="http://mapbox.com">Mapbox</a>', id: 'examples.map-i875mjb7' }).addTo(map); // L.marker([33.786, -118.265]).addTo(map) // .bindPopup("<b>Los Angeles, California</b><br /> Born.").openPopup(); L.marker([3.75, 8.788]).addTo(map) .bindPopup("<b>Malabo, Equitorial Guinea</b><br /> Wireline Field Engineer").openPopup(); L.marker([70.2, -148.46]).addTo(map) .bindPopup("<b>Prudhoe Bay, Alaska</b><br /> Wireline Field Engineer").openPopup(); L.marker([61.197, -149.838]).addTo(map) .bindPopup("<b>Anchorage, Alaska</b><br /> Wireline Field Engineer").openPopup(); L.marker([29.96, -90.068]).addTo(map) .bindPopup("<b>Houma, Louisiana</b><br /> Wireline Field Engineer").openPopup(); L.marker([48.8, 2.257]).addTo(map) .bindPopup("<b>Paris, France</b><br /> Well Integrity Train-the-Trainer").openPopup(); L.marker([52.457, 4.606]).addTo(map) .bindPopup("<b>Ijmuiden, Netherlands</b><br /> Well Integrity Training").openPopup(); L.marker([29.626, -95.610]).addTo(map) .bindPopup("<b>Sugar Land, Texas</b><br /> InTouch Engineer").openPopup(); L.marker([60.398, 5.3097]).addTo(map) .bindPopup("<b>Bergen, Norway</b><br /> Field Quality Champion").openPopup(); L.marker([10.452, -66.859]).addTo(map) .bindPopup("<b>Caracas, Venezuela</b><br /> Teenager").openPopup(); L.marker([34.439, -118.125]).addTo(map) .bindPopup("<b>Pasadena, California</b><br /> Caltech BS Geology 2003").openPopup(); L.marker([37.774, -122.419]).addTo(map) .bindPopup("<b>San Francisco, California</b><br /> Here!").openPopup(); // Samples // L.circle([51.508, -0.11], 500, { // color: 'red', // fillColor: '#f03', // fillOpacity: 0.5 // }).addTo(map).bindPopup("I am a circle."); // L.polygon([ // [51.509, -0.08], // [51.503, -0.06], // [51.51, -0.047] // ]).addTo(map).bindPopup("I am a polygon."); //Creating icon classes var redCircle = L.icon({ }); L.circle([51.508, -0.11], 500, { color: 'red', fillColor: '#f03', fillOpacity: 0.5 }).addTo(map).bindPopup("I am a circle."); var popup = L.popup(); function onMapClick(e) { popup .setLatLng(e.latlng) .setContent("You clicked the map at " + e.latlng.toString()) .openOn(map); } map.on('click', onMapClick);
/** * AuthController * * @description :: Server-side logic for managing user authorizations * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ var passport = require('passport'); /** * Triggers when user authenticates via passport * @param {Object} req Request object * @param {Object} res Response object * @param {Object} error Error object * @param {Object} user User profile * @param {Object} info Info if some error occurs * @private */ function _onPassportAuth(req, res, error, user, info) { if (error) { return res.serverError(error); } if (!user) { sails.log.debug('Authentication error (' + req.method + ' ' + req.path + '): ' + info.message); return res.unauthorized({ status: 401, code: 'E_WRONG_CREDENTIALS', message: 'Missing or wrong credentials.' }); } sails.log.debug('Authentication successful for user `' + user.email + '`.'); return res.ok({ token: CipherService.createToken(user), user: user }); } module.exports = { /** * Log in by local strategy in passport * @param {Object} req Request object * @param {Object} res Response object */ login: function (req, res) { passport.authenticate('local', _onPassportAuth.bind(this, req, res))(req, res); } };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _amazon_transformer = require('./amazon_transformer'); var _amazon_transformer2 = _interopRequireDefault(_amazon_transformer); var _noop_transformer = require('./noop_transformer'); var _noop_transformer2 = _interopRequireDefault(_noop_transformer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var transformers = { 'amazon': _amazon_transformer2.default }; var AffiliateManager = function () { function AffiliateManager() { _classCallCheck(this, AffiliateManager); this.affiliates = { noop: new _noop_transformer2.default() }; } _createClass(AffiliateManager, [{ key: 'addAffiliate', value: function addAffiliate(affiliateName) { for (var _len = arguments.length, affiliateInformation = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { affiliateInformation[_key - 1] = arguments[_key]; } this.affiliates[affiliateName] = new (Function.prototype.bind.apply(transformers[affiliateName], [null].concat(affiliateInformation)))(); } }, { key: 'getAffiliateForLink', value: function getAffiliateForLink(link) { if (link.match(/^.*amazon.com.*/g) && this.affiliates['amazon']) return 'amazon';else return 'noop'; } }, { key: 'transformLink', value: function transformLink(link) { var affiliate = this.getAffiliateForLink(link); return this.affiliates[this.getAffiliateForLink(link)].transform(link); } }]); return AffiliateManager; }(); exports.default = AffiliateManager; //# sourceMappingURL=affiliate_manager.js.map
var moduleFiles = require('module')._files; var mockfs = require('./mockfs'); var files = {}; for (var filename in moduleFiles) { files[filename] = { type: 'file', isModule: true, content: moduleFiles[filename] } } module.exports = new mockfs(files);
'use strict'; var passport = require('passport'), User = require('mongoose').model('User'), path = require('path'), config = require('./config'); module.exports = function() { // Serialize sessions passport.serializeUser(function(user, done) { done(null, user.id); }); // Deserialize sessions passport.deserializeUser(function(id, done) { User.findOne({ _id: id }, '-salt -password', function(err, user) { done(err, user); }); }); // Initialize strategies config.getGlobbedFiles('./config/strategies/**/*.js').forEach(function(strategy) { require(path.resolve(strategy))(); }); };
var searchData= [ ['quadapp',['QuadApp',['../classQuadApp.html',1,'']]] ];
'use strict'; var Dependency = require('webpack/lib/Dependency'); function RunnerEntryDependency(dependencies, name, type) { Dependency.call(this); this.dependencies = dependencies; this.name = name; this.type = type; } RunnerEntryDependency.prototype = Object.create(Dependency.prototype); RunnerEntryDependency.prototype.constructor = RunnerEntryDependency; RunnerEntryDependency.prototype.type = 'runner entry'; module.exports = RunnerEntryDependency;
var path = require('path'); var autoprefixer = require('autoprefixer'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var ManifestPlugin = require('webpack-manifest-plugin'); var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); var url = require('url'); var paths = require('./paths'); var getClientEnvironment = require('./env'); function ensureSlash(path, needsSlash) { var hasSlash = path.endsWith('/'); if (hasSlash && !needsSlash) { return path.substr(path, path.length - 1); } else if (!hasSlash && needsSlash) { return path + '/'; } else { return path; } } // We use "homepage" field to infer "public path" at which the app is served. // Webpack needs to know it to put the right <script> hrefs into HTML even in // single-page apps that may serve index.html for nested URLs like /todos/42. // We can't use a relative path in HTML because we don't want to load something // like /todos/42/static/js/bundle.7289d.js. We have to know the root. var homepagePath = require(paths.appPackageJson).homepage; var homepagePathname = homepagePath ? url.parse(homepagePath).pathname : '/'; // Webpack uses `publicPath` to determine where the app is being served from. // It requires a trailing slash, or the file assets will get an incorrect path. var publicPath = ensureSlash(homepagePathname, true); // `publicUrl` is just like `publicPath`, but we will provide it to our app // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz. var publicUrl = ensureSlash(homepagePathname, false); // Get environment variables to inject into our app. var env = getClientEnvironment(publicUrl); // Assert this just to be safe. // Development builds of React are slow and not intended for production. if (env['process.env'].NODE_ENV !== '"production"') { throw new Error('Production builds must have NODE_ENV=production.'); } // This is the production configuration. // It compiles slowly and is focused on producing a fast and minimal bundle. // The development configuration is different and lives in a separate file. module.exports = { // Don't attempt to continue if there are any errors. bail: true, // We generate sourcemaps in production. This is slow but gives good results. // You can exclude the *.map files from the build during deployment. devtool: 'source-map', // In production, we only want to load the polyfills and the app code. entry: ["react-c3-component", "c3", "d3"], }, output: { // The build folder. path: paths.appBuild, // Generated JS file names (with nested folders). // There will be one main bundle, and one file per asynchronous chunk. // We don't currently advertise code splitting but Webpack supports it. filename: 'static/js/[name].[chunkhash:8].js', chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js', // We inferred the "public path" (such as / or /my-project) from homepage. publicPath: publicPath }, resolve: { // This allows you to set a fallback for where Webpack should look for modules. // We read `NODE_PATH` environment variable in `paths.js` and pass paths here. // We use `fallback` instead of `root` because we want `node_modules` to "win" // if there any conflicts. This matches Node resolution mechanism. // https://github.com/facebookincubator/create-react-app/issues/253 fallback: paths.nodePaths, // These are the reasonable defaults supported by the Node ecosystem. // We also include JSX as a common component filename extension to support // some tools, although we do not recommend using it, see: // https://github.com/facebookincubator/create-react-app/issues/290 extensions: ['.js', '.json', '.jsx', ''], alias: { // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 'react-native': 'react-native-web' } }, module: { // First, run the linter. // It's important to do this before Babel processes the JS. preLoaders: [ { test: /\.(js|jsx)$/, loader: 'eslint', include: paths.appSrc } ], loaders: [ // Process JS with Babel. { test: /\.(js|jsx)$/, include: paths.appSrc, loader: 'babel', }, // The notation here is somewhat confusing. // "postcss" loader applies autoprefixer to our CSS. // "css" loader resolves paths in CSS and adds assets as dependencies. // "style" loader normally turns CSS into JS modules injecting <style>, // but unlike in development configuration, we do something different. // `ExtractTextPlugin` first applies the "postcss" and "css" loaders // (second argument), then grabs the result CSS and puts it into a // separate file in our build process. This way we actually ship // a single CSS file in production instead of JS code injecting <style> // tags. If you use code splitting, however, any async bundles will still // use the "style" loader inside the async code so CSS from them won't be // in the main CSS file. { test: /\.css$/, // "?-autoprefixer" disables autoprefixer in css-loader itself: // https://github.com/webpack/css-loader/issues/281 // We already have it thanks to postcss. We only pass this flag in // production because "css" loader only enables autoprefixer-powered // removal of unnecessary prefixes when Uglify plugin is enabled. // Webpack 1.x uses Uglify plugin as a signal to minify *all* the assets // including CSS. This is confusing and will be removed in Webpack 2: // https://github.com/webpack/webpack/issues/283 loader: ExtractTextPlugin.extract('style', 'css?importLoaders=1&-autoprefixer!postcss') // Note: this won't work without `new ExtractTextPlugin()` in `plugins`. }, // JSON is not enabled by default in Webpack but both Node and Browserify // allow it implicitly so we also enable it. { test: /\.json$/, loader: 'json' }, // "file" loader makes sure those assets end up in the `build` folder. // When you `import` an asset, you get its filename. { test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/, loader: 'file', query: { name: 'static/media/[name].[hash:8].[ext]' } }, // "url" loader works just like "file" loader but it also embeds // assets smaller than specified size as data URLs to avoid requests. { test: /\.(mp4|webm|wav|mp3|m4a|aac|oga)(\?.*)?$/, loader: 'url', query: { limit: 10000, name: 'static/media/[name].[hash:8].[ext]' } } ] }, // We use PostCSS for autoprefixing only. postcss: function() { return [ autoprefixer({ browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway ] }), ]; }, plugins: [ // This will output a file named stats.html in your output directory. // You can modify the name/location by passing a filename parameter into the constructor. // Makes the public URL available as %PUBLIC_URL% in index.html, e.g.: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In production, it will be an empty string unless you specify "homepage" // in `package.json`, in which case it will be the pathname of that URL. new InterpolateHtmlPlugin({ PUBLIC_URL: publicUrl }), // Generates an `index.html` file with the <script> injected. new HtmlWebpackPlugin({ inject: true, template: paths.appHtml, minify: { removeComments: true, collapseWhitespace: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeStyleLinkTypeAttributes: true, keepClosingSlash: true, minifyJS: true, minifyCSS: true, minifyURLs: true } }), // Makes some environment variables available to the JS code, for example: // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`. // It is absolutely essential that NODE_ENV was set to production here. // Otherwise React will be compiled in the very slow development mode. new webpack.DefinePlugin(env), // This helps ensure the builds are consistent if source hasn't changed: new webpack.optimize.OccurrenceOrderPlugin(), // Try to dedupe duplicated modules, if any: new webpack.optimize.DedupePlugin(), // Minify the code. new webpack.optimize.UglifyJsPlugin({ compress: { screw_ie8: true, // React doesn't support IE8 warnings: false }, mangle: { screw_ie8: true }, output: { comments: false, screw_ie8: true } }), // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`. new ExtractTextPlugin('static/css/[name].[contenthash:8].css'), // Generate a manifest file which contains a mapping of all asset filenames // to their corresponding output file so that tools can pick it up without // having to parse `index.html`. new ManifestPlugin({ fileName: 'asset-manifest.json' }), ], // Some libraries import Node modules but don't use them in the browser. // Tell Webpack to provide empty mocks for them so importing them works. node: { fs: 'empty', net: 'empty', tls: 'empty' } };
export default function PageQuerier(document, geometry) { this.document = document; this.geometry = geometry; this.range = null; } PageQuerier.prototype.levenshteinDistance = function (a, b) { // courtesy of github.com/kigiri if (a.length === 0) return b.length if (b.length === 0) return a.length let tmp, i, j, prev, val, row // swap to save some memory O(min(a,b)) instead of O(a) if (a.length > b.length) { tmp = a a = b b = tmp } row = Array(a.length + 1) // init the row for (i = 0; i <= a.length; i++) { row[i] = i } // fill in the rest for (i = 1; i <= b.length; i++) { prev = i for (j = 1; j <= a.length; j++) { if (b[i - 1] === a[j - 1]) { val = row[j - 1] // match } else { val = Math.min(row[j - 1] + 1, // substitution Math.min(prev + 1, // insertion row[j] + 1)) // deletion } row[j - 1] = prev prev = val } row[a.length] = prev } return row[a.length] }; PageQuerier.prototype.getTextFromNode = function (node) { if (node.outerText && node.outerText !== "") { return node.outerText; } else if (node.type === "button" && node.value !== "") { return node.value; } return null; }; PageQuerier.prototype.getElementByDigId = function (id) { var iframe = this.document.getElementById('siteUnderTest').contentDocument; var nodeList = iframe.querySelectorAll('[data-dig-id="' + id + '"]'); if (nodeList.length > 0) { return nodeList[0]; } else { return null; } }; PageQuerier.prototype.findTextSearch = function (text) { var iframe = this.document.getElementById('siteUnderTest').contentDocument; var n, textElement = null, a = [], walk = iframe.createTreeWalker(iframe.body, NodeFilter.SHOW_ELEMENT, null, false); while (n = walk.nextNode()) { var textFromNode = this.getTextFromNode(n); if (textFromNode) { if (textFromNode.search(text) != -1) { textElement = n; } var distance = this.levenshteinDistance(text.toLowerCase(), textFromNode.toLowerCase()); a.push({ term: textFromNode, distance: distance }); } } return { result: textElement ? "Success" : "NoMatch", allStrings: a, found: textElement }; }; PageQuerier.prototype.clickPageNode = function (node) { node.click(); }; PageQuerier.prototype.spacialSearch = function (anchorNode, spacialSearchQuery) { var formatCloseResult = function (relativeCoords, node, spacialSearchQuery) { return { htmlId: node.id, htmlClass: node.class, tolerance: spacialSearchQuery.tolerance, x: Math.round(relativeCoords.x), y: Math.round(relativeCoords.y) }; }; var iframe = this.document.getElementById('siteUnderTest').contentDocument; var n, textElement = null, a = [], walk = iframe.createTreeWalker(iframe.body, NodeFilter.SHOW_ELEMENT, null, false); var anchorCoords = this.getAbsCoordinates(anchorNode, iframe); var toleranceRect = this.getToleranceRect(spacialSearchQuery.tolerance, anchorCoords, spacialSearchQuery.direction); var closeResults = [] var succeedResults = [] while (n = walk.nextNode()) { if (spacialSearchQuery.elementType === "Checkbox") { if (n.tagName === "INPUT" && n.type === "checkbox") { var checkboxCoords = this.getAbsCoordinates(n, iframe); if (this.geometry.rectIntersect(toleranceRect, checkboxCoords)) { var relativeCoords = this.geometry.getRelativeCoords(anchorCoords, checkboxCoords); succeedResults.push({ found: n, relativeCoords: relativeCoords, distance: this.geometry.euclideanDistance(anchorCoords, checkboxCoords), alignment: this.getAlignmentScore(spacialSearchQuery.direction, relativeCoords), closeResults: [] }); } else { var closeMatchRect = this.getToleranceRect(spacialSearchQuery.tolerance * 3, anchorCoords, spacialSearchQuery.direction); if (this.geometry.rectIntersect(closeMatchRect, checkboxCoords)) { var relativeCoords = this.geometry.getRelativeCoords(anchorCoords, checkboxCoords); var singleResult = formatCloseResult(relativeCoords, n, spacialSearchQuery); closeResults.push(singleResult); } } } } else { throw "Element type not supported yet!"; } } if (succeedResults.length == 1) { delete succeedResults[0].distance; delete succeedResults[0].alignment; delete succeedResults[0].relativeCoords; succeedResults[0].result = "Success"; return succeedResults[0]; } else if (succeedResults.length > 1) { var isPrecise = this.sortByPriority(spacialSearchQuery.priority, succeedResults); if (!isPrecise) { var ambiguousResults = succeedResults.map(function (item) { return formatCloseResult(item.relativeCoords, item.found, spacialSearchQuery ); }); return { result: "AmbiguousMatch", found: null, closeResults: ambiguousResults } } delete succeedResults[0].alignment; delete succeedResults[0].distance; delete succeedResults[0].relativeCoords; succeedResults[0].result = "Success"; return succeedResults[0]; } return { result: "NoMatch", found: null, closeResults: closeResults } }; PageQuerier.prototype.getAbsCoordinates = function (node, doc) { var bodyRect = doc.body.getBoundingClientRect(); this.range = this.range || doc.createRange(); this.range.selectNodeContents(node); var nodeRect = this.range.getBoundingClientRect(); return { left: nodeRect.left - bodyRect.left, top: nodeRect.top - bodyRect.top, x: (nodeRect.left - bodyRect.left) + nodeRect.width / 2, y: (nodeRect.top - bodyRect.top) + nodeRect.height / 2 }; }; PageQuerier.prototype.sortByPriority = function (priority, results) { if (priority === "Distance") { results.sort(function (a, b) { return a.distance - b.distance; }); if (Math.round(results[0].distance) == Math.round(results[1].distance)) { return false; } } else if (priority === "Alignment") { results.sort(function (a, b) { return a.alignment - b.alignment; }); if (Math.round(results[0].alignment) == Math.round(results[1].alignment)) { return false; } } else if (priority === "AlignmentThenDistance") { results.sort(function (a, b) { var alignment = a.alignment - b.alignment; if (Math.round(alignment) === 0) { return a.distance - b.distance; } return Math.round(alignment); }); } else if (priority === "DistanceThenAlignment") { results.sort(function (a, b) { var distance = a.distance - b.distance; if (Math.round(distance) === 0) { return a.alignment - b.alignment; } return Math.round(distance); }); } return true; }; PageQuerier.prototype.getAlignmentScore = function (direction, relativeCoords) { if (direction == "East") { return Math.abs(relativeCoords.y); } else if (direction == "West") { return Math.abs(relativeCoords.y); } else if (direction == "North") { return Math.abs(relativeCoords.x); } else if (direction == "South") { return Math.abs(relativeCoords.x); } }; PageQuerier.prototype.getToleranceRect = function (tolerance, anchorCoords, direction) { if (direction == "East") { return { right: null, bottom: anchorCoords.y + tolerance, left: anchorCoords.x + 1, top: anchorCoords.y - tolerance }; } else if (direction == "West") { return { right: anchorCoords.x - 1, bottom: anchorCoords.y + tolerance, left: null, top: anchorCoords.y - tolerance }; } else if (direction == "North") { return { right: anchorCoords.x + tolerance, bottom: anchorCoords.y - 1, left: anchorCoords.x - tolerance, top: null }; } else if (direction == "South") { return { right: anchorCoords.x + tolerance, bottom: null, left: anchorCoords.x - tolerance, top: anchorCoords.y + 1 }; } };
/* --- script: Color.js name: Color description: Class for creating and manipulating colors in JavaScript. Supports HSB -> RGB Conversions and vice versa. license: MIT-style license authors: - Valerio Proietti requires: - Core/Array - Core/String - Core/Number - Core/Hash - Core/Function - MooTools.More provides: [Color] ... */ (function(){ var Color = this.Color = new Type('Color', function(color, type){ if (arguments.length >= 3){ type = 'rgb'; color = Array.slice(arguments, 0, 3); } else if (typeof color == 'string'){ if (color.match(/rgb/)) color = color.rgbToHex().hexToRgb(true); else if (color.match(/hsb/)) color = color.hsbToRgb(); else color = color.hexToRgb(true); } type = type || 'rgb'; switch (type){ case 'hsb': var old = color; color = color.hsbToRgb(); color.hsb = old; break; case 'hex': color = color.hexToRgb(true); break; } color.rgb = color.slice(0, 3); color.hsb = color.hsb || color.rgbToHsb(); color.hex = color.rgbToHex(); return Object.append(color, this); }); Color.implement({ mix: function(){ var colors = Array.slice(arguments); var alpha = (typeOf(colors.getLast()) == 'number') ? colors.pop() : 50; var rgb = this.slice(); colors.each(function(color){ color = new Color(color); for (var i = 0; i < 3; i++) rgb[i] = Math.round((rgb[i] / 100 * (100 - alpha)) + (color[i] / 100 * alpha)); }); return new Color(rgb, 'rgb'); }, invert: function(){ return new Color(this.map(function(value){ return 255 - value; })); }, setHue: function(value){ return new Color([value, this.hsb[1], this.hsb[2]], 'hsb'); }, setSaturation: function(percent){ return new Color([this.hsb[0], percent, this.hsb[2]], 'hsb'); }, setBrightness: function(percent){ return new Color([this.hsb[0], this.hsb[1], percent], 'hsb'); } }); var $RGB = function(r, g, b){ return new Color([r, g, b], 'rgb'); }; var $HSB = function(h, s, b){ return new Color([h, s, b], 'hsb'); }; var $HEX = function(hex){ return new Color(hex, 'hex'); }; Array.implement({ rgbToHsb: function(){ var red = this[0], green = this[1], blue = this[2], hue = 0; var max = Math.max(red, green, blue), min = Math.min(red, green, blue); var delta = max - min; var brightness = max / 255, saturation = (max != 0) ? delta / max : 0; if (saturation != 0){ var rr = (max - red) / delta; var gr = (max - green) / delta; var br = (max - blue) / delta; if (red == max) hue = br - gr; else if (green == max) hue = 2 + rr - br; else hue = 4 + gr - rr; hue /= 6; if (hue < 0) hue++; } return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)]; }, hsbToRgb: function(){ var br = Math.round(this[2] / 100 * 255); if (this[1] == 0){ return [br, br, br]; } else { var hue = this[0] % 360; var f = hue % 60; var p = Math.round((this[2] * (100 - this[1])) / 10000 * 255); var q = Math.round((this[2] * (6000 - this[1] * f)) / 600000 * 255); var t = Math.round((this[2] * (6000 - this[1] * (60 - f))) / 600000 * 255); switch (Math.floor(hue / 60)){ case 0: return [br, t, p]; case 1: return [q, br, p]; case 2: return [p, br, t]; case 3: return [p, q, br]; case 4: return [t, p, br]; case 5: return [br, p, q]; } } return false; } }); String.implement({ rgbToHsb: function(){ var rgb = this.match(/\d{1,3}/g); return (rgb) ? rgb.rgbToHsb() : null; }, hsbToRgb: function(){ var hsb = this.match(/\d{1,3}/g); return (hsb) ? hsb.hsbToRgb() : null; } }); })();
export * from './aliases'; // TODO: Figure out why export * does not work here !! export { createStubObject, getStubContainer, getStubRouter, getStubResponse, getStubApp, getStubLogger } from './fakes'; export { assertWasCalled, assertParameter, assertCall, assertCalledBefore, assertInstance } from './assertions'; export { default as stubModule } from './module';
/* global describe, it, require, beforeEach */ 'use strict'; // MODULES // var // Expectation library: chai = require( 'chai' ), // Matrix data structure: matrix = require( 'dstructs-matrix' ), // Check whether an element is a finite number isFiniteNumber = require( 'validate.io-finite' ), // Module to be tested: quantile = require( './../lib/matrix.js' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'matrix quantile', function tests() { var validationData = require( './fixtures/matrix.json' ), lambda = validationData.lambda, out, mat, d1, d2; d1 = new Float64Array( validationData.data ); d2 = new Float64Array( validationData.expected.map( function( d ) { if (d === 'Inf' ) { return Number.POSITIVE_INFINITY; } if ( d === '-Inf' ) { return Number.NEGATIVE_INFINITY; } return d; }) ); beforeEach( function before() { mat = matrix( d1, [5,5], 'float64' ); out = matrix( d2, [5,5], 'float64' ); }); it( 'should export a function', function test() { expect( quantile ).to.be.a( 'function' ); }); it( 'should throw an error if provided unequal length matrices', function test() { expect( badValues ).to.throw( Error ); function badValues() { quantile( matrix( [10,10] ), mat, lambda ); } }); it( 'should evaluate the quantile function for each matrix element', function test() { var actual, i; actual = matrix( [5,5], 'float64' ); actual = quantile( actual, mat, lambda ); for ( i = 0; i < actual.length; i++ ) { if ( isFiniteNumber( actual.data[ i ] ) && isFiniteNumber( out.data[ i ] ) ) { assert.closeTo( actual.data[ i ], out.data[ i ], 1e-12 ); } } }); it( 'should return an empty matrix if provided an empty matrix', function test() { var out, mat, expected; out = matrix( [0,0] ); expected = matrix( [0,0] ).data; mat = matrix( [0,10] ); assert.deepEqual( quantile( out, mat, lambda ).data, expected ); mat = matrix( [10,0] ); assert.deepEqual( quantile( out, mat, lambda ).data, expected ); mat = matrix( [0,0] ); assert.deepEqual( quantile( out, mat, lambda ).data, expected ); }); });
const jwt = require('jsonwebtoken'); const logger = require('../log/logger'); const config = require('../config.js'); const ApiError = require('./../helper.js').ApiError; const extractToken = (authHeader) => { if (!authHeader) { return } let bearer = authHeader.substr(7); if (!bearer || bearer.length < 10) { return } return bearer }; const parseToken = (token) => new Promise((resolve, reject) => { jwt.verify(token, config.token.secretKey, (err, decoded) => { if (err || !decoded) { return reject(new ApiError('Invalid token', 302)) } resolve(decoded.login) }) }); const generateToken = (user) => { logger.info('Logged in as ' + user.login); return jwt.sign(user, config.token.secretKey, { expiresIn: config.token.expiration }) }; module.exports = { extractToken, parseToken, generateToken };
var locomotive = require('locomotive'), user_model = require('../models/user'), passport = require('passport'); var AuthController = new locomotive.Controller(); AuthController.loginForm = function() { this.title = 'Log In'; this.render(); }; AuthController.login = function() { passport.authenticate('local', { successRedirect: this.urlFor({ controller:'pages', action: 'main' }), failureRedirect: this.urlFor({ action: 'login' }) } )(this.__req, this.__res, this.__next); }; AuthController.logout = function() { this.req.logOut(); this.res.redirect('/'); }; AuthController.signup = function() { this.title = 'Sign Up'; if (this.req.method === 'GET') { this.render(); } else { var controller = this; user_model.registerUser(this.param('email'), this.param('password'), function(err, user) { if (err) { controller.error(err); } else { controller.redirect('/'); } }); } }; module.exports = AuthController;
Gabscape = function() { SB.Game.call(this); } goog.inherits(Gabscape, SB.Game); Gabscape.prototype.initialize = function(param) { if (!param) param = {}; if (!param.displayStats) param.displayStats = Gabscape.default_display_stats; this.twitterInfo = param.info; SB.Game.prototype.initialize.call(this, param); this.initEntities(); } Gabscape.prototype.initEntities = function() { this.root = new SB.Entity; // var grid = new SB.Grid({size:64}); // this.root.addComponent(grid); var g1 = new Gabber({name: "Gabber1" }); g1.transform.position.set(15, 0, -20); /* var g2 = new Gabber({name: "Gabber2" }); g2.transform.position.set(-25, 0, -33); var g3 = new Gabber({name: "Gabber3" }); g3.transform.position.set(0, 0, -15); */ var viewer = SB.Prefabs.FPSController({ active : true, headlight : true, cameraPosition : new THREE.Vector3(0, 0, 5) }); this.gabatar = new Gabatar({ info : this.twitterInfo }); this.gabatar.transform.position.set(0, -2.5, 0); viewer.addChild(this.gabatar); viewer.transform.position.set(0, 2.5, 0); this.gabbers = [g1]; // , g2, g3]; this.activeGabber = null; this.root.addChild(g1); // this.root.addChild(g2); // this.root.addChild(g3); this.root.addChild(viewer); this.addEntity(this.root); this.root.realize(); } Gabscape.prototype.getTwitterData = function() { var that = this; Gabulous.getTimeline(function(result, text) { that.timelineCallback(result, text); }); } Gabscape.prototype.timelineCallback = function(result, responseText) { var foo = result; var statusInfo = this.getStatusInfo(result); this.updateStatus(statusInfo); var that = this; Gabulous.getFriends(this.twitterInfo.screen_name, function(result, text) { that.friendsCallback(result, text); }); } Gabscape.prototype.friendsCallback = function(result, responseText) { var foo = result; var friendsInfo = this.getFriendsInfo(result); this.updateFriends(friendsInfo); var that = this; Gabulous.getPublicTimeline(function(result, text) { that.publicTimelineCallback(result, text); }); } Gabscape.prototype.publicTimelineCallback = function(result, responseText) { var foo = result; var statusInfo = this.getStatusInfo(result); this.updatePublicTimeline(statusInfo); } Gabscape.prototype.updateStatus = function(message) { // document.getElementById("status").innerHTML = message; } Gabscape.prototype.getStatusInfo = function(status) { var info = ""; var i, len = status.length; for (i = 0; i < len; i++) { var stat = status[i]; info += ( "<img src='" + stat.user.profile_image_url + "'>" + "<b>" + stat.user.name +"</b>" + " @" + stat.user.screen_name + "<br/>" + stat.text + "<br/>" ); } return info; } Gabscape.prototype.updateFriends = function(message) { // document.getElementById("friends").innerHTML = message; } Gabscape.prototype.getFriendsInfo = function(friends) { var info = ""; var i, len = friends.length; for (i = 0; i < len; i++) { var friend = friends[i][0]; info += ( "<img src='" + friend.profile_image_url + "'>" + "<b>" + friend.name +"</b>" + " @" + friend.screen_name + "<br/>" + friend.status.text + "<br/>" ); } return info; } Gabscape.prototype.updatePublicTimeline = function(message) { // document.getElementById("public").innerHTML = message; } Gabscape.prototype.onKeyDown = function(keyCode, charCode) { this.whichKeyDown = keyCode; if (this.activeGabber) this.activeGabber.onKeyDown(keyCode, charCode); else SB.Game.prototype.onKeyDown.call(this, keyCode, charCode) } Gabscape.prototype.onKeyUp = function(keyCode, charCode) { var mi; var handled = false; switch (String.fromCharCode(keyCode)) { case 'H' : this.help(); handled = true; break; case '1' : mi = 1; break; case '2' : mi = 2; break; case '3' : mi = 3; break; default : break; } if (!handled && this.activeGabber) { this.activeGabber.onKeyUp(keyCode, charCode); } if (mi) { var gabber = this.gabbers[mi-1]; this.setActiveGabber(gabber); } if (!handled) SB.Game.prototype.onKeyUp.call(this, keyCode, charCode) } Gabscape.prototype.onKeyPress = function(keyCode, charCode) { SB.Game.prototype.onKeyPress.call(this, keyCode, charCode) } Gabscape.prototype.onTimeChanged = function(t) { return; if (!this.activeGabber) { var handled = false; switch (this.whichKeyDown) { case SB.Keyboard.KEY_LEFT : this.turn(+1); handled = true; break; case SB.Keyboard.KEY_UP : this.move(-1); handled = true; break; case SB.Keyboard.KEY_RIGHT : this.turn(-1); handled = true; break; case SB.Keyboard.KEY_DOWN : this.move(+1); handled = true; break; } if (!handled) { switch (String.fromCharCode(this.whichKeyDown)) { case 'A' : this.turn(+1); handled = true; break; case 'W' : this.move(-1); handled = true; break; case 'D' : this.turn(-1); handled = true; break; case 'S' : this.move(+1); handled = true; break; default : break; } } } } Gabscape.prototype.onTimeFractionChanged = function(fraction) { this.turnFraction = fraction; } Gabscape.prototype.setActiveGabber = function(gabber) { if (this.activeGabber) { this.activeGabber.setActive(false); } gabber.setActive(true); this.activeGabber = gabber; } Gabscape.prototype.help = function() { if (!this.helpScreen) { this.helpScreen = new GabscapeHelp(); } this.helpScreen.show(); } Gabscape.default_display_stats = false;
var client = require('socket.io-client'); var prefs = require('../../utils/user_preferences'); var _ = require('underscore'); var $ = require('jquery'); var Range = require('atom').Range; var existingRequestDecoration = []; module.exports = function(app) { app.factory('QuestionManager', ['AlertMessageHandler','$http', '$q', '$rootScope', function (AlertMessageHandler,$http, $q, $rootScope) { var isConnected = false; var socket = client.connect(prefs.getServerURL(), { reconnection: false }); /* handle connection even handler */ socket.on('connect_error', function(){ console.error('CodeOn - Connection Failed :'+prefs.getServerURL()); atom.notifications.addWarning('CodeOn - Connection Error: '+prefs.getServerURL() + " \n Check your server and restart your Atom.io"); }); socket.on('connect_timeout', function(){ console.error('CodeOn - Connection Timeout :'+prefs.getServerURL()); atom.notifications.addWarning(prefs.getServerURL()); }); socket.on('connect', function(){ //console.log('Connected'); //alert('CodeOn - Connected with :'+prefs.getServerURL()); }); /* socket.on('reconnect', function(){ console.log('Reconnected'); alert('CodeOn - Reconnected with :'+prefs.getServerURL()); }); */ socket.on('disconnect', function () { console.log('Disconnected'); atom.notifications.addWarning('CodeOn - Disconnected with: '+prefs.getServerURL() + " \n Check your server and restart your Atom.io"); }); var requestPromises = {}; var path; socket.on('request_uploaded', function(msg) { //run it when getting a new notification updateMyRequests(); atom.beep(); AlertMessageHandler.alertMessage("Title", "Request Posted!", "info", 3000); atom.workspace.getTopPanels()[0].hide(); }); //message_updated socket.on('message_updated', function(msg) { AlertMessageHandler.alertNewComment(); //chat box auto scroll down var myDiv = $('.chat-box-content'); myDiv.animate({ scrollTop: myDiv[0].scrollHeight }, 1000); requestPromises[msg.requestID].then(function(request) { atom.beep(); request.status.discussion = msg.discussion; request.status.state = msg.state; request.notification = "You received a new comment"; request.helperCurrentWorking = false; request.helperIsDone = false; request.helperHasMsg = true; }); }); socket.on('status_updated', function(msg) { if(msg.typeOfUpdate == "responseUpdate"){ requestPromises[msg.requestID].then(function(request) { request.status.state = msg.state; request.notification = "Waiting for actions"; if(msg.state=='resolved'){ request.notification = "Resolved."; } }); } }); socket.on('currentworkingrequest', function(data){ getJSON('/editor_questions/' + prefs.getEditorID()).then(function(editor_questions) { _.each(editor_questions, function(updated, requestID) { if(requestPromises.hasOwnProperty(requestID)) { requestPromises[requestID].then(function(request) { if(requestID==data.currentReq.question_id){ request.currentHelperName = data.currentUser; request.helperCurrentWorking = true; }else{ request.currentHelperName = ""; request.helperCurrentWorking = false; request.helperIsDone = false; request.helperHasMsg = false; } }); } }); }); }) socket.on('getMeCode',function(data){ var ed = atom.workspace.getTextEditors(); _.each(ed, function(editor){ if(data.path == editor.getPath()){ socket.emit('requestCurrentCode', { requestID: data.requestID, code: editor.getText() }); } }) }); socket.on('new_response', function(msg) { AlertMessageHandler.alertNewResponse(); requestPromises[msg.requestID].then(function(request) { atom.beep(); request.status.responses = msg.responses; request.status.latestResponse = msg.responses[msg.responses.length-1]; request.status.state = msg.state; request.notification = "You received a new response"; request.helperCurrentWorking = false; request.helperIsDone = true; request.helperHasMsg = false; // console.log(request) }); }); function getJSON(url) { return $http({ url: prefs.getServerURL() + url }).then(function(response) { return response.data; }); } function updateRequest(request, requestID, updated) { fetchRequest(requestID, updated).then(function(newInfo) { newInfo.transcript = request.transcript; newInfo.title = request.title; _.extend(request, newInfo); }); } function fetchRequest(requestID, updated) { var requestPromise = getJSON('/get_question/'+requestID), cwdPromise = getJSON('/get_cwd/'+requestID), tagsPromise = getJSON('/get_tags/'+requestID), // transcriptPromise = getJSON('/get_transcript/'+requestID), statusPromise = getJSON('/get_status/'+requestID); return $q.all([requestPromise, cwdPromise, tagsPromise, statusPromise]).then(function(info) { var request = info[0], cwd = info[1], tags = info[2], status = info[3], notification = status.state == "pending" ? "No response" :status.state == "new" ? "Received a response." :status.state == "new_comment" ? "Received a comment" :status.state == "action" ? "Waiting for actions" : "This request has been resolved."; return _.extend({ tags: tags, cwd: cwd, updated: updated, status: status, hasView: false, notification: notification }, request); }); } function contain(arr, ind){ var target = arr[ind]; for(i=ind+1;i<arr.length;i++){ if(target==arr[i]) return false; }; return true; } // function unique(input){ // var promises = []; // // _.each(input, function(val, ind){ // if(contain(input,ind)){ // promises.push(atom.workspace.open(val).then(function(){ // return val; // })); // } // }); // // return $q.all(promises); // } function updateMyRequests() { getJSON('/editor_questions/' + prefs.getEditorID()).then(function(editor_questions) { _.each(editor_questions, function(updated, requestID) { if(requestPromises.hasOwnProperty(requestID)) { requestPromises[requestID].then(function(request) { if(request.updated < updated) { requestPromises[requestID] = fetchRequest(requestID, updated); } }); } else { requestPromises[requestID] = fetchRequest(requestID, updated); // move this to after clicking done // var views = atom.views.getView(editor); // var rowGutter = views.shadowRoot.querySelector('div[data-buffer-row="'+location.start.row+'"]'); } }); $q.all(_.values(requestPromises)).then(function(requests) { $rootScope.requests = requests.sort(function(a, b) { return b.updated - a.updated; }); //This is to prevent open the same file when this file is not open // the reason is .open is asyn. function so it won't notice that previous //file has the same path unless we find out the unique path first var pathArr = []; _.each($rootScope.requests,function(request){ pathArr.push(request.changelog[1].path); }); //add decoration on gutter to all the request files // unique(pathArr).then(function(arrs){ // _.each($rootScope.requests, function(request,index){ // // if(request.status.state!=="resolved"){ // var hasIt = false; // var requestLocation = $rootScope.requests.length - index; // if(existingRequestDecoration.length>0){ // _.every(existingRequestDecoration, function(num, ind){ // if(num==requestLocation){ // hasIt = true; // return false; // } // return true; // }); // } // // if(!hasIt){ // // //add decoration on gutter to all the request files // atom.workspace.open(request.changelog[1].path).then(function(editor){ // existingRequestDecoration.push(requestLocation); // var location = request.changelog[1].beginningSelection[0]; // editor.scrollToScreenPosition([location.start.row, location.start.column],{center:true}); // editor.setCursorScreenPosition([location.start.row, location.start.column]); // // var range = new Range([location.start.row, location.start.row], [location.start.row, location.start.row]); // var lineMarker = editor.markBufferRange(range,{ // invalidate: 'never', // question_id: request.question_id // }); // // Decorate the lineMarker. // // var quo = ($rootScope.requests.length - index) %7; // editor.decorateMarker(lineMarker, { // type: 'line-number', // class:'request'+quo, // requestIndex: requestLocation, // lineNumber: range // }); // }) // } // request.removeButton = false // }); // }); }); }); } //when first open Atom updateMyRequests(); var rv = { sendIterationRequest: function(requestID, message) { socket.emit('messageFromRequester', { requestID: requestID, value: message, state: 'pending' }); }, markResolved: function(requestID) { socket.emit('setState', { requestID: requestID, state: 'resolved' }); }, anyChanges: function(){ socket.emit('somethingIsChangingOnRequeterSide'); }, markWaitingForAction: function(requestID){ socket.emit('setState', { requestID: requestID, state: 'action' }); }, isConnected: function() { return socket.io.connected; }, reconnect: function() { socket.io.reconnect(); }, updateTranscript: function(requestID, transcript){ socket.emit('updateTranscript', { requestID: requestID, editedTranscript: transcript }); }, updateTitle: function(requestID, title){ console.log(title); socket.emit('updateTitle', { requestID: requestID, editedTitle: title }); } }; socket.on('addNotification', function(notification) { //rv.emit('response', notification); $rootScope.$emit('codeon_response', notification) }); return rv; }]); }; //if it is marking waiting for actions // // console.log(msg); // $rootScope.filePath = msg.path; // var requestID = msg.requestID; // var exist = false; // var requestArray = $rootScope.requests; // // //if requestID is one in scope.requesst // for (var i=0;i<requestArray.length;i++){ // if(requestArray[i].question_id==requestID){ // exist = true; // break; // } // } // // if(exist){ // requestPromises[requestID].then(function(request) { // // // // if(msg.newTranscript.length!=0) // // request.transcript = msg.newTranscript[msg.newTranscript.length-1].transcript; // // if(msg.newTitle.length!=0) // // request.title = msg.newTitle[msg.newTitle.length-1].title; // // updateRequest(request, requestID, request.updated); // // }); // }
import { GET_USER_INFO_SUCCESS, GET_DOCUMENTS_BY_USER_SUCCESS, GET_ALL_USERS_SUCCESS, GET_SEARCH_USERS_SUCCESS, DELETE_USER_FAILURE, DELETE_USER_SUCCESS, UPDATE_USER_INFO_SUCCESS, UPDATE_USER_INFO_ERROR, } from '../../../actions/types'; import { getUserInformationSuccess, getUserDocumentsSuccess, getAllUsersSuccess, searchUserSuccess, updateUserInformationSuccess, updateUserInformationError, deleteUserSuccess, deleteUserFailure } from '../../../actions/users.action'; describe('Users actions', () => { it('should get user information', () => { const userInfo = {}; const expectedAction = { type: GET_USER_INFO_SUCCESS, userInfo } expect(getUserInformationSuccess(userInfo)).toEqual(expectedAction) }); it('should get documents by a user', () => { const userDocuments = {}; const expectedAction = { type: GET_DOCUMENTS_BY_USER_SUCCESS, userDocuments } expect(getUserDocumentsSuccess(userDocuments)).toEqual(expectedAction) }); it('should get all users', () => { const allUsers = {}; const expectedAction = { type: GET_ALL_USERS_SUCCESS, allUsers } expect(getAllUsersSuccess(allUsers)).toEqual(expectedAction) }); it('should search for user(s)', () => { const usersSearch = {}; const expectedAction = { type: GET_SEARCH_USERS_SUCCESS, usersSearch } expect(searchUserSuccess(usersSearch)).toEqual(expectedAction) }); it('should update user information', () => { const userInfo = {}; const expectedAction = { type: UPDATE_USER_INFO_SUCCESS, userInfo } expect(updateUserInformationSuccess(userInfo)).toEqual(expectedAction) }); it('should dipatch error on failure to update user information', () => { const updateError = {}; const expectedAction = { type: UPDATE_USER_INFO_ERROR, updateError } expect(updateUserInformationError(updateError)).toEqual(expectedAction) }); it('should delete a user information', () => { const status = {}; const expectedAction = { type: DELETE_USER_SUCCESS, status } expect(deleteUserSuccess(status)).toEqual(expectedAction) }); it('should dipatch error on failure to delete a user', () => { const status = {}; const expectedAction = { type: DELETE_USER_FAILURE, status } expect(deleteUserFailure(status)).toEqual(expectedAction) }); });
var path = require('path'); module.exports = { entry: [ './src/plumin.js' ], output: { path: path.join(__dirname, 'dist'), filename: 'plumin.js', library: 'plumin', libraryTarget: 'umd', }, resolve: { alias: { 'paper': 'paper/dist/paper-core.js', } }, externals: [{ './node/window': true, './node/extend': true, }], node: { Buffer: false, } };
var Cap = require('cap').Cap, decoders = require('cap').decoders, PROTOCOL = decoders.PROTOCOL; var c = new Cap(), device = Cap.findDevice(), filter = 'arp', bufSize = 10 * 1024 * 1024, buffer = new Buffer(65535); var linkType = c.open(device, filter, bufSize, buffer); c.setMinBytes && c.setMinBytes(0); var just_emitted = {}; just_emitted = false; c.on('packet', function (nbytes, trunc) { console.log('packet: length ' + nbytes + ' bytes, truncated? ' + (trunc ? 'yes' : 'no')); if (linkType === 'ETHERNET') { var ret = decoders.Ethernet(buffer); // console.log("protocol: " + PROTOCOL.ETHERNET[ret.info.type]); if (ret.info.type === PROTOCOL.ETHERNET.ARP) { // console.log('Decoding ARP ...'); // console.log("srcmac " + ret.info.srcmac); } if (ret.info.srcmac === "74:75:48:b8:55:23") { if (!just_emitted) { console.log("amazon dash button pressed") var open = require('open'); open('http://www.netflix.com/browse/'); just_emitted = true; setTimeout(function () { just_emitted = false; }, 3000); //sometimes one click triggers 2 or more ARP requests, this prevents multiple actions taking placep } } } });
import Controller from '@ember/controller'; import envConfig from 'ghost-admin/config/environment'; import {action} from '@ember/object'; import {inject as service} from '@ember/service'; import {tracked} from '@glimmer/tracking'; const DEFAULT_STEPS = { 'customise-design': { title: 'Customise your site', position: 'Step 1', next: 'connect-stripe' }, 'connect-stripe': { title: 'Connect to Stripe', position: 'Step 2', next: 'set-pricing', back: 'customise-design', skip: 'finalise' }, 'set-pricing': { title: 'Set up subscriptions', position: 'Step 3', next: 'finalise', back: 'connect-stripe' }, finalise: { title: 'Launch your site', position: 'Final step', back: 'set-pricing' } }; export default class LaunchController extends Controller { @service config; @service router; @service settings; queryParams = ['step']; @tracked previewGuid = (new Date()).valueOf(); @tracked previewSrc = ''; @tracked step = 'customise-design'; @tracked data = null; steps = DEFAULT_STEPS; skippedSteps = []; constructor(...args) { super(...args); const siteUrl = this.config.get('blogUrl'); if (envConfig.environment !== 'development' && !/^https:/.test(siteUrl)) { this.steps = { 'customise-design': { title: 'Customise your site', position: 'Step 1', next: 'set-pricing' }, 'set-pricing': { title: 'Set up subscriptions', position: 'Step 2', next: 'finalise', back: 'customise-design' }, finalise: { title: 'Launch your site', position: 'Final step', back: 'set-pricing' } }; } else { this.steps = DEFAULT_STEPS; } } get currentStep() { return this.steps[this.step]; } @action storeData(data) { this.data = data; } @action getData() { return this.data; } @action goToStep(step) { if (step) { this.step = step; } } @action goNextStep() { this.step = this.currentStep.next; } @action goBackStep() { let step = this.currentStep.back; while (this.skippedSteps.includes(step)) { this.skippedSteps = this.skippedSteps.filter(s => s !== step); step = this.steps[step].back; } this.step = step; } // TODO: remember when a step is skipped so "back" works as expected @action skipStep() { let step = this.currentStep.next; let skipToStep = this.currentStep.skip; while (step !== skipToStep) { this.skippedSteps.push(step); step = this.steps[step].next; } this.step = step; } @action registerPreviewIframe(element) { this.previewIframe = element; } @action refreshPreview() { this.previewGuid = (new Date()).valueOf(); } @action updatePreview(url) { this.previewSrc = url; } @action replacePreviewContents(html) { if (this.previewIframe) { this.previewIframe.contentWindow.document.open(); this.previewIframe.contentWindow.document.write(html); this.previewIframe.contentWindow.document.close(); } } @action close() { this.router.transitionTo('dashboard'); } @action reset() { this.data = null; this.step = 'customise-design'; this.skippedSteps = []; } }
import camelCase from 'lodash/camelCase'; /** * Convert the style tag to an object * * @param styles * @param keyConverter call back function * @return {*} */ export default (styles, keyConverter = camelCase) => { return String(styles).split(';').reduce((all, style) => { const parts = style.split(':'); if (parts.length === 2) { const key = keyConverter(String(parts[0]).trim()); let value = String(parts[1]).trim(); if (typeof all[key] !== 'undefined') { // duplicate keys are made in to arrays of values this is so we can handle // hacky styles like multiple widths for different clients etc const newValue = (typeof all[key] === 'string' ? [ all[key] ] : all[key]); newValue.push(value); value = newValue; } all[key] = value; } return all; }, {}); };
var searchData= [ ['arm_5fcan_5fsignalobjectevent_5ft',['ARM_CAN_SignalObjectEvent_t',['../group__can__interface__gr.html#ga7ceceac3e9aa0981c5cacfab88efb4eb',1,'Driver_CAN.h']]], ['arm_5fcan_5fsignalunitevent_5ft',['ARM_CAN_SignalUnitEvent_t',['../group__can__interface__gr.html#gaac07b9fdf614bf439414f5417aaa376e',1,'Driver_CAN.h']]], ['arm_5feth_5fmac_5fsignalevent_5ft',['ARM_ETH_MAC_SignalEvent_t',['../group__eth__mac__interface__gr.html#gadfc95cb09c541a29a72da86963668726',1,'Driver_ETH_MAC.h']]], ['arm_5feth_5fphy_5fread_5ft',['ARM_ETH_PHY_Read_t',['../group__eth__phy__interface__gr.html#ga987d5dd36f179192721c03df37d93e87',1,'Driver_ETH_PHY.h']]], ['arm_5feth_5fphy_5fwrite_5ft',['ARM_ETH_PHY_Write_t',['../group__eth__phy__interface__gr.html#gaf690fde16281b25f2ffa07f9c4e8e240',1,'Driver_ETH_PHY.h']]], ['arm_5fflash_5fsignalevent_5ft',['ARM_Flash_SignalEvent_t',['../group__flash__interface__gr.html#gabeb4ad43b1e6fa4ed956cd5c9371d327',1,'Driver_Flash.h']]], ['arm_5fi2c_5fsignalevent_5ft',['ARM_I2C_SignalEvent_t',['../group__i2c__interface__gr.html#ga24277c48248a09b0dd7f12bbe22ce13c',1,'Driver_I2C.h']]], ['arm_5fmci_5fsignalevent_5ft',['ARM_MCI_SignalEvent_t',['../group__mci__interface__gr.html#ga0d14651f6788c1ffd81544602565faf1',1,'Driver_MCI.h']]], ['arm_5fnand_5fsignalevent_5ft',['ARM_NAND_SignalEvent_t',['../group__nand__interface__gr.html#ga09f4cf2f2df0bb690bce38b13d77e50f',1,'Driver_NAND.h']]], ['arm_5fsai_5fsignalevent_5ft',['ARM_SAI_SignalEvent_t',['../group__sai__interface__gr.html#gad8ca8e2459e540928f6315b3df6da0ee',1,'Driver_SAI.h']]], ['arm_5fspi_5fsignalevent_5ft',['ARM_SPI_SignalEvent_t',['../group__spi__interface__gr.html#gafde9205364241ee81290adc0481c6640',1,'Driver_SPI.h']]], ['arm_5fstorage_5fcallback_5ft',['ARM_Storage_Callback_t',['../group__storage__interface__gr.html#ga4b290224fea782e6d2ad06f541b28a98',1,'Driver_Storage.h']]], ['arm_5fusart_5fsignalevent_5ft',['ARM_USART_SignalEvent_t',['../group__usart__interface__gr.html#gaa578c3829eea207e9e48df6cb6f038a1',1,'Driver_USART.h']]], ['arm_5fusbd_5fsignaldeviceevent_5ft',['ARM_USBD_SignalDeviceEvent_t',['../group__usbd__interface__gr.html#ga7c1878799699ddd34cec696da499f7bd',1,'Driver_USBD.h']]], ['arm_5fusbd_5fsignalendpointevent_5ft',['ARM_USBD_SignalEndpointEvent_t',['../group__usbd__interface__gr.html#gaae754763700fc5059a6bde57ea2d4e2c',1,'Driver_USBD.h']]], ['arm_5fusbh_5fhci_5finterrupt_5ft',['ARM_USBH_HCI_Interrupt_t',['../group__usbh__hci__gr.html#gac60df9d1f2b3a769f2c30141800a9806',1,'Driver_USBH.h']]], ['arm_5fusbh_5fpipe_5fhandle',['ARM_USBH_PIPE_HANDLE',['../group__usbh__host__gr.html#ga2e4d0ebd0851ba7bf364ae1d8948672c',1,'Driver_USBH.h']]], ['arm_5fusbh_5fsignalpipeevent_5ft',['ARM_USBH_SignalPipeEvent_t',['../group__usbh__host__gr.html#ga1a32ebfe0db4a002aae2b0c0f8ece30c',1,'Driver_USBH.h']]], ['arm_5fusbh_5fsignalportevent_5ft',['ARM_USBH_SignalPortEvent_t',['../group__usbh__host__gr.html#ga61edcbb6ee863fe87abee488d78e1051',1,'Driver_USBH.h']]] ];
version https://git-lfs.github.com/spec/v1 oid sha256:51941e9aff5db4fd97aba31709295c8e8363fdafdf02c7f838bb19b079065a18 size 1905
version https://git-lfs.github.com/spec/v1 oid sha256:90376ea74020742a3e78819ba7a530241ff893312fcf2fba7cd0d9ff1b6c5985 size 984
const DrawCard = require('../../drawcard.js'); const { Locations } = require('../../Constants'); class SpecializedDefenses extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Double province strength', condition: context => { if(!this.game.isDuringConflict()) { return false; } return this.game.currentConflict.conflictProvince.element.some(element => { if(element === 'all') { return true; } return this.game.rings[element].isConsideredClaimed(context.player) || this.game.currentConflict.ring.getElements().includes(element); }); }, effect: 'double {1}\'s province strength', effectArgs: context => context.game.currentConflict.conflictProvince, gameAction: ability.actions.cardLastingEffect(() => ({ target: this.game.currentConflict.conflictProvince, targetLocation: Locations.Provinces, effect: ability.effects.modifyProvinceStrengthMultiplier(2) })) }); } } SpecializedDefenses.id = 'specialized-defenses'; module.exports = SpecializedDefenses;
// @flow import setLightness from '../setLightness' describe('setLightness', () => { it('should update the lightness and return a hex color', () => { expect(setLightness(0.2, '#CCCD64')).toEqual('#4d4d19') }) it('should update the lightness of an 8-digit hex color and return a hex color', () => { expect(setLightness(0.2, '#6564CDB3')).toEqual('rgba(25,25,77,0.7)') }) it('should update the lightness of an 4-digit hex color and return a hex color', () => { expect(setLightness(0.2, '#0f08')).toEqual('rgba(0,102,0,0.53)') }) it('should update the lightness and return a color with opacity', () => { expect(setLightness(0.2, 'rgba(101,100,205,0.7)')).toEqual('rgba(25,25,77,0.7)') }) it('should update the lightness when passed a string', () => { expect(setLightness('0.2', '#CCCD64')).toEqual('#4d4d19') }) it('should return transparent when passed transparent', () => { expect(setLightness('0.2', 'transparent')).toEqual('transparent') }) })
import { combineReducers, routerReducer } from 'redux-seamless-immutable' // import resourceReducer from './resource'; // import loading from './loading'; // import notification from './notification'; // import references from './references'; // import saving from './saving'; import ui from './ui'; export default (resources) => { // const resourceReducers = {}; // [].forEach((resource) => { // resourceReducers[resource.name] = resourceReducer(resource.name, resource.options); // }); return combineReducers({ // ...resourceReducers, // loading, // notification, // references, // saving, ui, routing: routerReducer }); };
var defaultPlotColor = 'rgb(0,127,255)'; var mathcellStyle = document.createElement( 'style' ); mathcellStyle.type = 'text/css'; mathcellStyle.innerHTML = ` .mathcell { width: 5in; margin: .25in auto .25in auto; border: 2px solid black; display: flex; flex-direction: column; box-sizing: border-box; padding: .25in .5in .5in .5in; line-height: 2.5; } input[type=text] { -webkit-appearance: none; box-shadow: none; border: 1px solid black; border-radius: 5px; } input[type=number] { -webkit-appearance: none; -moz-appearance:textfield; box-shadow: none; border: 1px solid black; border-radius: 5px; } input[type=number]::-webkit-outer-spin-button, input[type=number]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } input[type=radio] { display: none; } input[type=radio] + label { display: inline-block; vertical-align: middle; min-width: 25px; height: 20px; line-height: 20px; text-align: center; border: 1px solid black; border-radius: 5px; background-color: #eee; } input[type=radio]:checked + label { border-width: 2px; background-color: #fafafa } /* Generated at http://www.cssportal.com/style-input-range/ Thumb is 20px by 25px with 5px radius Track is 10px high with 3px radius For MS, 1px margins top and right to avoid cutoffs Replace when major browsers support common styling */ input[type=range] { -webkit-appearance: none; margin: 10px 0; width: 100%; } input[type=range]:focus { outline: none; } input[type=range]::-webkit-slider-runnable-track { width: 100%; height: 10px; cursor: pointer; animate: 0.2s; box-shadow: 0px 0px 0px #000000; background: #FFFFFF; border-radius: 3px; border: 1px solid #000000; } input[type=range]::-webkit-slider-thumb { box-shadow: 0px 0px 0px #000000; border: 1px solid #000000; height: 20px; width: 25px; border-radius: 5px; background: #eee; cursor: pointer; -webkit-appearance: none; margin-top: -6px; } input[type=range]:focus::-webkit-slider-runnable-track { background: #FFFFFF; } input[type=range]::-moz-range-track { width: 100%; height: 10px; cursor: pointer; animate: 0.2s; box-shadow: 0px 0px 0px #000000; background: #FFFFFF; border-radius: 3px; border: 1px solid #000000; } input[type=range]::-moz-range-thumb { box-shadow: 0px 0px 0px #000000; border: 1px solid #000000; height: 20px; width: 25px; border-radius: 5px; background: #eee; cursor: pointer; } input[type=range]::-ms-track { width: 100%; height: 10px; cursor: pointer; animate: 0.2s; background: transparent; border-color: transparent; color: transparent; } input[type=range]::-ms-fill-lower { background: #FFFFFF; border: 1px solid #000000; border-radius: 3px; box-shadow: 0px 0px 0px #000000; } input[type=range]::-ms-fill-upper { background: #FFFFFF; border: 1px solid #000000; border-radius: 3px; box-shadow: 0px 0px 0px #000000; margin-right: 1px; } input[type=range]::-ms-thumb { box-shadow: 0px 0px 0px #000000; border: 1px solid #000000; height: 18px; width: 25px; border-radius: 5px; background: #eee; cursor: pointer; margin-top: 1px; } input[type=range]:focus::-ms-fill-lower { background: #FFFFFF; } input[type=range]:focus::-ms-fill-upper { background: #FFFFFF; } /* not in cssportal */ input[type=range]::-moz-focus-outer { border: 0; } `; document.getElementsByTagName( 'head' )[0].appendChild( mathcellStyle );
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.6.1-master-6397040 */ (function() { 'use strict'; /** * @ngdoc module * @name material.components.card * * @description * Card components. */ angular.module('material.components.card', [ 'material.core' ]) .directive('mdCard', mdCardDirective); /** * @ngdoc directive * @name mdCard * @module material.components.card * * @restrict E * * @description * The `<md-card>` directive is a container element used within `<md-content>` containers. * * Cards have constant width and variable heights; where the maximum height is limited to what can * fit within a single view on a platform, but it can temporarily expand as needed * * @usage * <hljs lang="html"> * <md-card> * <img src="img/washedout.png" class="md-card-image"> * <h2>Paracosm</h2> * <p> * The titles of Washed Out's breakthrough song and the first single from Paracosm share the * two most important words in Ernest Greene's musical language: feel it. It's a simple request, as well... * </p> * </md-card> * </hljs> * */ function mdCardDirective($mdTheming) { return { restrict: 'E', link: function($scope, $element, $attr) { $mdTheming($element); } }; } mdCardDirective.$inject = ["$mdTheming"]; })();
"use strict"; const TradeOfferManager = require('./index.js'); const Async = require('async'); const EconItem = require('./classes/EconItem.js'); const ITEMS_PER_CLASSINFO_REQUEST = 100; TradeOfferManager.prototype._digestDescriptions = function(descriptions) { var cache = this._assetCache; if (!this._language) { return; } if (descriptions && !(descriptions instanceof Array)) { descriptions = Object.keys(descriptions).map(key => descriptions[key]); } (descriptions || []).forEach((item) => { if (!item || !item.appid || !item.classid) { return; } cache[`${item.appid}_${item.classid}_${item.instanceid || '0'}`] = item; }); }; TradeOfferManager.prototype._mapItemsToDescriptions = function(appid, contextid, items) { var cache = this._assetCache; if (!(items instanceof Array)) { items = Object.keys(items).map(key => items[key]); } return items.map((item) => { item.appid = appid || item.appid; item.contextid = contextid || item.contextid; var key = `${item.appid}_${item.classid}_${item.instanceid || '0'}`; if (!cache[key]) { // This item isn't in our description cache return new EconItem(item); } for (let i in cache[key]) { if (cache[key].hasOwnProperty(i)) { item[i] = cache[key][i]; } } return new EconItem(item); }); }; TradeOfferManager.prototype._hasDescription = function(item, appid) { appid = appid || item.appid; return !!this._assetCache[appid + '_' + item.classid + '_' + (item.instanceid || '0')]; }; TradeOfferManager.prototype._addDescriptions = function(items, callback) { var descriptionRequired = items.filter(item => !this._hasDescription(item)); if (descriptionRequired.length == 0) { callback(null, this._mapItemsToDescriptions(null, null, items)); return; } this._requestDescriptions(descriptionRequired, (err) => { if (err) { callback(err); } else { callback(null, this._mapItemsToDescriptions(null, null, items)); } }); }; TradeOfferManager.prototype._requestDescriptions = function(classes, callback) { var apps = []; var appids = []; // Split this out into appids classes.forEach((item) => { var index = appids.indexOf(item.appid); if (index == -1) { index = appids.push(item.appid) - 1; var arr = []; arr.appid = item.appid; apps.push(arr); } // Don't add a class/instanceid pair that we already have in the list if (apps[index].indexOf(item.classid + '_' + (item.instanceid || '0')) == -1) { apps[index].push(item.classid + '_' + (item.instanceid || '0')); } }); Async.map(apps, (app, cb) => { var chunks = []; var items = []; // Split this into chunks of ITEMS_PER_CLASSINFO_REQUEST items while (app.length > 0) { chunks.push(app.splice(0, ITEMS_PER_CLASSINFO_REQUEST)); } Async.each(chunks, (chunk, chunkCb) => { var input = { "appid": app.appid, "language": this._language, "class_count": chunk.length }; chunk.forEach((item, index) => { var parts = item.split('_'); input['classid' + index] = parts[0]; input['instanceid' + index] = parts[1]; }); this.emit('debug', "Requesting classinfo for " + chunk.length + " items"); this._apiCall('GET', { "iface": "ISteamEconomy", "method": "GetAssetClassInfo" }, 1, input, (err, body) => { if (err) { chunkCb(err); return; } if (!body.result || !body.result.success) { chunkCb(new Error("Invalid API response")); return; } var chunkItems = Object.keys(body.result).map((id) => { if (!id.match(/^\d+(_\d+)?$/)) { return null; } var item = body.result[id]; item.appid = app.appid; return item; }).filter(item => !!item); items = items.concat(chunkItems); chunkCb(null); }); }, (err) => { if (err) { cb(err); } else { cb(null, items); } }); }, (err, result) => { if (err) { callback(err); return; } result.forEach(this._digestDescriptions.bind(this)); callback(); }); };
/** Python arduino module for interacting with html5 arduino model. This is not intended for real world arduino interaction. **/ var arduino = arduino || {}; // do not override arduino.HIGH = 1; arduino.LOW = 0; arduino.CHANGE = 2; arduino.RISING = 3; arduino.FALLING = 4; arduino.OUTPUT = 'OUTPUT'; arduino.INPUT = 'INPUT'; arduino.INPUT_PULLUP = 'INPUT_PULLUP'; arduino.OFF = 0; arduino.ON = 1; // dictionary object for maintaing references to all arduinos to reset them if programs are rerun arduino.mapping = {}; arduino.Timer1 = function(ard, period) { this.period = period; this.arduino = ard; // keep array that contains all timeout ids if (!this.arduino.board.timer) { this.arduino.board.timer = []; } }; arduino.Timer1.prototype.attachInterrupt = function (func) { this.func = func; this.detachInterrupt(); this.arduino.board.timer.push(window.setInterval(this.func, this.period)); }; arduino.Timer1.prototype.detachInterrupt = function () { var i; if (!this.arduino || !this.arduino.board.timer) { return; // nothing to do here } for (i = 0; i < this.arduino.board.timer.length; i++) { window.clearInterval(this.arduino.board.timer[i]); } this.arduino.board.timer = []; }; /****************/ /* DHT */ /****************/ arduino.dht = function(arduino, pin, type) { // we identify dht by their wired arduino and its port // the python function does already check if those arguments are valid this.arduino = arduino; //debugger; this.pin = pin; this.type = type; }; arduino.dht.prototype.begin = function() { this.begin = true; this.arduino.board.pinMode(this.pin, arduino.INPUT); this.arduino.board.digitalWrite(this.pin, arduino.HIGH); }; /* helper method to check if pin is connected to our sensor */ arduino.dht.prototype.isPinConnected = function(pin) { var nodes; var selctorQuery = '#' + this.arduino.board.port + ' .' + (pin.name ? pin.name : ("pin" + pin)); nodes = document.querySelectorAll(selctorQuery); // check for input mode return nodes && nodes.length > 0; }; arduino.dht.prototype.readHumidity = function() { // always read zero if begin is not called if(this.begin === false) { return null; } // currently we are working with ids in order to get the temp var id = "#hum_input_" + this.arduino.board.port; var rh = $(id); if(rh.length === 0) { return null; } if(this.isPinConnected(this.pin)) { // add time check, value changes only every 2 seconds // slow sensor var millis = new Date().getTime(); if(this.lastHumidityTime && (millis-2*1000) >= this.lastHumidityTime) { this.lastHumidityTime = millis; this.oldHumidityValue = rh.val(); // update oldtime return this.oldHumidityValue; } else if(!this.lastHumidityTime) { this.lastHumidityTime = millis; this.oldHumidityValue = rh.val(); // update oldtime return this.oldHumidityValue; } else { // 2 seconds have not passed yet, so return old data return this.oldHumidityValue; } } else { return null; } }; // ToDo: add noise via random arduino.dht.prototype.readTemperature = function() { // always read zero if begin is not called if(this.begin === false) { return null; } var id = "#temp_input_" + this.arduino.board.port; var rt = $(id); if(rt.length === 0) { return null; } if(this.isPinConnected(this.pin)) { // add time check, value changes only every 2 seconds // slow sensor var millis = new Date().getTime(); if(this.lastTempTime && (millis-2*1000) >= this.lastTempTime) { this.lastTempTime = millis; this.oldTempValue = rt.val(); // update oldtime return this.oldTempValue; } else if(!this.lastTempTime) { this.lastTempTime = millis; this.oldTempValue = rt.val(); // update oldtime return this.oldTempValue; } else { // 2 seconds have not passed yet, so return old data return this.oldTempValue; } } else { return null; } }; /***************/ /* Arduino Uno */ /***************/ arduino.uno = function (resetID, onID, lID, txID) { this.timeoutID = undefined; this.status = arduino.OFF; this.actions = {}; this.actions.reset = document.getElementById(resetID); this.actions.on = document.getElementById(onID); this.actions.onChange = []; // list of external event handlers for value changes this.int0 = undefined; // digital pin 2 this.int1 = undefined; // digital pin 3 this.interrupts = true; // enabled by default http://arduino.cc/en/pmwiki.php?n=Reference/Interrupts this.port = undefined; // setup io map this.io = {}; this.io.ledON = { 'pin': undefined, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'LEDON' }; this.io.ledTX = { 'pin': undefined, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'LEDTX' }; this.io.ledRX = { 'pin': undefined, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'LEDRX' }; this.io.pin0 = { 'pin': 0, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'RX' }; this.io.pin1 = { 'pin': 1, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'TX' }; this.io.pin2 = { 'pin': 2, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'INT0' }; this.io.pin3 = { 'pin': 3, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'INT1' }; this.io.pin4 = { 'pin': 4, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin5 = { 'pin': 5, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin6 = { 'pin': 6, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin7 = { 'pin': 7, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin8 = { 'pin': 8, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin9 = { 'pin': 9, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'PWM' }; this.io.pin10 = { 'pin': 10, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'PWM' }; this.io.pin11 = { 'pin': 11, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'PWM' }; this.io.pin12 = { 'pin': 12, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin13 = { 'pin': 13, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'LED' }; this.io.gnd = { 'pin': 'gnd', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'GND' }; this.io.vcc = { 'pin': 'vcc', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'VCC' }; this.io.analog0 = { 'pin': '14', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog0' }; this.io.analog1 = { 'pin': '15', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog1' }; this.io.analog2 = { 'pin': '16', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog2' }; this.io.analog3 = { 'pin': '17', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog3' }; this.io.analog4 = { 'pin': '18', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog4' }; this.io.analog5 = { 'pin': '19', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog5' }; // mapping of all digital pins this.io.digital = [this.io.pin0, this.io.pin1, this.io.pin2, this.io.pin3, this.io.pin4, this.io.pin5, this.io.pin6, this.io.pin7, this.io.pin8, this.io .pin9, this.io.pin10, this.io.pin11, this.io.pin12, this.io.pin13, this.io.analog0, this.io.analog1, this.io.analog2, this.io.analog3, this.io.analog4, this.io.analog5 ]; // mapping of all analog pins this.io.analog = [this.io.analog0, this.io.analog1, this.io.analog2, this.io .analog3, this.io.analog4, this.io.analog5 ]; }; /** Actives the interrupts for the arduino **/ arduino.uno.prototype.interrupts = function () { this.interrupts = true; }; /** Deactives the interrupts for the arduino **/ arduino.uno.prototype.noInterrupts = function () { this.interrupts = false; }; arduino.uno.prototype.setStatus = function (status) { // only set valid status if (status !== undefined && (status === arduino.OFF || status === arduino.ON)) { this.status = status; this.digitalWrite(this.io.ledON, status); // LED control } }; /** Returns value for given pin, should be used in callbacks and not as public arduino API **/ arduino.uno.prototype._getPinValue = function (pin) { // is there a leading pin? if (typeof pin === 'string' && pin.indexOf('pin') === 0) { pin = pin.replace(/pin/g, ''); } var io_index = this._pin(pin); if (io_index == null) { return null; } return this.io.digital[io_index].value; // current value for specified pin }; arduino.uno.prototype.digitalRead = function (pin) { return this._getPinValue(pin); }; /** Adds an eventlistener that will be triggered on pin writing changes **/ arduino.uno.prototype.addonChange = function (callback) { if (callback) { return this.actions.onChange.push(callback) - 1; // return index } }; arduino.uno.prototype.onReset = function (callback) { this.actions.reset.addEventListener('click', callback, false); }; arduino.uno.prototype.onOn = function (callback) { this.actions.on.addEventListener('click', callback, false); }; /** interrupt: die Nummer des Interrupts (int) function : die Funktion, die aufgerufen wird, wenn ein Interrupt eintrifft; diese Funktion darf keine Parameter und auch keine R�ckgaben enthalten. mode : definiert wann genau der Interrupt eingeleitet werden soll. Vier Konstanten sind bereits als zul�ssige Werte vordefiniert worden. **/ arduino.uno.prototype.attachInterrupt = function (interrupt, func, mode) { var interrupt_object = { 'func': func, 'mode': mode }; // handle case for int0 and int1 if ('INT0' === interrupt.toUpperCase()) { this.int0 = interrupt_object; } else if ('INT1' === interrupt.toUpperCase()) { this.int1 = interrupt_object; } }; arduino.uno.prototype.detachInterrupt = function (interrupt) { // handle case for int0 and int1 if ('INT0' === interrupt.toUpperCase() || interrupt === 0) { this.int0 = undefined; } else if ('INT1' === interrupt.toUpperCase() || interrupt === 1) { this.int1 = undefined; } }; arduino.uno.prototype.pinMode = function (pin, mode) { if (!mode || !(mode === arduino.INPUT || mode === arduino.OUTPUT || arduino.INPUT_PULLUP)) { throw new Error('Unallowed mode: ' + mode); // return if no value specified } if (pin < 0 || pin > this.io.digital.length) { throw new Error('Cannot write to specified pin -> not existing.'); } this.io.digital[pin].pinmode = mode; }; arduino.uno.prototype._pin = function (pin) { // analog pins are mapped to 14-19 inside the io.digital array var _int = parseInt(pin); if (!isNaN(_int)) { pin = _int; } switch (pin) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: return pin; case 14: case 'a0': return 14; case 15: case 'a1': return 15; case 'a2': case 16: return 16; case 'a3': case 17: return 17; case 'a4': case 18: return 18; case 'a5': case 19: return 19; default: return null; } }; arduino.uno.prototype.digitalWrite = function (pin, value) { var susp; var that = this; if (!(value === arduino.HIGH || value === arduino.LOW)) { throw new Sk.builtin.ValueError('Value is neither HIGH nor LOW.'); // return if no value specified } // get pin object var io; if (typeof pin === 'string' || typeof pin === 'number') { if (!isNaN(pin) && (pin < 0 || pin > this.io.digital.length)) { throw new Sk.builtin.ValueError( 'Cannot write to specified pin -> not existing.'); } pin = this._pin(pin); io = this.io.digital[pin]; } else if (pin.value !== undefined && pin.pinmode !== undefined) { io = pin; // got pin object, value, mode, name } else { throw new Sk.builtin.ValueError( 'Cannot write to specified pin -> not existing.'); } var old_value = io.value; // ToDo: do we really need this? // are we allowed to write? if (io.pinmode === arduino.OUTPUT) { susp = new Sk.misceval.Suspension(); susp.resume = function() { if("error" in susp.data) { throw new Sk.builtin.Exception(susp.data.error.message); } }; susp.data = { type: "Sk.promise", promise: new Promise(function(resolve, reject) { io.value = value; // trigger callbacks if (old_value !== io.value) { var i; for (i = 0; i < that.actions.onChange.length; i++) { that.actions.onChange[i].call(that, io, pin); } } resolve(); }) }; return susp; } }; /** Not part of the original arduino function set, however needed to simulate external write operations on the pins and trigger interrupt routines **/ arduino.uno.prototype.externalDigitalWrite = function (pin, value, ignorePinmode) { if (!(value === arduino.HIGH || value === arduino.LOW)) { throw new Error('Value is neither HIGH nor LOW.'); // return if no value specified } if (pin < 0 || pin > this.io.digital.length) { throw new Error('Cannot write to specified pin -> not existing.'); } ignorePinmode = ignorePinmode || false; var io = this.io.digital[pin]; // get pin object // only check pinMode if required, some calls just change the value // while simulation a button press and therefore are set to input if (!ignorePinmode && io.pinmode === arduino.OUTPUT) { throw new Error('Pinmode for pin: ' + pin + ' is set to OUTPUT.'); } var that = this; var old_value = io.value; io.value = value; // set value // check mode var isChange = old_value != value; var isLow = value === arduino.LOW; var isHigh = value === arduino.HIGH; var isFalling = old_value === arduino.HIGH && value === arduino.LOW; var isRising = old_value === arduino.LOW && value === arduino.HIGH; // check if we need to trigger interrupt function triggerInterrupt(interrupt, change, low, high, falling, rising) { if (!interrupt) return; // check mode if ((interrupt.mode = arduino.CHANGE && change) || (interrupt.mode = arduino.LOW && low) || (interrupt.mode = arduino.HIGH && high) || ( interrupt.mode = arduino.FALLING && falling) || (interrupt.mode = arduino.RISING && rising)) { susp = new Sk.misceval.Suspension(); susp.resume = function() { if("error" in susp.data) { throw new Sk.builtin.Exception(susp.data.error.message); } }; susp.data = { type: "Sk.promise", promise: new Promise(function(resolve, reject) { // trigger it interrupt.func.call(that); resolve(); }) }; return susp; } } if (this.interrupts) { triggerInterrupt(this.int0, isChange, isLow, isHigh, isFalling, isRising); triggerInterrupt(this.int1, isChange, isLow, isHigh, isFalling, isRising); } }; /*********************/ /* Arduino Mega Rev3 */ /*********************/ arduino.mega = function (resetID, onID, lID, txID) { this.timeoutID = undefined; this.status = arduino.OFF; this.actions = {}; this.actions.reset = document.getElementById(resetID); this.actions.on = document.getElementById(onID); this.actions.onChange = []; // list of external event handlers for value changes this.int0 = undefined; // digital pin 2 this.int1 = undefined; // digital pin 3 this.interrupts = true; this.port = undefined; // setup io map this.io = {}; this.io.ledON = { 'pin': undefined, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'LEDON' }; this.io.ledTX = { 'pin': undefined, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'LEDTX' }; this.io.ledRX = { 'pin': undefined, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'LEDRX' }; this.io.pin0 = { 'pin': 0, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'RX' }; this.io.pin1 = { 'pin': 1, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'TX' }; this.io.pin2 = { 'pin': 2, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'INT0' }; this.io.pin3 = { 'pin': 3, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'INT1' }; this.io.pin4 = { 'pin': 4, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin5 = { 'pin': 5, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin6 = { 'pin': 6, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin7 = { 'pin': 7, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin8 = { 'pin': 8, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin9 = { 'pin': 9, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'PWM' }; this.io.pin10 = { 'pin': 10, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'PWM' }; this.io.pin11 = { 'pin': 11, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'PWM' }; this.io.pin12 = { 'pin': 12, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin13 = { 'pin': 13, 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'LED' }; this.io.pin14 = { 'pin': '14', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin15 = { 'pin': '15', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin16 = { 'pin': '16', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin17 = { 'pin': '17', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin18 = { 'pin': '18', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin19 = { 'pin': '19', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin20 = { 'pin': '20', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin21 = { 'pin': '21', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin22 = { 'pin': '22', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin23 = { 'pin': '23', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin24 = { 'pin': '24', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin25 = { 'pin': '25', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin26 = { 'pin': '26', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin27 = { 'pin': '27', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin28 = { 'pin': '28', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin29 = { 'pin': '29', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin30 = { 'pin': '30', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin31 = { 'pin': '31', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin32 = { 'pin': '32', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin33 = { 'pin': '33', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin34 = { 'pin': '34', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin35 = { 'pin': '35', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin36 = { 'pin': '36', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin37 = { 'pin': '37', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin38 = { 'pin': '38', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin39 = { 'pin': '39', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin40 = { 'pin': '40', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin41 = { 'pin': '41', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin42 = { 'pin': '42', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin43 = { 'pin': '43', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin44 = { 'pin': '44', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin45 = { 'pin': '45', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin46 = { 'pin': '46', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin47 = { 'pin': '47', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin48 = { 'pin': '48', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin49 = { 'pin': '49', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin50 = { 'pin': '50', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin51 = { 'pin': '51', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin52 = { 'pin': '52', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.pin53 = { 'pin': '53', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': undefined }; this.io.gnd = { 'pin': 'gnd', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'GND' }; this.io.vcc = { 'pin': 'vcc', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'VCC' }; this.io.analog0 = { 'pin': '54', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog0' }; this.io.analog1 = { 'pin': '55', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog1' }; this.io.analog2 = { 'pin': '56', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog2' }; this.io.analog3 = { 'pin': '57', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog3' }; this.io.analog4 = { 'pin': '58', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog4' }; this.io.analog5 = { 'pin': '59', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog5' }; this.io.analog6 = { 'pin': '60', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog6' }; this.io.analog7 = { 'pin': '61', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog7' }; this.io.analog8 = { 'pin': '62', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog8' }; this.io.analog9 = { 'pin': '63', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog9' }; this.io.analog10 = { 'pin': '64', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog10' }; this.io.analog11 = { 'pin': '65', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog11' }; this.io.analog12 = { 'pin': '66', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog12' }; this.io.analog13 = { 'pin': '67', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog13' }; this.io.analog14 = { 'pin': '68', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog14' }; this.io.analog15 = { 'pin': '69', 'value': 0, 'pinmode': arduino.OUTPUT, 'name': 'analog15' }; // mapping of all analog pins this.io.analog = []; for(var i = 0; i <= 15; i++) { this.io.analog.push(this.io["analog" + i]); } // mapping of all digital pins this.io.digital = []; for(var j = 0; j <= 53; j++) { this.io.digital.push(this.io["pin" + j]); } this.io.digital = this.io.digital.concat(this.io.analog); }; /* inheritance code right here */ arduino.mega.prototype = Object.create(arduino.uno.prototype); /** Returns value for given pin, should be used in callbacks and not as public arduino API **/ arduino.mega.prototype._getPinValue = function (pin) { // is there a leading pin? if (typeof pin === 'string' && pin.indexOf('pin') === 0) { pin = pin.replace(/pin/g, ''); } var io_index = this._pin(pin); if (io_index == null) { return null; } return this.io.digital[io_index].value; // current value for specified pin }; arduino.mega.prototype.digitalRead = function (pin) { return this._getPinValue(pin); }; // needs to be overriden /** * Pin-Mapping of the code to the pin object. */ arduino.mega.prototype._pin = function (pin) { // analog pins start at index 54 in the digital io array var _int = parseInt(pin); if (!isNaN(_int)) { pin = _int; } if (pin >= 0 && pin <= 53) { return pin; } switch (pin) { case 54: case 'a0': return 54; case 55: case 'a1': return 55; case 'a2': case 56: return 56; case 'a3': case 57: return 57; case 'a4': case 58: return 58; case 'a5': case 59: return 59; case 'a6': case 60: return 60; case 'a7': case 61: return 61; case 'a8': case 62: return 62; case 'a9': case 63: return 63; case 'a10': case 64: return 64; case 'a11': case 65: return 65; case 'a12': case 66: return 66; case 'a13': case 67: return 67; case 'a14': case 68: return 68; case 'a15': case 69: return 69; default: return null; } }; // helper functions that fixes IE svg classList issues arduino.getClassList = function (element) { if (typeof element.classList === 'undefined') { var arr = (element.className instanceof SVGAnimatedString ? element.className .baseVal : element.className) .split(/\s+/); if ('' === arr[0]) { arr.pop(); } return arr; } else { return element.classList; } }; /* end of arduino api */ /* ToDo: we need a hook for plugging in the various arduino examples, each regged com port has a special callback function handling the specific example stuff */ var $builtinmodule = function (name) { var mod = {}; // html ids of the buttons mod.arduino_reset = new Sk.builtin.str('arduino_reset'); // should be overridable mod.arduino_on = new Sk.builtin.str('arduino_on'); // dito mod.HIGH = new Sk.builtin.int_(arduino.HIGH); mod.LOW = new Sk.builtin.int_(arduino.LOW); mod.INPUT = new Sk.builtin.str(arduino.INPUT); mod.INPUT_PULLUP = new Sk.builtin.str(arduino.INPUT_PULLUP); mod.OUTPUT = new Sk.builtin.str(arduino.OUTPUT); mod.CHANGE = new Sk.builtin.str(arduino.CHANGE); mod.CHANGE = new Sk.builtin.str(arduino.CHANGE); mod.FALLING = new Sk.builtin.str(arduino.FALLING); var timeoutID = []; // collection of timeoutIDs function write_callback(io, pin) { var nodes; var selctorQuery = '#' + this.port + ' .' + (pin.name ? pin.name : ("pin" + pin)); nodes = document.querySelectorAll(selctorQuery); if (!nodes || nodes.length <= 0) { console.log("Specified pin is not connected: " + pin.name); return; } var visibility = "hidden"; if (io.value) { visibility = "visible"; } var i; var classlist; for (i = 0; i < nodes.length; i++) { // fix for IE that does not have and classList attribute on svg elements classlist = arduino.getClassList(nodes[i]); if (classlist.length === 1) { nodes[i].setAttribute("visibility", visibility); } } } /* * internal helper method, that clears timeouts and clears the pins, and resets * the internal model of the arduino */ function resetAll(ard) { var i; for (i = 0; i < timeoutID.length; i++) { window.clearTimeout(timeoutID[i]); } timeoutID = []; // detach any interrupts if(ard.board.timer) { for (i = 0; i < ard.board.timer.length; i++) { window.clearInterval(ard.board.timer[i]); } ard.board.timer = []; } // ToDo: must be changed for mega for (i = 0; i <= 13; i++) { ard.board.digitalWrite(i, arduino.LOW); } ard.board.setStatus(arduino.OFF); //Sk.execLimit = 0; // execution limit set to 0 will stop asy } var CLASS_ARDUINO = 'Arduino'; var CLASS_TIMER = "Timer1"; var CLASS_DHT = "dht"; var timer_f = function ($gbl, $loc) { var init_f = function (self, ardu, timeout) { Sk.builtin.pyCheckArgs('__init__', arguments, 3, 3); if (Sk.abstr.typeName(ardu) !== CLASS_ARDUINO) { throw new Sk.builtin.ValueError('dht requires arduino object'); } if (!Sk.builtin.checkNumber(timeout)) { throw new Sk.builtin.TypeError( 'argument timeout must be a numeric type'); } var _timeout = Sk.ffi.remapToJs(timeout); var _arduino = ardu.v; // custom unmapping self.v = new arduino.Timer1(_arduino, _timeout); // detach previous interrupt, if any self.v.detachInterrupt(); }; $loc.__init__ = new Sk.builtin.func(init_f); var attach_f = function (self, func) { Sk.builtin.pyCheckArgs('attachInterrupt', arguments, 2, 2); if (!Sk.builtin.checkFunction(func)) { throw new Sk.builtin.TypeError('func must be a function type'); } // go, attaches interrupt and sets interval var callback = function () { Sk.misceval.callsimAsync(null, func).then(function success(r) {}, function failure(e) {}); }; self.v.attachInterrupt(callback); // call internal attachInterrupt method }; $loc.attachInterrupt = new Sk.builtin.func(attach_f); }; mod[CLASS_TIMER] = Sk.misceval.buildClass(mod, timer_f, CLASS_TIMER, []); /****************************/ /* DHT Class */ /****************************/ var dht_f = function($gbl, $loc) { var init_f = function(self, ard, pin, type) { Sk.builtin.pyCheckArgs('__init__', arguments, 4, 4); if (Sk.abstr.typeName(ard) !== CLASS_ARDUINO) { throw new Sk.builtin.ValueError('dht requires arduino object'); } if(!Sk.builtin.checkInt(pin)) { throw new Sk.builtin.TypeError("argument 'pin' must be of type 'int'"); } var _pin = Sk.ffi.remapToJs(pin); if(!Sk.builtin.checkString(type)) { throw new Sk.builtin.TypeError("argument 'type' must be of type 'int'"); } var _type = Sk.ffi.remapToJs(type); self.v = new arduino.dht(ard.v, _pin, _type); }; init_f.co_varnames = ['arduino', 'pin', 'type']; $loc.__init__ = new Sk.builtin.func(init_f); /* to be consistent with dht.c lib */ $loc.begin = new Sk.builtin.func(function(self){ Sk.builtin.pyCheckArgs('begin', arguments, 1, 1); self.v.begin(); }); /* either return valid float or nan */ $loc.readHumidity = new Sk.builtin.func(function(self){ Sk.builtin.pyCheckArgs('readHumidity', arguments, 1, 1); var hum = self.v.readHumidity(); if(hum === null || hum === undefined) { return Sk.builtin.float_(new Sk.builtin.str("nan")); } else { return new Sk.builtin.float_(hum); } }); /* either return valid float or nan */ $loc.readTemperature = new Sk.builtin.func(function(self){ Sk.builtin.pyCheckArgs('readTemperature', arguments, 1, 1); var temp = self.v.readTemperature(); if(temp === null || temp === undefined) { return Sk.builtin.float_(new Sk.builtin.str("nan")); } else { return new Sk.builtin.float_(temp); } }); }; mod[CLASS_DHT] = Sk.misceval.buildClass(mod, dht_f, CLASS_DHT, []); var arduino_f = function ($gbl, $loc) { var init_f = function (self, baud, port, timeout, sr) { Sk.builtin.pyCheckArgs('__init__', arguments, 3, 5); // ignore the actual arguments, due to the fact that we do not establish // a real connection to an hardware device var _port = Sk.ffi.remapToJs(port); var _reset = Sk.ffi.remapToJs(mod.arduino_reset) + "_" + _port; var _on = Sk.ffi.remapToJs(mod.arduino_on) + "_" + _port; var arduinoJS = {}; // get the class used on the svg in order to determine the board type var $board = $("#" + _port); if ($board.length === 0) { throw new Sk.builtin.ValueError("Cannot connect to specified port."); } var isArduinoMega = $board.hasClass("mega"); if (isArduinoMega) { arduinoJS.board = new arduino.mega(_reset, _on); } else { arduinoJS.board = new arduino.uno(_reset, _on); } arduinoJS.board.port = _port; self.v = arduinoJS; // we store the arduino instance in the Sk-space for external access if (_port in arduino.mapping) { // reset previous arduino instance and proceed // add dict for com4 ports and arduino objects resetAll(arduino.mapping[_port]); } arduino.mapping[_port] = self.v; self.tp$name = CLASS_ARDUINO; // set class name // add 'write' callback that toggles the visibility for items with exactly // one html class value (pin specifier) self.v.board.addonChange(write_callback); self.v.board.actions.reset.addEventListener('click', function () { resetAll(self.v); }, false); // check for external hooks if(typeof Sk.customArduinoCallback === "function") { // register custom change callback self.v.board.addonChange(Sk.customArduinoCallback); } if(typeof Sk.customArduinoInit === "function") { // call custom initialization Sk.customArduinoInit.call(undefined, self.v.board); } }; init_f.co_varnames = ['baud', 'port', 'timeout', 'sr']; init_f.$defaults = [new Sk.builtin.int_(9600), Sk.builtin.none.none$, new Sk.builtin.int_(2), Sk.builtin.none.none$]; $loc.__init__ = new Sk.builtin.func(init_f); $loc.tp$getattr = Sk.builtin.object.prototype.GenericGetAttr; $loc.tp$setattr = Sk.builtin.object.prototype.GenericSetAttr; $loc.interrupts = new Sk.builtin.func(function (self) { Sk.builtin.pyCheckArgs('interrupts', arguments, 1, 1); // first unwrap arduino board object var arduinoJS = self.v; arduinoJS.board.interrupts(); }); $loc.noInterrupts = new Sk.builtin.func(function (self) { Sk.builtin.pyCheckArgs('noInterrupts', arguments, 1, 1); // first unwrap arduino board object var arduinoJS = self.v; arduinoJS.board.noInterrupts(); }); $loc.setStatus = new Sk.builtin.func(function (self, status) { Sk.builtin.pyCheckArgs('setStatus', arguments, 2, 2); // first unwrap arduino board object var arduinoJS = self.v; var _status = Sk.remapToJs(status); if (!_status || (_status !== arduino.OFF && _status !== arduino.ON)) { throw new Sk.builtin.ValueError('status must be either ON or OFF'); } arduinoJS.board.setStatus(Sk.remapToJs(status)); }); $loc.attachInterrupt = new Sk.builtin.func(function (self, interrupt, func, mode) { Sk.builtin.pyCheckArgs('attachInterrupt', arguments, 4, 4); // ToDo: check if mode is one of the 4 predefined values, FALLING; RASING,... // first unwrap arduino board object var arduinoJS = self.v; //debugger; var _interrupt = Sk.ffi.remapToJs(interrupt); var _mode = Sk.ffi.remapToJs(mode); arduinoJS.board.attachInterrupt(_interrupt, func, _mode); }); $loc.detachInterrupt = new Sk.builtin.func(function (self, interrupt) { Sk.builtin.pyCheckArgs('detachInterrupt', arguments, 2, 2); // first unwrap arduino board object var arduinoJS = self.v; var _interrupt = Sk.ffi.remapToJs(interrupt); arduinoJS.board.detachInterrupt(_interrupt); }); $loc.pinMode = new Sk.builtin.func(function (self, pin, mode) { Sk.builtin.pyCheckArgs('pinMode', arguments, 3, 3); // first unwrap arduino board object var arduinoJS = self.v; var _pin = Sk.ffi.remapToJs(pin); var _mode = Sk.ffi.remapToJs(mode); arduinoJS.board.pinMode(_pin, _mode); }); $loc.digitalWrite = new Sk.builtin.func(function (self, pin, value) { Sk.builtin.pyCheckArgs('digitalWrite', arguments, 3, 3); if (!Sk.builtin.checkNumber(pin) && !Sk.builtin.checkString(pin)) { throw new Sk.builtin.TypeError( "argument pin must be a 'int' or 'string' type"); } if (!Sk.builtin.checkNumber(value)) { throw new Sk.builtin.TypeError( "argument value must be a 'int' type"); } // first unwrap arduino board object var arduinoJS = self.v; var _pin = Sk.ffi.remapToJs(pin); var _value = Sk.ffi.remapToJs(value); // we add a small timeout var susp = new Sk.misceval.Suspension(); susp.resume = function() { return Sk.builtin.none.none$; }; susp.data = {type: "Sk.promise", promise: new Promise(function(resolve){ if (typeof setTimeout === "undefined") { // We can't sleep (eg test environment), so resume immediately arduinoJS.board.digitalWrite(_pin, _value); resolve(); } else { arduinoJS.board.digitalWrite(_pin, _value); setTimeout(resolve, 10); // wait 10 ms for each write } })}; return susp; }); $loc.digitalRead = new Sk.builtin.func(function (self, pin) { Sk.builtin.pyCheckArgs('digitalRead', arguments, 2, 2); // first unwrap arduino board object // ToDo: add check for valid pin numbers or pin names var arduinoJS = self.v; var _pin = Sk.ffi.remapToJs(pin); // we add a small timeout var susp = new Sk.misceval.Suspension(); susp.resume = function() { return susp.data.result; }; susp.data = { type: "Sk.promise", promise: new Promise(function(resolve) { if (typeof setTimeout === "undefined") { // We can't sleep (eg test environment), so resume immediately var vv_js = arduinoJS.board.digitalRead(_pin); if (vv_js == null) { throw new Sk.builtin.ValueError('invalid pin'); } resolve(Sk.ffi.remapToPy(vv_js)); } else { setTimeout(function(){ resolve(Sk.ffi.remapToPy(arduinoJS.board.digitalRead(_pin))); }, 10); // wait 10 ms for each write } }), }; return susp; }); }; mod[CLASS_ARDUINO] = Sk.misceval.buildClass(mod, arduino_f, CLASS_ARDUINO, []); function write_ledmatrix(io, pin) { // we have to determine the when we are allowed to 'light' and when to // turn the leds off /* col1, ..., col6 ------------- | | | | | | | ------------- | | | | | | | ------------- | | | | | | | ------------- */ //debugger; if (isNaN(pin) || pin < 0 || pin > 19) { //|| cols.indexOf(pin) === -1) { return; } var nodes; var pin_classname = pin.name ? pin.name : ("pin" + pin); nodes = document.getElementsByClassName(pin_classname); // iterate over all nodes and check if we can turn on or off var sibling_index; var fill; var sibling_value; var i; function classname_map(x) { return x.indexOf(pin_classname, x.length - pin_classname.length) === - 1; } for (i = 0; i < nodes.length; i++) { // 1. get other pin index for specified fill = '#fafafa'; var siblings = Array.prototype.filter.call(arduino.getClassList(nodes[i]), classname_map); if (siblings.length > 0) { sibling_value = this._getPinValue(siblings[0]); // HIGH value on col and HIGH on row if (io.value === arduino.HIGH && sibling_value === arduino.HIGH) { fill = 'lime'; } nodes[i].setAttribute("fill", fill); } } } mod.ledMatrix = new Sk.builtin.func(function (ard) { Sk.builtin.pyCheckArgs('ledMatrix', arguments, 1, 1); if (Sk.abstr.typeName(ard) !== CLASS_ARDUINO) { throw new Sk.builtin.ValueError('ledMatrix needs arduino object'); } ard.v.board.addonChange(write_ledmatrix); }); /** * delay function that accepts milliseconds */ mod.delay = new Sk.builtin.func(function (delay) { Sk.builtin.pyCheckArgs('delay', arguments, 1, 1); if(!Sk.builtin.checkInt(delay)) { throw new Sk.builtin.TypeError("argument 'delay' must be of type 'int'"); } var _delay = Sk.ffi.remapToJs(delay); if (_delay < 10) { _delay = 10; } var susp = new Sk.misceval.Suspension(); susp.resume = function() { return Sk.builtin.none.none$; }; susp.data = {type: "Sk.promise", promise: new Promise(function(resolve) { if (typeof setTimeout === "undefined") { // We can't sleep (eg test environment), so resume immediately resolve(); } else { setTimeout(resolve, _delay); } })}; return susp; }); mod.disableExecutionLimit = new Sk.builtin.func(function () { Sk.builtin.pyCheckArgs('disableExecutionLimit', arguments, 0, 0); Sk.execLimit = Number.POSITIVE_INFINITY; return Sk.builtin.none.none$; }); mod.enableExecutionLimit = new Sk.builtin.func(function () { Sk.builtin.pyCheckArgs('enableExecutionLimit', arguments, 0, 0); Sk.execLimit = 30 * 1000; // 30 secs return Sk.builtin.none.none$; }); return mod; };
var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); var expect = chai.expect; var helpers = require('../helpers'); var firebaseServer; var client; var reporting; beforeEach(() => { firebaseServer = helpers.newFirebaseServer(); client = helpers.newFirebaseClient(); reporting = new helpers.FirebaseReporting({ firebase: helpers.newFirebaseClient() }); }); afterEach(() => { if (firebaseServer) { firebaseServer.close(); firebaseServer = null; } }); describe('evaluator', () => { it('should store correct metric for single data point', (done) => { reporting.addMetric('value', ['min']); const data = {value: 50}; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter().min('value').select(1)).to.become([50]) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); it('should store correct metric for multiple data points', (done) => { reporting.addMetric('value', ['min']); const data = [{value: 50}, {value: 2}, {value: 5}]; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter().min('value').select(1)).to.become([2]) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); }); describe('value', () => { it('should retrieve metric with default filter', (done) => { reporting.addMetric('value', ['min']); const data = {value: 50}; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter().min('value').value()).to.become(50) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); it('should retrieve metric with custom filter', (done) => { reporting.addFilter('custom', ['mode']); reporting.addMetric('value', ['min']); const data = {value: 50, mode: 1}; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter('custom', { mode: 1 }).min('value').value()).to.become(50), expect(reporting.filter('custom', { mode: 2 }).min('value').value()).to.become(null) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); }); describe('select', () => { it('should retrieve metric with default filter', (done) => { reporting.addMetric('value', ['min']); const data = {value: 50}; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter().min('value').select(1)).to.become([50]) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); it('should retrieve metric with custom filter', (done) => { reporting.addFilter('custom', ['mode']); reporting.addMetric('value', ['min']); const data = {value: 50, mode: 1}; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter('custom').min('value').select(1)).to.become([50]) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); }); describe('count', () => { it('should retrieve metric with default filter', (done) => { reporting.addMetric('value', ['min']); const data = [{value: 50},{value: 2},{value: 5}]; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter().min('value').count()).to.become(1) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); it('should retrieve metric with custom filter', (done) => { reporting.addFilter('custom', ['mode']); reporting.addMetric('value', ['min']); const data = [{value: 50, mode: 1},{value: 2, mode: 2},{value: 5, mode: 3}]; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter('custom').min('value').count()).to.become(3) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); }); describe('lesser', () => { it('should retrieve metric with default filter', (done) => { reporting.addMetric('value', ['min']); const data = [{value: 50},{value: 2},{value: 5}]; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter().min('value').lesser(5).count()).to.become(1), expect(reporting.filter().min('value').lesser(1).count()).to.become(0) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); it('should retrieve metric with custom filter', (done) => { reporting.addFilter('custom', ['mode']); reporting.addMetric('value', ['min']); const data = [{value: 50, mode: 1},{value: 2, mode: 2},{value: 5, mode: 1}]; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter('custom').min('value').lesser(50).count()).to.become(2), expect(reporting.filter('custom').min('value').lesser(2).count()).to.become(1) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); }); describe('greater', () => { it('should retrieve metric with default filter', (done) => { reporting.addMetric('value', ['min']); const data = [{value: 50},{value: 2},{value: 3}]; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter().min('value').greater(2).count()).to.become(1), expect(reporting.filter().min('value').greater(3).count()).to.become(0) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); it('should retrieve metric with custom filter', (done) => { reporting.addFilter('custom', ['mode']); reporting.addMetric('value', ['min']); const data = [{value: 50, mode: 1},{value: 2, mode: 2},{value: 5, mode: 1}]; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter('custom').min('value').greater(5).count()).to.become(1), expect(reporting.filter('custom').min('value').greater(0).count()).to.become(2) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); }); describe('equal', () => { it('should retrieve metric with default filter', (done) => { reporting.addMetric('value', ['min']); const data = [{value: 50},{value: 2},{value: 5}]; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter().min('value').equal(2).count()).to.become(1), expect(reporting.filter().min('value').equal(5).count()).to.become(0), expect(reporting.filter().min('value').equal(50).count()).to.become(0) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); it('should retrieve metric with custom filter', (done) => { reporting.addFilter('custom', ['mode']); reporting.addMetric('value', ['min']); const data = [{value: 50, mode: 1},{value: 2, mode: 2},{value: 5, mode: 1}]; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter('custom').min('value').equal(50).count()).to.become(0), expect(reporting.filter('custom').min('value').equal(2).count()).to.become(1), expect(reporting.filter('custom').min('value').equal(5).count()).to.become(1) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); }); describe('between', () => { it('should retrieve metric with default filter', (done) => { reporting.addMetric('value', ['min']); const data = [{value: 50},{value: 2},{value: 5}]; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter().min('value').between(0, 5).count()).to.become(1), expect(reporting.filter().min('value').between(10, 50).count()).to.become(0) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); it('should retrieve metric with custom filter', (done) => { reporting.addFilter('custom', ['mode']); reporting.addMetric('value', ['min']); const data = [{value: 50, mode: 1},{value: 2, mode: 2},{value: 5, mode: 1}]; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter('custom').min('value').between(10, 50).count()).to.become(0), expect(reporting.filter('custom').min('value').between(0, 50).count()).to.become(2), expect(reporting.filter('custom').min('value').between(1, 5).count()).to.become(2), expect(reporting.filter('custom').min('value').between(1, 2).count()).to.become(1), expect(reporting.filter('custom').min('value').between(4, 5).count()).to.become(1) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); }); describe('during', () => { it('should retrieve metrics with default filter', (done) => { reporting.addMetric('value', ['min']); reporting.enableRetainer('minute', 'value', ['min']); reporting.enableRetainer('second', 'value', ['min']); const data = [{value: 50},{value: 2},{value: 5}]; const start = new Date().getTime() - 1000*60*60; const end = new Date().getTime() + 1000*60*60; const bucketsecond = reporting.getEmptyBuckets('second', start, end); bucketsecond[reporting.getRetainerBucketKey('second')] = 2; const bucketminute = reporting.getEmptyBuckets('minute', start, end); bucketminute[reporting.getRetainerBucketKey('minute')] = 2; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter().min('value').during('minute').range(start, end).valuesAsObject(true)).to.become(bucketminute), expect(reporting.filter().min('value').during('second').range(start, end).valuesAsObject(true)).to.become(bucketsecond) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); it('should retrieve metrics with custom filter', (done) => { reporting.addFilter('custom', ['mode']); reporting.addMetric('value', ['min']); reporting.enableRetainer('minute', 'value', ['min']); reporting.enableRetainer('second', 'value', ['min']); const data = [{value: 50, mode: 1},{value: 2, mode: 2},{value: 5, mode: 1}]; const start = new Date().getTime() - 1000*60*60; const end = new Date().getTime() + 1000*60*60; const bucketsecond1 = reporting.getEmptyBuckets('second', start, end); bucketsecond1[reporting.getRetainerBucketKey('second')] = 5; const bucketsecond2 = reporting.getEmptyBuckets('second', start, end); bucketsecond2[reporting.getRetainerBucketKey('second')] = 2; const bucketminute1 = reporting.getEmptyBuckets('minute', start, end); bucketminute1[reporting.getRetainerBucketKey('minute')] = 5; const bucketminute2 = reporting.getEmptyBuckets('minute', start, end); bucketminute2[reporting.getRetainerBucketKey('minute')] = 2; reporting.saveMetrics(data).then(() => { expect(Promise.all([ expect(reporting.filter('custom', { mode: 1 }).min('value').during('minute').range(start, end).valuesAsObject(true)).to.become(bucketminute1), expect(reporting.filter('custom', { mode: 2 }).min('value').during('minute').range(start, end).valuesAsObject(true)).to.become(bucketminute2), expect(reporting.filter('custom', { mode: 1 }).min('value').during('second').range(start, end).valuesAsObject(true)).to.become(bucketsecond1), expect(reporting.filter('custom', { mode: 2 }).min('value').during('second').range(start, end).valuesAsObject(true)).to.become(bucketsecond2) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }); it('should retrieve metrics across time gaps', (done) => { reporting.addMetric('value', ['min']); reporting.enableRetainer('second', 'value', ['min']); reporting.enableRetainer('minute', 'value', ['min']); const data1 = [{value: 50},{value: 3}]; const data2 = [{value: 5},{value: 2}]; const start = new Date().getTime() - 1000*60*60; const end = new Date().getTime() + 1000*60*60; const bucketsecond = reporting.getEmptyBuckets('second', start, end); bucketsecond[reporting.getRetainerBucketKey('second')] = 3; const bucketminute = reporting.getEmptyBuckets('minute', start, end); bucketminute[reporting.getRetainerBucketKey('minute')] = 2; reporting.saveMetrics(data1).then(() => { setTimeout(() => { bucketsecond[reporting.getRetainerBucketKey('second')] = 2; reporting.saveMetrics(data2).then(() => { expect(Promise.all([ expect(reporting.filter().min('value').during('second').range(start, end).valuesAsObject(true)).to.become(bucketsecond), expect(reporting.filter().min('value').during('minute').range(start, end).valuesAsObject(true)).to.become(bucketminute) ])).notify(done); }).catch((err) => { done(new Error(err)); }); }, 1000); }).catch((err) => { done(new Error(err)); }); }); });
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ var GetValue = require('../utils/object/GetValue'); // Contains the plugins that Phaser uses globally and locally. // These are the source objects, not instantiated. var inputPlugins = {}; /** * @namespace Phaser.Input.InputPluginCache */ var InputPluginCache = {}; /** * Static method called directly by the Core internal Plugins. * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin) * Plugin is the object to instantiate to create the plugin * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input) * * @name Phaser.Input.InputPluginCache.register * @type {function} * @static * @since 3.10.0 * * @param {string} key - A reference used to get this plugin from the plugin cache. * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated. * @param {string} mapping - If this plugin is to be injected into the Input Plugin, this is the property key used. * @param {string} settingsKey - The key in the Scene Settings to check to see if this plugin should install or not. * @param {string} configKey - The key in the Game Config to check to see if this plugin should install or not. */ InputPluginCache.register = function (key, plugin, mapping, settingsKey, configKey) { inputPlugins[key] = { plugin: plugin, mapping: mapping, settingsKey: settingsKey, configKey: configKey }; }; /** * Returns the input plugin object from the cache based on the given key. * * @name Phaser.Input.InputPluginCache.getCore * @type {function} * @static * @since 3.10.0 * * @param {string} key - The key of the input plugin to get. * * @return {Phaser.Input.Types.InputPluginContainer} The input plugin object. */ InputPluginCache.getPlugin = function (key) { return inputPlugins[key]; }; /** * Installs all of the registered Input Plugins into the given target. * * @name Phaser.Input.InputPluginCache.install * @type {function} * @static * @since 3.10.0 * * @param {Phaser.Input.InputPlugin} target - The target InputPlugin to install the plugins into. */ InputPluginCache.install = function (target) { var sys = target.scene.sys; var settings = sys.settings.input; var config = sys.game.config; for (var key in inputPlugins) { var source = inputPlugins[key].plugin; var mapping = inputPlugins[key].mapping; var settingsKey = inputPlugins[key].settingsKey; var configKey = inputPlugins[key].configKey; if (GetValue(settings, settingsKey, config[configKey])) { target[mapping] = new source(target); } } }; /** * Removes an input plugin based on the given key. * * @name Phaser.Input.InputPluginCache.remove * @type {function} * @static * @since 3.10.0 * * @param {string} key - The key of the input plugin to remove. */ InputPluginCache.remove = function (key) { if (inputPlugins.hasOwnProperty(key)) { delete inputPlugins[key]; } }; module.exports = InputPluginCache;
var express = require('express'); var path = require('path'); var bodyParser = require('body-parser'); var routes = require('./controllers/index'); var users = require('./controllers/users'); var mysql = require('mysql'); var connection = require("express-myconnection"); var app =express(); var multipart = require('connect-multiparty'); //Create Sql Connection /*var connection = connection(mysql, { host: "107.21.183.146", user: "tcst", password: "tabcaps", database: "react_poc" },'request'); app.use(connection);*/ var connection = connection(mysql, { host: "localhost", user: "root", password: "root", database: "node" },'request'); app.use(connection); // view engine setup app.set('views', path.join(__dirname, 'views')); app.use(express.static('/home/ec2-user/www/SampleReactApp')); app.set('view engine', 'jade'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // to support encoded bodies app.use(multipart()); app.use(require('./controllers')); app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); app.listen('3000', function(){ console.log('server is running..'); }); module.exports = app;