Example #1
0
// TODO: implement _unvalidatedMessageIndexes, for messages saved as
// .clientDate awaiting a valid .serverDate

/**
 * Update a Message
 * @param {string} id The message's serverDate
 * @param {object} updates An object literal containing only the data to be
 *     updated.
 */
function update(updates) {
  var id = updates.serverDate,
      localId = updates.clientDate;

  // Check if the update is an acknowledgement of a previously sent message.
  // This will false positive if the server sends a clientDate incorrectly,
  // and that exact timestamp exists on our side. The chances of an *exact*
  // microsecond id collision is very low. I hope.
  if (localId && id && _messages[localId]) {
    // Migrate message

    _messages[id] = merge(_messages[localId], updates);
    delete _messages[localId];

    console.log('moving ', localId, 'to', id);

  } else if (localId && id === undefined) {
    // New message, before server ack
    _messages[localId] = updates;

  } else if (_messages[id] === undefined) {
    // Server sent message unknown to us
    _messages[id] = updates;

  } else {
    // Server sent message known to us -- merge
    _messages[id] = merge(_messages[id], updates);
  }

  console.log('updated store', _messages);

}
    getAll: function() {
        if ( !setlistSongs ) {
            setlistSongs = {};

            var songs = $.ajax({
                url: API_HOST + '/setlist_songs?setlist_id=1',
                async: false
            }).responseJSON;

            for ( var i = 0, len = songs.length; i < len; i++ ) {
                var song = songs[ i ];
                song.capo = song.capo ? song.capo : 0;
                var newSong = merge(
                    {
                        key: song.key,
                        capo: song.capo,
                        id: song.id
                    },
                    merge( song.song, { capo: song.capo, key: song.key ? song.key : song.song.key } )
                );
                newSong.originalKey = song.song.key;

                setlistSongs[ newSong.id ] = newSong;
            }
        }

        return setlistSongs;
    },
Example #3
0
/**
 * Create a view for which matches for a path with the provided routes
 *
 * @param {Route} routes
 * @returns {Promise<ReactComponent>}
 */
function createView(match) {
  var views = {};

  for (var i = match.activeTrace.length - 1; i >= 0; i--) {
    var step = match.activeTrace[i];

    views = merge(views, collectSubViews(step.props, views));

    if (step.route.view !== undefined) {
      var props = merge(step.props, views);
      return step.route.view(props);
    }
  }
}
  setPath: function(path, navigation, cb) {
    var match = matchRoutes(this.getRoutes(this.props), path);
    var handler = match.getHandler();

    var state = {
      match: match,
      handler: handler,
      prefix: this.state.prefix,
      navigation: navigation
    };

    navigation = merge(navigation, {match: match});

    if (this.props.onBeforeNavigation &&
        this.props.onBeforeNavigation(path, navigation) === false) {
      return;
    }

    if (navigation.onBeforeNavigation &&
        navigation.onBeforeNavigation(path, navigation) === false) {
      return;
    }

    this.delegateSetRoutingState(state, function() {
      if (this.props.onNavigation) {
        this.props.onNavigation();
      }
      cb();
    }.bind(this));
  },
Example #5
0
    return function (opts) {
        /**
         * @type {{promise: Promise, resolve: Function, reject: Function}} Deferred
         */
        var d = deferred();
        xhr({
            withCredentials: true,
            json: opts && opts.body ? opts.body : {},
            uri: apiHost + config.uri(opts),
            method: config.method,
            headers: merge({
                "Cache-Control": "no-cache"
            }, config.headers || {})
        }, function (err, resp, body) {
            if (err) {
                d.reject({error: err});
                return;
            }
            switch (body.status) {
                case 'success' :
                    d.resolve(body.data);
                    break;
                case 'error' :
                    d.reject(merge(body.data, {
                        bodyMessage : body.message
                    }));
                    break;
                default :
                    break;
            }
        });

        return d.promise;
    }
ReactOverlayView.prototype.draw = function() {
	var props = merge(this.props);
	if (this.props.position) {
		var point = this.getProjection()
			.fromLatLngToDivPixel(this.props.position);

		props.style = merge({
			left: point.x,
			top: point.y
		}, this.props.style);
	}

	React.renderComponent(
		React.DOM.div(props),
		this._containerElement
	)
};
/**
 * A <DefaultRoute> component is a special kind of <Route> that
 * renders when its parent matches but none of its siblings do.
 * Only one such route may be used at any given level in the
 * route hierarchy.
 */
function DefaultRoute(props) {
  return Route(
    merge(props, {
      path: null,
      isDefault: true
    })
  );
}
Example #8
0
Dispatcher.create = function(prototype) {
  invariant(
    'object' === typeof prototype,
    'Expecting an [Object] prototype parameter to create but got `%s`',
    typeof prototype
  );
  return merge(Dispatcher.prototype, prototype);
};
Example #9
0
/**
 * Creates a list object
 */
function createList(values) {
  return merge({
    id: null,
    parent: null,
    value: null,
    children: [],
  }, values);
}
MapOverlayView.prototype.draw = function() {
  var props = merge(this.props, {position: null, mapPane: null});
  if (this.props.position) {
    var point = this.getProjection()
      .fromLatLngToDivPixel(this.props.position);

    props.style = merge({
      position: 'absolute',
      left: point.x,
      top: point.y
    }, this.props.style);
  }

  React.renderComponent(
    cloneWithProps(<div />, props),
    this._containerElement
  )
};
Example #11
0
  render: function () {
    var props = merge(this.props, {
      href: this.getHref(),
      className: this.getClassName(),
      onClick: this.handleClick
    });

    return React.DOM.a(props, this.props.children);
  }
Example #12
0
function buildProps(props) {
  var builtProps = {
    className: props.className || null,
    style: props.style ? merge(props.style) : null,
    styles: undefined
  };
  applyStyles(builtProps, props.styles);
  return builtProps;
}
Example #13
0
function getComponent(fieldComponent, field, model, onValueUpdate) {
  var component = <fieldComponent model={model} config={field} onValueUpdate={onValueUpdate} key={field.key} />;
  if (field.props) {
    var props = typeof field.props === 'function' ? field.props(model, field) : field.props;
    component = React.addons.cloneWithProps(component, merge(props, {
      key: component.props.key
    }));
  }
  return component;
}
Example #14
0
function collectSubViews(props, subViews) {
  var r = getViewProps(props);
  var views = {};

  for (var name in r.views) {
    views[name] = makeViewFactory(r.views[name], merge(r.props, subViews));
  }

  return views;
}
Example #15
0
 function render(props) {
   onChange = sinon.spy();
   onUpdate = sinon.spy();
   props = merge(props, {schema: <TestSchema />, onChange, onUpdate});
   form = TestUtils.renderIntoDocument(Form(props));
   fields = {};
   boxes = TestUtils.scryRenderedDOMComponentsWithTag(form, 'input');
   TestUtils.scryRenderedComponentsWithType(form, Field).forEach(function(field) {
     fields[field.value().name] = field;
   });
 }
Example #16
0
  this.addItem = function (product) {
    var existingIndex  = findItemIndex(this.items, product);

    if (existingIndex == -1) {
      this.items.push(merge({ quantity: 1 }, product));
    } else {
      this.items[existingIndex].quantity += 1;
    }

    this.total = this.total + product.price;
    this.totalItems++;
  };
	getMapProps: function() {
		return merge(this.props, {
			style: null,
			width: null,
			height: null,
			onClick: null,
			bounds: null,
			zoom: this.props.zoom != null ?
				this.props.zoom : zoomLevelToFitBounds(this.props.bounds, this.props.width, this.props.height),
			center: this.props.center || this.props.bounds.getCenter()
		});
	}
Example #18
0
 function render(props) {
   onChange = sinon.spy();
   onUpdate = sinon.spy();
   props = merge(props, {schema: TestMapping(), onChange, onUpdate});
   form = TestUtils.renderIntoDocument(Form(props));
   fields = {};
   boxes = TestUtils.scryRenderedDOMComponentsWithTag(form, 'input');
   TestUtils.scryRenderedComponentsWithType(form, Field).forEach(function(field) {
     var path = field.props.value.path;
     var name = path[path.length - 1];
     fields[name] = field;
   });
 }
CookieStore.dispatchToekn = AppDispatcher.register(function(payload) {
	var action = payload.action;
	var data = action.data;

	switch(action.type) {

		case CookieActionTypes.UPDATE:
			_data = merge(_data, data);
			break;

		default:
			//Do nothing
	}
});
Example #20
0
    describe("when calling the factory",function(){
        var unsubscriber = sinon.spy(),
            listenable1 = {listen: sinon.stub().returns(unsubscriber)},
            listenable2 = {listen: sinon.stub().returns(unsubscriber)},
            listenables = {
                firstAction: listenable1,
                secondAction: listenable2
            },
            context = {
                onFirstAction: sinon.spy(),
                onSecondAction: sinon.spy()
            },
            result = merge(context, listenToMany(listenables));

        it("should return object with componentWillMount and componentWillUnmount methods",function(){
            assert.isFunction(result.componentWillMount);
            assert.isFunction(result.componentWillUnmount);
        });

        describe("when calling the added componentWillMount",function(){
            result.componentWillMount();

            it("should add all methods from ListenerMethods",function(){
                for(var m in Reflux.ListenerMethods){
                    assert.equal(result[m],Reflux.ListenerMethods[m]);
                }
            });

            it("should add to a subscriptions array (via listenToMany)",function(){
                var subs = result.subscriptions;
                assert.isArray(subs);
                assert.equal(subs[0].listenable,listenable1);
                assert.equal(subs[1].listenable,listenable2);
            });

            it("should call listen on the listenables correctly (via listenToMany)",function(){
                assert.equal(listenable1.listen.callCount,1);
                assert.deepEqual(listenable1.listen.firstCall.args,[context.onFirstAction,result]);
                assert.equal(listenable2.listen.callCount,1);
                assert.deepEqual(listenable2.listen.firstCall.args,[context.onSecondAction,result]);
            });
        });

        describe("the componentWillUnmount method",function(){

            it("should be the same as ListenerMethods stopListeningToAll",function(){
                assert.equal(assert.equal(result.componentWillUnmount,Reflux.ListenerMethods.stopListeningToAll));
            });
        });
    });
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var o;"undefined"!=typeof window?o=window:"undefined"!=typeof global?o=global:"undefined"!=typeof self&&(o=self),o.ReactGoogleMaps=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";

var merge = require('react/lib/merge');
var ReactDefaultInjection = require('./src/ui/ReactDefaultInjection');
var ReactMapComponents = require('./src/ReactMapComponents');
var MapPropTypes = require('./src/ui/MapPropTypes');

ReactDefaultInjection.inject();

module.exports = merge(
  ReactMapComponents,
  {
    PropTypes: MapPropTypes
  }
);
},{"./src/ReactMapComponents":3,"./src/ui/MapPropTypes":10,"./src/ui/ReactDefaultInjection":11,"react/lib/merge":undefined}],2:[function(require,module,exports){
Example #22
0
 updateMetadata: function(newData) {
   if (_.isUndefined(this.state.metadata.title) && _.has(newData, 'identifier')) {
     var isbnNo = _.find(newData.identifier, function(val) {
       return val.slice(0,5) === "ISBN:";
     });
     if (!_.isUndefined(isbnNo)) {
       this.updateFromISBN(isbnNo, newData.identifier.indexOf(isbnNo));
     } else if (!_.isUndefined(this.state.errors.identifier)) {
       var errors = _.clone(this.state.errors);
       errors.identifier = [];
       this.setState({errors: errors});
     }
   }
   this.setState({
     metadata: merge(this.state.metadata, newData)
   });
 },
Example #23
0
 }, function (err, resp, body) {
     if (err) {
         d.reject({error: err});
         return;
     }
     switch (body.status) {
         case 'success' :
             d.resolve(body.data);
             break;
         case 'error' :
             d.reject(merge(body.data, {
                 bodyMessage : body.message
             }));
             break;
         default :
             break;
     }
 });
Example #24
0
Dispatcher.injectTestHelpers = function() {
  Dispatcher.prototype = merge(Dispatcher.prototype, {
    __: {
      flush: function() {
        _callbacks = [];
        _promises = []
      },

      promises: function() {
        return _promises;
      },

      callbacks: function() {
        return _callbacks;
      }
    }
  });
}
Example #25
0
    render: function() {
        var songData = [];
        var songs = [];
        for ( var i in this.props.songs ) {
            if ( this.props.songs.hasOwnProperty( i ) ) {
                songData.push( this.props.songs[ i ] );
            }
        }

        songData.sort( function( a, b ) {
            if ( a.title > b.title ) {
              return 1;
            }
            if ( a.title < b.title ) {
              return -1;
            }
            // a must be equal to b
            return 0;
        });

        for ( var i = 0, len = songData.length; i < len; i++ ) {
            var songProps = songData[ i ];
            songs.push( SongListItemLarge( merge( { num: i + 1 }, songProps ) ) );
        }

        return React.DOM.table(
            { className: 'table table-striped table-hover song-list' },
            React.DOM.thead(
                {},
                React.DOM.tr(
                    { className: 'info' },
                    React.DOM.th(),
                    React.DOM.th( { className: 'name-header' }, 'Name' ),
                    React.DOM.th( {}, 'Key' ),
                    React.DOM.th( {}, 'Actions' )
                )
            ),
            React.DOM.tbody(
                {},
                songs
            )
        );
    }
Example #26
0
 render: function() {
   var errors = merge(this.state.errors, this.props.errors || {});
   return (
     <F.Row>
       <F.Column size={[12, 10, 8]}>
         <fieldset className="metadata">
           <legend>Metadata</legend>
           {_.map(window.metadataSchema, function(field) {
             if (field.key === 'title') {
               return <AutocompleteField name={field.description} key={field.key}
                                         value={this.state.metadata[field.key]}
                                         error={errors.title}
                                         onChange={this.updateMetadata} />;
             } else if (field.multivalued) {
               return <FieldSet name={field.description} key={field.key}
                                values={this.state.metadata[field.key] || []}
                                errors={errors[field.key] || []}
                                onChange={function(values) {
                                  var update = {};
                                  update[field.key] = values
                                  this.updateMetadata(update);
                                }.bind(this)} />;
             } else {
               return <Field name={field.description} key={field.key}
                             value={this.state.metadata[field.key]}
                             errors={errors[field.key]}
                             onChange={function(value) {
                               var update = {};
                               update[field.key] = value;
                               this.updateMetadata(update);
                             }.bind(this)} />;
             }
           }, this)}
         </fieldset>
       </F.Column>
     </F.Row>
   );
 }
  _handleDoneLeaving: function(key) {
    var component = this.refs[key];

    if (component.componentDidLeave) {
      component.componentDidLeave();
    }

    delete this.currentlyTransitioningKeys[key];

    var currentChildMapping = ReactTransitionChildMapping.getChildMapping(
      this.props.children
    );

    if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) {
      // This entered again before it fully left. Add it again.
      this.performEnter(key);
    } else {
      var newChildren = merge(this.state.children);
      delete newChildren[key];
      this.setState({
        children: newChildren
      });
    }
  },
var AppDispatcher = require('../dispatcher/AppDispatcher');
var EventEmitter = require('events').EventEmitter;
var UserConstants = require('../constants/UserConstants');
var merge = require('react/lib/merge');

var CHANGE_EVENT = 'change';

var user = null;

var UserStore = merge(EventEmitter.prototype, {
	getUser: function(){
		return user;
	},
	emitChange: function() {
		this.emit(CHANGE_EVENT);
	},
	addChangeListener: function(callback) {
		this.on(CHANGE_EVENT, callback);
	},
	removeChangeListener: function(callback) {
		this.removeListener(CHANGE_EVENT, callback);
	}
});

AppDispatcher.register(function(payload) {
	var action = payload.action;

	switch(action.actionType) {
		case UserConstants.GET_USER:
			user = action.user;
			break;
		default:
Example #29
0
function velocity(node) {
  return merge(node, {
    x: node.x + node.vx,
    y: node.y + node.vy
  });
}
var CHANGE_EVENT = 'change';

var _twits = [];

var TwitterClientStore = merge(EventEmitter.prototype, {
  getAll: function () {
    return _twits;
  },

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  /**
   * @param {function} callback
   */
  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  /**
   * @param {function} callback
   */
  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }

});

// Register to handle all updates
AppDispatcher.register(function(payload) {