export function createListActionHandler(types) {
  const { request, failure, success } = types;

  invariant(request, 'Pass a valid request action type.');
  invariant(failure, 'Pass a valid failure action type.');
  invariant(success, 'Pass a valid success action type.');

  return (action, list, emitChange) => {
    switch (action.type) {
    case request:
      list.expectPage();
      emitChange();
      break;

    case failure:
      list.cancelPage();
      emitChange();
      break;

    case success:
      list.receivePage(
        action.response.result,
        action.response.nextPageUrl
      );
      emitChange();
      break;
    }
  };
}
Example #2
0
    value: function replace(path) {
      invariant(this.history.length, 'You cannot replace the current path with no history');

      this.history[this.history.length - 1] = path;

      this._notifyChange(LocationActions.REPLACE);
    }
Example #3
0
 render: function () {
   invariant(
     false,
     '%s elements should not be rendered',
     this.constructor.displayName
   );
 }
Example #4
0
      run: function (callback) {
        invariant(
          !Router.isRunning,
          'Router is already running'
        );

        dispatchHandler = function (error, transition, newState) {
          if (error)
            Router.handleError(error);

          if (pendingTransition !== transition)
            return;

          pendingTransition = null;

          if (transition.abortReason) {
            Router.handleAbort(transition.abortReason);
          } else {
            callback.call(Router, Router, nextState = newState);
          }
        };

        if (!(location instanceof StaticLocation)) {
          if (location.addChangeListener)
            location.addChangeListener(Router.handleLocationChange);

          Router.isRunning = true;
        }

        // Bootstrap using the current path.
        Router.refresh();
      },
Example #5
0
  injectEventPluginsByName: function(injectedNamesToPlugins) {
    for (var pluginName in injectedNamesToPlugins) {
      if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
        continue;
      }

      var PluginModule = injectedNamesToPlugins[pluginName];
      for (var eventName in PluginModule.eventTypes) {
        if (!PluginModule.eventTypes.hasOwnProperty(eventName)) {
          continue;
        }

        invariant(
          !MapEvent.isStandardName[eventName],
          'injectEventPluginsByName(...): Event `%s` has already been defined, ' +
            'an event can only be handled once',
          eventName
        );

        var EventConfig = PluginModule.eventTypes[eventName];

        MapEvent.isStandardName[eventName] = true;
        MapEvent.getEventName[eventName] = EventConfig.name || eventName;
        MapEvent.getDispatcher[eventName] = PluginModule.executeDispatch;
        if (EventConfig.effects) {
          MapEvent.getOptionSideEffectEvent[EventConfig.effects] = eventName;
        }
      }
    }
  }
  getRouterState: function(props) {
    var path;
    var prefix;

    var parent = this.getParentRouter();

    if (props.contextual && parent) {

      var parentMatch = parent.getMatch();

      invariant(
        props.path || isString(parentMatch.unmatchedPath),
        "contextual router has nothing to match on: %s", parentMatch.unmatchedPath
      );

      path = props.path || parentMatch.unmatchedPath;
      prefix = parentMatch.matchedPath;
    } else {

      path = props.path || this.getEnvironment().getPath();

      invariant(
        isString(path),
        ("router operate in environment which cannot provide path, " +
         "pass it a path prop; or probably you want to make it contextual")
      );

      prefix = '';
    }

    if (path[0] !== '/') {
      path = '/' + path;
    }

    var match = matchRoutes(this.getRoutes(props), path);
    var handler = match.getHandler();

    return {
      match: match,
      handler: handler,
      prefix: prefix,
      navigation: {}
    };
  },
Example #7
0
  getInitialState: function () {
    
    var displayName = this.constructor.displayName || this.constructor.name || '';
    invariant(
      typeof this.getStateStream === 'function',
      '%s use the StateStreamMixin it should provide a \'getStateStream\' function',
      displayName
    );
    
    var stateStream = this.getStateStream(this.props);
    
    invariant(
      isObservable(stateStream),
      '\'%s.getStateStream\' should return an Rx.Observable, given : %s', 
      displayName, stateStream
    );
    
    var initializing = true;
    var streamResolved = false;
    var initialState = null;
    
    this.__stateSubscription = stateStream.subscribe(function (val) {
      invariant(
        typeof val === 'object',
        'The observable returned by \'%s.getStateStream\' should publish Objects or null given : %s', 
        displayName, val
      );
      initialState = val;
      streamResolved = true;
      if (!initializing) {
        this.setState(val);
      }
    }.bind(this));
    
    if (!streamResolved) {
      waitForStream(stateStream);
    }
    
    initializing = false;

    stateSubscriptions.push(this.__stateSubscription);
    
    return initialState;
  },
Example #8
0
  injectParams: function (pattern, params) {
    params = params || {};

    var { tokens } = compilePattern(pattern);
    var parenCount = 0, pathname = '', splatIndex = 0;

    var token, paramName, paramValue;
    for (var i = 0, len = tokens.length; i < len; ++i) {
      token = tokens[i];

      if (token === '*') {
        paramValue = Array.isArray(params.splat) ? params.splat[splatIndex++] : params.splat;

        invariant(
          paramValue != null || parenCount > 0,
          'Missing splat #%s for path "%s"',
          splatIndex, pattern
        );

        if (paramValue != null)
          pathname += paramValue;
      } else if (token === '(') {
        parenCount += 1;
      } else if (token === ')') {
        parenCount -= 1;
      } else if (token.charAt(0) === ':') {
        paramName = token.substring(1);
        paramValue = params[paramName];

        invariant(
          paramValue != null || parenCount > 0,
          'Missing "%s" parameter for path "%s"',
          paramName, pattern
        );

        if (paramValue != null)
          pathname += paramValue;
      } else {
        pathname += token;
      }
    }

    return pathname.replace(/\/+/g, '/');
  },
Example #9
0
function _format(localizer, formatter, value, format, culture) {
  let result = typeof format === 'function' 
    ? format(value, culture, localizer)
    : formatter.call(localizer, value, format, culture)

  invariant(result == null || typeof result === 'string'
    , '`localizer format(..)` must return a string, null, or undefined')

  return result
}
Example #10
0
  handleServerAction (action) {
    invariant(action.type, 'Empty action type: %s', action.type)

    var payload = {
      action: action,
      source: PayloadSources.SERVER_ACTION
    }

    return this.dispatch(payload)
  }
Example #11
0
  handleViewAction (action) {
    invariant(action.type, 'Empty action type: %s', action.type)

    var payload = {
      action: action,
      source: PayloadSources.VIEW_ACTION
    }

    return this.dispatch(payload)
  }
Example #12
0
  register: function(callback) {
    invariant(
      'function' === typeof callback,
      'Dispatcher#register() requires param1 to be a callback [Function], received `%s`',
      typeof callback
    );

    _callbacks.push(callback);
    return _callbacks.length;
  },
Example #13
0
    this.parse = (value, format, culture, dateValidator) => {
      let result = spec.parse.call(this, value, format, culture, dateValidator)

      invariant(result == null 
        || typeof(result) === 'string'
        || (result instanceof Date && !isNaN(result.getTime()))
        , 'date localizer `parse(..)` must return a valid Date, string, null, or undefined')

      return result
    }
Example #14
0
  goBack: function () {
    var location = this.getLocation();

    invariant(
      location,
      'You cannot use goBack without a location'
    );

    location.pop();
  },
ReactComponentBase.applyMixins = function applyMixins(mixins)  {
  mixins = Array.prototype.slice.call(arguments);
  invariant(
      mixins && mixins.length > 0,
      'You should provide at least one mixin'
  );
  for (var i = 0; i < mixins.length; i++) {
      mixSpecIntoComponent(this, mixins[i]);
  }
};
Example #16
0
  transitionTo: function (to, params, query) {
    var location = this.getLocation();

    invariant(
      location,
      'You cannot use transitionTo without a location'
    );

    location.push(this.makePath(to, params, query));
  },
Example #17
0
  replaceWith: function (to, params, query) {
    var location = this.getLocation();

    invariant(
      location,
      'You cannot use replaceWith without a location'
    );

    location.replace(this.makePath(to, params, query));
  },
Example #18
0
TestLocation.prototype.replace = function (path) {
  invariant(
    this.history.length,
    'You cannot replace the current path with no history'
  );

  this.history[this.history.length - 1] = path;

  this._notifyChange(LocationActions.REPLACE);
};
  const callListMethod = (method, args) => {
    const id = args.shift();
    invariant(
      typeof id !== 'undefined',
      'Indexed pagination store methods expect ID as first parameter.'
    );

    const list = getList(id);
    return list[method].call(list, args);
  };
    unregister: function (id) {
        invariant(
            this._callbacks[id],
            "Dispatcher.unregister(...): `%s` does not map " +
            "to a registered callback.",
            id
        );

        delete this._callbacks[id];
    },
Example #21
0
  setup: function (location) {
    invariant(
      ExecutionEnvironment.canUseDOM,
      'You cannot setup the URL store in an environment with no DOM'
    );

    if (_location != null) {
      warning(
        _location === location,
        'The URL store was already setup using ' + _location + ' location. ' +
        'You cannot use ' + location + ' location on the same page'
      );

      return; // Don't setup twice.
    }

    if (location === 'history' && !supportsHistory()) {
      location = 'disabledHistory';
      return;
    }

    var changeEvent = getWindowChangeEvent(location);

    invariant(
      changeEvent || location === 'disabledHistory',
      'The URL store location "' + location + '" is not valid. ' +
      'It must be either "hash" or "history"'
    );

    _location = location;

    if (location === 'hash' && window.location.hash === '')
      URLStore.replace('/');

    if (window.addEventListener) {
      window.addEventListener(changeEvent, notifyChange, false);
    } else {
      window.attachEvent(changeEvent, notifyChange);
    }

    notifyChange();
  },
Example #22
0
  componentWillMount: function () {
    var behavior = this.getScrollBehavior();

    invariant(
      behavior == null || canUseDOM,
      'Cannot use scroll behavior without a DOM'
    );

    if (behavior != null)
      this._scrollPositions = {};
  },
Example #23
0
	componentWillMount: function () {
		var tabsCount = this.getTabsCount(),
			panelsCount = this.getPanelsCount();

		invariant(
			tabsCount === panelsCount,
			'There should be an equal number of Tabs and TabPanels. ' +
			'Received %s Tabs and %s TabPanels.',
			tabsCount, panelsCount
		);
	},
Example #24
0
 handleMoveIndividuFormChange: function(whatChanged, kind, value) {
   invariant(this.state.editedEntity, 'handler called without editedEntity in state.');
   var movedIndividuId = this.state.editedEntity.id;
   var oldEntityData = models.findEntityAndRole(movedIndividuId, kind, this.props.entitiesMetadata,
     this.state.testCase);
   var newEntityId = whatChanged === 'entity' ? value : oldEntityData.id;
   var newRole = whatChanged === 'role' ? value : oldEntityData.role;
   var newTestCase = models.moveIndividuInEntity(movedIndividuId, kind, newEntityId, newRole,
     this.props.entitiesMetadata, this.state.testCase);
   this.setState({testCase: newTestCase}, this.repair);
 },
Example #25
0
  waitFor: function(promiseIndexes, callback) {

    invariant(
      Object.prototype.hasOwnProperty.call(promiseIndexes, 'length'),
      'First parameter must be an [Array] of promise indices to wait for, received `%s`',
      typeof promiseIndexes
    );

    invariant(
      'function' === typeof callback,
      'Second parameter must be a callback [Function], received `%s`',
      typeof callback
    );

    var selectedPromises = promiseIndexes.map(function(index) {
      return _promises[index];
    });

    Promise.all(selectedPromises).then(callback);
  }
Example #26
0
  return function(...args) {
    var mixinResult     = apply(this, mixinProp, ...args) || {};
    var prototypeResult = apply(this, prototypeProp, ...args) || {};

    invariant(
      isObject(prototypeResult) && isObject(mixinResult),
      `\`${propName}\` must return an object or null.`
    );

    return Object.assign({}, mixinResult, prototypeResult);
  };
Example #27
0
function getWindowScrollPosition() {
  invariant(
    canUseDOM,
    'Cannot get current scroll position without a DOM'
  );

  return {
    x: window.scrollX,
    y: window.scrollY
  };
}
Example #28
0
  _invoke: function*(ch) {
    invariant(!ch.closed,
              'Dispatcher._invoke: cannot put on a closed channel');
    this._isPending.push(ch);

    // Start the handler
    yield put(ch, this._pendingPayload);
    // Wait for it to finish
    yield take(ch);

    this._isHandled.push(ch);
  },
Example #29
0
function getNextItem(listItem) {
  var parentList = listItem.parent.children;
  invariant(
    parentList.indexOf(listItem) !== -1,
    'List item not in parent list'
  );
  var ind = parentList.indexOf(listItem);

  if (parentList[ind + 1]) {
    return parentList[ind + 1];
  }
}
Example #30
0
  constructor({ format, parse, formats, propType }){
    invariant(typeof format === 'function'
      , 'number localizer `format(..)` must be a function')
    invariant(typeof parse === 'function'
      , 'number localizer `parse(..)` must be a function')
    checkFormats(REQUIRED_NUMBER_FORMATS, formats)
    
    this.propType = propType || localePropType
    this.formats = formats

    this.format = (value, str, culture) => _format(this, format, value, str, culture)

    this.parse = (value, culture) => {
      let result = parse.call(this, value, culture)

      invariant(result == null || typeof result === 'number'
        , 'number localizer `parse(..)` must return a number, null, or undefined')

      return result
    }
  }