Polymer Redux

Creates a Class mixin for decorating Elements with a given Redux store.

@polymerMixin

@param {Object} store Redux store.
@return {Function} Class mixin.
164895
function PolymerRedux(store) {
  if (!store) {
    throw new TypeError('PolymerRedux: expecting a redux store.');
  } else if (!['getState', 'dispatch', 'subscribe'].every(function (k) {
    return typeof store[k] === 'function';
  })) {
    throw new TypeError('PolymerRedux: invalid store object.');
  }

  var subscribers = new Map();

  /**
   * Binds element's properties to state changes from the Redux store.
   *
   * @example
   *     const update = bind(el, props) // set bindings
   *     update(state) // manual update
   *
   * @private
   * @param {HTMLElement} element
   * @param {Object} properties
   * @return {Function} Update function.
   */
  var bind = function bind(element, properties) {
    var bindings = Object.keys(properties).filter(function (name) {
      var property = properties[name];
      if (Object.prototype.hasOwnProperty.call(property, 'statePath')) {
        if (!property.readOnly && property.notify) {
          console.warn('PolymerRedux: <' + element.constructor.is + '>.' + name + ' has "notify" enabled, two-way bindings goes against Redux\'s paradigm');
        }
        return true;
      }
      return false;
    });

    /**
     * Updates an element's properties with the given state.
     *
     * @private
     * @param {Object} state
     */
    var update = function update(state) {
      var propertiesChanged = false;
      bindings.forEach(function (name) {
        // Perhaps .reduce() to a boolean?
        var statePath = properties[name].statePath;

        var value = typeof statePath === 'function' ? statePath.call(element, state) : (0, _path.get)(state, statePath);

        var changed = element._setPendingPropertyOrPath(name, value, true);
        propertiesChanged = propertiesChanged || changed;
      });
      if (propertiesChanged) {
        element._invalidateProperties();
      }
    };

    // Redux listener
    var unsubscribe = store.subscribe(function () {
      var detail = store.getState();
      update(detail);

      element.dispatchEvent(new window.CustomEvent('state-changed', { detail: detail }));
    });

    subscribers.set(element, unsubscribe);

    return update(store.getState());
  };

  /**
   * Unbinds an element from state changes in the Redux store.
   *
   * @private
   * @param {HTMLElement} element
   */
  var unbind = function unbind(element) {
    var off = subscribers.get(element);
    if (typeof off === 'function') {
      off();
    }
  };

  /**
   * Merges a property's object value using the defaults way.
   *
   * @private
   * @param {Object} what Initial prototype
   * @param {String} which Property to collect.
   * @return {Object} the collected values
   */
  var collect = function collect(what, which) {
    var res = {};
    while (what) {
      res = Object.assign({}, what[which], res); // Respect prototype priority
      what = Object.getPrototypeOf(what);
    }
    return res;
  };

  /**
   * ReduxMixin
   *
   * @example
   *     const ReduxMixin = PolymerRedux(store)
   *     class Foo extends ReduxMixin(Polymer.Element) { }
   *
   * @polymerMixinClass
   *
   * @param {Polymer.Element} parent The polymer parent element.
   * @return {Function} PolymerRedux mixed class.
   */
  return function (parent) {
    return function (_parent) {
      _inherits(ReduxMixin, _parent);

      function ReduxMixin() {
        _classCallCheck(this, ReduxMixin);

        // Collect the action creators first as property changes trigger
        // dispatches from observers, see #65, #66, #67
        var _this = _possibleConstructorReturn(this, (ReduxMixin.__proto__ || Object.getPrototypeOf(ReduxMixin)).call(this));

        var actions = collect(_this.constructor, 'actions');
        Object.defineProperty(_this, '_reduxActions', {
          configurable: true,
          value: actions
        });
        return _this;
      }

      _createClass(ReduxMixin, [{
        key: 'connectedCallback',
        value: function connectedCallback() {
          _get(ReduxMixin.prototype.__proto__ || Object.getPrototypeOf(ReduxMixin.prototype), 'connectedCallback', this).call(this);
          var properties = collect(this.constructor, 'properties');
          bind(this, properties);
        }
      }, {
        key: 'disconnectedCallback',
        value: function disconnectedCallback() {
          _get(ReduxMixin.prototype.__proto__ || Object.getPrototypeOf(ReduxMixin.prototype), 'disconnectedCallback', this).call(this);
          unbind(this);
        }

        /**
         * Dispatches an action to the Redux store.
         *
         * @example
         *     element.dispatch({ type: 'ACTION' })
         *
         * @example
         *     element.dispatch('actionCreator', 'foo', 'bar')
         *
         * @example
         *     element.dispatch((dispatch) => {
         *         dispatch({ type: 'MIDDLEWARE'})
         *     })
         *
         * @param  {...*} args
         * @return {Object} The action.
         */

      }, {
        key: 'dispatch',
        value: function dispatch() {
          var _this2 = this;

          for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }

          var actions = this._reduxActions;

          // Action creator
          var action = args[0];

          if (typeof action === 'string') {
            if (typeof actions[action] !== 'function') {
              throw new TypeError('PolymerRedux: <' + this.constructor.is + '> invalid action creator "' + action + '"');
            }
            action = actions[action].apply(actions, _toConsumableArray(args.slice(1)));
          }

          // Proxy async dispatch
          if (typeof action === 'function') {
            var originalAction = action;
            action = function action() {
              for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                args[_key2] = arguments[_key2];
              }

              // Replace redux dispatch
              args.splice(0, 1, function () {
                return _this2.dispatch.apply(_this2, arguments);
              });
              return originalAction.apply(undefined, args);
            };

            // Copy props from the original action to the proxy.
            // see https://github.com/tur-nr/polymer-redux/issues/98
            Object.keys(originalAction).forEach(function (prop) {
              action[prop] = originalAction[prop];
            });
          }

          return store.dispatch(action);
        }

        /**
         * Gets the current state in the Redux store.
         *
         * @return {*}
         */

      }, {
        key: 'getState',
        value: function getState() {
          return store.getState();
        }
      }]);

      return ReduxMixin;
    }(parent);
  };
}
55958
function createRemote(item, store) {
      // Check existing item id property;
      var itemId = item[store.idProperty];
      // Store resources url
      var url = !itemId ? store._rootUrl : store._rootUrl + "/" + itemId;
      // Set up request
      var xhr = new XMLHttpRequest();
      xhr.open("POST", url, true);
      xhr.setRequestHeader("Content-Type", "application/json");
      // Request callback
      xhr.onload = function(e) {
        // If operation has been completed - ready state 4
        if (xhr.readyState === 4) {
          // Response status successfully completed - status 200
          if (xhr.status === 200) {
            // Set response item to be returned
            item = JSON.parse(xhr.response);
            // Refresh local data object
            vcomet.StoreMemory.create(item, store);
            // Trigger user callback once data has been retrieved
            vcomet.triggerCallback("onCreateRemote", store, store, [item]);
            // Trigger onSourceChanged event
            vcomet.triggerCallback("onSourceChanged", store);
          }
        }
      };
      // Execute request with post payload data
      store.onLoaded(function(){xhr.send(JSON.stringify(item))});
    }
102570
function (store, json) {
    var handledRecords = [], key, records, handleRecord, Model;
    handleRecord = function (record) {
      this.completeJsonForRecord(store, record, Model, json, handledRecords);
    };
    for (key in json) {
      if (json.hasOwnProperty(key)) {
        records = json[key];
        Model = store.modelFor(singularize(key));
        forEach(records, handleRecord, this);
      }
    }
    return json;
  }
802028
public ConditionTextFormatter create(final TokenStore store) {
        ArgUtils.notNull(store, "store");
        
        final ConditionTextFormatter formatter = new ConditionTextFormatter(store.getConcatenatedToken());
        
        for(Token token : store.getTokens()) {
            
            if(token instanceof Token.Condition) {
                // 条件の場合
                final Token.Condition conditionToken = token.asCondition();
                final String condition = conditionToken.getCondition();
                formatter.addCondition(condition);
                
                if(isConditionOperator(conditionToken)) {
                    setupConditionOperator(formatter, conditionToken);
                    
                } else if(isConditionLocale(conditionToken)) {
                    setupConditionLocale(formatter, conditionToken);
                    
                } else if(isConditionLocaleSymbol(conditionToken)) {
                    final LocaleSymbol localeSymbol = setupConditionLocaleSymbol(formatter, conditionToken);
                    formatter.addTerm(new LocaelSymbolTerm<String>(localeSymbol));
                    
                } else if(isConditionDbNum(conditionToken)) {
                    setupConditionDbNum(formatter, conditionToken);
                    
                } else if(isConditionColor(conditionToken)) {
                    setupConditionColor(formatter, conditionToken);
                    
                }
                
            } else if(token instanceof Token.Word) {
                formatter.addTerm(new WordTerm<String>(token.asWord()));
                
            } else if(token instanceof Token.EscapedChar) {
                formatter.addTerm(new EscapedCharTerm<String>(token.asEscapedChar()));
                
            } else if(token instanceof Token.Underscore) {
                formatter.addTerm(new UnderscoreTerm<String>(token.asUnderscore()));
                
            } else if(token instanceof Token.Asterisk) {
                formatter.addTerm(new AsteriskTerm<String>(token.asAsterisk()));
                
            } else if(token instanceof Token.Factor) {
                // 因子を記号'@'で分割する
                List<Token> list = convertFactor(token.asFactor());
                
                for(Token item : list) {
                    if(item.equals(Token.Symbol.SYMBOL_AT_MARK)) {
                        formatter.addTerm(TextTerm.atMark(item.asSymbol()));
                    } else {
                        formatter.addTerm(new OtherTerm<String>(item));
                    }
                }
                
            }
            
        }
        
        return formatter;
        
    }
580053
function Class() {
        var i, mixins, mixin, self = this;

        // All construction is actually done in the init method
        if (!initializing) {
          // Run class constuctor
          if (self.init) {
            self.init.apply(self, arguments);
          }

          // Run mixin constructors
          mixins = self.Mixins;
          if (mixins) {
            i = mixins.length;
            while (i--) {
              mixin = mixins[i];
              if (mixin.init) {
                mixin.init.apply(self, arguments);
              }
            }
          }
        }
      }
1082200
function RedisWrapper(opt, key) {
	return {
		_promise: new Promise(
			(resolve, reject) => opt.redis.hget(
				opt.namespace,
				key,
				(err, json) => {
					if (err) {
						reject(err);
						return;
					}
					try {
						const val = opt.deserialize(json);
						resolve(val);
					} catch (e) {
						reject(e);
					}
				}
			),
			[]
		),
		tree: []
	};
}
713402
function(name, observable, oneTime) {
      var property = this.propertyForAttribute(name);
      if (!property) {
        // TODO(sjmiles): this mixin method must use the special form
        // of `super` installed by `mixinMethod` in declaration/prototype.js
        return this.mixinSuper(arguments);
      } else {
        // use n-way Polymer binding
        var observer = this.bindProperty(property, observable, oneTime);
        // NOTE: reflecting binding information is typically required only for
        // tooling. It has a performance cost so it's opt-in in Node.bind.
        if (Platform.enableBindingsReflection && observer) {
          observer.path = observable.path_;
          this._recordBinding(property, observer);
        }
        if (this.reflect[property]) {
          this.reflectPropertyToAttribute(property);
        }
        return observer;
      }
    }
969709
function create(item, store) {
      var data = store.rootData.asObject();
      // New item has id
      if (item[store.idProperty]) {
        // Check item duplicated
        if (!data[item[store.idProperty]]) {
          // Create item
          data[item[store.idProperty]] = item;
        } else {
          // Item already exists
          return vcomet.error.log(
            "store",
            "Item with id " + item[store.idProperty] + " already exists"
          );
        }
      } else {
        // Add id value to item
        item[store.idProperty] = Object.keys(data).length.toString();
        // Create item
        data[item[store.idProperty]] = item;
      }
      if (item[store.idProperty]) {
        // Update store data
        store.rootData = store.data = new Result(data, store, store.data.__sorted);
        // Update store data items length
        store.size = Object.keys(store.data).length;
        // Trigger onSourceChanged event
        vcomet.triggerCallback("onSourceChanged", store);
        return item;
      } else {
        return vcomet.error.log("store", "Incorrect item format");
      }
    }
368195
function getMergedStore(target) {
        var classKey = target.getClassName();
        if (__mergedStore[classKey]) {
            return __mergedStore[classKey];
        }
        __mergedStore[classKey] = {};
        var store = __mergedStore[classKey];
        var currentTarget = target;
        var currentKey = classKey;
        while (currentKey) {
            var initialStore = __decoratorInitialStore[currentKey];
            for (var property in initialStore) {
                store[property] = initialStore[property];
            }
            var parent_1 = void 0;
            var done = false;
            do {
                parent_1 = Object.getPrototypeOf(currentTarget);
                if (!parent_1.getClassName) {
                    done = true;
                    break;
                }
                if (parent_1.getClassName() !== currentKey) {
                    break;
                }
                currentTarget = parent_1;
            } while (parent_1);
            if (done) {
                break;
            }
            currentKey = parent_1.getClassName();
            currentTarget = parent_1;
        }
        return store;
    }
1354891
function (options) {
  if (!(this instanceof Store)) {
    return new Store(options)
  }

  this._opts = options || {}
  this.db = new Datastore({ filename: this._opts.filename, autoload: true })
}
456365
function filterStore(operation, store, args) {
  const filter = obj => {
    switch (operation) {
      case 'omit':
        return _.isFunction(args[0])
          ? _.omitBy(obj, args[0])
          : _.omit(obj, args);
      case 'pick':
        return _.isFunction(args[0])
          ? _.pickBy(obj, args[0])
          : _.pick(obj, args);
      default:
        break;
    }
  };
  switch (store) {
    case 'context':
    case 'functions':
    case 'directives':
    case 'plugins':
    case 'types':
      _.set(this, `_${store}`, filter(_.get(this, `_${store}`)));
      break;
    default:
      assert(false, `invalid store for ${operation} operation`);
      break;
  }
  return this;
}
711884
function hyperRepeat(store) {
  this.compile = compile;

  this.state = function(config, state) {
    var res = store.get(config.path, state);
    if (!res.completed) return false;
    return state.set(config.source, res.value);
  };

  this.children = function(config, state, children) {
    var items = state.get(config.source);
    var arr = [];
    if (!items) return arr;

    var target = config.target;
    var i, c, child;

    var path = ['state', target];

    for (i = 0; i < items.length; i++) {
      function update() {return items[i]};

      for (c = 0; c < children.length; c++) {
        child = children[c];
        if (!child) continue;
        // TODO set the key prop
        child = child.updateIn(path, update);
        arr.push(child);
      }
    }
    return arr;
  };
}
648156
function( options ){
		var store = new XStore( options );

		// If the store has an id, register it in Fluxify and in the dispatcher
		if( store._id ){
			this.stores[ store._id ] = store;
			this.dispatcher.registerStore( store._id, store );
		}

		return store;
	}
1183067
function mixin() {
        var args = arguments;

        if (Object$assign) {
            return Object$assign.apply(null, args);
        }

        var target = {};

        each(args, function (it) {
            each(it, function (v, k) {
                target[k] = v;
            });
        });

        return args[0] = target;
    }
617068
function giveStore(ecModel) {
    var store = ecModel[ATTR];
    if (!store) {
        store = ecModel[ATTR] = [{}];
    }
    return store;
}
552867
function RevisionGuard (store, options) {
  options = options || {};

  var defaults = {
    queueTimeout: 1000,
    queueTimeoutMaxLoops: 3//,
    // startRevisionNumber: 1
  };

  _.defaults(options, defaults);

  this.options = options;

  if (!store || !_.isObject(store)) {
    var err = new Error('store not injected!');
    debug(err);
    throw err;
  }

  this.store = store;

  this.definition = {
    correlationId: 'correlationId', // optional
    id: 'id',                       // optional
    name: 'name',                   // optional
//    aggregateId: 'aggregate.id',    // optional
//    context: 'context.name',        // optional
//    aggregate: 'aggregate.name',    // optional
    payload: 'payload'              // optional
//    revision: 'revision'            // optional
//    version: 'version',             // optional
//    meta: 'meta'                    // optional, if defined theses values will be copied to the notification (can be used to transport information like userId, etc..)
  };

  this.queue = new Queue({ queueTimeout: this.options.queueTimeout });

  this.currentHandlingRevisions = {};

  this.onEventMissing(function (info, evt) {
    debug('missing events: ', info, evt);
  });
}
602954
function construct(target) {
    mixin(target, {
      values: obj,
      parent: parent || null,
      root: root || target,
      prop: prop === undefined ? null : prop,
      // .on(event[, prop], callback)
      on: on,
      // .off(event[, prop][, callback])
      off: off,
      // .trigger(event[, prop])
      trigger: trigger,
      toJSON: toJSON,
      // internal: dependency tracking
      deps: deps
    });

    // Wrap mutating array method to update
    // state and notify listeners
    function wrapMutatingArrayMethod(method, func) {
      return function() {
        var result = [][method].apply(obj, arguments);
        this.len = this.values.length;
        cache = {};
        children = {};
        func.apply(this, arguments);
        target.parent.trigger('update', target.prop);
        return result;
      };
    }

    // Wrap callback of an array method to
    // provide this content to the currently processed item
    function proxyArrayMethod(method) {
      return function(callback) {
        return [][method].apply(
          obj,
          [function(el, i) {
            return callback.apply(target(i), [].slice.call(arguments));
          }].concat([].slice.call(arguments, 1))
        );
      };
    }

    if (Array.isArray(obj)) {
      mixin(target, {
        // Function prototype already contains length
        // `len` specifies array length
        len: obj.length,

        pop: wrapMutatingArrayMethod('pop', function() {
          trigger('delete', this.len, 1);
        }),

        push: wrapMutatingArrayMethod('push', function() {
          trigger('insert', this.len - 1, 1);
        }),

        reverse: wrapMutatingArrayMethod('reverse', function() {
          trigger('delete', 0, this.len);
          trigger('insert', 0, this.len);
        }),

        shift: wrapMutatingArrayMethod('shift', function() {
          trigger('delete', 0, 1);
        }),

        unshift: wrapMutatingArrayMethod('unshift', function() {
          trigger('insert', 0, 1);
        }),

        sort: wrapMutatingArrayMethod('sort', function() {
          trigger('delete', 0, this.len);
          trigger('insert', 0, this.len);
        }),

        splice: wrapMutatingArrayMethod('splice', function() {
          if (arguments[1]) {
            trigger('delete', arguments[0], arguments[1]);
          }
          if (arguments.length > 2) {
            trigger('insert', arguments[0], arguments.length - 2);
          }
        })

      });

      ['forEach', 'every', 'some', 'filter', 'map', 'reduce', 'reduceRight']
        .forEach(function(method) {
          target[method] = proxyArrayMethod(method);
        });
    }
  }