Example #1
0
	makeEmbedsSecure: function makeEmbedsSecure( post, callback ) {
		if ( ! post.__contentDOM ) {
			throw new Error( 'this transform must be used as part of withContentDOM' );
		}

		let iframes = post.__contentDOM.querySelectorAll( 'iframe' );

		const badFrames = [];

		forEach( iframes, function( iframe ) {
			iframe.setAttribute( 'sandbox', '' );
			if ( ! startsWith( iframe.src, 'http' ) ) {
				badFrames.push( iframe );
			} else {
				iframe.src = iframe.src.replace( /^http:/, 'https:' );
			}
		} );

		forEach( badFrames, function( frame ) {
			frame.parentNode.removeChild( frame );
		} );

		if ( post.is_external || post.is_jetpack ) {
			let embeds = post.__contentDOM.querySelectorAll( 'embed,object' );

			forEach( embeds, function( embed ) {
				embed.parentNode.removeChild( embed );
			} );
		}

		callback();
	},
        .then(() => {
          const removed = diff(this.chart.series, newConfig.series, isSameSeries)

          forEach(removed, removeSeries)
          forEach(newConfig.series, this.updateSeries)

          this.chart.redraw()
        })
function parseChildren (child, parent) {
  if (isString(child)) {
    parent.name = child || ''
    return
  }

  if (isArray(child)) {
    forEach(child, x => parseChildren(x, parent))
    return
  }

  if (!isObject(child)) return

  const {props} = child
  const type = camelCase(child.type)
  const node = omit(props, 'children')

  if (isEmpty(node) && !isObject(props.children) && !isArray(props.children)) {
    if (type === 'title') {
      parent.title = {
        text: props.children
      }
    } else {
      parent[type] = props.children === undefined
        ? true
        : props.children
    }

    return
  }

  forEach(node, (value, name) => {
    if (looksLikeAnEventHandler(name)) {
      node.events = node.events || {}
      node.events[lowerCase(name.slice(2))] = value
    }
  })

  if (parent.isRoot && includes(seriesTypes, type)) {
    node.type = type
    node.isSeries = true
    parent.series = parent.series || []
    parent.series.push(node)
  } else if (parent.isSeries && type === 'point') {
    parent.data = parent.data || []
    parent.data.push(node)
  } else {
    parent[type] = node
  }

  if (isArray(props.children)) {
    forEach(props.children, children =>
      parseChildren(children, node))
  } else {
    parseChildren(props.children, node)
  }
}
Example #4
0
    forEach(variables, (vars, queryName) => {
      if (fragments[queryName]) { // if not in fragments, ignore
        resultVariables[queryName] = {};
        const queryVariablesTypes = variablesTypes[queryName];

        // No variables types defined for this query
        invariant(
          queryVariablesTypes,
          'Relate: Query to %s doesn\'t have variables types defined in %s!',
          queryName,
          displayName || 'a component'
        );

        // Check if every variable has a type
        forEach(vars, (value, variable) => {
          invariant(
            queryVariablesTypes[variable],
            'Relate: Query to %s does not have variable "%s" type defined in %s!',
            queryName,
            variable,
            displayName || 'a component'
          );

          // add variable prepared for query e.g. {type: 'String', value: 'something'}
          const type = queryVariablesTypes[variable];

          if (typeof type === 'object') {
            // deep query
            Object.assign(resultVariables[queryName], getVariables({
              variables: {[variable]: value},
              fragments: {[variable]: fragments[queryName]},
              variablesTypes: {[variable]: type}
            }));
          } else {
            resultVariables[queryName][variable] = {
              type: queryVariablesTypes[variable],
              value
            };
          }
        });

        // Check if every required variable type is met
        forEach(queryVariablesTypes, (type, variable) => {
          if (typeof type !== 'object') {
            invariant(
              type.slice(-1) !== '!' || vars[variable] || (type === 'Boolean!' && vars[variable] === false),
              'Relate: Query to %s requires the variable "%s" in %s!',
              queryName,
              variable,
              displayName || 'a component'
            );
          }
        });
      }
    });
Example #5
0
export const update = (f, meta = {}) => {
  const newState = typeof f === 'function' ? f(state) : f;
  state = cloneDeep({
    ...state,
    ...newState
  });

  const frozenState = Object.freeze(state);

  forEach(listeners, apply(frozenState, meta));
  forEach(middlewares, apply(frozenState, meta));
}
export default function createBetterExcerpt( post ) {
	if ( ! post || ! post.content ) {
		return post;
	}

	function removeElement( element ) {
		element.parentNode && element.parentNode.removeChild( element );
	}

	// Spin up a new DOM for the linebreak markup
	const dom = domForHtml( post.content );
	dom.id = '__better_excerpt__';
	dom.innerHTML = post.content;

	// Ditch any photo captions with the wp-caption-text class, styles, scripts
	forEach( dom.querySelectorAll( '.wp-caption-text, style, script, blockquote[class^="instagram-"]' ), removeElement );

	// limit to paras and brs
	dom.innerHTML = striptags( dom.innerHTML, [ 'p', 'br' ] );

	// Strip any empty p and br elements from the beginning of the content
	forEach( dom.querySelectorAll( 'p,br' ), function( element ) {
		// is this element non-empty? bail on our iteration.
		if ( element.childNodes.length > 0 && trim( element.textContent ).length > 0 ) {
			return false;
		}
		element.parentNode && element.parentNode.removeChild( element );
	} );

	// now strip any p's that are empty and remove styles
	forEach( dom.querySelectorAll( 'p' ), function( element ) {
		if ( trim( element.textContent ).length === 0 ) {
			element.parentNode && element.parentNode.removeChild( element );
		} else {
			element.removeAttribute( 'style' );
		}
	} );

	// now limit it to the first three elements
	forEach( dom.querySelectorAll( '#__better_excerpt__ > p, #__better_excerpt__ > br' ), function( element, index ) {
		if ( index >= 3 ) {
			element.parentNode && element.parentNode.removeChild( element );
		}
	} );

	post.better_excerpt = trim( dom.innerHTML );
	dom.innerHTML = '';

	return post;
}
Example #7
0
  _updateDays (data) {
    const days = {}

    // 1. Compute average per day.
    forEach(data, elem => {
      const date = new Date(elem.date)
      const dayId = moment(date).format('YYYYMMDD')
      const hourId = date.getHours()

      const { value } = elem

      if (!days[dayId]) {
        days[dayId] = {
          hours: new Array(24),
          timestamp: elem.date,
        }
      }

      const { hours } = days[dayId]

      if (!hours[hourId]) {
        hours[hourId] = {
          date,
          nb: 1,
          value,
        }
      } else {
        const hour = hours[hourId]
        hour.value = (hour.value * hour.nb + value) / (hour.nb + 1)
        hour.nb++
      }
    })

    // 2. Compute color gen.
    const colorGen = computeColorGen(days)

    // 3. Define color cells.
    forEach(days, day => {
      forEach(day.hours, hour => {
        if (hour) {
          hour.color = colorGen(hour.value)
        }
      })
    })

    this.setState({
      days: computeMissingDays(sortBy(days, 'timestamp')),
    })
  }
Example #8
0
normalizePost.createBetterExcerpt = function createBetterExcerpt( post, callback ) {
	if ( ! post || ! post.content ) {
		callback();
		return;
	}

	function removeElement( element ) {
		element.parentNode && element.parentNode.removeChild( element );
	}

	let betterExcerpt = striptags( post.content, [ 'p', 'br' ] );

	// Spin up a new DOM for the linebreak markup
	const dom = document.createElement( 'div' );
	dom.id = '__better_excerpt__';
	dom.innerHTML = betterExcerpt;

	// Ditch any photo captions with the wp-caption-text class
	forEach( dom.querySelectorAll( '.wp-caption-text' ), removeElement );

	// Strip any empty p and br elements from the beginning of the content
	forEach( dom.querySelectorAll( 'p,br' ), function( element ) {
		// is this element non-empty? bail on our iteration.
		if ( element.childNodes.length > 0 && trim( element.textContent ).length > 0 ) {
			return false;
		}
		element.parentNode && element.parentNode.removeChild( element );
	} );

	// now strip any p's that are empty
	forEach( dom.querySelectorAll( 'p' ), function( element ) {
		if ( trim( element.textContent ).length === 0 ) {
			element.parentNode && element.parentNode.removeChild( element );
		}
	} );

	// now limit it to the first three elements
	forEach( dom.querySelectorAll( '#__better_excerpt__ > p, #__better_excerpt__ > br' ), function( element, index ) {
		if ( index >= 3 ) {
			element.parentNode && element.parentNode.removeChild( element );
		}
	} );

	post.better_excerpt = trim( dom.innerHTML );
	dom.innerHTML = '';

	callback();
},
Example #9
0
  const availableHosts = filter(validHosts, host => {
    let kept = false

    forEach(srs, sr => !(kept = intersection(sr.$PBDs, host.$PBDs).length > 0))

    return kept
  })
Example #10
0
var createStore = function(spec) {
  _each(RESERVED_KEYS, function(key) {
    if (spec[key]) {
      throw new Error("Reserved key '" + key + "' found in store definition");
    }
  });

  var constructor = function(options) {
    options = options || {};
    Store.call(this);

    // Assign mixins first
    if (_isArray(spec.mixins)) {
      spec.mixins.forEach(createStore.mixSpecIntoComponent.bind(null, this));
    }

    createStore.mixSpecIntoComponent(this, spec);

    if (this.initialize) {
      this.initialize(options);
    }
  };

  inherits(constructor, Store);
  return constructor;
};
	YoastReplaceVarPlugin.prototype.registerModifications = function() {
		var callback = this.replaceVariables.bind( this );

		forEach( modifiableFields, function( field ) {
			this._app.registerModification( field, callback, 'replaceVariablePlugin', 10 );
		}.bind( this ) );
	};
export default function decodeEntities( post ) {
	forEach( [ 'excerpt', 'title', 'site_name' ], function( prop ) {
		if ( post[ prop ] ) {
			post[ prop ] = decode( post[ prop ] );
		}
	} );

	if ( post.parent && post.parent.title ) {
		post.parent.title = decode( post.parent.title );
	}

	if ( post.author ) {
		if ( post.author.name ) {
			post.author.name = decode( post.author.name );
		}
		if ( post.author.avatar_URL ) {
			post.author.avatar_URL = safeImageURL( post.author.avatar_URL );
		}
	}

	if ( post.tags ) {
		// tags is an object
		forOwn( post.tags, function( tag ) {
			tag.name = decode( tag.name );
		} );
	}

	return post;
}
/**
 * @param {object} token
 * @param {Array} $links
 * @constructor
 */
function JsonWebToken (token, $links) {
  this.iss = undefined // Issuer
  this.sub = undefined // Subject
  this.aud = undefined // Audience
  this.exp = undefined // Expiration Time
  this.nbf = undefined // Not Before
  this.iat = undefined // Issued At
  this.jti = undefined // JWT ID

  var data = JSON.parse(atob(token.split('.')[1]))
  if (data) {
    var self = this
    _forEach(this, function (value, key) {
      self[key] = data[key] || undefined
      delete data[key]
    })
    if (this.exp) {
      this.exp = new Date(this.exp * 1000)
    }
    if (this.nbf) {
      this.nbf = new Date(this.nbf * 1000)
    }
    if (this.iat) {
      this.iat = new Date(this.iat * 1000)
    }
    this.$links = $links || []
    // Store remaining data
    this.payload = data
  }

  this.$context = JsonWebToken.$context
  this.token = token || undefined
}
Example #14
0
normalizePost.waitForImagesToLoad = function waitForImagesToLoad( post, callback ) {
	function acceptLoadedImages( images ) {
		post.images = map( images, convertImageToObject );

		post.content_images = filter( map( post.content_images, function( image ) {
			return find( post.images, { src: image.src } );
		} ), Boolean );

		callback();
	}

	let imagesToCheck = [];

	if ( post.featured_image ) {
		imagesToCheck.push( imageForURL( post.featured_image ) );
	}

	forEach( post.content_images, function( image ) {
		imagesToCheck.push( imageForURL( image.src ) );
	} );

	// dedupe the set of images
	imagesToCheck = uniqBy( imagesToCheck, function( image ) {
		return image.src;
	} );

	if ( imagesToCheck.length === 0 ) {
		callback();
		return;
	}

	post.images = imagesToCheck;
	async.filter( post.images, keepImagesThatLoad, acceptLoadedImages );
};
Example #15
0
function maxWidthPhotonishURL( imageURL, width ) {
	if ( ! imageURL ) {
		return imageURL;
	}

	let parsedURL = url.parse( imageURL, true, true ), // true, true means allow protocol-less hosts and parse the querystring
		isGravatar, sizeParam;

	if ( ! parsedURL.host ) {
		return imageURL;
	}

	isGravatar = parsedURL.host.indexOf( 'gravatar.com' ) !== -1;

	delete parsedURL.search;
	// strip other sizing params
	forEach( [ 'h', 'crop', 'resize', 'fit' ], function( param ) {
		delete parsedURL.query[ param ];
	} );

	sizeParam = isGravatar ? 's' : 'w';
	parsedURL.query[ sizeParam ] = width * imageScaleFactor;

	if ( ! isGravatar ) {
		// gravatar doesn't support these, only photon / files.wordpress
		parsedURL.query.quality = DEFAULT_PHOTON_QUALITY;
		parsedURL.query.strip = 'info'; // strip all exif data, leave ICC intact
	}

	return url.format( parsedURL );
}
Example #16
0
  function confirmBlueprinted(isMobile, routing) {
    routing = !!routing;
    var blueprintPath = path.join(root,  'blueprints', 'ng2', 'files');
    var mobileBlueprintPath = path.join(root, 'blueprints', 'mobile', 'files');
    var expected = unique(walkSync(blueprintPath).concat(isMobile ? walkSync(mobileBlueprintPath) : []).sort());
    var actual = walkSync('.').sort();

    forEach(Blueprint.renamedFiles, function (destFile, srcFile) {
      expected[expected.indexOf(srcFile)] = destFile;
    });

    expected.forEach(function (file, index) {
      expected[index] = file.replace(/__name__/g, 'app');
      expected[index] = expected[index].replace(/__styleext__/g, 'css');
      expected[index] = expected[index].replace(/__path__/g, 'src');
    });

    if (isMobile) {
      expected = expected.filter(p => p.indexOf('app.component.html') < 0);
      expected = expected.filter(p => p.indexOf('app.component.css') < 0);
    }

    if (!routing) {
      expected = expected.filter(p => p.indexOf('app-routing.module.ts') < 0);
    }

    removeIgnored(expected);
    removeIgnored(actual);

    expected.sort();

    expect(expected).to.deep.equal(
      actual,
      EOL + ' expected: ' + util.inspect(expected) + EOL + ' but got: ' + util.inspect(actual));
  }
Example #17
0
 function clearCache() {
     forEach(require.cache, function (cachedModule, resolvedPath) {
         if (resolvedPath.match(/\.node$/) === null) {
             delete require.cache[resolvedPath];
         }
     });
 }
export function loadCriteriaNameAction (tree, ids) {
  function onSuccess (response) {
    tree.set('locationCriteria',
      assign({},
        response.data,
        tree.get('locationCriteria')))

    tree.commit()

    forEach(ids, id => {
      delete onGoingCalls[id]
    })

    return response
  }

  const promise = loadCriteriaName(ids, getApiFetchConfig(tree))
    .then(saveResponseTokenAsCookie)
    .then(onSuccess)
    .catch(pushResponseErrorToState(tree))

  forEach(ids, id => {
    onGoingCalls[id] = promise
  })

  return promise
}
Example #19
0
  /**
   * Returns serialized representation that can be appended
   * to network paths as a query parameter.
   *
   * @returns {Object} Query string object
   */
  toQueryString() {
    const queryString = {};

    if (!isEmpty(this.filter)) {
      queryString.query = this.filter;
    }

    if (!isEmpty(this.fields)) {
      queryString.fields = this.fields.join(',');
    }

    if (this.limit) {
      queryString.limit = this.limit;
    }

    if (this.skip > 0) {
      queryString.skip = this.skip;
    }

    if (!isEmpty(this.sort)) {
      queryString.sort = this.sort;
    }

    const keys = Object.keys(queryString);
    forEach(keys, key => {
      queryString[key] = isString(queryString[key]) ? queryString[key] : JSON.stringify(queryString[key]);
    });

    return queryString;
  }
Example #20
0
      data = data.sort((a, b) => {
        const fields = Object.keys(json.sort);
        forEach(fields, field => {
          // Find field in objects.
          const aField = nested(a, field);
          const bField = nested(b, field);

          // Elements which do not contain the field should always be sorted
          // lower.
          if (aField && !bField) {
            return -1;
          }

          if (bField && !aField) {
            return 1;
          }

          // Sort on the current field. The modifier adjusts the sorting order
          // (ascending (-1), or descending(1)). If the fields are equal,
          // continue sorting based on the next field (if any).
          if (aField !== bField) {
            const modifier = json.sort[field]; // 1 or -1.
            return (aField < bField ? -1 : 1) * modifier;
          }

          return 0;
        });

        return 0;
      });
Example #21
0
File: index.js Project: Ajusa/ajcss
function verifyIndex (index, files) {
  each(index, (file, url) => {
    if (!files[file.source]) {
      throw new Error(`Invalid reference '${file.source}'`)
    }
  })
}
Example #22
0
function expectBundleContainments(bundleFile, testFiles) {
  var extractedFiles = unpack(bundleFile.bundled).map(function(row) { return row.id; });

  forEach(testFiles, function(f) {
    expect(extractedFiles).to.contain(f.path);
  });
}
Example #23
0
function compareTwoStrings(str1, str2) {
  var pairs1 = wordLetterPairs(str1.toUpperCase());
  var pairs2 = wordLetterPairs(str2.toUpperCase());
  var intersection = 0;
  var union = pairs1.length + pairs2.length;

  _forEach(pairs1, function (pair1) {
    for(var i = 0; i < pairs2.length; i++) {
      var pair2 = pairs2[i];
      if (pair1 === pair2) {
        intersection++;
        pairs2.splice(i, 1);
        break;
      }
    }
  });

  return (2.0 * intersection) / union;

  // private functions ---------------------------
  function letterPairs(str) {
    var numPairs = str.length - 1;
    var pairs = [];
    for(var i = 0; i < numPairs; i++) {
      pairs[i] = str.substring(i, i + 2);
    }
    return pairs;
  }

  function wordLetterPairs(str) {
    return _flattenDeep(_map(str.split(' '), letterPairs));
  }
}
Example #24
0
TestPlugin.prototype.preprocess = function preprocess(bundle, testFiles, done) {

  /*jshint validthis:true */
  var plugin = this;

  var total = 1 + testFiles.length;

  var processed = [];

  function fileProcessed(file, result) {
    file.bundled = result;

    processed.push(file);

    if (processed.length == total) {
      done();
    }
  }

  function process(preprocessor, file) {
    preprocessor(file.bundled || '', file, function(result) {
      fileProcessed(file, result);
    });
  }

  process(plugin.bundlePreprocessor, bundle);

  // Karma does not necessarily preprocess test files in the order they are given.
  var shuffledTestFiles = testFiles.slice(0).reverse();

  forEach(shuffledTestFiles, function(file) {
    process(plugin.testFilePreprocessor, file);
  });
};
Example #25
0
normalizePost.decodeEntities = function decodeEntities( post, callback ) {
	forEach( [ 'excerpt', 'title', 'site_name' ], function( prop ) {
		if ( post[ prop ] ) {
			post[ prop ] = formatting.decodeEntities( post[ prop ] );
		}
	} );

	if ( post.parent && post.parent.title ) {
		post.parent.title = formatting.decodeEntities( post.parent.title );
	}

	if ( post.author ) {
		if ( post.author.name ) {
			post.author.name = formatting.decodeEntities( post.author.name );
		}
		if ( post.author.avatar_URL ) {
			post.author.avatar_URL = safeImageURL( post.author.avatar_URL );
		}
	}

	if ( post.tags ) {
		// tags is an object
		forOwn( post.tags, function( tag ) {
			tag.name = formatting.decodeEntities( tag.name );
		} );
	}

	callback();
};
Example #26
0
  this._commit = function(change, info) {
    var selectionHasChanged = this._commitChange(change);

    var collaboratorsChange = null;
    forEach(this.getCollaborators(), function(collaborator) {
      // transform local version of collaborator selection
      var id = collaborator.collaboratorId;
      var oldSelection = collaborator.selection;
      var newSelection = DocumentChange.transformSelection(oldSelection, change);
      if (oldSelection !== newSelection) {
        collaboratorsChange = collaboratorsChange || {};
        collaborator = clone(collaborator);
        collaborator.selection = newSelection;
        collaboratorsChange[id] = collaborator;
      }
    });

    var update = {
      change: change
    };
    if (selectionHasChanged) {
      update.selection = this.selection;
    }
    if (collaboratorsChange) {
      update.collaborators = collaboratorsChange;
    }
    this._triggerUpdateEvent(update, info);
  };
 this.getToolRegistry = function() {
   var toolRegistry = new Registry();
   forEach(this.config.tools, function(tool) {
     toolRegistry.add(tool.Class.static.name, tool);
   });
   return toolRegistry;
 };
Example #28
0
            return _forEach( videos, video => {

                /* Set the poster if it exists */
                let poster = video.getAttribute( 'data-poster' );

                if ( poster ){
                    video.setAttribute( 'poster', poster );
                }

                /* Get all the sources and set real attributes */
                _forEach( video.querySelectorAll( 'source' ), source => {
                    let src = source.getAttribute( 'data-src' );

                    if ( src ){
                        source.setAttribute( 'src', src );
                    }
                } );

                /* Load sources to be usable by video, then play it! */
                video.load();

                if ( autoplay ) {
                    video.play();
                }
            } );
Example #29
0
  this._updateCollaborators = function(collaborators) {
    var collaboratorsChange = {};

    forEach(collaborators, function(collaborator, collaboratorId) {
      if (collaborator) {
        var oldSelection;
        var old = this.collaborators[collaboratorId];
        if (old) {
          oldSelection = old.selection;
        }
        var newSelection = Selection.fromJSON(collaborator.selection);
        newSelection.attach(this.doc);

        // Assign colorIndex (try to restore from old record)
        collaborator.colorIndex = old ? old.colorIndex : this._getNextColorIndex();
        collaborator.selection = newSelection;
        this.collaborators[collaboratorId] = collaborator;
        if (!newSelection.equals(oldSelection)) {
          collaboratorsChange[collaboratorId] = collaborator;
        }
      } else {
        collaboratorsChange[collaboratorId] = null;
        delete this.collaborators[collaboratorId];
      }
    }.bind(this));

    if (Object.keys(collaboratorsChange).length>0) {
      return collaboratorsChange;
    }
  };
 this.getComponentRegistry = function() {
   var componentRegistry = new Registry();
   forEach(this.config.components, function(ComponentClass, name) {
     componentRegistry.add(name, ComponentClass);
   });
   return componentRegistry;
 };