Esempio n. 1
0
    it("should delete the selection and any edges connected to it", () => {
      let newGraph = reducer(graph, action);

      expect(keys(newGraph.nodes)).toEqual(['2', '3']);
      expect(keys(newGraph.edges)).toEqual([]);
      expect(keys(newGraph.captions)).toEqual([]);
    });
Esempio n. 2
0
export const deepDiff = (prev, next, name = null, notes) => {
  const isRefEntity = isReferenceEntity(prev) && isReferenceEntity(next)

  if (!_isEqual(prev, next)) {
    const isFunc = _isFunction(prev) && _isFunction(next)

    if (isFunc) {
      if (prev.name === next.name) {
        return notes.concat(`${name} (fn)`)
      }
    } else if (isRefEntity) {
      const keys = _union(_keys(prev), _keys(next))
      const result = keys.reduce((acc, key) => deepDiff(prev[key], next[key], addPath(name, key), acc), []);
      return notes.concat(result.length == 0 ? name : result)
    }
  } else if (prev !== next) {
    if (isRefEntity) {
      const keys = _union(_keys(prev), _keys(next))
      const result = keys.reduce((acc, key) => deepDiff(prev[key], next[key], addPath(name, key), acc), []);
      return notes.concat(result.length == 0 ? name : result)
    } else {
      return notes.concat(name)
    }
  }

  return notes
}
Esempio n. 3
0
const deepDiff = (prev, next, name) => {
  const notify = (type, status) => {
    console.group(name)
    console[type](`%c%s`, `font-weight: bold`, status)
    console.log(`%cbefore`, `font-weight: bold`, prev)
    console.log(`%cafter `, `font-weight: bold`, next)
    console.groupEnd()
  }

  const isRefEntity = isRequiredUpdateObject(prev) && isRequiredUpdateObject(next)

  if (!_isEqual(prev, next)) {
    const isFunc = _isFunction(prev) && _isFunction(next)

    if (isFunc) {
      if (prev.name === next.name) {
        notify(`warn`, `Value is a function. Possibly avoidable re-render?`)
      }
    } else if (isRefEntity) {
      const keys = _union(_keys(prev), _keys(next))
      keys.forEach(key => deepDiff(prev[key], next[key], `${name}.${key}`))
    }
  } else if (prev !== next) {
    notify(`error`, `Value did not change. Avoidable re-render!`)

    if (isRefEntity) {
      const keys = _union(_keys(prev), _keys(next))
      keys.forEach(key => deepDiff(prev[key], next[key], `${name}.${key}`))
    }
  } else if (prev === next && !isRefEntity) {
    notify(`error`, `Value did not change. Avoidable re-render!`)
  }
}
Esempio n. 4
0
 refDeepDiff(){
   let keys;
   if(this.useImmutable && this.isImmutable()){
     // Immutable.List's instance do not have _keys, so forEach do not execute 😎
     keys = _union(this.prev._keys, this.next._keys);
   } else {
     keys = _union(_keys(this.prev), _keys(this.next))
   }
   keys.forEach(key => {
     return new DeepDiff(this.prev[key], this.next[key], `${this.name}.${key}`, this.opts).run()
   })
 }
Esempio n. 5
0
/**
 * Given a defaults object and a source object, copy the value from the source
 * if it contains the same key, otherwise return the default. Skip keys that
 * only exist in the source object.
 * @param {object} defaults - Default schema
 * @param {object} source - Source object to copy properties from
 * @returns {object} - Result has identical keys to defaults
 * @static
 * @memberof helper
*/
function merge_or_apply(defaults, source) {
	var defaultKeys = keys(defaults);
	var sourceKeys = keys(source);
	return reduce(defaultKeys, function(result, key) {
		if (sourceKeys.indexOf(key) > -1) {
			result[key] = source[key];
			return result;
		} else {
			result[key] = defaults[key];
			return result;
		}
	}, {});
}
Esempio n. 6
0
function filterGraph(data) {
	var visited = {};
	var filtered = {};
	var graph = data.graph;
	var baseUrl = data.loader.baseURL;

	keys(graph).forEach(function visit(name) {
		// don't visit a node twice
		if (visited[name]) return;

		visited[name] = true;
		var node = graph[name];

		if (node) {
			var address = node.load.address;
			var pattern = getGlobPattern(data);
			var relative = address.replace(baseUrl, "");

			if (multimatch(relative, pattern).length) {
				node.dependencies.forEach(visit);
				filtered[name] = node;
			}
		}
	});

	return assign({}, omit(data, "graph"), { graph: filtered });
}
Esempio n. 7
0
 deleteAssets(compilation) {
   if (this.deleteAssetsMap && compilation) {
     each(keys(this.deleteAssetsMap), (key) => {
       delete compilation.assets[key];
     });
   }
 }
export const spawnPatternModelJsonValidator = (json) => {
    let isValid = true;

    for (let i = 0; i < ACCEPTED_KEYS.length; i++) {
        const key = ACCEPTED_KEYS[i];

        if ((key === 'altitude' || key === 'speed') && json.category === 'departure') {
            continue;
        }

        if (key === 'origin' && json.category === 'arrival') {
            continue;
        }

        if (!_has(json, key) && !_has(ACCEPTED_OPTIONAL_KEYS, key)) {
            console.warn(`spawnPattern is missing a required key: ${key}`);

            isValid = false;
        }
    }

    const jsonKeys = _keys(json);
    const unsupportedKeys = _difference(jsonKeys, ALL_KEYS);

    if (unsupportedKeys.length > 0) {
        console.warn(`Unsupported key(s) found in spawnPattern: ${unsupportedKeys.join(', ')}`);
    }

    return isValid;
};
Esempio n. 9
0
export function parseHeaders(headers, tokenFormat) {
  if (!headers) {
    return {};
  }

  const newHeaders  = {};

  let blankHeaders  = true;

  keys(tokenFormat).forEach((key) => {
    if (headers[key] === undefined) {
      if (headers.get && headers.get(key)) {
        newHeaders[key] = headers.get(key);
      }
    } else {
      newHeaders[key] = headers[key];
    }

    if (newHeaders[key]) {
      if (isArray(newHeaders[key])) {
        newHeaders[key] = newHeaders[key][0];
      }

      blankHeaders = false;
    }
  });

  if (!blankHeaders) {
    return newHeaders;
  }

  return {};
}
Esempio n. 10
0
  render() {
    const { notifications } = this.props;
    const numOfNotifications = keys(notifications).length;

    return (
      <Wrapper className='icon' onSelection={ this.handleSelection }>
        <Button className='notification--button'>
          <div className='flag_icon icon' style={ { marginRight: '10px' } }>
            <span>{ numOfNotifications || null }</span><img src={ Flag }/>
          </div>
        </Button>
        <Menu className='notification--menu'>
          <ul>
            <MenuItem>
              <a onClick={ this.handleClear } href='#' className='clearAllButton'>
                <li className='text-right padding14'>
                  Clear all <i className='circle-x'/>
                </li>
              </a>
            </MenuItem>
            { this.renderNotifications() }
          </ul>
        </Menu>
      </Wrapper>
      );
  }
/**
 * Extract the matched courses from all children.
 * @private
 * @param {Object} expr - the current result expression
 * @param {Requirement} ctx - the host requirement
 * @returns {Course[]} - the list of matched courses
 */
export default function getMatchesFromChildren(
	expr: ModifierChildrenExpression | ModifierChildrenWhereExpression,
	ctx: Requirement,
): Course[] {
	if (expr.$type !== 'modifier') {
		return []
	}

	// grab all the child requirement names from this requirement
	let childKeys = keys(ctx).filter(isRequirementName)

	// either use all of the child requirements in the computation,
	if (expr.$children === '$all') {
		// do nothing; the default case.
	} else if (Array.isArray(expr.$children)) {
		// or just use some of them (those listed in expr.$children)
		const requested = expr.$children.map(c => c.$requirement)
		childKeys = childKeys.filter(key => requested.includes(key))
	}

	// `uniq` had the same problem here that the dirty course stuff struggles
	// with. That is, uniq works on a per-object basis, so when you write down
	// the same course for several reqs, they'll be different objects.
	// Therefore, we turn each object into a sorted JSON representation of
	// itself, and uniq based on that.
	// (I opted for passing iteratee to uniq, rather than mapping, to let lodash optimize a bit.)

	// finally, collect the matching courses from the requested children
	const matches = childKeys.map(key => collectMatches((ctx: any)[key]))
	const flatMatches = flatten(matches)
	const uniquedMatches = uniqBy(flatMatches, stringify)

	return uniquedMatches
}
Esempio n. 12
0
  getLanguageChanger() {
    const {hearing, dispatch, activeLanguage} = this.props;
    const availableLanguages = { fi: 'Kuuleminen Suomeksi', sv: 'Enkäten på svenska', en: 'Questionnaire in English'};
    const languageOptionsArray = keys(hearing.title).map((lang, index) => {
      if (getAttr(hearing.title, lang, {exact: true}) && lang === activeLanguage) {
        return (<div className="language-link-active">
          {availableLanguages[lang]}
        </div>);
      }

      if (getAttr(hearing.title, lang, {exact: true}) &&
        keys(hearing.title).filter((key) => key === activeLanguage).length === 0 &&
        index === 0) {
        return (<div className="language-link-active">
          {availableLanguages[lang]}
        </div>);
      }

      if (getAttr(hearing.title, lang, {exact: true})) {
        return (<div className="language-link">
          <a onClick={(event) => { event.preventDefault(); dispatch(setLanguage(lang)); }} href="" >
            {availableLanguages[lang]}
          </a>
        </div>);
      }

      return null;
    });

    if (languageOptionsArray.length > 1) {
      return languageOptionsArray;
    }

    return null;
  }
Esempio n. 13
0
    const languageOptionsArray = keys(hearing.title).map((lang, index) => {
      if (getAttr(hearing.title, lang, {exact: true}) && lang === activeLanguage) {
        return (<div className="language-link-active">
          {availableLanguages[lang]}
        </div>);
      }

      if (getAttr(hearing.title, lang, {exact: true}) &&
        keys(hearing.title).filter((key) => key === activeLanguage).length === 0 &&
        index === 0) {
        return (<div className="language-link-active">
          {availableLanguages[lang]}
        </div>);
      }

      if (getAttr(hearing.title, lang, {exact: true})) {
        return (<div className="language-link">
          <a onClick={(event) => { event.preventDefault(); dispatch(setLanguage(lang)); }} href="" >
            {availableLanguages[lang]}
          </a>
        </div>);
      }

      return null;
    });
Esempio n. 14
0
LastCallWebpackPlugin.prototype.deleteAssets = function(compilation) {
  if (this.deleteAssetsMap && compilation) {
    each(keys(this.deleteAssetsMap), function(key) {
      delete compilation.assets[key];
    });
  }
};
Esempio n. 15
0
LastCallWebpackPlugin.prototype.getAssetsAndProcessors = function(assets, phase) {
  var assetProcessors = this.options.assetProcessors;
  var assetNames = keys(assets);
  var assetsAndProcessors = [];

  each(assetNames, function (assetName) {
    each(assetProcessors, function(assetProcessor) {
      if (assetProcessor.phase === phase) {
        var regExpResult = assetProcessor.regExp.exec(assetName);
        assetProcessor.regExp.lastIndex = 0;
        if (regExpResult) {
          var assetAndProcessor = {
            assetName: assetName,
            regExp: assetProcessor.regExp,
            processor: assetProcessor.processor,
            regExpResult: regExpResult,
          };
          assetsAndProcessors.push(assetAndProcessor);
        }
      }
    });
  });

  return assetsAndProcessors;
};
Esempio n. 16
0
 generateFileMap: function(fileMapVariables) {
   var tokens        = this._fileMapTokens(fileMapVariables);
   var fileMapValues = values(tokens);
   var tokenValues   = fileMapValues.map(function(token) { return token(fileMapVariables); });
   var tokenKeys     = keys(tokens);
   return zipObject(tokenKeys,tokenValues);
 },
Esempio n. 17
0
 res.body.edges.forEach((edge) => {
   const nodeKeys = keys(edge.node);
   nodeKeys.forEach((key) => {
     const includesField = includes(allowedFields, key);
     assert.ok(includesField, `${key} is not in allowed keys`);
   });
 });
Esempio n. 18
0
export default function fillShape(source, sink) {
  if (typeof sink === 'function') {
    sink = sink(source); //eslint-disable-line
  }

  if (sink === true) {
    return source;
  } else if (sink === undefined) {
    return undefined;
  }

  let filledObject = {};
  keys(sink).forEach((key) => {
    if (source[key] === undefined) {
      return;
    } else if (typeof sink[key] === 'object'
      || typeof sink[key] === 'function'
      || sink[key] === true) {
      filledObject[key] = fillShape(source[key], sink[key]);
    } else {
      throw new Error('Values in the sink must be another object, function, or `true`');
    }
  });
  return filledObject;
}
Esempio n. 19
0
  handleClear(event) {
    event.preventDefault();
    const { notifications, clearAll } = this.props;

    clearAll(keys(notifications));

  }
Esempio n. 20
0
test('Clear with a function: filtering', function(t) {
  var helper = fixture();

  var checkType = {
    numeric: false,
    disjunctiveFacet: false,
    conjunctiveFacet: false,
    exclude: false
  };

  helper.clearRefinements(function(value, key, type) {
    checkType[type] = true;

    return key.indexOf('1') !== -1;
  });

  t.equal(keys(checkType).length, 4, 'There should be only 4 refinements');
  forEach(checkType, function(typeTest, type) { t.ok(typeTest, 'clear should go through: ' + type); });

  t.deepEqual(helper.state.facetsRefinements, {facet2: ['0']});
  t.deepEqual(helper.state.disjunctiveFacetsRefinements, {disjunctiveFacet2: ['0']});
  t.deepEqual(helper.state.facetsExcludes, {excluded2: ['0']});
  t.deepEqual(helper.state.numericRefinements, {numeric2: {'>=': [0], '<': [10]}});

  t.end();
});
Esempio n. 21
0
  renderNotifications() {
    const { notifications } = this.props;
    if (notifications && keys(notifications).length) {
      const sortedNotifications = chronologicalNotificationSort(notifications);

      return map(sortedNotifications, (item, key) => (
        <MenuItem key={ item.id }>
          <Link
            className='notification--item-link'
            to={ `/TransactionRequestDetail/${item.key}` }>
            <li className='padding14'>
              <div>
                <TimeAgo time={ item.sent_time }/>, { item.sender_account } requested
              </div>
              <div className='text-right'>
                { numeral(item.payload
                  && item.payload.total * (item.payload.direction || 1)
                  || 0).format(MONEY_FORMAT) }
              </div>
            </li>
          </Link>
        </MenuItem>
      ));
    } else {
      return (
        <li className='padding14'>
          <div className='text-center'>
            (empty)
          </div>
        </li>
      );
    }
  }
UpdateBusinessObjectHandler.prototype.execute = function(context) {

  var element = context.element,
      businessObject = context.businessObject,
      changed = [ element ]; // this will not change any diagram-js elements

  if (!element) {
    throw new Error('element required');
  }

  if (!businessObject) {
    throw new Error('businessObject required');
  }

  var properties = context.properties,
      oldProperties = context.oldProperties || getProperties(businessObject, keys(properties));

  // update properties
  setProperties(businessObject, properties);

  // store old values
  context.oldProperties = oldProperties;
  context.changed = changed;

  // indicate changed on objects affected by the update
  return changed;
};
Esempio n. 23
0
    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = AutoControlledComponent.__proto__ || Object.getPrototypeOf(AutoControlledComponent)).call.apply(_ref, [this].concat(args))), _this), _this.trySetState = function (maybeState, state) {
      var autoControlledProps = _this.constructor.autoControlledProps;

      if (process.env.NODE_ENV !== 'production') {
        var name = _this.constructor.name;
        // warn about failed attempts to setState for keys not listed in autoControlledProps

        var illegalKeys = _difference(_keys(maybeState), autoControlledProps);
        if (!_isEmpty(illegalKeys)) {
          console.error([name + ' called trySetState() with controlled props: "' + illegalKeys + '".', 'State will not be set.', 'Only props in static autoControlledProps will be set on state.'].join(' '));
        }
      }

      var newState = Object.keys(maybeState).reduce(function (acc, prop) {
        // ignore props defined by the parent
        if (_this.props[prop] !== undefined) return acc;

        // ignore props not listed in auto controlled props
        if (autoControlledProps.indexOf(prop) === -1) return acc;

        acc[prop] = maybeState[prop];
        return acc;
      }, {});

      if (state) newState = _extends({}, newState, state);

      if (Object.keys(newState).length > 0) _this.setState(newState);
    }, _temp), _possibleConstructorReturn(_this, _ret);
Esempio n. 24
0
 renderSections(sections) {
   const { form } = this.props;
   let self = this;
   /**
    * Make sure section fields exist in schema
    */
   let schemaKeys = keys(form.schema._schema);
   sections.forEach((section) => {
     section.fields.forEach((field) => {
       /**
        * Check if field is a custom object instead of a string
        */
       if (typeof field === 'object') {
         field.fields.forEach((innerField) => {
           if (!includes(schemaKeys, innerField)) {
             throw new Error(`Section field ${innerField} does not exist in schema`);
           }
         });
       } else {
         if (!includes(schemaKeys, field)) {
           throw new Error(`Section field ${field} does not exist in schema`);
         }
       }
     });
   });
   let renderedSections = sections.map((section, i) => {
     return (
       <div key={ i } className="ui segment">
         <h3>{ section.title }</h3>
         { self.renderFields(section.fields) }
       </div>
     );
   });
   return renderedSections;
 }
Esempio n. 25
0
  this.serializeNested = function (dest, current, attribute, opts) {
    var that = this;

    var embeds = [];
    var attributes = [];

    if (opts && opts.attributes) {
      embeds = opts.attributes.filter(function (attr) {
        return opts[attr];
      });

      attributes = opts.attributes.filter(function (attr) {
        return !opts[attr];
      });
    } else {
      attributes = _keys(dest);
    }

    var ret = {};
    if (attributes) { ret.attributes = pick(dest, attributes); }

    embeds.forEach(function (embed) {
      if (isComplexType(dest[embed])) {
        that.serialize(ret, dest, embed, opts[embed]);
      }
    });

    return ret.attributes;
  };
Esempio n. 26
0
 render() {
   const { autosave, children, form, type } = this.props;
   const { errors, formDoc } = this.state;
   const self = this;
   if (!!children) {
     return (
       <form className="ui form" onSubmit={ this.onSubmit }>
       { children }
       </form>
     );
   } else if (!!form.sections) {
     return (
       <form className="ui form" onSubmit={ this.onSubmit }>
         { self.renderSections(form.sections) }
         <div className="actions">
           { type === 'insert' || !autosave ? <BlueFormInput className={ get(form, 'options.submitClassName') } text={ get(form, 'options.submitText') } type="submit" /> : null }
         </div>
       </form>
     );
   } else {
     let fieldKeys = keys(form.schema._schema);
     return (
       <form className="ui form" onSubmit={ this.onSubmit }>
         { self.renderFields(fieldKeys) }
         <div className="actions">
           { type === 'insert' || !autosave ? <BlueFormInput className={ get(form, 'options.submitClassName') } text={ get(form, 'options.submitText') } type="submit" /> : null }
         </div>
       </form>
     );
   }
 }
Esempio n. 27
0
export function areHeadersBlank(headers, tokenFormat) {
  if (!headers) {
    return true;
  }

  const allKeys = keys(tokenFormat);

  for (let i = 0; i < allKeys.length; ++i) {
    const key = allKeys[i];

    let value;

    if (headers[key] === undefined) {
      if (headers.has && headers.has(key)) {
        value = headers.get(key);
      } else {
        continue;
      }
    } else {
      value = headers[key];
    }

    if (value && value.toLowerCase() !== (tokenFormat[key] || '').toLocaleLowerCase()) {
      return false;
    }
  }

  return true;
}
Esempio n. 28
0
/**
 * Looks for "@loader" in the dependency graph
 * @param {Object} graph - The dependency graph
 * @return {boolean} true if found, false otherwise
 */
function includesAtLoader(graph) {
	var found = false;

	var isAtLoader = function(name) {
		return name === "@loader";
	};

	keys(graph).forEach(function(name) {
		var node = graph[name];

		if (isPluginExcludedFromBuild(node)) {
			return;
		}

		if (isAtLoader(name)) {
			return (found = true);
		}

		defaultTo(node.dependencies, []).forEach(function(depName) {
			if (isAtLoader(depName)) {
				return (found = true);
			}
		});
	});

	return found;
}
Esempio n. 29
0
	it('should have correct number of exports', function testNumberOfExports() {
		const actual = keys(Facade).length
		/* istanbul ignore next */
		if (actual !== exportHelper.totalExports) {
			/* istanbul ignore next */
			/* eslint-disable no-console */
			console.error(
				`${exportHelper.suite}\nnamedExports`,
				keys(Facade).sort()
			)
			/* istanbul ignore next */
			console.error(Facade)
			/* eslint-enable no-console */
		}
		expect(actual).toBe(exportHelper.totalExports)
	})
Esempio n. 30
0
module.exports = function eslintPlugin(config, pckg) {
  return eslint(getGlobPattern(config, pckg), {
    configFile: require.resolve('lookly-preset-eslint/eslint'),
    globals: keys(pckg.provide),
    silent: config.silent,
  });
};