<commit_before>//Top Sites
browser.topSites.get()
  .then((sites) => {
    var div = document.getElementById('topsites');

    if (!sites.length) {
      div.innerText = 'No sites returned from the topSites API.';
      return;
    }

    sites.splice(12);

    for (let site of sites) {
      let p = document.createElement('p');
      p.className = 'list-group-item';
      let a = document.createElement('a');
      a.href = site.url;
      a.innerText = site.title || site.url;
      p.appendChild(a);
      div.appendChild(p);
    }
  });

document.getElementById('topsites').style.marginLeft = -100 + "%";

//bookmarks
function onFulfilled(children) {
  var divbm = document.getElementById('bookmarks');

  for (child of children) {
    let p = document.createElement('p');
    p.className = 'list-group-item';
    let a = document.createElement('a');

    //filter out non-bookmark items, specifically seperators
    var bookmarksArray = [];
    var seperatorsArray = [];
    if ((child.url != undefined) && (child.url.startsWith("http")) && (child.type != "seperator")) {
      bookmarksArray.push(child);
      console.log("bookmark");
    } else {
      if (child.type = "seperator") {
        seperatorsArray.push(child);
        console.log("seperator");
      }
    }

    /*
     * I eventually want to add support for reading the contents of
     * folders in the bookmarks toolbar.  However, that adds more
     * complexity to an already shaky function.  I will add support
     * for folders when I begin using a seperate folder specifically
     * for this addon, rather than the bookmarks toolbar.  So, expect
     * improvements sometime around the 2.0 release.
     *
     * ~Isaac
     */

    //add bookmark info to sidebar items
    for (i = 0; i < bookmarksArray.length; i++) {
      a.href = bookmarksArray[i].url;
      a.innerText = bookmarksArray[i].title || bookmarksArray[i].url;
    }

    //attach sidebar items to each other
    p.appendChild(a);
    divbm.appendChild(p);
  }
}

function onRejected(error) {
  console.log(`An error: ${error}`);
}

var gettingChildren = browser.bookmarks.getChildren("toolbar_____");
gettingChildren.then(onFulfilled, onRejected);

document.getElementById('bookmarks').style.marginLeft = -100 + "%";

//notes
var VERSION = 1;

window.onload = () => {
  var $textarea = document.querySelector('#note-content');

  var initNote = () => {
    browser.storage.sync.get().then( data => {

      if (data.version === undefined) {
        data = {
          version: VERSION,
          content: ''
        };
        browser.storage.sync.set(data);
      }

      $textarea.value = data.content;
    });
  };
  initNote();

  // when user writing
  $textarea.addEventListener('keyup', event => {
    browser.storage.sync.set({ content: event.target.value });
  });

  // when actived window or tab changed
  browser.tabs.onActivated.addListener(initNote);
  browser.windows.onFocusChanged.addListener(initNote);
};

//Weather, Theme
function onError(error) {
  console.log(`Error: ${error}`);
}

function onGot(item) {
  var color = "";
  if (item.color) {
    place = item.color;
  }
  var weather = document.getElementById('weather');
  weather.href += place;
}

var getting = browser.storage.local.get("color");
getting.then(onGot, onError);

/* Toggles
 * The below functions are used to toggle the various
 * panels/dropdowns in this extension. They are labeled
 * pretty clearly as to what they do.
 */

/* Callback functions
 * There's probably a better name for these, but they're
 * here so the toggle functions below are readable.
 */

//search
function growSearch() {
  var searchPopOver = document.getElementById('searchBoxId');
  var box = document.getElementById('searchbox');
  var button = document.getElementById('sbsubmit');
  searchPopOver.style.maxHeight = "60px";
  searchPopOver.style.padding = "1.2em 0";
  searchPopOver.style.boxShadow = "0 .4rem .4rem rgba(0,0,0,0.35)";
  searchPopOver.style.borderTop = "2px solid var(--highlight-color)";
  box.style.visibility = "visible";
  box.focus();
  button.style.visibility = "visible";
}

function shrinkSearch() {
  var searchPopOver = document.getElementById('searchBoxId');
  var box = document.getElementById('searchbox');
  var button = document.getElementById('sbsubmit');
  searchPopOver.style.maxHeight = "0px";
  searchPopOver.style.padding = "0";
  searchPopOver.style.boxShadow = "none";
  searchPopOver.style.borderTop = "none";
  box.style.visibility = "collapse";
  button.style.visibility = "collapse";
}

//topsites
function shrinkTopSites() {
  var sidebar = document.getElementById('topsites');
  var width = document.getElementById('topsites').scrollWidth;
  document.getElementById('topsites').style.transition = "all .25s ease-out";
  sidebar.style.marginLeft = -width + "px";
  sidebar.style.boxShadow = "none";
}

function growTopSites() {
  var sidebar = document.getElementById('topsites');
  var width = document.getElementById('topsites').scrollWidth;
  document.getElementById('topsites').style.transition = "all .25s ease-out";
  sidebar.style.marginLeft = "0px";
  sidebar.style.boxShadow = "0 0 .4rem rgba(0,0,0,0.35)";
}

//bookmarks
function shrinkBookmarks() {
  var sidebar = document.getElementById('bookmarks');
  var width = document.getElementById('bookmarks').scrollWidth;
  document.getElementById('bookmarks').style.transition = "all .25s ease-out";
  sidebar.style.marginLeft = -width + "px";
  sidebar.style.boxShadow = "none";
}

function growBookmarks() {
  var sidebar = document.getElementById('bookmarks');
  var width = document.getElementById('bookmarks').scrollWidth;
  document.getElementById('bookmarks').style.transition = "all .25s ease-out";
  sidebar.style.marginLeft = "0px";
  sidebar.style.boxShadow = "0 0 .4rem rgba(0,0,0,0.35)";
}

//toggle top sites sidebar
function showTopSites(event) {
  var sidebar = document.getElementById('topsites');
  var width = document.getElementById('topsites').scrollWidth;
  document.getElementById('topsites').style.transition = "all .25s ease-out";
  if(sidebar.style.marginLeft == "0px" || sidebar.style.marginLeft == null) {
    shrinkTopSites();
  } else {
    shrinkBookmarks();
    shrinkSearch();
    growTopSites();
  }
}

var toggleID = document.getElementById('toggle');
toggleID.onclick = showTopSites;

//toggle bookmarks sidebar
function showBookmarks(event) {
  var sidebarbm = document.getElementById('bookmarks');
  var width = document.getElementById('bookmarks').scrollWidth;
  document.getElementById('bookmarks').style.transition = "all .25s ease-out";
  if(sidebarbm.style.marginLeft == "0px" || sidebarbm.style.marginLeft == null) {
    shrinkBookmarks();
  } else {
    shrinkTopSites();
    shrinkSearch();
    growBookmarks();
  }
}

var toggleID = document.getElementById('bmtoggle');
toggleID.onclick = showBookmarks;

//toggle searchbox
function showSearch(event) {
  var searchPopOver = document.getElementById('searchBoxId');
  var box = document.getElementById('searchbox');
  var button = document.getElementById('sbsubmit');
  var sidebar = document.getElementById('topsites');
  var width = document.getElementById('topsites').scrollWidth;
  if(searchPopOver.style.maxHeight == "0px" || searchPopOver.style.maxHeight == null) {
    if(sidebar.style.marginLeft = "0px") {
      shrinkTopSites();
    }
    growSearch();
  } else {
    shrinkSearch();
  }
}

var toggleSearch = document.getElementById('searchToggle');
toggleSearch.onclick = showSearch;
<commit_msg>begin attempt to read contents of folders.<commit_after>//Top Sites
browser.topSites.get()
  .then((sites) => {
    var div = document.getElementById('topsites');

    if (!sites.length) {
      div.innerText = 'No sites returned from the topSites API.';
      return;
    }

    sites.splice(12);

    for (let site of sites) {
      let p = document.createElement('p');
      p.className = 'list-group-item';
      let a = document.createElement('a');
      a.href = site.url;
      a.innerText = site.title || site.url;
      p.appendChild(a);
      div.appendChild(p);
    }
  });

document.getElementById('topsites').style.marginLeft = -100 + "%";

//bookmarks
function onFulfilled(children) {
  var divbm = document.getElementById('bookmarks');

  for (child of children) {
    let p = document.createElement('p');
    p.className = 'list-group-item';
    let a = document.createElement('a');

    //filter out non-bookmark items, specifically seperators
    var bookmarksArray = [];
    var seperatorsArray = [];
    if ((child.url != undefined) && (child.url.startsWith("http")) && (child.type != "seperator")) {
      bookmarksArray.push(child);
      console.log("bookmark");
    } else {
      if (child.type = "seperator") {
        seperatorsArray.push(child);
        console.log("seperator");
      }
    } else { //attempt to read folder contents
      if (child.children != undefined) {
        bookmarksArray.push(getAllBookmarks(element.children));
        console.log("folder");
      }
    }

    /*
     * I eventually want to add support for reading the contents of
     * folders in the bookmarks toolbar.  However, that adds more
     * complexity to an already shaky function.  I will add support
     * for folders when I begin using a seperate folder specifically
     * for this addon, rather than the bookmarks toolbar.  So, expect
     * improvements sometime around the 2.0 release.
     *
     * ~Isaac
     */

    //add bookmark info to sidebar items
    for (i = 0; i < bookmarksArray.length; i++) {
      a.href = bookmarksArray[i].url;
      a.innerText = bookmarksArray[i].title || bookmarksArray[i].url;
    }

    //attach sidebar items to each other
    p.appendChild(a);
    divbm.appendChild(p);
  }
}

function onRejected(error) {
  console.log(`An error: ${error}`);
}

var gettingChildren = browser.bookmarks.getChildren("toolbar_____");
gettingChildren.then(onFulfilled, onRejected);

document.getElementById('bookmarks').style.marginLeft = -100 + "%";

//notes
var VERSION = 1;

window.onload = () => {
  var $textarea = document.querySelector('#note-content');

  var initNote = () => {
    browser.storage.sync.get().then( data => {

      if (data.version === undefined) {
        data = {
          version: VERSION,
          content: ''
        };
        browser.storage.sync.set(data);
      }

      $textarea.value = data.content;
    });
  };
  initNote();

  // when user writing
  $textarea.addEventListener('keyup', event => {
    browser.storage.sync.set({ content: event.target.value });
  });

  // when actived window or tab changed
  browser.tabs.onActivated.addListener(initNote);
  browser.windows.onFocusChanged.addListener(initNote);
};

//Weather, Theme
function onError(error) {
  console.log(`Error: ${error}`);
}

function onGot(item) {
  var color = "";
  if (item.color) {
    place = item.color;
  }
  var weather = document.getElementById('weather');
  weather.href += place;
}

var getting = browser.storage.local.get("color");
getting.then(onGot, onError);

/* Toggles
 * The below functions are used to toggle the various
 * panels/dropdowns in this extension. They are labeled
 * pretty clearly as to what they do.
 */

/* Callback functions
 * There's probably a better name for these, but they're
 * here so the toggle functions below are readable.
 */

//search
function growSearch() {
  var searchPopOver = document.getElementById('searchBoxId');
  var box = document.getElementById('searchbox');
  var button = document.getElementById('sbsubmit');
  searchPopOver.style.maxHeight = "60px";
  searchPopOver.style.padding = "1.2em 0";
  searchPopOver.style.boxShadow = "0 .4rem .4rem rgba(0,0,0,0.35)";
  searchPopOver.style.borderTop = "2px solid var(--highlight-color)";
  box.style.visibility = "visible";
  box.focus();
  button.style.visibility = "visible";
}

function shrinkSearch() {
  var searchPopOver = document.getElementById('searchBoxId');
  var box = document.getElementById('searchbox');
  var button = document.getElementById('sbsubmit');
  searchPopOver.style.maxHeight = "0px";
  searchPopOver.style.padding = "0";
  searchPopOver.style.boxShadow = "none";
  searchPopOver.style.borderTop = "none";
  box.style.visibility = "collapse";
  button.style.visibility = "collapse";
}

//topsites
function shrinkTopSites() {
  var sidebar = document.getElementById('topsites');
  var width = document.getElementById('topsites').scrollWidth;
  document.getElementById('topsites').style.transition = "all .25s ease-out";
  sidebar.style.marginLeft = -width + "px";
  sidebar.style.boxShadow = "none";
}

function growTopSites() {
  var sidebar = document.getElementById('topsites');
  var width = document.getElementById('topsites').scrollWidth;
  document.getElementById('topsites').style.transition = "all .25s ease-out";
  sidebar.style.marginLeft = "0px";
  sidebar.style.boxShadow = "0 0 .4rem rgba(0,0,0,0.35)";
}

//bookmarks
function shrinkBookmarks() {
  var sidebar = document.getElementById('bookmarks');
  var width = document.getElementById('bookmarks').scrollWidth;
  document.getElementById('bookmarks').style.transition = "all .25s ease-out";
  sidebar.style.marginLeft = -width + "px";
  sidebar.style.boxShadow = "none";
}

function growBookmarks() {
  var sidebar = document.getElementById('bookmarks');
  var width = document.getElementById('bookmarks').scrollWidth;
  document.getElementById('bookmarks').style.transition = "all .25s ease-out";
  sidebar.style.marginLeft = "0px";
  sidebar.style.boxShadow = "0 0 .4rem rgba(0,0,0,0.35)";
}

//toggle top sites sidebar
function showTopSites(event) {
  var sidebar = document.getElementById('topsites');
  var width = document.getElementById('topsites').scrollWidth;
  document.getElementById('topsites').style.transition = "all .25s ease-out";
  if(sidebar.style.marginLeft == "0px" || sidebar.style.marginLeft == null) {
    shrinkTopSites();
  } else {
    shrinkBookmarks();
    shrinkSearch();
    growTopSites();
  }
}

var toggleID = document.getElementById('toggle');
toggleID.onclick = showTopSites;

//toggle bookmarks sidebar
function showBookmarks(event) {
  var sidebarbm = document.getElementById('bookmarks');
  var width = document.getElementById('bookmarks').scrollWidth;
  document.getElementById('bookmarks').style.transition = "all .25s ease-out";
  if(sidebarbm.style.marginLeft == "0px" || sidebarbm.style.marginLeft == null) {
    shrinkBookmarks();
  } else {
    shrinkTopSites();
    shrinkSearch();
    growBookmarks();
  }
}

var toggleID = document.getElementById('bmtoggle');
toggleID.onclick = showBookmarks;

//toggle searchbox
function showSearch(event) {
  var searchPopOver = document.getElementById('searchBoxId');
  var box = document.getElementById('searchbox');
  var button = document.getElementById('sbsubmit');
  var sidebar = document.getElementById('topsites');
  var width = document.getElementById('topsites').scrollWidth;
  if(searchPopOver.style.maxHeight == "0px" || searchPopOver.style.maxHeight == null) {
    if(sidebar.style.marginLeft = "0px") {
      shrinkTopSites();
    }
    growSearch();
  } else {
    shrinkSearch();
  }
}

var toggleSearch = document.getElementById('searchToggle');
toggleSearch.onclick = showSearch;
<|endoftext|>


<commit_before>$(function() {
  configureScroll();
  configureOffcanvas();
  toggleSpeakers();
  animateNav();
});

function configureScroll () {
  $('nav a').click(goToScroll);
  $('.register a').click(goToScroll);
  $('.navbar-brand').click(goToScroll);
}

function goToScroll() {
  var offset = 50;
  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
    if (target.length) {
      $('html,body').animate({
        scrollTop: target.offset().top - offset
      }, 1000);
      return false;
    }
  }
}

function configureOffcanvas () {
 //stick in the fixed 100% height behind the navbar but don't wrap it
 $('#slide-nav.navbar .container').append($('
SECCIONES
'));

  // Enter your ids or classes
  var toggler = '.navbar-toggle';
  var pagewrapper = '#page-content';
  var navigationwrapper = '.navbar-header';
  var menuwidth = '100%'; // the menu inside the slide menu itself
  var slidewidth = '50%';
  var menuneg = '-100%';
  var slideneg = '-100%';

  $("#slide-nav").on("click", toggler, function (e) {
    var selected = $(this).hasClass('slide-active');

    $('#slidemenu').stop().animate({
      left: selected ? menuneg : '0px'
    });

    $('#navbar-height-col').stop().animate({
      left: selected ? slideneg : '0px'
    });

    $(pagewrapper).stop().animate({
      left: selected ? '0px' : slidewidth
    });

    $(navigationwrapper).stop().animate({
      left: selected ? '0px' : slidewidth
    });

    $(this).toggleClass('slide-active', !selected);
    $('#slidemenu').toggleClass('slide-active');

    $('#page-content, .navbar, body, .navbar-header').toggleClass('slide-active');
  });

  var selected = '#slidemenu, #page-content, body, .navbar, .navbar-header';

  $(window).on("resize", function () {
    if ($(window).width() > 767 && $('.navbar-toggle').is(':hidden')) {
      $(selected).removeClass('slide-active');
    }
  });
}

function toggleSpeakers () {
  $('.speakers .expand').click(function() {
      $(this).find('.description').slideToggle();
      $(this).find('.more').toggleClass('less');
  });
}

function animateNav () {
  var navbar = $('.navbar');
  var links = $('.link-on-top');
  $(window).scroll(function () {
    var scroll = $(window).scrollTop();
    if (scroll >= 30) {
        navbar.removeClass('navbar-top');
        links.addClass('link-on-scroll');
    } else {
        navbar.addClass('navbar-top');
        links.removeClass('link-on-scroll');
    }
  });
}

(function (d, s, id) {
    if ('https:' == document.location.protocol || d.getElementById(id)) return;
    var js, fjs = d.getElementsByTagName(s)[0]; js = d.createElement(s); js.id = id;
    js.src = "http://bettercontactform.com/contact/media/d/6/d6ae80b1b686bc01ef3f667f33e40fa5c4bb1ae1.js";
    fjs.parentNode.insertBefore(js, fjs);
    }(document, "script", "bcf-render"));<commit_msg>Modificado link de BetterContactForm<commit_after>$(function() {
  configureScroll();
  configureOffcanvas();
  toggleSpeakers();
  animateNav();
});

function configureScroll () {
  $('nav a').click(goToScroll);
  $('.register a').click(goToScroll);
  $('.navbar-brand').click(goToScroll);
}

function goToScroll() {
  var offset = 50;
  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
    if (target.length) {
      $('html,body').animate({
        scrollTop: target.offset().top - offset
      }, 1000);
      return false;
    }
  }
}

function configureOffcanvas () {
 //stick in the fixed 100% height behind the navbar but don't wrap it
 $('#slide-nav.navbar .container').append($('
SECCIONES
'));

  // Enter your ids or classes
  var toggler = '.navbar-toggle';
  var pagewrapper = '#page-content';
  var navigationwrapper = '.navbar-header';
  var menuwidth = '100%'; // the menu inside the slide menu itself
  var slidewidth = '50%';
  var menuneg = '-100%';
  var slideneg = '-100%';

  $("#slide-nav").on("click", toggler, function (e) {
    var selected = $(this).hasClass('slide-active');

    $('#slidemenu').stop().animate({
      left: selected ? menuneg : '0px'
    });

    $('#navbar-height-col').stop().animate({
      left: selected ? slideneg : '0px'
    });

    $(pagewrapper).stop().animate({
      left: selected ? '0px' : slidewidth
    });

    $(navigationwrapper).stop().animate({
      left: selected ? '0px' : slidewidth
    });

    $(this).toggleClass('slide-active', !selected);
    $('#slidemenu').toggleClass('slide-active');

    $('#page-content, .navbar, body, .navbar-header').toggleClass('slide-active');
  });

  var selected = '#slidemenu, #page-content, body, .navbar, .navbar-header';

  $(window).on("resize", function () {
    if ($(window).width() > 767 && $('.navbar-toggle').is(':hidden')) {
      $(selected).removeClass('slide-active');
    }
  });
}

function toggleSpeakers () {
  $('.speakers .expand').click(function() {
      $(this).find('.description').slideToggle();
      $(this).find('.more').toggleClass('less');
  });
}

function animateNav () {
  var navbar = $('.navbar');
  var links = $('.link-on-top');
  $(window).scroll(function () {
    var scroll = $(window).scrollTop();
    if (scroll >= 30) {
        navbar.removeClass('navbar-top');
        links.addClass('link-on-scroll');
    } else {
        navbar.addClass('navbar-top');
        links.removeClass('link-on-scroll');
    }
  });
}

(function (d, s, id) {
    if ('https:' == document.location.protocol || d.getElementById(id)) return;
    var js, fjs = d.getElementsByTagName(s)[0]; js = d.createElement(s); js.id = id;
    js.src = "http://bettercontactform.com/contact/media/6/b/6b7a2e11a9e4fdb02f95ab248b7d91162b8bb4a7.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, "script", "bcf-render"));<|endoftext|>


<commit_before>module.exports = function (options) {
    options = options || {};

    return function buildProduction(assetGraph, cb) {
        var query = assetGraph.query,
            followRelationsQueryObj = query.or({to: {type: 'I18n'}},
                                               {type: query.not(['JavaScriptInclude', 'JavaScriptExtJsRequire', 'JavaScriptCommonJsRequire', 'HtmlAnchor']),
                                                to: query.and({url: query.not(/^https?:/)}, {url: query.not(options.blacklistUrlRegExp)})});

        assetGraph
            .populate({followRelations: followRelationsQueryObj})
            // Remove bootstrapper scripts injected by buildDevelopment:
            .removeRelations({type: 'HtmlScript', node: {id: 'bootstrapper'}, from: {type: 'Html'}}, {detach: true, removeOrphan: true})
            .if(options.version)
                .addContentVersionMetaElement({type: 'Html'}, options.version, true)
            .endif()
            .if(options.less)
                // Replace Less assets with their Css counterparts:
                .compileLessToCss({type: 'Less'})

                // Remove the in-browser less compiler and its incoming relations,
                // even if it's included from a CDN and thus hasn't been populated:
                .removeRelations({to: {url: /\/less(?:-\d+\.\d+\.\d+)?(?:\.min)?\.js$/}}, {unresolved: true, detach: true, removeOrphan: true})

                // Find and populate CssImage relations from the compiled Less assets:
                .populate({from: {type: 'Css'}})
            .endif()
            .removeRelations({type: 'JavaScriptInclude', to: {type: ['Css', 'JavaScript']}}, {detach: true, unresolved: true})
            .convertCssImportsToHtmlStyles()
            .removeAssets({isEmpty: true, type: ['Css', 'JavaScript']}, true)
            .externalizeRelations({from: {type: query.not('Htc')}, type: ['HtmlStyle', 'HtmlScript'], node: function (node) {return !node.hasAttribute('nobundle');}})
            .mergeIdenticalAssets(query.or({isImage: true}, {type: ['JavaScript', 'Css']}))
            // First execute explicit instructions in the query strings for images that are to be sprited:
            .processImages({isImage: true, url: /\?(?:|.*&)sprite(?:[&=#]|$)/})
            .spriteBackgroundImages()
            // Execute explicit and automatic optimizations for all images, including the generated sprite images:
            .processImages({isImage: true}, {pngcrush: options.pngcrush, optipng: options.optipng, pngquant: options.pngquant, jpegtran: options.jpegtran})
            .bundleRequireJs({type: 'Html'})
            // https://github.com/One-com/assetgraph/issues/82
            .queue(function removeDuplicateHtmlStyles(assetGraph) {
                assetGraph.findAssets({type: 'Html', isInitial: true}).forEach(function (htmlAsset) {
                    var seenCssAssetsById = {};
                    assetGraph.findRelations({from: htmlAsset, type: 'HtmlStyle'}).forEach(function (htmlStyle) {
                        if (seenCssAssetsById[htmlStyle.to.id]) {
                            htmlStyle.detach();
                        } else {
                            seenCssAssetsById[htmlStyle.to.id] = true;
                        }
                    });
                });
            })
            .bundleRelations({type: 'HtmlStyle', to: {type: 'Css'}, node: function (node) {return !node.hasAttribute('nobundle');}})
            .bundleRelations({type: 'HtmlScript', to: {type: 'JavaScript'}, node: function (node) {return !node.hasAttribute('nobundle');}})
            .removeNobundleAttribute({type: ['HtmlScript', 'HtmlStyle']})
            .inlineCssImagesWithLegacyFallback({type: 'Html', isInline: false}, options.inlineSize)
            .if(options.mangleTopLevel)
                .pullGlobalsIntoVariables({type: 'JavaScript'})
            .endif()
            .minifyAssets()
            .if(options.localeIds)
                .cloneForEachLocale({type: 'Html', isInitial: true}, {
                    localeIds: options.localeIds,
                    supportedLocaleIds: options.localeIds,
                    localeCookieName: options.localeCookieName,
                    infoObject: options.localizationInfoObject,
                    defaultLocaleId: options.defaultLocaleId
                })
                .runJavaScriptConditionalBlocks({isInitial: true}, 'LOCALIZE', true)
            .endif()
            .removeAssets({type: 'I18n'}, true)
            .if(!options.noCompress)
                .compressJavaScript({type: 'JavaScript'}, 'uglifyJs', {toplevel: options.mangleTopLevel, defines: options.defines})
            .endif()
            .inlineRelations({
                type: ['HtmlStyle', 'HtmlScript'],
                from: {isInline: false}, // Excludes relations occurring in conditional comments
                to: function (asset) {return asset.isAsset && asset.rawSrc.length < 4096;}
            })
            .if(options.noCompress)
                .prettyPrintAssets(function (asset) {
                    return asset.type === 'JavaScript' && (!asset.isInline || asset.incomingRelations.every(function (incomingRelation) {
                        return incomingRelation.type === 'HtmlScript';
                    }));
                })
                .prettyPrintAssets({type: 'Css'})
            .endif()
            .setAsyncOrDeferOnHtmlScripts({to: {isInline: false, url: /^file:/}}, options.asyncScripts, options.deferScripts)
            .omitFunctionCall({type: ['JavaScriptGetStaticUrl', 'JavaScriptTrHtml']})
            .inlineRelations({type: ['JavaScriptGetText', 'JavaScriptTrHtml']})
            .if(options.manifest)
                .addCacheManifest({isInitial: true})
                .if(options.localeIds && options.negotiateManifest)
                    .queue(function stripLocaleIdFromHtmlCacheManifestRelations(assetGraph) {
                        // This would be much less fragile if an asset could have a canonical url as well as an url (under consideration):
                        assetGraph.findRelations({type: 'HtmlCacheManifest'}).forEach(function (htmlCacheManifest) {
                            htmlCacheManifest.href = htmlCacheManifest.href.replace(/\.\w+\.appcache$/, '.appcache');
                        });
                    })
                .endif()
            .endif()
            .moveAssetsInOrder({isInitial: query.not(true), type: query.not('CacheManifest')}, function (asset, assetGraph) {
                var targetUrl = "/static/";
                // Conservatively assume that all GETSTATICURL relations pointing at non-images are intended to be fetched via XHR
                // and thus cannot be put on a CDN because of same origin restrictions:
                if (options.cdnRoot && asset.type !== 'Htc' && (asset.isImage || assetGraph.findRelations({to: asset, type: 'StaticUrlMapEntry'}).length === 0)) {
                    targetUrl = options.cdnRoot;
                    if (/^\/\//.test(options.cdnRoot)) {
                        assetGraph.findRelations({to: asset}).forEach(function (incomingRelation) {
                            incomingRelation.hrefType = 'protocolRelative';
                        });
                    }
                }
                return targetUrl + asset.md5Hex.substr(0, 10) + asset.extension + asset.url.replace(/^[^#\?]*(?:)/, ''); // Preserve query string and fragment identifier
            })
            .run(cb);
    };
};
<commit_msg>buildProduction: Skip assets that haven't been loaded in most of the transforms.<commit_after>module.exports = function (options) {
    options = options || {};

    return function buildProduction(assetGraph, cb) {
        var query = assetGraph.query,
            followRelationsQueryObj = query.or({to: {type: 'I18n'}},
                                               {type: query.not(['JavaScriptInclude', 'JavaScriptExtJsRequire', 'JavaScriptCommonJsRequire', 'HtmlAnchor']),
                                                to: query.and({url: query.not(/^https?:/)}, {url: query.not(options.blacklistUrlRegExp)})});

        assetGraph
            .populate({followRelations: followRelationsQueryObj})
            // Remove bootstrapper scripts injected by buildDevelopment:
            .removeRelations({type: 'HtmlScript', node: {id: 'bootstrapper'}, from: {type: 'Html'}}, {detach: true, removeOrphan: true})
            .if(options.version)
                .addContentVersionMetaElement({type: 'Html'}, options.version, true)
            .endif()
            .if(options.less)
                // Replace Less assets with their Css counterparts:
                .compileLessToCss({type: 'Less', isLoaded: true})

                // Remove the in-browser less compiler and its incoming relations,
                // even if it's included from a CDN and thus hasn't been populated:
                .removeRelations({to: {url: /\/less(?:-\d+\.\d+\.\d+)?(?:\.min)?\.js$/}}, {unresolved: true, detach: true, removeOrphan: true})

                // Find and populate CssImage relations from the compiled Less assets:
                .populate({from: {type: 'Css'}})
            .endif()
            .removeRelations({type: 'JavaScriptInclude', to: {type: ['Css', 'JavaScript']}}, {detach: true, unresolved: true})
            .convertCssImportsToHtmlStyles()
            .removeAssets({isLoaded: true, isEmpty: true, type: ['Css', 'JavaScript']}, true)
            .externalizeRelations({from: {type: query.not('Htc')}, type: ['HtmlStyle', 'HtmlScript'], node: function (node) {return !node.hasAttribute('nobundle');}})
            .mergeIdenticalAssets(query.or({isImage: true}, {isLoaded: true, type: ['JavaScript', 'Css']}))
            // First execute explicit instructions in the query strings for images that are to be sprited:
            .processImages({isImage: true, isLoaded: true, url: /\?(?:|.*&)sprite(?:[&=#]|$)/})
            .spriteBackgroundImages()
            // Execute explicit and automatic optimizations for all images, including the generated sprite images:
            .processImages({isImage: true, isLoaded: true}, {pngcrush: options.pngcrush, optipng: options.optipng, pngquant: options.pngquant, jpegtran: options.jpegtran})
            .bundleRequireJs({type: 'Html'})
            // https://github.com/One-com/assetgraph/issues/82
            .queue(function removeDuplicateHtmlStyles(assetGraph) {
                assetGraph.findAssets({type: 'Html', isInitial: true}).forEach(function (htmlAsset) {
                    var seenCssAssetsById = {};
                    assetGraph.findRelations({from: htmlAsset, type: 'HtmlStyle'}).forEach(function (htmlStyle) {
                        if (seenCssAssetsById[htmlStyle.to.id]) {
                            htmlStyle.detach();
                        } else {
                            seenCssAssetsById[htmlStyle.to.id] = true;
                        }
                    });
                });
            })
            .bundleRelations({type: 'HtmlStyle', to: {type: 'Css', isLoaded: true}, node: function (node) {return !node.hasAttribute('nobundle');}})
            .bundleRelations({type: 'HtmlScript', to: {type: 'JavaScript', isLoaded: true}, node: function (node) {return !node.hasAttribute('nobundle');}})
            .removeNobundleAttribute({type: ['HtmlScript', 'HtmlStyle']})
            .inlineCssImagesWithLegacyFallback({type: 'Html', isInline: false}, options.inlineSize)
            .if(options.mangleTopLevel)
                .pullGlobalsIntoVariables({type: 'JavaScript', isLoaded: true})
            .endif()
            .minifyAssets({isLoaded: true})
            .if(options.localeIds)
                .cloneForEachLocale({type: 'Html', isInitial: true}, {
                    localeIds: options.localeIds,
                    supportedLocaleIds: options.localeIds,
                    localeCookieName: options.localeCookieName,
                    infoObject: options.localizationInfoObject,
                    defaultLocaleId: options.defaultLocaleId
                })
                .runJavaScriptConditionalBlocks({isInitial: true}, 'LOCALIZE', true)
            .endif()
            .removeAssets({type: 'I18n'}, true)
            .if(!options.noCompress)
                .compressJavaScript({type: 'JavaScript', isLoaded: true}, 'uglifyJs', {toplevel: options.mangleTopLevel, defines: options.defines})
            .endif()
            .inlineRelations({
                type: ['HtmlStyle', 'HtmlScript'],
                from: {isInline: false}, // Excludes relations occurring in conditional comments
                to: function (asset) {return asset.isLoaded && asset.isAsset && asset.rawSrc.length < 4096;}
            })
            .if(options.noCompress)
                .prettyPrintAssets(function (asset) {
                    return asset.isLoaded && asset.type === 'JavaScript' && (!asset.isInline || asset.incomingRelations.every(function (incomingRelation) {
                        return incomingRelation.type === 'HtmlScript';
                    }));
                })
                .prettyPrintAssets({type: 'Css', isLoaded: true})
            .endif()
            .setAsyncOrDeferOnHtmlScripts({to: {isInline: false, url: /^file:/}}, options.asyncScripts, options.deferScripts)
            .omitFunctionCall({type: ['JavaScriptGetStaticUrl', 'JavaScriptTrHtml']})
            .inlineRelations({type: ['JavaScriptGetText', 'JavaScriptTrHtml']})
            .if(options.manifest)
                .addCacheManifest({isInitial: true})
                .if(options.localeIds && options.negotiateManifest)
                    .queue(function stripLocaleIdFromHtmlCacheManifestRelations(assetGraph) {
                        // This would be much less fragile if an asset could have a canonical url as well as an url (under consideration):
                        assetGraph.findRelations({type: 'HtmlCacheManifest'}).forEach(function (htmlCacheManifest) {
                            htmlCacheManifest.href = htmlCacheManifest.href.replace(/\.\w+\.appcache$/, '.appcache');
                        });
                    })
                .endif()
            .endif()
            .moveAssetsInOrder({isLoaded: true, isInitial: query.not(true), type: query.not('CacheManifest')}, function (asset, assetGraph) {
                var targetUrl = "/static/";
                // Conservatively assume that all GETSTATICURL relations pointing at non-images are intended to be fetched via XHR
                // and thus cannot be put on a CDN because of same origin restrictions:
                if (options.cdnRoot && asset.type !== 'Htc' && (asset.isImage || assetGraph.findRelations({to: asset, type: 'StaticUrlMapEntry'}).length === 0)) {
                    targetUrl = options.cdnRoot;
                    if (/^\/\//.test(options.cdnRoot)) {
                        assetGraph.findRelations({to: asset}).forEach(function (incomingRelation) {
                            incomingRelation.hrefType = 'protocolRelative';
                        });
                    }
                }
                return targetUrl + asset.md5Hex.substr(0, 10) + asset.extension + asset.url.replace(/^[^#\?]*(?:)/, ''); // Preserve query string and fragment identifier
            })
            .run(cb);
    };
};
<|endoftext|>


<commit_before>var _ = require('underscore'),
    urlTools = require('urltools'),
    cssom = require('cssom-papandreou'),
    AssetGraph = require('../'),
    uglifyJs = AssetGraph.JavaScript.uglifyJs;

module.exports = function (queryObj, options) {
    options = options || {};
    var bundleStrategyName = options.strategyName || 'oneBundlePerIncludingAsset';

    return function bundleRelations(assetGraph) {
        function getDiscriminatorForRelation(relation) {
            var discriminatorFragments = [],
                i,
                attribute;
            if (relation.to.isLoaded) {
                discriminatorFragments.push('isLoaded');
            }
            var isInsideHead = false,
                parentNode = relation.node.parentNode;
            while (parentNode) {
                if (parentNode.nodeName.toLowerCase() === 'head') {
                    isInsideHead = true;
                    break;
                }
                parentNode = parentNode.parentNode;
            }
            if (isInsideHead) {
                discriminatorFragments.push('head');
            } else {
                discriminatorFragments.push('body');
            }
            if (relation.conditionalComments) {
                Array.prototype.push.apply(discriminatorFragments, _.pluck(relation.conditionalComments, 'nodeValue'));
            }
            if (relation.type === 'HtmlStyle') {
                discriminatorFragments.push(relation.node.getAttribute('media') || 'all');
                for (i = 0 ; i < relation.node.attributes.length ; i += 1) {
                    attribute = relation.node.attributes[i];
                    if (attribute.name !== 'media' &&
                        (attribute.name !== 'rel' || attribute.value !== 'stylesheet') &&
                        (attribute.name !== 'href' || relation.node.nodeName.toLowerCase() !== 'link') &&
                        (attribute.name !== 'type' || attribute.value !== 'text/css' || !relation.to || relation.to.type !== 'Css')) {
                        return 'nobundle';
                    }
                }
            } else if (relation.type === 'HtmlScript') {
                if (relation.to.strict) {
                    discriminatorFragments.push('strict');
                    var warning = new Error('Global "use strict"-directive. Splitting into multiple bundles to avoid side effects.');
                    warning.asset = relation.to;
                    assetGraph.emit('info', warning);
                }
                if (relation.node.getAttribute('defer') === 'defer') {
                    discriminatorFragments.push('defer');
                }
                if (relation.node.getAttribute('async') === 'async') {
                    discriminatorFragments.push('async');
                }
                for (i = 0 ; i < relation.node.attributes.length ; i += 1) {
                    attribute = relation.node.attributes[i];
                    if (attribute.name !== 'src' &&
                        (attribute.name !== 'defer' || attribute.value !== 'defer') &&
                        (attribute.name !== 'async' || attribute.value !== 'async') &&
                        (attribute.name !== 'type' || attribute.value !== 'text/javascript' || !relation.to || relation.to.type !== 'JavaScript')) {

                        return 'nobundle';
                    }
                }
            }
            return discriminatorFragments.join(':');
        }

        // Reuses the parse trees of existing assets, so be careful!
        function makeBundle(assetsToBundle) {
            if (assetsToBundle.length === 0) {
                throw new Error('makeBundle: Bundle must contain at least one asset');
            } else if (assetsToBundle.length === 1) {
                // Shortcut
                return [assetsToBundle[0]];
            }

            var type = assetsToBundle[0].type,
                incomingType = {Css: 'HtmlStyle', JavaScript: 'HtmlScript'}[type],
                constructorOptions = {
                    lastKnownByteLength: assetsToBundle.reduce(function (sumOfLastKnownByteLengths, asset) {
                        return sumOfLastKnownByteLengths + asset.lastKnownByteLength;
                    }, 0)
                };

            if (type === 'JavaScript') {
                constructorOptions.parseTree = new uglifyJs.AST_Toplevel({body: []});
                assetsToBundle.forEach(function (asset, i) {
                    assetGraph.findRelations({from: asset, type: 'JavaScriptInclude'}, true).forEach(function (relation) {
                        if (relation.parentNode === asset.parseTree) {
                            // This INCLUDE relation is a top level statement, update its .parentNode property to point at
                            // the top level statements array of the bundle:
                            relation.parentNode = constructorOptions.parseTree;
                        }
                    });

                    // Append asset to new bundle
                    Array.prototype.push.apply(constructorOptions.parseTree.body, asset.parseTree.body);

                    if (asset.parseTree.end && asset.parseTree.end.comments_before) {
                        if (i === assetsToBundle.length - 1) {
                            var endToken = (constructorOptions.parseTree.end = constructorOptions.parseTree.end || new uglifyJs.AST_Token({type: 'eof', comments_before: []}));
                            Array.prototype.push.apply(endToken.comments_before, asset.parseTree.end.comments_before);
                        } else {
                            var nextAsset = assetsToBundle[i + 1],
                                startToken = (nextAsset.parseTree.start = nextAsset.parseTree.start || new uglifyJs.AST_Token({type: 'eof', comments_before: []}));
                            Array.prototype.unshift.apply(startToken.comments_before, asset.parseTree.end.comments_before);
                        }
                    }
                });
            } else {
                // type === 'Css'
                constructorOptions.parseTree = new cssom.CSSStyleSheet();
                // Make sure that all @import rules go at the top of the bundle:
                var importRules = [];
                assetsToBundle.forEach(function (asset) {
                    var cssRules = asset.parseTree.cssRules;
                    asset.parseTree.parentStyleSheet = constructorOptions.parseTree;
                    for (var i = 0 ; i < cssRules.length ; i += 1) {
                        if (cssRules[i].type === cssom.CSSRule.IMPORT_RULE) {
                            importRules.push(cssRules[i]);
                            cssRules.splice(i, 1);
                            i -= 1;
                        }
                    }
                    Array.prototype.push.apply(constructorOptions.parseTree.cssRules, cssRules);
                });
                if (importRules.length > 0) {
                    Array.prototype.unshift.apply(constructorOptions.parseTree.cssRules, importRules);
                }
            }

            var bundleAsset = new AssetGraph[type](constructorOptions);

            bundleAsset.url = urlTools.resolveUrl(assetGraph.root, 'bundle-' + bundleAsset.id + bundleAsset.extension);
            bundleAsset._outgoingRelations = assetGraph.findRelations({from: assetsToBundle});
            bundleAsset._outgoingRelations.forEach(function (outgoingRelation) {
                outgoingRelation.remove();
                outgoingRelation.from = bundleAsset;
            });

            var seenReferringAssets = {},
                incomingRelations = assetGraph.findRelations({type: incomingType, to: assetsToBundle}),
                // Point at the bundled asset with a root-relative href if at least one of the relations
                // being bundled have a more specific hrefType than 'relative':
                bundleRelationHrefType = incomingRelations.some(function (incomingRelation) {
                    return incomingRelation.hrefType !== 'relative';
                }) ? 'rootRelative' : 'relative';

            incomingRelations.forEach(function (incomingRelation) {
                if (!(incomingRelation.from.id in seenReferringAssets)) {
                    var bundleRelation = new AssetGraph[incomingType]({
                        hrefType: bundleRelationHrefType,
                        to: bundleAsset
                    });
                    bundleRelation.attach(incomingRelation.from, 'before', incomingRelation);
                    if (incomingType === 'HtmlStyle') {
                        var media = incomingRelation.node.getAttribute('media');
                        if (media && media !== 'all') {
                            bundleRelation.node.setAttribute('media', media);
                            bundleRelation.from.markDirty();
                        }
                    } else if (incomingType === 'HtmlScript') {
                        for (var i = 0 ; i < incomingRelations.length ; i += 1) {
                            var otherIncomingRelation = incomingRelations[i];
                            if (otherIncomingRelation.assetGraph && otherIncomingRelation.node.hasAttribute('data-main')) {
                                var existingHtmlRequireJsMainRelations = assetGraph.findRelations({
                                    from: otherIncomingRelation.from,
                                    type: 'HtmlRequireJsMain'
                                }).filter(function (relation) {
                                    return relation.node === otherIncomingRelation.node;
                                });
                                if (existingHtmlRequireJsMainRelations.length === 1) {
                                    var existingHtmlRequireJsMainRelation = existingHtmlRequireJsMainRelations[0];
                                    bundleRelation.node.setAttribute('data-main', otherIncomingRelation.node.getAttribute('data-main'));
                                    existingHtmlRequireJsMainRelation.node = bundleRelation.node;
                                    break;
                                } else {
                                    throw new Error('transforms.bundleRelations: Unexpected number of existing HtmlRequireJsMain relations found');
                                }
                            }
                        }
                    }
                    seenReferringAssets[incomingRelation.from.id] = true;
                }
                incomingRelation.detach();
            });

            assetGraph.addAsset(bundleAsset);

            assetsToBundle.forEach(function (asset) {
                if (assetGraph.findRelations({to: asset}).length === 0) {
                    assetGraph.removeAsset(asset);
                }
            });
            return bundleAsset;
        }

        var bundleStrategyByName = {};

        // Quick and dirty bundling strategy that gets you down to one <script> and one <link rel='stylesheet'>
        // per document, but doesn't do any cross-page optimization.
        bundleStrategyByName.oneBundlePerIncludingAsset = function () {
            var assetsToBundleById = {},
                bundleAssets = [],
                relationsByIncludingAsset = {};

            assetGraph.findRelations(queryObj).forEach(function (relation) {
                assetsToBundleById[relation.to.id] = relation.to; // Means not in a bundle yet
                (relationsByIncludingAsset[relation.from.id] = relationsByIncludingAsset[relation.from.id] || []).push(relation);
            });

            Object.keys(relationsByIncludingAsset).forEach(function (includingAssetId) {
                var relationsToBundle = relationsByIncludingAsset[includingAssetId];

                _.unique(_.pluck(relationsToBundle, 'type')).forEach(function (relationType) {
                    var currentBundle = [],
                        bundleDiscriminator,
                        relationsOfTypeToBundle = relationsToBundle.filter(function (relation) {
                            return relation.type === relationType;
                        });

                    function flushBundle() {
                        if (currentBundle.length > 0) {
                            bundleAssets.push(makeBundle(currentBundle)); // FIXME
                            currentBundle = [];
                        }
                    }
                    assetGraph.findRelations(assetGraph.constructor.query.or({type: relationType}, {type: 'HtmlConditionalComment'}), true).forEach(function (outgoingRelation) {
                        if (outgoingRelation.type === 'HtmlConditionalComment') {
                            if (assetGraph.findRelations({from: outgoingRelation.to, type: relationType}, true).length > 0) {
                                flushBundle();
                            }
                        } else if (relationsOfTypeToBundle.indexOf(outgoingRelation) !== -1) {
                            // Make sure that we don't bundle HtmlStyles with different media attributes together etc.:
                            var discriminator = getDiscriminatorForRelation(outgoingRelation);
                            if (bundleDiscriminator && (discriminator === 'nobundle' || bundleDiscriminator === 'nobundle' || discriminator !== bundleDiscriminator)) {
                                flushBundle();
                            }
                            bundleDiscriminator = discriminator;
                            if (assetGraph.findRelations({to: outgoingRelation.to}).length > 1) {
                                currentBundle.push(outgoingRelation.to.clone(outgoingRelation));
                            } else {
                                currentBundle.push(outgoingRelation.to);
                            }
                        } else {
                            flushBundle();
                        }
                    });
                    flushBundle();
                });
            });
            return bundleAssets;
        };

        // Cross-page optimizing bundling strategy that never puts the same chunk in multiple bundles, but still tries
        // to create as few bundles as possible. Also preserves inclusion order.
        bundleStrategyByName.sharedBundles = function () {
            var assetIndex = {},
                seenIncludingAssets = {},
                bundles = [],
                relationsByIncludingAsset = {};

            assetGraph.findRelations(queryObj).forEach(function (relation) {
                assetIndex[relation.to.id] = null; // Means not in a bundle yet
                seenIncludingAssets[relation.from.id] = relation.from;
                (relationsByIncludingAsset[relation.from.id] = relationsByIncludingAsset[relation.from.id] || []).push(relation);
            });

            function splitBundle(bundle, index) {
                var newBundle = bundle.splice(index);
                newBundle.forEach(function (asset) {
                    assetIndex[asset.id] = newBundle;
                });
                if (newBundle.length > 0) {
                    bundles.push(newBundle);
                }
                return newBundle;
            }

            _.values(seenIncludingAssets).forEach(function (includingAsset) {
                var relationsToBundle = relationsByIncludingAsset[includingAsset.id];

                _.unique(_.pluck(relationsToBundle, 'type')).forEach(function (relationType) {
                    var outgoingRelations = assetGraph.findRelations({from: includingAsset, type: [relationType, 'HtmlConditionalComment']}, true), // includeUnresolved
                        previousBundle,
                        bundleDiscriminator,
                        canAppendToPreviousBundle = false,
                        previousBundleIndex;

                    outgoingRelations.forEach(function (outgoingRelation) {
                        if (outgoingRelation.type === 'HtmlConditionalComment') {
                            if (assetGraph.findRelations({from: outgoingRelation.to, type: relationType}).length > 0) {
                                canAppendToPreviousBundle = false;
                            }
                            return;
                        }

                        // Make sure that we don't bundle HtmlStyles with different media attributes together etc.:
                        var discriminator = getDiscriminatorForRelation(outgoingRelation);
                        if (bundleDiscriminator && (discriminator === 'nobundle' || bundleDiscriminator === 'nobundle' || discriminator !== bundleDiscriminator)) {
                            canAppendToPreviousBundle = false;
                        }
                        bundleDiscriminator = discriminator;

                        var existingBundle = assetIndex[outgoingRelation.to.id];
                        if (existingBundle === null) {
                            // Not bundled yet, append to previousBundle if possible, else create a new one
                            if (canAppendToPreviousBundle) {
                                previousBundle.push(outgoingRelation.to);
                                previousBundleIndex = previousBundle.length - 1;
                            } else {
                                if (previousBundle && previousBundleIndex !== previousBundle.length - 1) {
                                    splitBundle(previousBundle, previousBundleIndex + 1);
                                }
                                previousBundle = [outgoingRelation.to];
                                previousBundleIndex = 0;
                                bundles.push(previousBundle);
                                canAppendToPreviousBundle = true;
                            }
                            assetIndex[outgoingRelation.to.id] = previousBundle;
                        } else if (existingBundle) {
                            // Already in another bundle
                            canAppendToPreviousBundle = false;
                            var indexInExistingBundle = existingBundle.indexOf(outgoingRelation.to);
                            if (previousBundle && existingBundle === previousBundle) {
                                if (indexInExistingBundle === previousBundleIndex + 1) {
                                    previousBundleIndex = indexInExistingBundle;
                                } else {
                                    splitBundle(previousBundle, indexInExistingBundle + 1);
                                    existingBundle = assetIndex[outgoingRelation.to.id];
                                    indexInExistingBundle = existingBundle.indexOf(outgoingRelation.to);
                                    if (indexInExistingBundle !== 0) {
                                        existingBundle = splitBundle(existingBundle, indexInExistingBundle);
                                    }
                                    previousBundle = existingBundle;
                                    previousBundleIndex = 0;
                                }
                            } else {
                                if (previousBundle && previousBundleIndex !== (previousBundle.length - 1)) {
                                    splitBundle(previousBundle, previousBundleIndex + 1);
                                }
                                if (indexInExistingBundle !== 0) {
                                    existingBundle = splitBundle(existingBundle, indexInExistingBundle);
                                }
                                previousBundle = existingBundle;
                                previousBundleIndex = 0;
                            }
                        } else {
                            // The relation doesn't point at an asset matched by queryObj
                            previousBundle = null;
                            canAppendToPreviousBundle = false;
                        }
                    });
                    // No more outgoing relations for this asset, make sure that the asset that was bundled
                    // last is at the last position in its bundle:
                    if (previousBundle && previousBundleIndex !== previousBundle.length - 1) {
                        splitBundle(previousBundle, previousBundleIndex + 1);
                    }
                });
            });

            return bundles.map(makeBundle);
        };

        var bundleAssets = bundleStrategyByName[bundleStrategyName]();
        assetGraph.recomputeBaseAssets();
        bundleAssets.forEach(function (bundleAsset) {
            assetGraph.findRelations({to: bundleAsset}).forEach(function (incomingRelation) {
                incomingRelation.refreshHref();
            });
            assetGraph.findRelations({from: bundleAsset}).forEach(function (outgoingRelation) {
                outgoingRelation.refreshHref();
            });
        });
    };
};
<commit_msg>bundleRelations: Ignore the charset attribute when deciding whether a relation can be bundled.<commit_after>var _ = require('underscore'),
    urlTools = require('urltools'),
    cssom = require('cssom-papandreou'),
    AssetGraph = require('../'),
    uglifyJs = AssetGraph.JavaScript.uglifyJs;

module.exports = function (queryObj, options) {
    options = options || {};
    var bundleStrategyName = options.strategyName || 'oneBundlePerIncludingAsset';

    return function bundleRelations(assetGraph) {
        function getDiscriminatorForRelation(relation) {
            var discriminatorFragments = [],
                i,
                attribute;
            if (relation.to.isLoaded) {
                discriminatorFragments.push('isLoaded');
            }
            var isInsideHead = false,
                parentNode = relation.node.parentNode;
            while (parentNode) {
                if (parentNode.nodeName.toLowerCase() === 'head') {
                    isInsideHead = true;
                    break;
                }
                parentNode = parentNode.parentNode;
            }
            if (isInsideHead) {
                discriminatorFragments.push('head');
            } else {
                discriminatorFragments.push('body');
            }
            if (relation.conditionalComments) {
                Array.prototype.push.apply(discriminatorFragments, _.pluck(relation.conditionalComments, 'nodeValue'));
            }
            if (relation.type === 'HtmlStyle') {
                discriminatorFragments.push(relation.node.getAttribute('media') || 'all');
                for (i = 0 ; i < relation.node.attributes.length ; i += 1) {
                    attribute = relation.node.attributes[i];
                    if (attribute.name !== 'charset' &&
                        attribute.name !== 'media' &&
                        (attribute.name !== 'rel' || attribute.value !== 'stylesheet') &&
                        (attribute.name !== 'href' || relation.node.nodeName.toLowerCase() !== 'link') &&
                        (attribute.name !== 'type' || attribute.value !== 'text/css' || !relation.to || relation.to.type !== 'Css')) {
                        return 'nobundle';
                    }
                }
            } else if (relation.type === 'HtmlScript') {
                if (relation.to.strict) {
                    discriminatorFragments.push('strict');
                    var warning = new Error('Global "use strict"-directive. Splitting into multiple bundles to avoid side effects.');
                    warning.asset = relation.to;
                    assetGraph.emit('info', warning);
                }
                if (relation.node.getAttribute('defer') === 'defer') {
                    discriminatorFragments.push('defer');
                }
                if (relation.node.getAttribute('async') === 'async') {
                    discriminatorFragments.push('async');
                }
                for (i = 0 ; i < relation.node.attributes.length ; i += 1) {
                    attribute = relation.node.attributes[i];
                    if (attribute.name !== 'charset' &&
                        attribute.name !== 'src' &&
                        (attribute.name !== 'defer' || attribute.value !== 'defer') &&
                        (attribute.name !== 'async' || attribute.value !== 'async') &&
                        (attribute.name !== 'type' || attribute.value !== 'text/javascript' || !relation.to || relation.to.type !== 'JavaScript')) {

                        return 'nobundle';
                    }
                }
            }
            return discriminatorFragments.join(':');
        }

        // Reuses the parse trees of existing assets, so be careful!
        function makeBundle(assetsToBundle) {
            if (assetsToBundle.length === 0) {
                throw new Error('makeBundle: Bundle must contain at least one asset');
            } else if (assetsToBundle.length === 1) {
                // Shortcut
                return [assetsToBundle[0]];
            }

            var type = assetsToBundle[0].type,
                incomingType = {Css: 'HtmlStyle', JavaScript: 'HtmlScript'}[type],
                constructorOptions = {
                    lastKnownByteLength: assetsToBundle.reduce(function (sumOfLastKnownByteLengths, asset) {
                        return sumOfLastKnownByteLengths + asset.lastKnownByteLength;
                    }, 0)
                };

            if (type === 'JavaScript') {
                constructorOptions.parseTree = new uglifyJs.AST_Toplevel({body: []});
                assetsToBundle.forEach(function (asset, i) {
                    assetGraph.findRelations({from: asset, type: 'JavaScriptInclude'}, true).forEach(function (relation) {
                        if (relation.parentNode === asset.parseTree) {
                            // This INCLUDE relation is a top level statement, update its .parentNode property to point at
                            // the top level statements array of the bundle:
                            relation.parentNode = constructorOptions.parseTree;
                        }
                    });

                    // Append asset to new bundle
                    Array.prototype.push.apply(constructorOptions.parseTree.body, asset.parseTree.body);

                    if (asset.parseTree.end && asset.parseTree.end.comments_before) {
                        if (i === assetsToBundle.length - 1) {
                            var endToken = (constructorOptions.parseTree.end = constructorOptions.parseTree.end || new uglifyJs.AST_Token({type: 'eof', comments_before: []}));
                            Array.prototype.push.apply(endToken.comments_before, asset.parseTree.end.comments_before);
                        } else {
                            var nextAsset = assetsToBundle[i + 1],
                                startToken = (nextAsset.parseTree.start = nextAsset.parseTree.start || new uglifyJs.AST_Token({type: 'eof', comments_before: []}));
                            Array.prototype.unshift.apply(startToken.comments_before, asset.parseTree.end.comments_before);
                        }
                    }
                });
            } else {
                // type === 'Css'
                constructorOptions.parseTree = new cssom.CSSStyleSheet();
                // Make sure that all @import rules go at the top of the bundle:
                var importRules = [];
                assetsToBundle.forEach(function (asset) {
                    var cssRules = asset.parseTree.cssRules;
                    asset.parseTree.parentStyleSheet = constructorOptions.parseTree;
                    for (var i = 0 ; i < cssRules.length ; i += 1) {
                        if (cssRules[i].type === cssom.CSSRule.IMPORT_RULE) {
                            importRules.push(cssRules[i]);
                            cssRules.splice(i, 1);
                            i -= 1;
                        }
                    }
                    Array.prototype.push.apply(constructorOptions.parseTree.cssRules, cssRules);
                });
                if (importRules.length > 0) {
                    Array.prototype.unshift.apply(constructorOptions.parseTree.cssRules, importRules);
                }
            }

            var bundleAsset = new AssetGraph[type](constructorOptions);

            bundleAsset.url = urlTools.resolveUrl(assetGraph.root, 'bundle-' + bundleAsset.id + bundleAsset.extension);
            bundleAsset._outgoingRelations = assetGraph.findRelations({from: assetsToBundle});
            bundleAsset._outgoingRelations.forEach(function (outgoingRelation) {
                outgoingRelation.remove();
                outgoingRelation.from = bundleAsset;
            });

            var seenReferringAssets = {},
                incomingRelations = assetGraph.findRelations({type: incomingType, to: assetsToBundle}),
                // Point at the bundled asset with a root-relative href if at least one of the relations
                // being bundled have a more specific hrefType than 'relative':
                bundleRelationHrefType = incomingRelations.some(function (incomingRelation) {
                    return incomingRelation.hrefType !== 'relative';
                }) ? 'rootRelative' : 'relative';

            incomingRelations.forEach(function (incomingRelation) {
                if (!(incomingRelation.from.id in seenReferringAssets)) {
                    var bundleRelation = new AssetGraph[incomingType]({
                        hrefType: bundleRelationHrefType,
                        to: bundleAsset
                    });
                    bundleRelation.attach(incomingRelation.from, 'before', incomingRelation);
                    if (incomingType === 'HtmlStyle') {
                        var media = incomingRelation.node.getAttribute('media');
                        if (media && media !== 'all') {
                            bundleRelation.node.setAttribute('media', media);
                            bundleRelation.from.markDirty();
                        }
                    } else if (incomingType === 'HtmlScript') {
                        for (var i = 0 ; i < incomingRelations.length ; i += 1) {
                            var otherIncomingRelation = incomingRelations[i];
                            if (otherIncomingRelation.assetGraph && otherIncomingRelation.node.hasAttribute('data-main')) {
                                var existingHtmlRequireJsMainRelations = assetGraph.findRelations({
                                    from: otherIncomingRelation.from,
                                    type: 'HtmlRequireJsMain'
                                }).filter(function (relation) {
                                    return relation.node === otherIncomingRelation.node;
                                });
                                if (existingHtmlRequireJsMainRelations.length === 1) {
                                    var existingHtmlRequireJsMainRelation = existingHtmlRequireJsMainRelations[0];
                                    bundleRelation.node.setAttribute('data-main', otherIncomingRelation.node.getAttribute('data-main'));
                                    existingHtmlRequireJsMainRelation.node = bundleRelation.node;
                                    break;
                                } else {
                                    throw new Error('transforms.bundleRelations: Unexpected number of existing HtmlRequireJsMain relations found');
                                }
                            }
                        }
                    }
                    seenReferringAssets[incomingRelation.from.id] = true;
                }
                incomingRelation.detach();
            });

            assetGraph.addAsset(bundleAsset);

            assetsToBundle.forEach(function (asset) {
                if (assetGraph.findRelations({to: asset}).length === 0) {
                    assetGraph.removeAsset(asset);
                }
            });
            return bundleAsset;
        }

        var bundleStrategyByName = {};

        // Quick and dirty bundling strategy that gets you down to one <script> and one <link rel='stylesheet'>
        // per document, but doesn't do any cross-page optimization.
        bundleStrategyByName.oneBundlePerIncludingAsset = function () {
            var assetsToBundleById = {},
                bundleAssets = [],
                relationsByIncludingAsset = {};

            assetGraph.findRelations(queryObj).forEach(function (relation) {
                assetsToBundleById[relation.to.id] = relation.to; // Means not in a bundle yet
                (relationsByIncludingAsset[relation.from.id] = relationsByIncludingAsset[relation.from.id] || []).push(relation);
            });

            Object.keys(relationsByIncludingAsset).forEach(function (includingAssetId) {
                var relationsToBundle = relationsByIncludingAsset[includingAssetId];

                _.unique(_.pluck(relationsToBundle, 'type')).forEach(function (relationType) {
                    var currentBundle = [],
                        bundleDiscriminator,
                        relationsOfTypeToBundle = relationsToBundle.filter(function (relation) {
                            return relation.type === relationType;
                        });

                    function flushBundle() {
                        if (currentBundle.length > 0) {
                            bundleAssets.push(makeBundle(currentBundle)); // FIXME
                            currentBundle = [];
                        }
                    }
                    assetGraph.findRelations(assetGraph.constructor.query.or({type: relationType}, {type: 'HtmlConditionalComment'}), true).forEach(function (outgoingRelation) {
                        if (outgoingRelation.type === 'HtmlConditionalComment') {
                            if (assetGraph.findRelations({from: outgoingRelation.to, type: relationType}, true).length > 0) {
                                flushBundle();
                            }
                        } else if (relationsOfTypeToBundle.indexOf(outgoingRelation) !== -1) {
                            // Make sure that we don't bundle HtmlStyles with different media attributes together etc.:
                            var discriminator = getDiscriminatorForRelation(outgoingRelation);
                            if (bundleDiscriminator && (discriminator === 'nobundle' || bundleDiscriminator === 'nobundle' || discriminator !== bundleDiscriminator)) {
                                flushBundle();
                            }
                            bundleDiscriminator = discriminator;
                            if (assetGraph.findRelations({to: outgoingRelation.to}).length > 1) {
                                currentBundle.push(outgoingRelation.to.clone(outgoingRelation));
                            } else {
                                currentBundle.push(outgoingRelation.to);
                            }
                        } else {
                            flushBundle();
                        }
                    });
                    flushBundle();
                });
            });
            return bundleAssets;
        };

        // Cross-page optimizing bundling strategy that never puts the same chunk in multiple bundles, but still tries
        // to create as few bundles as possible. Also preserves inclusion order.
        bundleStrategyByName.sharedBundles = function () {
            var assetIndex = {},
                seenIncludingAssets = {},
                bundles = [],
                relationsByIncludingAsset = {};

            assetGraph.findRelations(queryObj).forEach(function (relation) {
                assetIndex[relation.to.id] = null; // Means not in a bundle yet
                seenIncludingAssets[relation.from.id] = relation.from;
                (relationsByIncludingAsset[relation.from.id] = relationsByIncludingAsset[relation.from.id] || []).push(relation);
            });

            function splitBundle(bundle, index) {
                var newBundle = bundle.splice(index);
                newBundle.forEach(function (asset) {
                    assetIndex[asset.id] = newBundle;
                });
                if (newBundle.length > 0) {
                    bundles.push(newBundle);
                }
                return newBundle;
            }

            _.values(seenIncludingAssets).forEach(function (includingAsset) {
                var relationsToBundle = relationsByIncludingAsset[includingAsset.id];

                _.unique(_.pluck(relationsToBundle, 'type')).forEach(function (relationType) {
                    var outgoingRelations = assetGraph.findRelations({from: includingAsset, type: [relationType, 'HtmlConditionalComment']}, true), // includeUnresolved
                        previousBundle,
                        bundleDiscriminator,
                        canAppendToPreviousBundle = false,
                        previousBundleIndex;

                    outgoingRelations.forEach(function (outgoingRelation) {
                        if (outgoingRelation.type === 'HtmlConditionalComment') {
                            if (assetGraph.findRelations({from: outgoingRelation.to, type: relationType}).length > 0) {
                                canAppendToPreviousBundle = false;
                            }
                            return;
                        }

                        // Make sure that we don't bundle HtmlStyles with different media attributes together etc.:
                        var discriminator = getDiscriminatorForRelation(outgoingRelation);
                        if (bundleDiscriminator && (discriminator === 'nobundle' || bundleDiscriminator === 'nobundle' || discriminator !== bundleDiscriminator)) {
                            canAppendToPreviousBundle = false;
                        }
                        bundleDiscriminator = discriminator;

                        var existingBundle = assetIndex[outgoingRelation.to.id];
                        if (existingBundle === null) {
                            // Not bundled yet, append to previousBundle if possible, else create a new one
                            if (canAppendToPreviousBundle) {
                                previousBundle.push(outgoingRelation.to);
                                previousBundleIndex = previousBundle.length - 1;
                            } else {
                                if (previousBundle && previousBundleIndex !== previousBundle.length - 1) {
                                    splitBundle(previousBundle, previousBundleIndex + 1);
                                }
                                previousBundle = [outgoingRelation.to];
                                previousBundleIndex = 0;
                                bundles.push(previousBundle);
                                canAppendToPreviousBundle = true;
                            }
                            assetIndex[outgoingRelation.to.id] = previousBundle;
                        } else if (existingBundle) {
                            // Already in another bundle
                            canAppendToPreviousBundle = false;
                            var indexInExistingBundle = existingBundle.indexOf(outgoingRelation.to);
                            if (previousBundle && existingBundle === previousBundle) {
                                if (indexInExistingBundle === previousBundleIndex + 1) {
                                    previousBundleIndex = indexInExistingBundle;
                                } else {
                                    splitBundle(previousBundle, indexInExistingBundle + 1);
                                    existingBundle = assetIndex[outgoingRelation.to.id];
                                    indexInExistingBundle = existingBundle.indexOf(outgoingRelation.to);
                                    if (indexInExistingBundle !== 0) {
                                        existingBundle = splitBundle(existingBundle, indexInExistingBundle);
                                    }
                                    previousBundle = existingBundle;
                                    previousBundleIndex = 0;
                                }
                            } else {
                                if (previousBundle && previousBundleIndex !== (previousBundle.length - 1)) {
                                    splitBundle(previousBundle, previousBundleIndex + 1);
                                }
                                if (indexInExistingBundle !== 0) {
                                    existingBundle = splitBundle(existingBundle, indexInExistingBundle);
                                }
                                previousBundle = existingBundle;
                                previousBundleIndex = 0;
                            }
                        } else {
                            // The relation doesn't point at an asset matched by queryObj
                            previousBundle = null;
                            canAppendToPreviousBundle = false;
                        }
                    });
                    // No more outgoing relations for this asset, make sure that the asset that was bundled
                    // last is at the last position in its bundle:
                    if (previousBundle && previousBundleIndex !== previousBundle.length - 1) {
                        splitBundle(previousBundle, previousBundleIndex + 1);
                    }
                });
            });

            return bundles.map(makeBundle);
        };

        var bundleAssets = bundleStrategyByName[bundleStrategyName]();
        assetGraph.recomputeBaseAssets();
        bundleAssets.forEach(function (bundleAsset) {
            assetGraph.findRelations({to: bundleAsset}).forEach(function (incomingRelation) {
                incomingRelation.refreshHref();
            });
            assetGraph.findRelations({from: bundleAsset}).forEach(function (outgoingRelation) {
                outgoingRelation.refreshHref();
            });
        });
    };
};
<|endoftext|>


<commit_before>/*!
 *
 *  Web Starter Kit
 *  Copyright 2015 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */
/* eslint-env browser */

(function() {
  'use strict';

  // Check to make sure service workers are supported in the current browser,
  // and that the current page is accessed from a secure origin. Using a
  // service worker from an insecure origin will trigger JS console errors. See
  // http://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features
  var isLocalhost = Boolean(window.location.hostname === 'localhost' ||
      // [::1] is the IPv6 localhost address.
      window.location.hostname === '[::1]' ||
      // 127.0.0.1/8 is considered localhost for IPv4.
      window.location.hostname.match(
        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
      )
    );

  if ('serviceWorker' in navigator &&
      (window.location.protocol === 'https:' || isLocalhost)) {
    navigator.serviceWorker.register('service-worker.js')
    .then(function(registration) {
      // Check to see if there's an updated version of service-worker.js with
      // new files to cache:
      // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-registration-update-method
      if (typeof registration.update === 'function') {
        registration.update();
      }

      // updatefound is fired if service-worker.js changes.
      registration.onupdatefound = function() {
        // updatefound is also fired the very first time the SW is installed,
        // and there's no need to prompt for a reload at that point.
        // So check here to see if the page is already controlled,
        // i.e. whether there's an existing service worker.
        if (navigator.serviceWorker.controller) {
          // The updatefound event implies that registration.installing is set:
          // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
          var installingWorker = registration.installing;

          installingWorker.onstatechange = function() {
            switch (installingWorker.state) {
              case 'installed':
                // At this point, the old content will have been purged and the
                // fresh content will have been added to the cache.
                // It's the perfect time to display a "New content is
                // available; please refresh." message in the page's interface.
                break;

              case 'redundant':
                throw new Error('The installing ' +
                                'service worker became redundant.');

              default:
                // Ignore
            }
          };
        }
      };
    }).catch(function(e) {
      console.error('Error during service worker registration:', e);
    });
  }

  createThreeJsBg();

    //Show hamburger menu events

    $('#nav-icon3,.menu-item').click(function(){
        $(".nav--overlay").fadeToggle();
        $('#nav-icon3').toggleClass('open');
    });

    //read scroll
    $(window).scroll(function() {
    var scroll = $(window).scrollTop();
        console.log(scroll);
    if (scroll >= 530) {
       $("#nav-icon3 span").css("background-color","black");
        $("#nav-icon3.open span").css("background-color","white");
    } else {
        $("#nav-icon3 span").css("background-color","white");
        $("#nav-icon3.open span").css("background-color","white");
    }
});

  // Ajax form submit
  // validate input
  function validateEmail( email ) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test( email );
  }
  var form = $("form");
  // submit form
  form.submit( function(evt) {
    evt.preventDefault();
    var input = $(".email-input").val();

    // Test if email is validated
    if ( validateEmail( input ) ) {
      $.ajax({
        url: form.attr("action"),
        method: form.attr("method"),
        data: form.serialize(),
        dataType: 'json',
        contentType: "application/json; charset=utf-8"
      })
      .done(function(data) {
        if ( data.result == "success" ) {
          form.hide();
          $("#form-hide").hide();
          $("#form-response").text("");
          $("#form-response").append("
Thank you!

Check your inbox to confirm your subscription.
");
        } else {
          $("#form-response").text("Something went wrong, give it another shot!");
        }
      });
    } else {
      $("#form-response").text("Invalid email, give it another shot!");
    }
  })

})();

function createThreeJsBg(){
  /*scene*/
  var scene = new THREE.Scene();
  scene.fog = new THREE.FogExp2( "red", 0.0003);
  /*camera*/
  var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  /*renderer*/
  var renderer = new THREE.WebGLRenderer({antialias:true}); //create canvas
  renderer.setSize(window.innerWidth, window.innerHeight); //set canvas size;
  renderer.setClearColor(new THREE.Color(0x292a5d, 1.0));// set rendering background color
  document.getElementById("bg--threejs").appendChild(renderer.domElement); // pass in _canvas
  window.addEventListener("resize", function(){
    renderer.setSize(window.innerWidth, window.innerHeight);
  })
  var cloud;
  var cloud2;
  var cloud3;
  var cloud4;
  function createPointCloud(arg){
      var texture = new THREE.TextureLoader().load(arg.img);
      var geom = new THREE.Geometry();
      var material = new THREE.PointsMaterial({
        size: 11,
        transparent: true,
        opacity: 1,
        map: texture,
        sizeAttenuation: false,
        color: 0xffffff,
        blending: THREE.AdditiveBlending,
      })
      var num= arg.num;
      var range = 500;
      for (var i = 0; i < num; i++) {
        var particle = new THREE.Vector3(
          Math.random()*range-range/2,
          Math.random()*range-range/2,
          Math.random()*range-range/2
          )
        geom.vertices.push(particle);
      };
      return {
        geom:geom,
        material :material
      }
  }
  var a = createPointCloud({img:'images/threejs/6-06.png',num:11,size:100,})
  cloud = new THREE.Points(a.geom, a.material);
  scene.add(cloud);
  var b = createPointCloud({img:"images/threejs/7-07.png",num:22,size:100,})
  cloud2 = new THREE.Points(b.geom, b.material);
  scene.add(cloud2);
  var c = createPointCloud({img:"images/threejs/8-08.png",num:30,size:100,})
  cloud3 = new THREE.Points(c.geom, c.material);
  scene.add(cloud3);
  function createPointCloud4(img){
      var texture = new THREE.TextureLoader().load(img);
      var geom = new THREE.Geometry();
      var material = new THREE.PointsMaterial({
        size: 7,
        transparent:true,
        opacity:0.2,
        map: texture,
        sizeAttenuation:true,
        color:0xffffff,
      })
      var num= 1;
      var range = 1;
      for (var i = 0; i < num; i++) {
        var particle = new THREE.Vector3(
          Math.random()*range-range/2,
         0.4,
          Math.random()*range-range/2-10
          )
        geom.vertices.push(particle);
      };
      geom.applyMatrix(new THREE.Matrix4().makeTranslation(-1,-1,7));
      cloud4 = new THREE.Points(geom, material);
      cloud4.name ="pointCloud";
      scene.add(cloud4);
  }
  createPointCloud4("images/imm2016logotype_lgbg.svg")
  var light = new THREE.PointLight(0xffffff);
  light.lookAt(scene.position);
  light.position.set(40,170,11);
  light.castShadow = true;
  scene.add(light);
  var light = new THREE.AmbientLight( 0x404040 ); // soft white light
  scene.add( light );
  function render() {
        cloud.rotation.x += 0.0001;
        cloud.rotation.z += 0.001;
        cloud2.rotation.x += 0.0008;
        cloud2.rotation.z += 0.002;
        cloud3.rotation.y += 0.0008;
        cloud3.rotation.z += 0.002;
        cloud4.rotation.z += 0.002;
        requestAnimationFrame( render );
        renderer.render( scene, camera );
  }
  render();

}
<commit_msg>Remove the console logs<commit_after>/*!
 *
 *  Web Starter Kit
 *  Copyright 2015 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */
/* eslint-env browser */

(function() {
  'use strict';

  // Check to make sure service workers are supported in the current browser,
  // and that the current page is accessed from a secure origin. Using a
  // service worker from an insecure origin will trigger JS console errors. See
  // http://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features
  var isLocalhost = Boolean(window.location.hostname === 'localhost' ||
      // [::1] is the IPv6 localhost address.
      window.location.hostname === '[::1]' ||
      // 127.0.0.1/8 is considered localhost for IPv4.
      window.location.hostname.match(
        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
      )
    );

  if ('serviceWorker' in navigator &&
      (window.location.protocol === 'https:' || isLocalhost)) {
    navigator.serviceWorker.register('service-worker.js')
    .then(function(registration) {
      // Check to see if there's an updated version of service-worker.js with
      // new files to cache:
      // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-registration-update-method
      if (typeof registration.update === 'function') {
        registration.update();
      }

      // updatefound is fired if service-worker.js changes.
      registration.onupdatefound = function() {
        // updatefound is also fired the very first time the SW is installed,
        // and there's no need to prompt for a reload at that point.
        // So check here to see if the page is already controlled,
        // i.e. whether there's an existing service worker.
        if (navigator.serviceWorker.controller) {
          // The updatefound event implies that registration.installing is set:
          // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
          var installingWorker = registration.installing;

          installingWorker.onstatechange = function() {
            switch (installingWorker.state) {
              case 'installed':
                // At this point, the old content will have been purged and the
                // fresh content will have been added to the cache.
                // It's the perfect time to display a "New content is
                // available; please refresh." message in the page's interface.
                break;

              case 'redundant':
                throw new Error('The installing ' +
                                'service worker became redundant.');

              default:
                // Ignore
            }
          };
        }
      };
    }).catch(function(e) {
      console.error('Error during service worker registration:', e);
    });
  }

  createThreeJsBg();

    //Show hamburger menu events

    $('#nav-icon3,.menu-item').click(function(){
        $(".nav--overlay").fadeToggle();
        $('#nav-icon3').toggleClass('open');
    });

    //read scroll
    $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll >= 530) {
       $("#nav-icon3 span").css("background-color","black");
        $("#nav-icon3.open span").css("background-color","white");
    } else {
        $("#nav-icon3 span").css("background-color","white");
        $("#nav-icon3.open span").css("background-color","white");
    }
});

  // Ajax form submit
  // validate input
  function validateEmail( email ) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test( email );
  }
  var form = $("form");
  // submit form
  form.submit( function(evt) {
    evt.preventDefault();
    var input = $(".email-input").val();

    // Test if email is validated
    if ( validateEmail( input ) ) {
      $.ajax({
        url: form.attr("action"),
        method: form.attr("method"),
        data: form.serialize(),
        dataType: 'json',
        contentType: "application/json; charset=utf-8"
      })
      .done(function(data) {
        if ( data.result == "success" ) {
          form.hide();
          $("#form-hide").hide();
          $("#form-response").text("");
          $("#form-response").append("
Thank you!

Check your inbox to confirm your subscription.
");
        } else {
          $("#form-response").text("Something went wrong, give it another shot!");
        }
      });
    } else {
      $("#form-response").text("Invalid email, give it another shot!");
    }
  })

})();

function createThreeJsBg(){
  /*scene*/
  var scene = new THREE.Scene();
  scene.fog = new THREE.FogExp2( "red", 0.0003);
  /*camera*/
  var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  /*renderer*/
  var renderer = new THREE.WebGLRenderer({antialias:true}); //create canvas
  renderer.setSize(window.innerWidth, window.innerHeight); //set canvas size;
  renderer.setClearColor(new THREE.Color(0x292a5d, 1.0));// set rendering background color
  document.getElementById("bg--threejs").appendChild(renderer.domElement); // pass in _canvas
  window.addEventListener("resize", function(){
    renderer.setSize(window.innerWidth, window.innerHeight);
  })
  var cloud;
  var cloud2;
  var cloud3;
  var cloud4;
  function createPointCloud(arg){
      var texture = new THREE.TextureLoader().load(arg.img);
      var geom = new THREE.Geometry();
      var material = new THREE.PointsMaterial({
        size: 11,
        transparent: true,
        opacity: 1,
        map: texture,
        sizeAttenuation: false,
        color: 0xffffff,
        blending: THREE.AdditiveBlending,
      })
      var num= arg.num;
      var range = 500;
      for (var i = 0; i < num; i++) {
        var particle = new THREE.Vector3(
          Math.random()*range-range/2,
          Math.random()*range-range/2,
          Math.random()*range-range/2
          )
        geom.vertices.push(particle);
      };
      return {
        geom:geom,
        material :material
      }
  }
  var a = createPointCloud({img:'images/threejs/6-06.png',num:11,size:100,})
  cloud = new THREE.Points(a.geom, a.material);
  scene.add(cloud);
  var b = createPointCloud({img:"images/threejs/7-07.png",num:22,size:100,})
  cloud2 = new THREE.Points(b.geom, b.material);
  scene.add(cloud2);
  var c = createPointCloud({img:"images/threejs/8-08.png",num:30,size:100,})
  cloud3 = new THREE.Points(c.geom, c.material);
  scene.add(cloud3);
  function createPointCloud4(img){
      var texture = new THREE.TextureLoader().load(img);
      var geom = new THREE.Geometry();
      var material = new THREE.PointsMaterial({
        size: 7,
        transparent:true,
        opacity:0.2,
        map: texture,
        sizeAttenuation:true,
        color:0xffffff,
      })
      var num= 1;
      var range = 1;
      for (var i = 0; i < num; i++) {
        var particle = new THREE.Vector3(
          Math.random()*range-range/2,
         0.4,
          Math.random()*range-range/2-10
          )
        geom.vertices.push(particle);
      };
      geom.applyMatrix(new THREE.Matrix4().makeTranslation(-1,-1,7));
      cloud4 = new THREE.Points(geom, material);
      cloud4.name ="pointCloud";
      scene.add(cloud4);
  }
  createPointCloud4("images/imm2016logotype_lgbg.svg")
  var light = new THREE.PointLight(0xffffff);
  light.lookAt(scene.position);
  light.position.set(40,170,11);
  light.castShadow = true;
  scene.add(light);
  var light = new THREE.AmbientLight( 0x404040 ); // soft white light
  scene.add( light );
  function render() {
        cloud.rotation.x += 0.0001;
        cloud.rotation.z += 0.001;
        cloud2.rotation.x += 0.0008;
        cloud2.rotation.z += 0.002;
        cloud3.rotation.y += 0.0008;
        cloud3.rotation.z += 0.002;
        cloud4.rotation.z += 0.002;
        requestAnimationFrame( render );
        renderer.render( scene, camera );
  }
  render();

}
<|endoftext|>