<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { ApolloProvider } from 'react-apollo';
import { Provider } from 'react-redux';
import { ConnectedRouter, routerMiddleware } from 'connected-react-router';
import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { createHttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { setContext } from 'apollo-link-context';
import { getMainDefinition } from 'apollo-utilities';
import { InMemoryCache } from 'apollo-cache-inmemory';
import cookie from 'cookies-js';
import lodashMerge from 'lodash.mergewith';
import { createBrowserHistory } from 'history';
// eslint-disable-next-line
import fervorClientResolvers from 'fervorClientResolvers';
// eslint-disable-next-line
import fervorConfigRendering from 'fervorConfigRendering';

import initStore from '../../shared/store';

const browserHistory = createBrowserHistory();
const store = initStore(
  {},
  [routerMiddleware(browserHistory)],
  browserHistory,
);

const cache = (new InMemoryCache({})).restore(window.APOLLO_STATE.apollo);

const httpLink = createHttpLink({ uri: '/graphql' });
const location = window.location;
const wsLink = new WebSocketLink({
  uri: `ws${location.protocol === 'https:' ? 's' : ''}://${location.hostname}${
    location.port !== 80 && location.port !== 443 ? `:${location.port}` : ''
  }/graphql`,
  options: {
    reconnect: true,
  },
});
const protocolSelectorLink = ({ query }) => {
  const definition = getMainDefinition(query);
  return (
    definition.kind === 'OperationDefinition' &&
    definition.operation === 'subscription'
  );
};
const middlewareLink = setContext(() => {
  const authJWT = cookie.get('authJWT');
  if (!authJWT) { return undefined; }
  return {
    headers: {
      Authorization: `Bearer ${authJWT}`,
    },
  };
});

const { defaults, typeDefs, ...otherApolloSettings } = lodashMerge({}, ...fervorClientResolvers, (objValue, srcValue) => {
  if (objValue instanceof Array || typeof objValue === 'string') {
    return objValue.concat(srcValue);
  }
  return undefined;
});
const link = ApolloLink.from([protocolSelectorLink, middlewareLink, httpLink, wsLink]);
const webClient = new ApolloClient({
  cache,
  link,
  ...otherApolloSettings,
  typeDefs,
});
cache.writeData({ data: defaults || {} });

const appOptions = (
  fervorConfigRendering.client &&
  typeof fervorConfigRendering.client.getAppOptions === 'function'
) ? fervorConfigRendering.client.getAppOptions() : {};

class App extends React.PureComponent {
  static propTypes = {
    Routes: PropTypes.oneOfType([
      PropTypes.func,
      PropTypes.object,
    ]).isRequired,
    componentCache: PropTypes.object.isRequired,
  };
  render() {
    const { App: AppWrapper } = fervorConfigRendering.client;
    const RoutesComponent = this.props.Routes;

    if (AppWrapper) {
      return (
        <AppWrapper appOptions={appOptions}>
          <ApolloProvider client={webClient}>
            <Provider store={store}>
              <ConnectedRouter history={browserHistory}>
                <RoutesComponent componentCache={this.props.componentCache} />
              </ConnectedRouter>
            </Provider>
          </ApolloProvider>
        </AppWrapper>
      );
    }

    return (
      <React.Fragment>
        <ApolloProvider client={webClient}>
          <Provider store={store}>
            <ConnectedRouter history={browserHistory}>
              <RoutesComponent componentCache={this.props.componentCache} />
            </ConnectedRouter>
          </Provider>
        </ApolloProvider>
      </React.Fragment>
    );
  }
}

export default App;
<commit_msg>Apollo link splitting should group http and ws together<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { ApolloProvider } from 'react-apollo';
import { Provider } from 'react-redux';
import { ConnectedRouter, routerMiddleware } from 'connected-react-router';
import { ApolloClient } from 'apollo-client';
import { ApolloLink, split } from 'apollo-link';
import { createHttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { setContext } from 'apollo-link-context';
import { getMainDefinition } from 'apollo-utilities';
import { InMemoryCache } from 'apollo-cache-inmemory';
import cookie from 'cookies-js';
import lodashMerge from 'lodash.mergewith';
import { createBrowserHistory } from 'history';
// eslint-disable-next-line
import fervorClientResolvers from 'fervorClientResolvers';
// eslint-disable-next-line
import fervorConfigRendering from 'fervorConfigRendering';

import initStore from '../../shared/store';

const browserHistory = createBrowserHistory();
const store = initStore(
  {},
  [routerMiddleware(browserHistory)],
  browserHistory,
);

const cache = (new InMemoryCache({})).restore(window.APOLLO_STATE.apollo);

const httpLink = createHttpLink({ uri: '/graphql' });
const location = window.location;
const wsLink = new WebSocketLink({
  uri: `ws${location.protocol === 'https:' ? 's' : ''}://${location.hostname}${
    location.port !== 80 && location.port !== 443 ? `:${location.port}` : ''
  }/graphql`,
  options: {
    reconnect: true,
  },
});
const protocolSelector = ({ query }) => {
  const definition = getMainDefinition(query);
  return (
    definition.kind === 'OperationDefinition' &&
    definition.operation === 'subscription'
  );
};
const connectionLink = split(protocolSelector, wsLink, httpLink);
const middlewareLink = setContext(() => {
  const authJWT = cookie.get('authJWT');
  if (!authJWT) { return undefined; }
  return {
    headers: {
      Authorization: `Bearer ${authJWT}`,
    },
  };
});

const { defaults, typeDefs, ...otherApolloSettings } = lodashMerge({}, ...fervorClientResolvers, (objValue, srcValue) => {
  if (objValue instanceof Array || typeof objValue === 'string') {
    return objValue.concat(srcValue);
  }
  return undefined;
});
const link = ApolloLink.from([middlewareLink, connectionLink]);
const webClient = new ApolloClient({
  cache,
  link,
  ...otherApolloSettings,
  typeDefs,
});
cache.writeData({ data: defaults || {} });

const appOptions = (
  fervorConfigRendering.client &&
  typeof fervorConfigRendering.client.getAppOptions === 'function'
) ? fervorConfigRendering.client.getAppOptions() : {};

class App extends React.PureComponent {
  static propTypes = {
    Routes: PropTypes.oneOfType([
      PropTypes.func,
      PropTypes.object,
    ]).isRequired,
    componentCache: PropTypes.object.isRequired,
  };
  render() {
    const { App: AppWrapper } = fervorConfigRendering.client;
    const RoutesComponent = this.props.Routes;

    if (AppWrapper) {
      return (
        <AppWrapper appOptions={appOptions}>
          <ApolloProvider client={webClient}>
            <Provider store={store}>
              <ConnectedRouter history={browserHistory}>
                <RoutesComponent componentCache={this.props.componentCache} />
              </ConnectedRouter>
            </Provider>
          </ApolloProvider>
        </AppWrapper>
      );
    }

    return (
      <React.Fragment>
        <ApolloProvider client={webClient}>
          <Provider store={store}>
            <ConnectedRouter history={browserHistory}>
              <RoutesComponent componentCache={this.props.componentCache} />
            </ConnectedRouter>
          </Provider>
        </ApolloProvider>
      </React.Fragment>
    );
  }
}

export default App;
<|endoftext|>


<commit_before>var $carousels = [];
var loadedCarousels = {};
var css = {
    'containers': '.carousel__js',
    'handles': '.carousel__link--next, .carousel__link--prev'
};

export function init() {
    $carousels = $(css.containers);

    //prevent flicker effect on page load
    $carousels.on('init', function () {
        $(css.containers).css("visibility", "visible");
    });

    $.each($carousels, function (i, carousel) {
        var $carousel = $(carousel);
        loadedCarousels[$carousel.attr("id")] = false;
        $carousel.slick({
            speed: 300,
            slidesToShow: 1,
            infinite: false,
            prevArrow: '<button class="carousel__link--prev">Vorhergehendes Bild</button>',
            nextArrow: '<button class="carousel__link--next">Nächstes Bild</button>',
            slide: ".carousel__item"
        });
        registerListener($carousel);
    });

    $('.video_carousel__js').slick({
        speed: 300,
        infinite: false,
        slide: ".carousel__item",
        lazyLoad: "ondemand",
        slidesToShow: 1,
        slidesToScroll: 1,
        initialSlide: 0,
        dots: false,
        arrows: false,
        mobileFirst: true,
        centerMode: true,
        responsive: [
            {
                breakpoint: 1024, // desktop
                settings: {
                    slidesToShow: 3,
                    slidesToScroll: 3,
                    dots: true,
                    arrows: true,
                    prevArrow: '<button class="carousel__link--prev">Vorhergehendes Bild</button>',
                    nextArrow: '<button class="carousel__link--next">Nächstes Bild</button>',
                    centerMode: false
                }
            }, {
                breakpoint: 720, // tablet
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2,
                    dots: true,
                    arrows: true,
                    prevArrow: '<button class="carousel__link--prev">Vorhergehendes Bild</button>',
                    nextArrow: '<button class="carousel__link--next">Nächstes Bild</button>',
                    centerMode: false
                }
            }
        ]
    });

    $(window).scroll(function () {
        if (isWithinVerticalViewport($carousels) && $carousels.find(".has-waggled").attr("class") == undefined) {
            $(".carousel__link--prev, .carousel__link--next").addClass("waggle");
        } else { // perhaps this isn't even necessary?
            $(".carousel__link--prev, .carousel__link--next").removeClass("waggle");
        }
    });
}

function registerListener($carousel) {
    // load all images after user starts interacting with carousel
    $carousel.on('beforeChange', function (event, slick, currentSlide, nextSlide) {
        if (loadedCarousels[$carousel.attr("id")] === false) {
            loadedCarousels[$carousel.attr("id")] = true;
            loadLazyImages(slick.$slides.find(".image-figure__js"));
        }
    });

    $(css.handles).on("touchstart mouseup", function () {
        $(this).removeClass("untouched");
        // if only the handles are clicked / touched: stop waggeling
        $(".carousel__link--prev, .carousel__link--next").removeClass("waggle").addClass("has-waggled");
    }).on("touchend touchcancel", function () {
        $(this).addClass("untouched");
    });

    $carousel.on('swipe mouseover mouseenter', function (event, slick, direction) {
        // on "interacting" with the carousel
        if ($(this).find(".carousel__link--next").hasClass("waggle")) {
            // no more waggeling // and only do it once
            $(".carousel__link--prev, .carousel__link--next").removeClass("waggle").addClass("has-waggled");
        }
    });
}

function loadLazyImages(images) {
    images.each(function (i, image) {
        var $image = $(image);
        if ($image.data("src")) {
            $image.attr("srcset", $image.data("srcset"));
            $image.attr("src", $image.data("src"));

        }
    });
}

function isWithinVerticalViewport($element) {

    var win = $(window);

    var viewport = {
        top: win.scrollTop()// ,
        // left: win.scrollLeft()
    };
    // viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = $element.offset();
    // bounds.right = bounds.left + this.outerWidth();
    bounds.bottom = bounds.top + $element.outerHeight();

    // return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
    return (!(viewport.bottom < bounds.top || viewport.top > bounds.bottom));
}

<commit_msg>don't drive users crazy waggeling all over the place<commit_after>var $carousels = [];
var loadedCarousels = {};
var css = {
    'containers': '.carousel__js',
    'handles': '.carousel__link--next, .carousel__link--prev'
};

export function init() {
    $carousels = $(css.containers);

    //prevent flicker effect on page load
    $carousels.on('init', function () {
        $(css.containers).css("visibility", "visible");
    });

    $.each($carousels, function (i, carousel) {
        var $carousel = $(carousel);
        loadedCarousels[$carousel.attr("id")] = false;
        $carousel.slick({
            speed: 300,
            slidesToShow: 1,
            infinite: false,
            prevArrow: '<button class="carousel__link--prev">Vorhergehendes Bild</button>',
            nextArrow: '<button class="carousel__link--next">Nächstes Bild</button>',
            slide: ".carousel__item"
        });
        registerListener($carousel);
    });

    $('.video_carousel__js').slick({
        speed: 300,
        infinite: false,
        slide: ".carousel__item",
        lazyLoad: "ondemand",
        slidesToShow: 1,
        slidesToScroll: 1,
        initialSlide: 0,
        dots: false,
        arrows: false,
        mobileFirst: true,
        centerMode: true,
        responsive: [
            {
                breakpoint: 1024, // desktop
                settings: {
                    slidesToShow: 3,
                    slidesToScroll: 3,
                    dots: true,
                    arrows: true,
                    prevArrow: '<button class="carousel__link--prev">Vorhergehendes Bild</button>',
                    nextArrow: '<button class="carousel__link--next">Nächstes Bild</button>',
                    centerMode: false
                }
            }, {
                breakpoint: 720, // tablet
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2,
                    dots: true,
                    arrows: true,
                    prevArrow: '<button class="carousel__link--prev">Vorhergehendes Bild</button>',
                    nextArrow: '<button class="carousel__link--next">Nächstes Bild</button>',
                    centerMode: false
                }
            }
        ]
    });
}

function registerListener($carousel) {
    // load all images after user starts interacting with carousel
    $carousel.on('beforeChange', function (event, slick, currentSlide, nextSlide) {
        if (loadedCarousels[$carousel.attr("id")] === false) {
            loadedCarousels[$carousel.attr("id")] = true;
            loadLazyImages(slick.$slides.find(".image-figure__js"));
        }
    });

    $carousel.on('swipe mouseover mouseenter', function (event, slick, direction) {
        // on "interacting" with the carousel
        if ($(this).find(".carousel__link--next").hasClass("waggle")) {
            // no more animation // and only do it once
            $(this).find(".carousel__link--prev").removeClass("waggle").addClass("has-waggled");
            $(this).find(".carousel__link--next").removeClass("waggle").addClass("has-waggled");
        }
    });

    $carousel.find(css.handles).on("touchstart mouseup", function () {
        $(this).removeClass("untouched");
        // if the handles are clicked / touched: stop the animation
        $(this).removeClass("waggle").addClass("has-waggled");
        $(this).removeClass("waggle").addClass("has-waggled");
    }).on("touchend touchcancel", function () {
        $(this).addClass("untouched");
    });

    $(window).scroll(function () {
        // as soon as the gallery is within the viewport (and handles weren't animated before)
        if (isWithinVerticalViewport($carousel) && $carousel.find(".has-waggled").attr("class") == undefined) {
            // animate them
            $carousel.find(".carousel__link--prev").addClass("waggle");
            $carousel.find(".carousel__link--next").addClass("waggle");
        }
    });
}

function loadLazyImages(images) {
    images.each(function (i, image) {
        var $image = $(image);
        if ($image.data("src")) {
            $image.attr("srcset", $image.data("srcset"));
            $image.attr("src", $image.data("src"));

        }
    });
}

function isWithinVerticalViewport($element) {

    var win = $(window);

    var viewport = {
        top: win.scrollTop()// ,
        // left: win.scrollLeft()
    };
    // viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = $element.offset();
    // bounds.right = bounds.left + this.outerWidth();
    bounds.bottom = bounds.top + $element.outerHeight();

    // return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
    return (!(viewport.bottom < bounds.top || viewport.top > bounds.bottom));
}

<|endoftext|>


<commit_before>module.exports = function (grunt) {
    return function (list, opts) {
        var files = list.sort().map(function (entry) {
            var f = entry.replace(/.*\//, '');
            return [f.replace('.html', '').replace(/-/g, ' '), f];
        }).filter(function (e) { return e[0] !== 'index'; });
        var rows = [];
        for (var i = 0; i < files.length; i += 5) {
            var cols = [];
            for (var j = 0; j < 5; ++j) {
                if (i + j >= files.length) {
                    break;
                }
                var file = files[i + j];
                cols.push('    ' + file[0] + '	');
            }
            rows.push('
\n' + cols.join('\n') + '\n
');
        }
        var body = '
\n' + rows.join('\n') + '\n
';
        return [
            '<title>' + opts.title + '</title>',
            '<link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css">',
            '
',
            '
' + opts.heading + '
',
            '
' + opts.description + '
',
            '
Contributions ' + 'welcome.',
            'Source ',
            'here.
',
            body,
            '
'
        ].join('\n');
    };
};
<commit_msg>display four examples per row to avoid line wrap<commit_after>module.exports = function (grunt) {
    var PER_ROW = 4;
    return function (list, opts) {
        var files = list.sort().map(function (entry) {
            var f = entry.replace(/.*\//, '');
            return [f.replace('.html', '').replace(/-/g, ' '), f];
        }).filter(function (e) { return e[0] !== 'index'; });
        var rows = [];
        for (var i = 0; i < files.length; i += PER_ROW) {
            var cols = [];
            for (var j = 0; j < PER_ROW; ++j) {
                if (i + j >= files.length) {
                    break;
                }
                var file = files[i + j];
                cols.push('    ' + file[0] + '	');
            }
            rows.push('
\n' + cols.join('\n') + '\n
');
        }
        var body = '
\n' + rows.join('\n') + '\n
';
        return [
            '<title>' + opts.title + '</title>',
            '<link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css">',
            '
',
            '
' + opts.heading + '
',
            '
' + opts.description + '
',
            '
Contributions ' + 'welcome.',
            'Source ',
            'here.
',
            body,
            '
'
        ].join('\n');
    };
};
<|endoftext|>


<commit_before>import $ from 'jquery'
import ScaleText from 'scale-text'

const maxColumns = 3
const buildStatusPadding = 11

function numberOfColumns(projects) {
  return Math.min(maxColumns, projects.length)
}

function numberOfRows(projects) {
  return Math.ceil(projects.length / maxColumns)
}

function buildStatusWidth(projects, $view) {
  return $view.innerWidth() / numberOfColumns(projects) - buildStatusPadding
}

function buildStatusHeight(projects) {
  return window.innerHeight / numberOfRows(projects) - buildStatusPadding
}

function resizeEachContainer(projects, $containers, $view) {
  $containers
    .height(buildStatusHeight(projects, $view))
    .width(buildStatusWidth(projects, $view))
}

function getProjectNames(projects) {
  return projects.map((project) => {
    return project.name
  })
}

function everyPieceOfTextOnTheScreen(projects, $container) {
  const allTheTextInContainers = []
  $container.find('.monitor-inner-container').each((_, elem) => {
    allTheTextInContainers.push(elem.textContent)
  })
  return allTheTextInContainers.length > 0 ? allTheTextInContainers : getProjectNames(projects)
}

function scaleFontToContainerSize(projects, $containers, $view) {
  $containers.css('font-size', new ScaleText(
    everyPieceOfTextOnTheScreen(projects, $containers),
    buildStatusHeight(projects, $view),
    buildStatusWidth(projects, $view)).ideal())
}

export function styleProjects(projects, containers, view) {
  const $containers = $(containers)
  const $view = $(view)
  resizeEachContainer(projects, $containers, $view)
  scaleFontToContainerSize(projects, $containers, $view)
}
<commit_msg>fixes clipping issue but padding is still missing #124<commit_after>import $ from 'jquery'
import ScaleText from 'scale-text'

const maxColumns = 3
const buildStatusPadding = 14

function numberOfColumns(projects) {
  return Math.min(maxColumns, projects.length)
}

function numberOfRows(projects) {
  return Math.ceil(projects.length / maxColumns)
}

function buildStatusWidth(projects, $view) {
  return $view.innerWidth() / numberOfColumns(projects) - buildStatusPadding
}

function buildStatusHeight(projects) {
  return window.innerHeight / numberOfRows(projects) - buildStatusPadding
}

function resizeEachContainer(projects, $containers, $view) {
  $containers
    .height(buildStatusHeight(projects, $view))
    .width(buildStatusWidth(projects, $view))
}

function getProjectNames(projects) {
  return projects.map((project) => {
    return project.name
  })
}

function everyPieceOfTextOnTheScreen(projects, $container) {
  const allTheTextInContainers = []
  $container.find('.monitor-inner-container').each((_, elem) => {
    allTheTextInContainers.push(elem.textContent)
  })
  return allTheTextInContainers.length > 0 ? allTheTextInContainers : getProjectNames(projects)
}

function scaleFontToContainerSize(projects, $containers, $view) {
  $containers.css('font-size', new ScaleText(
    everyPieceOfTextOnTheScreen(projects, $containers),
    buildStatusHeight(projects, $view),
    buildStatusWidth(projects, $view)).ideal())
}

export function styleProjects(projects, containers, view) {
  const $containers = $(containers)
  const $view = $(view)
  resizeEachContainer(projects, $containers, $view)
  scaleFontToContainerSize(projects, $containers, $view)
}
<|endoftext|>


<commit_before><script>
//----------------------------------------------------------------------------------------------------
var cwGBM;

var gbmPathwaysModule = (function () {

  var cyDiv;
  var viewAbstractsButton, zoomSelectedButton;
  var searchBox;
  var mouseOverReadout;
  var edgeSelectionOn = false;

  //--------------------------------------------------------------------------------------------
  function initializeUI () {
      cyDiv = $("#cyGbmPathways");
      viewAbstractsButton = $("#cwGBMViewAbstractsButton");
      zoomSelectedButton  = $("#cwGBMZoomSelectedButton");
      searchBox = $("#gbmPathwaysSearchBox");
      mouseOverReadout = $("#gbmPathwaysMouseOverReadoutDiv")
      loadNetwork();
      $(window).resize(handleWindowResize);
      };

  //--------------------------------------------------------------------------------------------
  function loadNetwork () {

       // the pathways graph is included explicitly by widget.html, so the
       // curatedGBMpathways is already defined
    console.log("loadGBMPathwaysNetwork, node count: " + curatedGBMpathways.elements.nodes.length);
    cwGBM = $("#cyGbmPathways");
    cwGBM.cytoscape({
       elements: curatedGBMpathways.elements,
       style: curatedGBMVizmap[0].style,
       showOverlay: false,
       minZoom: 0.01,
       maxZoom: 8.0,
       layout: {
         name: "preset",
         fit: true
         },
     ready: function() {
        console.log("cwGBM ready");
        cwGBM = this;
        cwGBM.on('mouseover', 'node', function(evt){
           var node = evt.cyTarget;
           mouseOverReadout.text(node.data().label);
           })
        cwGBM.on('mouseover', 'edge', function(evt){
           var edge = evt.cyTarget;
           mouseOverReadout.text(edge.data().canonicalName);
           })
        cwGBM.on('select', 'edge', function(evt){
           var edge = evt.cyTarget;
           console.log("selected edge");
           var pmid = edge.data().pmid;
           console.log("pmid: " + pmid);
           openCenteredBrowserWindow("http://www.ncbi.nlm.nih.gov/pubmed/?term=" + pmid, "pubmed abstract", 800, 600)
           });
        $("#cwGBMMovieButton").button()
        zoomSelectedButton.button();
        zoomSelectedButton.click(zoomSelection);
        viewAbstractsButton.button();
        viewAbstractsButton.click(toggleEdgeSelection);
        searchBox.keydown(doSearch);
        //$("#cwGBMMovieButton").click(cwGBMtogglePlayMovie);
        //$("#gbmPathwaysSearchBox").keydown(readGbmPathwaysSearchBox);

        cwGBM.edges().unselectify();
        console.log("cwGBM.reset");
        cwGBM.reset();
        handleWindowResize();
        //requestNanoStringExpressionData();
        } // cy.ready
       })
    .cytoscapePanzoom({ });   // need to learn about options

    } // loadGBMPathwaysNetwork

   //----------------------------------------------------------------------------------------------------
   function handleWindowResize () {
      console.log("gbmPathways window resize: " + $(window).width() + ", " + $(window).height());
      cyDiv.width(0.95 * $(window).width());
      cyDiv.height(0.8 * $(window).height());
      cwGBM.resize();
      cwGBM.fit(50);
      } // handleWindowResize

   //----------------------------------------------------------------------------------------------------
   function zoomSelection() {
      cwGBM.fit(cwGBM.$(':selected'), 50)
      }

   //----------------------------------------------------------------------------------------------------
   function toggleEdgeSelection () {
     if(edgeSelectionOn){
        cwGBM.edges().unselectify();
        edgeSelectionOn = false;
        viewAbstractsButton.button("option", "label", "Enable Abstracts");
        }
      else{
        cwGBM.edges().selectify();
        edgeSelectionOn = true;
        viewAbstractsButton.button("option", "label", "Disable Abstracts");
        }
      } // toggleEdgeSelection

   //----------------------------------------------------------------------------------------------------
   nodeNames = function(){
     nodes = cwGBM.filter("node:visible");
     result = [];
     for(var i=0; i < nodes.length; i++){
       result.push(nodes[i].data().label)
       } // for i
     return(result)
     } // nodeNames

   //----------------------------------------------------------------------------------------------------
   function doSearch(e) {
      var keyCode = e.keyCode || e.which;
      if (keyCode == 13) {
         searchString = searchBox.val();
         console.log("searchString: " + searchString);
         names = nodeNames()
         matches = []
         for(var i=0; i < names.length; i++){
            if(names[i].beginsWith(searchString)) {
               console.log(searchString + " matched " + names[i]);
               s = "cwGBM.filter('node[name=\"" + names[i] + "\"]').select()";
               JAVASCRIPT_EVAL (s);
               } // if searchString matched beginning of node
            } // for i
         } // if 13 (return key)
      } // doSearch

   //----------------------------------------------------------------------------------------------------
   return{
     init: function(){
       onReadyFunctions.push(initializeUI);
       //addJavascriptMessageHandler("pairedDistributionsPlot", pairedDistributionsPlot);
       //socketConnectedFunctions.push(runDemo);
       }
     };

   }); // gbmPathwaysModule
//----------------------------------------------------------------------------------------------------
gbmPathway = gbmPathwaysModule()
gbmPathway.init();

</script>
<commit_msg>"function nodeNames" not "nodeNames = function" to keep private<commit_after><script>
//----------------------------------------------------------------------------------------------------
var cwGBM;

var gbmPathwaysModule = (function () {

  var cyDiv;
  var viewAbstractsButton, zoomSelectedButton;
  var searchBox;
  var mouseOverReadout;
  var edgeSelectionOn = false;

  //--------------------------------------------------------------------------------------------
  function initializeUI () {
      cyDiv = $("#cyGbmPathways");
      viewAbstractsButton = $("#cwGBMViewAbstractsButton");
      zoomSelectedButton  = $("#cwGBMZoomSelectedButton");
      searchBox = $("#gbmPathwaysSearchBox");
      mouseOverReadout = $("#gbmPathwaysMouseOverReadoutDiv")
      loadNetwork();
      $(window).resize(handleWindowResize);
      };

  //--------------------------------------------------------------------------------------------
  function loadNetwork () {

       // the pathways graph is included explicitly by widget.html, so the
       // curatedGBMpathways is already defined
    console.log("loadGBMPathwaysNetwork, node count: " + curatedGBMpathways.elements.nodes.length);
    cwGBM = $("#cyGbmPathways");
    cwGBM.cytoscape({
       elements: curatedGBMpathways.elements,
       style: curatedGBMVizmap[0].style,
       showOverlay: false,
       minZoom: 0.01,
       maxZoom: 8.0,
       layout: {
         name: "preset",
         fit: true
         },
     ready: function() {
        console.log("cwGBM ready");
        cwGBM = this;
        cwGBM.on('mouseover', 'node', function(evt){
           var node = evt.cyTarget;
           mouseOverReadout.text(node.data().label);
           })
        cwGBM.on('mouseover', 'edge', function(evt){
           var edge = evt.cyTarget;
           mouseOverReadout.text(edge.data().canonicalName);
           })
        cwGBM.on('select', 'edge', function(evt){
           var edge = evt.cyTarget;
           console.log("selected edge");
           var pmid = edge.data().pmid;
           console.log("pmid: " + pmid);
           openCenteredBrowserWindow("http://www.ncbi.nlm.nih.gov/pubmed/?term=" + pmid, "pubmed abstract", 800, 600)
           });
        $("#cwGBMMovieButton").button()
        zoomSelectedButton.button();
        zoomSelectedButton.click(zoomSelection);
        viewAbstractsButton.button();
        viewAbstractsButton.click(toggleEdgeSelection);
        searchBox.keydown(doSearch);
        //$("#cwGBMMovieButton").click(cwGBMtogglePlayMovie);
        //$("#gbmPathwaysSearchBox").keydown(readGbmPathwaysSearchBox);

        cwGBM.edges().unselectify();
        console.log("cwGBM.reset");
        cwGBM.reset();
        handleWindowResize();
        //requestNanoStringExpressionData();
        } // cy.ready
       })
    .cytoscapePanzoom({ });   // need to learn about options

    } // loadGBMPathwaysNetwork

   //----------------------------------------------------------------------------------------------------
   function handleWindowResize () {
      console.log("gbmPathways window resize: " + $(window).width() + ", " + $(window).height());
      cyDiv.width(0.95 * $(window).width());
      cyDiv.height(0.8 * $(window).height());
      cwGBM.resize();
      cwGBM.fit(50);
      } // handleWindowResize

   //----------------------------------------------------------------------------------------------------
   function zoomSelection() {
      cwGBM.fit(cwGBM.$(':selected'), 50)
      }

   //----------------------------------------------------------------------------------------------------
   function toggleEdgeSelection () {
     if(edgeSelectionOn){
        cwGBM.edges().unselectify();
        edgeSelectionOn = false;
        viewAbstractsButton.button("option", "label", "Enable Abstracts");
        }
      else{
        cwGBM.edges().selectify();
        edgeSelectionOn = true;
        viewAbstractsButton.button("option", "label", "Disable Abstracts");
        }
      } // toggleEdgeSelection

   //----------------------------------------------------------------------------------------------------
   function nodeNames(){
     nodes = cwGBM.filter("node:visible");
     result = [];
     for(var i=0; i < nodes.length; i++){
       result.push(nodes[i].data().label)
       } // for i
     return(result)
     } // nodeNames

   //----------------------------------------------------------------------------------------------------
   function doSearch(e) {
      var keyCode = e.keyCode || e.which;
      if (keyCode == 13) {
         searchString = searchBox.val();
         console.log("searchString: " + searchString);
         names = nodeNames()
         matches = []
         for(var i=0; i < names.length; i++){
            if(names[i].beginsWith(searchString)) {
               console.log(searchString + " matched " + names[i]);
               s = "cwGBM.filter('node[name=\"" + names[i] + "\"]').select()";
               JAVASCRIPT_EVAL (s);
               } // if searchString matched beginning of node
            } // for i
         } // if 13 (return key)
      } // doSearch

   //----------------------------------------------------------------------------------------------------
   return{
     init: function(){
       onReadyFunctions.push(initializeUI);
       //addJavascriptMessageHandler("pairedDistributionsPlot", pairedDistributionsPlot);
       //socketConnectedFunctions.push(runDemo);
       }
     };

   }); // gbmPathwaysModule
//----------------------------------------------------------------------------------------------------
gbmPathway = gbmPathwaysModule()
gbmPathway.init();

</script>
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Text } from 'react-native';

import styles from '../../styles/styles';
import InPageImage from '../inPageImage';
import AnimalText from '../animalText';
import AnimalTemplate from '../animalTemplate';

const IMAGES = [
  require('../../images/animals/kozorozecSibirsky/01.jpg'),
  require('../../images/animals/kozorozecSibirsky/02.jpg'),
  require('../../images/animals/kozorozecSibirsky/03.jpg'),
];

const THUMBNAILS = [
  require('../../images/animals/kozorozecSibirsky/01-thumb.jpg'),
  require('../../images/animals/kozorozecSibirsky/02-thumb.jpg'),
  require('../../images/animals/kozorozecSibirsky/03-thumb.jpg'),
];

var AnimalDetail = React.createClass({
  render() {
    return (
      <AnimalTemplate firstIndex={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}>
        <AnimalText>
          Kozorožec sibiřský (<Text style={styles.italic}>Capra sibirica</Text>) je jedním z druhů divoce žijících koz. Na první pohled vás nepochybně upoutá svými mohutnými, obloukovitě zahnutými rohy. U samců tyto rohy dorůstají průměrné délky 100–148 cm, zatímco v případě samic jejich délka obvykle nepřesáhne 40 cm. Na rozích si mimo jiné můžete všimnout i vystupujících prstenců, podle nichž lze určit stáří zvířete.
        </AnimalText>
        <AnimalText>
          Domovem tohoto druhu kozorožce je centrální a severní Asie. Hojně se vyskytuje v horských oblastech jižní Sibiře a na území směrem od Afghánistánu a Pákistánu až po Mongolsko. Jeho přirozeným prostředím jsou vysokohorské tundry, louky a polopouště. Jídelníček kozorožce tedy tvoří převážně horské byliny, trávy, pupeny, mechy a lišejníky. Během léta také s oblibou olizují sůl, která jim dodává potřebné minerály.
        </AnimalText>
      <InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
        <AnimalText>
          Samci většinou žijí samotářsky nebo vytvářejí menší skupinky. Samice naopak žijí spolu s mláďaty ve velkých stádech, která čítají až 50 jedinců. V období říje svádí samci boje o samice a stáda obou pohlaví se za účelem rozmnožování obvykle slučují. Samice bývají březí zhruba 160 dnů a rodí obvykle jedno mládě. Rohy se u mláďat objevují až po 3 či 4 týdnech od narození. Plné velikosti kozorožci dorůstají v 9 letech, přičemž dospělý samec může vážit až 130 kg. V průměru se ve volné přírodě dožívají 15 let, v lidské péči až 22 let. Mezi hlavní predátory kozorožců patří především medvědi, vlci a levharti sněžní. Menší jedince mohou ulovit také rysi nebo rosomáci.
        </AnimalText>
      <InPageImage indexes={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
        <AnimalText>
          Jejich chov je v zoologických zahradách poměrně vzácný a v České republice jsou k vidění pouze v Brně a Olomouci. V naší zoo se těmto sudokopytníkům daří více než dobře. Máme zde početnou skupinku kozorožců, kteří se pravidelně rozmnožují a novými přírůstky nás obdařují každý rok.
        </AnimalText>
      </AnimalTemplate>
    );
  }
});

module.exports = AnimalDetail;
<commit_msg>Update kozorozecSibirsky.adult.js<commit_after>import React, { Component } from 'react';
import { Text } from 'react-native';

import styles from '../../styles/styles';
import InPageImage from '../inPageImage';
import AnimalText from '../animalText';
import AnimalTemplate from '../animalTemplate';

const IMAGES = [
  require('../../images/animals/kozorozecSibirsky/01.jpg'),
  require('../../images/animals/kozorozecSibirsky/02.jpg'),
  require('../../images/animals/kozorozecSibirsky/03.jpg'),
];

const THUMBNAILS = [
  require('../../images/animals/kozorozecSibirsky/01-thumb.jpg'),
  require('../../images/animals/kozorozecSibirsky/02-thumb.jpg'),
  require('../../images/animals/kozorozecSibirsky/03-thumb.jpg'),
];

var AnimalDetail = React.createClass({
  render() {
    return (
      <AnimalTemplate firstIndex={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}>
        <AnimalText>
          Kozorožec sibiřský (<Text style={styles.italic}>Capra sibirica</Text>) je jedním z druhů divoce žijících koz. Na první pohled vás nepochybně upoutá svými mohutnými, obloukovitě zahnutými rohy. U samců tyto rohy dorůstají průměrné délky 100–148 cm, zatímco v případě samic jejich délka obvykle nepřesáhne 40 cm. Na rozích si mimo jiné můžete všimnout i vystupujících prstenců, podle nichž lze určit stáří zvířete.
        </AnimalText>
        <AnimalText>
          Domovem tohoto druhu kozorožce je centrální a severní Asie. Hojně se vyskytuje v horských oblastech jižní Sibiře a na území směrem od Afghánistánu a Pákistánu až po Mongolsko. Jeho přirozeným prostředím jsou vysokohorské tundry, louky a polopouště. Jídelníček kozorožce tedy tvoří převážně horské byliny, trávy, pupeny, mechy a lišejníky. Během léta také s oblibou olizuje sůl, která mu dodává potřebné minerály.
        </AnimalText>
      <InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
        <AnimalText>
          Samci většinou žijí samotářsky nebo vytvářejí menší skupinky. Samice naopak žijí spolu s mláďaty ve velkých stádech, která čítají až 50 jedinců. V období říje svádí samci boje o samice a stáda obou pohlaví se za účelem rozmnožování obvykle slučují. Samice bývají březí zhruba 160 dnů a rodí obvykle jedno mládě. Rohy se u mláďat objevují až po 3 či 4 týdnech od narození. Plné velikosti kozorožci dorůstají v 9 letech, přičemž dospělý samec může vážit až 130 kg. V průměru se ve volné přírodě dožívají 15 let, v lidské péči až 22 let. Mezi hlavní predátory kozorožců patří především medvědi, vlci a levharti sněžní. Menší jedince mohou ulovit také rysi nebo rosomáci.
        </AnimalText>
      <InPageImage indexes={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
        <AnimalText>
          Jejich chov je v zoologických zahradách poměrně vzácný a v České republice jsou k vidění pouze v Brně a Olomouci. V naší zoo se těmto sudokopytníkům daří více než dobře. Máme zde početnou skupinku kozorožců, kteří se pravidelně rozmnožují a novými přírůstky nás obdařují každý rok.
        </AnimalText>
      </AnimalTemplate>
    );
  }
});

module.exports = AnimalDetail;
<|endoftext|>


<commit_before>// JavaScript Document

// Scripts written by __gulp_init_author_name__ @ __gulp_init_author_company__

module.exports = {
    scripts(gulp, plugins, ran_tasks, on_error) {
        // task-specific plugins
        const ESLINT  = require("gulp-eslint");
        const WEBPACK = require("webpack-stream");

        // process scripts
        const PROCESS_SCRIPTS = (js_directory, destination_file_name = "modern.js", compare_file_name = "modern.js", source = [global.settings.paths.src + "/assets/scripts/*.js"]) => {
            return new Promise((resolve, reject) => {
                const WEBPACK_CONFIG = {
                    mode: "development",
                };

                // update webpack config for the current target destination and file name
                WEBPACK_CONFIG.mode   = plugins.argv.dist ? "production" : WEBPACK_CONFIG.mode;
                WEBPACK_CONFIG.output = {
                    filename: destination_file_name
                };

                const TASK = gulp.src(source)
                    // prevent breaking on error
                    .pipe(plugins.plumber({errorHandler: on_error}))
                    // check if source is newer than destination
                    .pipe(plugins.newer(js_directory + "/" + compare_file_name))
                    // lint all scripts
                    .pipe(ESLINT())
                    // print lint errors
                    .pipe(ESLINT.format())
                    // run webpack
                    .pipe(WEBPACK(WEBPACK_CONFIG))
                    // generate a hash and add it to the file name
                    .pipe(plugins.hash({template: "<%= name %>.<%= hash %><%= ext %>"}))
                    // output scripts to compiled directory
                    .pipe(gulp.dest(js_directory))
                    // generate a hash manfiest
                    .pipe(plugins.hash.manifest(".hashmanifest-scripts", {
                        deleteOld: true,
                        sourceDir: js_directory
                    }))
                    // output hash manifest in root
                    .pipe(gulp.dest("."))
                    // reject after errors
                    .on("error", () => {
                        reject(TASK);
                    })
                    // return the task after completion
                    .on("end", () => {
                        resolve(TASK);
                    });
            });
        };

        // scripts task, lints, concatenates, & compresses JS
        return new Promise ((resolve) => {
            // set JS directory
            const JS_DIRECTORY = plugins.argv.dist ? global.settings.paths.dist + "/assets/scripts" : global.settings.paths.dev + "/assets/scripts";

            // set the source directory
            const SOURCE_DIRECTORY = global.settings.paths.src + "/assets/scripts";

            // set up an empty merged stream
            const MERGED_STREAMS = plugins.merge();
            // get the script source folder list
            const SCRIPT_FOLDERS = plugins.fs.readdirSync(SOURCE_DIRECTORY);
            // get the script destination file list
            const SCRIPT_FILES   = plugins.fs.existsSync(JS_DIRECTORY) ? plugins.fs.readdirSync(JS_DIRECTORY) : false;

            // process all the script folders
            const PROCESS_SCRIPT_FOLDERS = () => {
                return Promise.resolve().then(() => {
                    // shift to the next folder
                    const FOLDER_NAME = SCRIPT_FOLDERS.shift();

                    // find the existing destination script file name
                    const FILE_NAME   = SCRIPT_FILES ? SCRIPT_FILES.find((name) => {
                        return name.match(new RegExp(FOLDER_NAME + ".[a-z0-9]{8}.js"));
                    }) : FOLDER_NAME + ".js";

                    // process all scripts, update the stream
                    return PROCESS_SCRIPTS(JS_DIRECTORY, FOLDER_NAME + ".js", FILE_NAME, SOURCE_DIRECTORY + "/" + FOLDER_NAME + "/**/*").then((processed) => {
                        MERGED_STREAMS.add(processed);
                    });
                }).then(() => SCRIPT_FOLDERS.length > 0 ? PROCESS_SCRIPT_FOLDERS() : resolve());
            };

            PROCESS_SCRIPT_FOLDERS().then(() => {
                // wrap up
                return MERGED_STREAMS
                    // prevent breaking on error
                    .pipe(plugins.plumber({
                        errorHandler: on_error,
                    }))
                    // notify that task is complete, if not part of default or watch
                    .pipe(plugins.gulpif(gulp.seq.indexOf("scripts") > gulp.seq.indexOf("default"), plugins.notify({
                        title:   "Success!",
                        message: "Scripts task complete!",
                        onLast:  true,
                    })))
                    // push task to ran_tasks array
                    .on("data", () => {
                        if (ran_tasks.indexOf("scripts") < 0) {
                            ran_tasks.push("scripts");
                        }
                    })
                    // resolve the promise on end
                    .on("end", () => {
                        resolve();
                    });
            });

        });
    }
};
<commit_msg>Properly set up multiple entry points for webpack<commit_after>// JavaScript Document

// Scripts written by __gulp_init_author_name__ @ __gulp_init_author_company__

module.exports = {
    scripts(gulp, plugins, ran_tasks, on_error) {
        // task-specific plugins
        const ESLINT  = require("gulp-eslint");
        const GLOB    = require("glob");
        const WEBPACK = require("webpack-stream");

        // scripts task, lints, concatenates, & compresses JS
        return new Promise ((resolve) => {
            // set JS directory
            const JS_DIRECTORY = plugins.argv.dist ? global.settings.paths.dist + "/assets/scripts" : global.settings.paths.dev + "/assets/scripts";

            // set the source directory
            const SOURCE_DIRECTORY = global.settings.paths.src + "/assets/scripts";

            const WEBPACK_CONFIG = {
                name:   "critical",
                mode:   "development",
                entry:   {
                    "critical":       GLOB.sync(SOURCE_DIRECTORY + "/critical/**/*.js"),
                    "legacy":         GLOB.sync(SOURCE_DIRECTORY + "/legacy/**/*.js"),
                    "modern":         GLOB.sync(SOURCE_DIRECTORY + "/modern/**/*.js"),
                    "service-worker": GLOB.sync(SOURCE_DIRECTORY + "/service-worker/**/*.js"),
                },
                output: {
                    path:     plugins.path.resolve(__dirname, JS_DIRECTORY),
                    filename: "[name].js",
                },
            };

            // update webpack config for the current target destination and file name
            WEBPACK_CONFIG.mode = plugins.argv.dist ? "production" : WEBPACK_CONFIG.mode;

            gulp.src(SOURCE_DIRECTORY + "/**/*")
                // prevent breaking on error
                .pipe(plugins.plumber({errorHandler: on_error}))
                // check if source is newer than destination
                .pipe(plugins.gulpif(!plugins.argv.dist, plugins.newer(JS_DIRECTORY)))
                // lint all scripts
                .pipe(ESLINT())
                // print lint errors
                .pipe(ESLINT.format())
                // run webpack
                .pipe(WEBPACK(WEBPACK_CONFIG))
                // generate a hash and add it to the file name
                .pipe(plugins.hash({template: "<%= name %>.<%= hash %><%= ext %>"}))
                // output scripts to compiled directory
                .pipe(gulp.dest(JS_DIRECTORY))
                // generate a hash manfiest
                .pipe(plugins.hash.manifest(".hashmanifest-scripts", {
                    deleteOld: true,
                    sourceDir: JS_DIRECTORY
                }))
                // output hash manifest in root
                .pipe(gulp.dest("."))
                // notify that task is complete, if not part of default or watch
                .pipe(plugins.gulpif(gulp.seq.indexOf("scripts") > gulp.seq.indexOf("default"), plugins.notify({
                    title:   "Success!",
                    message: "Scripts task complete!",
                    onLast:  true,
                })))
                // push task to ran_tasks array
                .on("data", () => {
                    if (ran_tasks.indexOf("scripts") < 0) {
                        ran_tasks.push("scripts");
                    }
                })
                // resolve the promise on end
                .on("end", () => {
                    resolve();
                });

        });
    }
};
<|endoftext|>


<commit_before>/*
 * This is a sample at here.
 * https://facebook.github.io/react-native/docs/animations.html
 */

'user strict';

import React from 'react-native';
var {
  Animated
} = React;

class AnimatedDemo extends React.Component {
  constructor(props: any) {
    super(props);
    this.state = {
      bounceValue: new Animated.Value(0),
    };
  }
  render(): ReactElement {
    return (
      <Animated.Image
        source={{uri: 'http://i.imgur.com/XMKOH81.jpg'}}
        style={{
          flex: 1,
          transform: [
            {scale: this.state.bounceValue},
          ]
        }}
      />
    );
  }
  componentDidMount() {
    this.state.bounceValue.setValue(1.5);
    Animated.spring(
      this.state.bounceValue,
      {
        toValue: 0.8,
        friction: 1,
      }
    ).start();
  }
}

module.exports = AnimatedDemo;
<commit_msg>Transform animated_demo.js to ES5.<commit_after>/*
 * This is a sample at here.
 * https://facebook.github.io/react-native/docs/animations.html
 */

'user strict';

var React = require('react-native');
var {
  Animated
} = React;

var AnimatedDemo = React.createClass({

  getInitialState() {
    return {
      bounceValue: new Animated.Value(0)
    }
  },

  render: function() {
    return (
      <Animated.Image
        source={{uri: 'http://i.imgur.com/XMKOH81.jpg'}}
        style={{
          flex: 1,
          transform: [
            {scale: this.state.bounceValue},
          ]
        }}
      />
    );
  },

  componentDidMount: function() {
    this.state.bounceValue.setValue(1.5);
    Animated.spring(
      this.state.bounceValue,
      {
        toValue: 0.8,
        friction: 1,
      }
    ).start();
  }
});

module.exports = AnimatedDemo;
<|endoftext|>


<commit_before>/* eslint-disable no-new, no-param-reassign */
/* global Vue, CommitsPipelineStore, PipelinesService, Flash */

window.Vue = require('vue');
window.Vue.use(require('vue-resource'));
require('../../lib/utils/common_utils');
require('../../vue_shared/vue_resource_interceptor');
require('../../vue_shared/components/pipelines_table');
require('./pipelines_service');
const PipelineStore = require('./pipelines_store');

/**
 *
 * Uses `pipelines-table-component` to render Pipelines table with an API call.
 * Endpoint is provided in HTML and passed as `endpoint`.
 * We need a store to store the received environemnts.
 * We need a service to communicate with the server.
 *
 * Necessary SVG in the table are provided as props. This should be refactored
 * as soon as we have Webpack and can load them directly into JS files.
 */

(() => {
  window.gl = window.gl || {};
  gl.commits = gl.commits || {};
  gl.commits.pipelines = gl.commits.pipelines || {};

  gl.commits.pipelines.PipelinesTableView = Vue.component('pipelines-table', {

    components: {
      'pipelines-table-component': gl.pipelines.PipelinesTableComponent,
    },

    /**
     * Accesses the DOM to provide the needed data.
     * Returns the necessary props to render `pipelines-table-component` component.
     *
     * @return {Object}
     */
    data() {
      const pipelinesTableData = document.querySelector('#commit-pipeline-table-view').dataset;
      const svgsData = document.querySelector('.pipeline-svgs').dataset;
      const store = new PipelineStore();

      // Transform svgs DOMStringMap to a plain Object.
      const svgsObject = gl.utils.DOMStringMapToObject(svgsData);

      return {
        endpoint: pipelinesTableData.endpoint,
        svgs: svgsObject,
        store,
        state: store.state,
        isLoading: false,
      };
    },

    /**
     * When the component is about to be mounted, tell the service to fetch the data
     *
     * A request to fetch the pipelines will be made.
     * In case of a successfull response we will store the data in the provided
     * store, in case of a failed response we need to warn the user.
     *
     */
    beforeMount() {
      const pipelinesService = new gl.commits.pipelines.PipelinesService(this.endpoint);

      this.isLoading = true;
      return pipelinesService.all()
        .then(response => response.json())
        .then((json) => {
          this.store.storePipelines(json);
          this.isLoading = false;
        })
        .catch(() => {
          this.isLoading = false;
          new Flash('An error occurred while fetching the pipelines, please reload the page again.', 'alert');
        });
    },

    beforeUpdate() {
      if (this.state.pipelines.length && this.$children) {
        PipelineStore.startTimeAgoLoops.call(this, Vue);
      }
    },

    template: `

            No pipelines to show

 0">
          <pipelines-table-component
            :pipelines="state.pipelines"
            :svgs="svgs">
          </pipelines-table-component>

    `,
  });
})();
<commit_msg>Adds frontend needed changes to accomodate for new endpoint schema<commit_after>/* eslint-disable no-new, no-param-reassign */
/* global Vue, CommitsPipelineStore, PipelinesService, Flash */

window.Vue = require('vue');
window.Vue.use(require('vue-resource'));
require('../../lib/utils/common_utils');
require('../../vue_shared/vue_resource_interceptor');
require('../../vue_shared/components/pipelines_table');
require('./pipelines_service');
const PipelineStore = require('./pipelines_store');

/**
 *
 * Uses `pipelines-table-component` to render Pipelines table with an API call.
 * Endpoint is provided in HTML and passed as `endpoint`.
 * We need a store to store the received environemnts.
 * We need a service to communicate with the server.
 *
 * Necessary SVG in the table are provided as props. This should be refactored
 * as soon as we have Webpack and can load them directly into JS files.
 */

(() => {
  window.gl = window.gl || {};
  gl.commits = gl.commits || {};
  gl.commits.pipelines = gl.commits.pipelines || {};

  gl.commits.pipelines.PipelinesTableView = Vue.component('pipelines-table', {

    components: {
      'pipelines-table-component': gl.pipelines.PipelinesTableComponent,
    },

    /**
     * Accesses the DOM to provide the needed data.
     * Returns the necessary props to render `pipelines-table-component` component.
     *
     * @return {Object}
     */
    data() {
      const pipelinesTableData = document.querySelector('#commit-pipeline-table-view').dataset;
      const svgsData = document.querySelector('.pipeline-svgs').dataset;
      const store = new PipelineStore();

      // Transform svgs DOMStringMap to a plain Object.
      const svgsObject = gl.utils.DOMStringMapToObject(svgsData);

      return {
        endpoint: pipelinesTableData.endpoint,
        svgs: svgsObject,
        store,
        state: store.state,
        isLoading: false,
      };
    },

    /**
     * When the component is about to be mounted, tell the service to fetch the data
     *
     * A request to fetch the pipelines will be made.
     * In case of a successfull response we will store the data in the provided
     * store, in case of a failed response we need to warn the user.
     *
     */
    beforeMount() {
      const pipelinesService = new gl.commits.pipelines.PipelinesService(this.endpoint);

      this.isLoading = true;
      return pipelinesService.all()
        .then(response => response.json())
        .then((json) => {
          // depending of the endpoint the response can either bring a `pipelines` key or not.
          const pipelines = json.pipelines || json;
          this.store.storePipelines(pipelines);
          this.isLoading = false;
        })
        .catch(() => {
          this.isLoading = false;
          new Flash('An error occurred while fetching the pipelines, please reload the page again.', 'alert');
        });
    },

    beforeUpdate() {
      if (this.state.pipelines.length && this.$children) {
        PipelineStore.startTimeAgoLoops.call(this, Vue);
      }
    },

    template: `

            No pipelines to show

 0">
          <pipelines-table-component
            :pipelines="state.pipelines"
            :svgs="svgs">
          </pipelines-table-component>

    `,
  });
})();
<|endoftext|>


<commit_before>angular.module('ManageIQ').service('eventNotifications', ['$timeout', '$window', '$httpParamSerializerJQLike', 'API', function($timeout, $window, $httpParamSerializerJQLike, API) {
  if (!ManageIQ.angular.eventNotificationsData) {
    ManageIQ.angular.eventNotificationsData = {
      state: {
        groups: [],
        unreadNotifications: false,
        toastNotifications: [],
        drawerShown: false,
      },
      toastDelay: 8 * 1000,
      observerCallbacks: [],
    };
  }

  // psudo constants
  this.EVENT_NOTIFICATION = 'event';
  this.TASK_NOTIFICATION = 'task';

  this.ERROR = 'danger';
  this.WARNING = 'warning';
  this.INFO = 'info';
  this.SUCCESS = 'success';

  var state = ManageIQ.angular.eventNotificationsData.state;
  var observerCallbacks = ManageIQ.angular.eventNotificationsData.observerCallbacks;
  var _this = this;

  var updateUnreadCount = function(group) {
    if (group) {
      group.unreadCount = group.notifications.filter(function(notification) {
        return notification.unread;
      }).length;
    }
    state.unreadNotifications = state.groups.find(function(nextGroup) {
      return nextGroup.unreadCount > 0;
    }) !== undefined;
  };

  var notifyObservers = function() {
    angular.forEach(observerCallbacks, function(callback) {
      callback();
    });
  };

  var levelToType = function(level) {
    if (level === 'error') {
      return 'danger';
    }
    return level;
  };

  this.doReset = function(seed) {
    state.groups.splice(0, state.groups.length);
    var events = {
      notificationType: this.EVENT_NOTIFICATION,
      heading: __('Events'),
      unreadCount: 0,
      notifications: [],
    };
    state.groups.push(events);
    /*
    state.groups.push(
      {
        notificationType: this.TASK_NOTIFICATION,
        heading: __('Tasks'),
        unreadCount: 0,
        notifications: [],
      }
    );
    */
    state.unreadNotifications = false;
    state.toastNotifications = [];

    if (seed) {
      API.get('/api/notifications?expand=resources&attributes=details&sort_by=id&sort_order=desc&limit=100')
        .then(function(data) {
          data.resources.forEach(function(resource) {
            var msg = miqFormatNotification(resource.details.text, resource.details.bindings);
            events.notifications.push({
              id: resource.id,
              notificationType: _this.EVENT_NOTIFICATION,
              unread: !resource.seen,
              type: resource.details.level,
              message: msg,
              data: {
                link: _.get(resource.details, 'bindings.link'),
              },
              href: resource.href,
              timeStamp: resource.details.created_at,
            });
          });

          updateUnreadCount(events);
          notifyObservers();
        });
    }
  };

  this.registerObserverCallback = function(callback) {
    observerCallbacks.push(callback);
  };

  this.unregisterObserverCallback = function(callback) {
    var index = observerCallbacks.indexOf(callback);
    if (index > -1) {
      observerCallbacks.splice(index, 1);
    }
  };

  this.state = function() {
    return state;
  };

  this.setDrawerShown = function(shown) {
    state.drawerShown = shown;
    notifyObservers();
  };

  this.add = function(notificationType, type, message, notificationData, id) {
    var newNotification = {
      id: id,
      notificationType: notificationType,
      unread: true,
      type: levelToType(type),
      message: message,
      data: notificationData,
      actionTitle: notificationData.link ? __('View details') : undefined,
      actionCallback: notificationData.link ? this.viewDetails : undefined,
      href: id ? $window.location.origin + '/api/notifications/' + id : undefined,
      timeStamp: (new Date()).getTime(),
    };

    var group = state.groups.find(function(notificationGroup) {
      return notificationGroup.notificationType === notificationType;
    });
    if (group) {
      if (group.notifications) {
        group.notifications.splice(_.sortedIndexBy(group.notifications, newNotification, function(x) {
          return -x.timeStamp;
        }), 0, newNotification);
      } else {
        group.notifications = [newNotification];
      }
      updateUnreadCount(group);
    }
    this.showToast(newNotification);
    notifyObservers();
  };

  this.update = function(notificationType, type, message, notificationData, id, showToast) {
    var notification;
    var group = state.groups.find(function(notificationGroup) {
      return notificationGroup.notificationType === notificationType;
    });

    if (group) {
      notification = group.notifications.find(function(notification) {
        return notification.id === id;
      });

      if (notification) {
        if (showToast) {
          notification.unread = true;
        }
        notification.type = levelToType(type);
        notification.message = message;
        notification.data = notificationData;
        notification.timeStamp = (new Date()).getTime();
        updateUnreadCount(group);
      }
    }

    if (showToast) {
      if (!notification) {
        notification = {
          type: type,
          message: message,
        };
      }

      this.showToast(notification);
    }
    notifyObservers();
  };

  this.markRead = function(notification, group) {
    if (notification) {
      notification.unread = false;
      this.removeToast(notification);
      if (notification.href) {
        API.post(notification.href, {action: 'mark_as_seen'});
      }
    }
    if (group) {
      updateUnreadCount(group);
    } else {
      state.groups.forEach(function(group) {
        updateUnreadCount(group);
      });
    }
    notifyObservers();
  };

  this.viewDetails = function(notification) {
    $window.location.href = '/restful_redirect?' + $httpParamSerializerJQLike(notification.data.link);
  };

  this.markUnread = function(notification, group) {
    if (notification) {
      notification.unread = true;
    }
    if (group) {
      updateUnreadCount(group);
    } else {
      state.groups.forEach(function(group) {
        updateUnreadCount(group);
      });
    }
    notifyObservers();
  };

  this.markAllRead = function(group) {
    if (group) {
      var resources = group.notifications.map(function(notification) {
        notification.unread = false;
        _this.removeToast(notification);
        return { href: notification.href };
      }).filter(function(notification) {
        return notification.href;
      });
      if (resources.length > 0) {
        API.post('/api/notifications', {action: 'mark_as_seen', resources: resources});
      }
      group.unreadCount = 0;
      updateUnreadCount();
    }
    notifyObservers();
  };

  this.markAllUnread = function(group) {
    if (group) {
      group.notifications.forEach(function(notification) {
        notification.unread = true;
      });
      group.unreadCount = group.notifications.length;
      updateUnreadCount();
      notifyObservers();
    }
  };

  this.clear = function(notification, group) {
    var index;

    if (notification) {
      this.removeToast(notification);
      if (notification.href) {
        API.delete(notification.href);
      }
    }

    if (!group) {
      group = state.groups.find(function(nextGroup) {
        return notification.notificationType === nextGroup.notificationType;
      });
    }

    if (group) {
      index = group.notifications.indexOf(notification);
      if (index > -1) {
        group.notifications.splice(index, 1);
        updateUnreadCount(group);
        notifyObservers();
      }
    }
  };

  this.clearAll = function(group) {
    if (group) {
      var resources = group.notifications.map(function(notification) {
        _this.removeToast(notification);
        return { href: notification.href };
      }).filter(function(notification) {
        return notification.href;
      });
      if (resources.length > 0) {
        API.post('/api/notifications', {action: 'delete', resources: resources});
      }
      group.notifications = [];
      updateUnreadCount(group);
      notifyObservers();
    }
  };

  this.removeToast = function(notification) {
    var index = state.toastNotifications.indexOf(notification);
    if (index > -1) {
      state.toastNotifications.splice(index, 1);
      notifyObservers();
    }
  };

  this.showToast = function(notification, persist) {
    var $this = this;
    notification.show = true;
    state.toastNotifications.push(notification);
    notifyObservers();

    // any toast notifications with out 'danger' or 'error' status are automatically removed after a delay
    if (persist !== true && notification.type !== 'danger' && notification.type !== 'error') {
      notification.viewing = false;
      $timeout(function() {
        notification.show = false;
        if (!notification.viewing) {
          $this.removeToast(notification);
        }
      }, ManageIQ.angular.eventNotificationsData.toastDelay);
    }
  };

  this.setViewingToast = function(notification, viewing) {
    notification.viewing = viewing;
    if (!viewing && !notification.show) {
      this.removeToast(notification);
    }
  };

  this.dismissToast = function(notification) {
    notification.show = false;
    this.removeToast(notification);
  };

  this.doReset(true);

  listenToRx(function(data) {
    if (data.notification) {
      var msg = miqFormatNotification(data.notification.text, data.notification.bindings);
      _this.add('event', data.notification.level, msg, {link: _.get(data.notification, 'bindings.link')}, data.notification.id);
    }
  });
}]);
<commit_msg>Throttle notification toast messages and display only 3 at most<commit_after>angular.module('ManageIQ').service('eventNotifications', ['$timeout', '$window', '$httpParamSerializerJQLike', 'API', function($timeout, $window, $httpParamSerializerJQLike, API) {
  if (!ManageIQ.angular.eventNotificationsData) {
    ManageIQ.angular.eventNotificationsData = {
      state: {
        groups: [],
        unreadNotifications: false,
        toastNotifications: [],
        drawerShown: false,
      },
      toastDelay: 8 * 1000,
      observerCallbacks: [],
    };
  }

  // psudo constants
  this.EVENT_NOTIFICATION = 'event';
  this.TASK_NOTIFICATION = 'task';

  this.ERROR = 'danger';
  this.WARNING = 'warning';
  this.INFO = 'info';
  this.SUCCESS = 'success';

  var state = ManageIQ.angular.eventNotificationsData.state;
  var observerCallbacks = ManageIQ.angular.eventNotificationsData.observerCallbacks;
  var _this = this;

  var updateUnreadCount = function(group) {
    if (group) {
      group.unreadCount = group.notifications.filter(function(notification) {
        return notification.unread;
      }).length;
    }
    state.unreadNotifications = state.groups.find(function(nextGroup) {
      return nextGroup.unreadCount > 0;
    }) !== undefined;
  };

  var notifyObservers = function() {
    angular.forEach(observerCallbacks, function(callback) {
      callback();
    });
  };

  var levelToType = function(level) {
    if (level === 'error') {
      return 'danger';
    }
    return level;
  };

  this.doReset = function(seed) {
    state.groups.splice(0, state.groups.length);
    var events = {
      notificationType: this.EVENT_NOTIFICATION,
      heading: __('Events'),
      unreadCount: 0,
      notifications: [],
    };
    state.groups.push(events);
    /*
    state.groups.push(
      {
        notificationType: this.TASK_NOTIFICATION,
        heading: __('Tasks'),
        unreadCount: 0,
        notifications: [],
      }
    );
    */
    state.unreadNotifications = false;
    state.toastNotifications = [];

    if (seed) {
      API.get('/api/notifications?expand=resources&attributes=details&sort_by=id&sort_order=desc&limit=100')
        .then(function(data) {
          data.resources.forEach(function(resource) {
            var msg = miqFormatNotification(resource.details.text, resource.details.bindings);
            events.notifications.push({
              id: resource.id,
              notificationType: _this.EVENT_NOTIFICATION,
              unread: !resource.seen,
              type: resource.details.level,
              message: msg,
              data: {
                link: _.get(resource.details, 'bindings.link'),
              },
              href: resource.href,
              timeStamp: resource.details.created_at,
            });
          });

          updateUnreadCount(events);
          notifyObservers();
        });
    }
  };

  this.registerObserverCallback = function(callback) {
    observerCallbacks.push(callback);
  };

  this.unregisterObserverCallback = function(callback) {
    var index = observerCallbacks.indexOf(callback);
    if (index > -1) {
      observerCallbacks.splice(index, 1);
    }
  };

  this.state = function() {
    return state;
  };

  this.setDrawerShown = function(shown) {
    state.drawerShown = shown;
    notifyObservers();
  };

  this.add = function(notificationType, type, message, notificationData, id) {
    var newNotification = {
      id: id,
      notificationType: notificationType,
      unread: true,
      type: levelToType(type),
      message: message,
      data: notificationData,
      actionTitle: notificationData.link ? __('View details') : undefined,
      actionCallback: notificationData.link ? this.viewDetails : undefined,
      href: id ? $window.location.origin + '/api/notifications/' + id : undefined,
      timeStamp: (new Date()).getTime(),
    };

    var group = state.groups.find(function(notificationGroup) {
      return notificationGroup.notificationType === notificationType;
    });
    if (group) {
      if (group.notifications) {
        group.notifications.splice(_.sortedIndexBy(group.notifications, newNotification, function(x) {
          return -x.timeStamp;
        }), 0, newNotification);
      } else {
        group.notifications = [newNotification];
      }
      updateUnreadCount(group);
    }
    this.showToast(newNotification);
    notifyObservers();
  };

  this.update = function(notificationType, type, message, notificationData, id, showToast) {
    var notification;
    var group = state.groups.find(function(notificationGroup) {
      return notificationGroup.notificationType === notificationType;
    });

    if (group) {
      notification = group.notifications.find(function(notification) {
        return notification.id === id;
      });

      if (notification) {
        if (showToast) {
          notification.unread = true;
        }
        notification.type = levelToType(type);
        notification.message = message;
        notification.data = notificationData;
        notification.timeStamp = (new Date()).getTime();
        updateUnreadCount(group);
      }
    }

    if (showToast) {
      if (!notification) {
        notification = {
          type: type,
          message: message,
        };
      }

      this.showToast(notification);
    }
    notifyObservers();
  };

  this.markRead = function(notification, group) {
    if (notification) {
      notification.unread = false;
      this.removeToast(notification);
      if (notification.href) {
        API.post(notification.href, {action: 'mark_as_seen'});
      }
    }
    if (group) {
      updateUnreadCount(group);
    } else {
      state.groups.forEach(function(group) {
        updateUnreadCount(group);
      });
    }
    notifyObservers();
  };

  this.viewDetails = function(notification) {
    $window.location.href = '/restful_redirect?' + $httpParamSerializerJQLike(notification.data.link);
  };

  this.markUnread = function(notification, group) {
    if (notification) {
      notification.unread = true;
    }
    if (group) {
      updateUnreadCount(group);
    } else {
      state.groups.forEach(function(group) {
        updateUnreadCount(group);
      });
    }
    notifyObservers();
  };

  this.markAllRead = function(group) {
    if (group) {
      var resources = group.notifications.map(function(notification) {
        notification.unread = false;
        _this.removeToast(notification);
        return { href: notification.href };
      }).filter(function(notification) {
        return notification.href;
      });
      if (resources.length > 0) {
        API.post('/api/notifications', {action: 'mark_as_seen', resources: resources});
      }
      group.unreadCount = 0;
      updateUnreadCount();
    }
    notifyObservers();
  };

  this.markAllUnread = function(group) {
    if (group) {
      group.notifications.forEach(function(notification) {
        notification.unread = true;
      });
      group.unreadCount = group.notifications.length;
      updateUnreadCount();
      notifyObservers();
    }
  };

  this.clear = function(notification, group) {
    var index;

    if (notification) {
      this.removeToast(notification);
      if (notification.href) {
        API.delete(notification.href);
      }
    }

    if (!group) {
      group = state.groups.find(function(nextGroup) {
        return notification.notificationType === nextGroup.notificationType;
      });
    }

    if (group) {
      index = group.notifications.indexOf(notification);
      if (index > -1) {
        group.notifications.splice(index, 1);
        updateUnreadCount(group);
        notifyObservers();
      }
    }
  };

  this.clearAll = function(group) {
    if (group) {
      var resources = group.notifications.map(function(notification) {
        _this.removeToast(notification);
        return { href: notification.href };
      }).filter(function(notification) {
        return notification.href;
      });
      if (resources.length > 0) {
        API.post('/api/notifications', {action: 'delete', resources: resources});
      }
      group.notifications = [];
      updateUnreadCount(group);
      notifyObservers();
    }
  };

  this.removeToast = function(notification) {
    var index = state.toastNotifications.indexOf(notification);
    if (index > -1) {
      state.toastNotifications.splice(index, 1);
      notifyObservers();
    }
  };

  var simpleShow = function(notification, persist) {
    var $this = this;
    notification.show = true;
    // Remove the very first element of the array if it's too long
    if (state.toastNotifications.length === 3) {
      state.toastNotifications.shift();
    }
    state.toastNotifications.push(notification);
    notifyObservers();

    // any toast notifications with out 'danger' or 'error' status are automatically removed after a delay
    if (persist !== true && notification.type !== 'danger' && notification.type !== 'error') {
      notification.viewing = false;
      $timeout(function() {
        notification.show = false;
        if (!notification.viewing) {
          $this.removeToast(notification);
        }
      }, ManageIQ.angular.eventNotificationsData.toastDelay);
    }
  }.bind(this);

  var throttledShow = _.throttle(simpleShow, 500);

  this.showToast = function(notification, persist) {
    if (state.toastNotifications.length < 3) {
      simpleShow(notification, persist);
    } else {
      throttledShow(notification, persist);
    }
  };

  this.setViewingToast = function(notification, viewing) {
    notification.viewing = viewing;
    if (!viewing && !notification.show) {
      this.removeToast(notification);
    }
  };

  this.dismissToast = function(notification) {
    notification.show = false;
    this.removeToast(notification);
  };

  this.doReset(true);

  listenToRx(function(data) {
    if (data.notification) {
      var msg = miqFormatNotification(data.notification.text, data.notification.bindings);
      _this.add('event', data.notification.level, msg, {link: _.get(data.notification, 'bindings.link')}, data.notification.id);
    }
  });
}]);
<|endoftext|>


<commit_before>const fs = require("fs");
const path = require("path");
const webpack = require("webpack");
const process = require("process");
const express = require("express");
const proxy = require("http-proxy-middleware");
const WebpackIsomorphicToolsPlugin = require("webpack-isomorphic-tools/plugin");
const webpackSharedConfig = require("../config/webpack-shared-config");
const detectEnvironmentVariables = require("../lib/detectEnvironmentVariables");
const getWebpackAdditions = require("../lib/getWebpackAdditions").default;
const buildWebpackEntries = require("../lib/buildWebpackEntries").default;
const {
  additionalLoaders,
  additionalPreLoaders,
  additionalExternals,
  vendor,
  plugins
} = getWebpackAdditions();
import { getLogger } from "../lib/server/logger";
const logger = getLogger();

let assetPath = require(path.join(process.cwd(), "src", "config", "application")).default.assetPath;
if (assetPath.substr(-1) !== "/") {
  assetPath = assetPath + "/";
}

const PORT = 8888;
const OUTPUT_PATH = path.join(process.cwd(), "build");
const OUTPUT_FILE = "app.bundle.js";
const PUBLIC_PATH = assetPath;

const webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require("../config/webpack-isomorphic-tools-config"))
  .development(process.env.NODE_ENV !== "production");

process.env.NODE_PATH = path.join(__dirname, "../..");
const isProduction = process.env.NODE_ENV === "production";

let environmentPlugins = [];

if (isProduction) {
  environmentPlugins = environmentPlugins.concat([
    webpackIsomorphicToolsPlugin,
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    })
  ]);
}
else {
  environmentPlugins = environmentPlugins.concat([
    webpackIsomorphicToolsPlugin,
    new webpack.HotModuleReplacementPlugin(),
  ]);
}

// The config/application.js file is consumed on both the server side and the
// client side. However, we want developers to have access to environment
// constiables in there so they can override defaults with an environment
// constiable. For that reason we are going to perform static analysis on that
// file to determine all of the environment constiables that are used in that
// file and make sure that webpack makes those available in the application.
const configEnvVariables = detectEnvironmentVariables(path.join(process.cwd(), "src", "config", "application.js"));
configEnvVariables.push("NODE_ENV");
const exposedEnvironmentVariables = {};
configEnvVariables.forEach((v) => {
  exposedEnvironmentVariables[v] = JSON.stringify(process.env[v]);
});

const compiler = webpack({
  context: process.cwd(),
  devtool: isProduction ? null : "cheap-module-eval-source-map",
  entry: {
    ...buildWebpackEntries(isProduction),
    vendor: vendor
  },
  module: {
    loaders: [
    ].concat(webpackSharedConfig.loaders, additionalLoaders),
    preLoaders: [
    // only place client specific preLoaders here
    ].concat(webpackSharedConfig.preLoaders, additionalPreLoaders),
  },
  node: {
    fs: "empty"
  },
  output: {
    path: OUTPUT_PATH,
    filename: `[name]-${OUTPUT_FILE}`,
    chunkFilename: `[name]-chunk-${OUTPUT_FILE}`,
    publicPath: PUBLIC_PATH
  },
  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      "process.env": exposedEnvironmentVariables
    }),

    // Make it so *.server.js files return empty function in client
    new webpack.NormalModuleReplacementPlugin(/\.server(\.js)?$/, () => {}),

    new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.bundle.js"),
    new webpack.optimize.CommonsChunkPlugin("commons", "commons.bundle.js"),
    new webpack.optimize.AggressiveMergingPlugin()
  ].concat(environmentPlugins, webpackSharedConfig.plugins, plugins),
  resolve: {
    ...webpackSharedConfig.resolve
  },
  externals: {
    ...additionalExternals
  }
});

module.exports = function (buildOnly) {
  if (!buildOnly && !isProduction) {
    const app = express();
    app.use(require("webpack-dev-middleware")(compiler, {
      noInfo: true,
      publicPath: PUBLIC_PATH
    }));
    app.use(require("webpack-hot-middleware")(compiler));

    // Proxy http requests from server to client in development mode
    app.use(proxy({
      changeOrigin: false,
      target: "http://localhost:8880",
      logLevel: logger.level,
      logProvider: () => {
        return logger;
      },
      onError: (err, req, res) => {
        // When the client is restarting, show our polling message
        res.status(200).sendFile("poll.html", {root: path.join(__dirname, "../lib")});
      }
    }));

    app.listen(PORT, "localhost", function (error) {
      if (error) {
        logger.error(error);
        return;
      }

      logger.info(`Server running on http://localhost:${PORT}`);
    });
  }
  else {
    logger.info("Bundling assets…");
    compiler.run((error, stats) => {
      fs.writeFileSync("webpack-bundle-stats.json", JSON.stringify(stats.toJson()));
      const errors = stats.toJson().errors;
      if (errors.length) {
        errors.forEach((e) => {
          logger.error(e);
        });
        return;
      }

      logger.info("Assets have been prepared for production.");
      logger.info("Assets can be served from the \"/assets\" route but it is recommended that you serve the generated \"build\" folder from a Content Delivery Network");
    });
  }
};

<commit_msg>Fix typo in comments<commit_after>const fs = require("fs");
const path = require("path");
const webpack = require("webpack");
const process = require("process");
const express = require("express");
const proxy = require("http-proxy-middleware");
const WebpackIsomorphicToolsPlugin = require("webpack-isomorphic-tools/plugin");
const webpackSharedConfig = require("../config/webpack-shared-config");
const detectEnvironmentVariables = require("../lib/detectEnvironmentVariables");
const getWebpackAdditions = require("../lib/getWebpackAdditions").default;
const buildWebpackEntries = require("../lib/buildWebpackEntries").default;
const {
  additionalLoaders,
  additionalPreLoaders,
  additionalExternals,
  vendor,
  plugins
} = getWebpackAdditions();
import { getLogger } from "../lib/server/logger";
const logger = getLogger();

let assetPath = require(path.join(process.cwd(), "src", "config", "application")).default.assetPath;
if (assetPath.substr(-1) !== "/") {
  assetPath = assetPath + "/";
}

const PORT = 8888;
const OUTPUT_PATH = path.join(process.cwd(), "build");
const OUTPUT_FILE = "app.bundle.js";
const PUBLIC_PATH = assetPath;

const webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require("../config/webpack-isomorphic-tools-config"))
  .development(process.env.NODE_ENV !== "production");

process.env.NODE_PATH = path.join(__dirname, "../..");
const isProduction = process.env.NODE_ENV === "production";

let environmentPlugins = [];

if (isProduction) {
  environmentPlugins = environmentPlugins.concat([
    webpackIsomorphicToolsPlugin,
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    })
  ]);
}
else {
  environmentPlugins = environmentPlugins.concat([
    webpackIsomorphicToolsPlugin,
    new webpack.HotModuleReplacementPlugin(),
  ]);
}

// The config/application.js file is consumed on both the server side and the
// client side. However, we want developers to have access to environment
// variables in there so they can override defaults with an environment
// variable. For that reason we are going to perform static analysis on that
// file to determine all of the environment variables that are used in that
// file and make sure that webpack makes those available in the application.
const configEnvVariables = detectEnvironmentVariables(path.join(process.cwd(), "src", "config", "application.js"));
configEnvVariables.push("NODE_ENV");
const exposedEnvironmentVariables = {};
configEnvVariables.forEach((v) => {
  exposedEnvironmentVariables[v] = JSON.stringify(process.env[v]);
});

const compiler = webpack({
  context: process.cwd(),
  devtool: isProduction ? null : "cheap-module-eval-source-map",
  entry: {
    ...buildWebpackEntries(isProduction),
    vendor: vendor
  },
  module: {
    loaders: [
    ].concat(webpackSharedConfig.loaders, additionalLoaders),
    preLoaders: [
    // only place client specific preLoaders here
    ].concat(webpackSharedConfig.preLoaders, additionalPreLoaders),
  },
  node: {
    fs: "empty"
  },
  output: {
    path: OUTPUT_PATH,
    filename: `[name]-${OUTPUT_FILE}`,
    chunkFilename: `[name]-chunk-${OUTPUT_FILE}`,
    publicPath: PUBLIC_PATH
  },
  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      "process.env": exposedEnvironmentVariables
    }),

    // Make it so *.server.js files return empty function in client
    new webpack.NormalModuleReplacementPlugin(/\.server(\.js)?$/, () => {}),

    new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.bundle.js"),
    new webpack.optimize.CommonsChunkPlugin("commons", "commons.bundle.js"),
    new webpack.optimize.AggressiveMergingPlugin()
  ].concat(environmentPlugins, webpackSharedConfig.plugins, plugins),
  resolve: {
    ...webpackSharedConfig.resolve
  },
  externals: {
    ...additionalExternals
  }
});

module.exports = function (buildOnly) {
  if (!buildOnly && !isProduction) {
    const app = express();
    app.use(require("webpack-dev-middleware")(compiler, {
      noInfo: true,
      publicPath: PUBLIC_PATH
    }));
    app.use(require("webpack-hot-middleware")(compiler));

    // Proxy http requests from server to client in development mode
    app.use(proxy({
      changeOrigin: false,
      target: "http://localhost:8880",
      logLevel: logger.level,
      logProvider: () => {
        return logger;
      },
      onError: (err, req, res) => {
        // When the client is restarting, show our polling message
        res.status(200).sendFile("poll.html", {root: path.join(__dirname, "../lib")});
      }
    }));

    app.listen(PORT, "localhost", function (error) {
      if (error) {
        logger.error(error);
        return;
      }

      logger.info(`Server running on http://localhost:${PORT}`);
    });
  }
  else {
    logger.info("Bundling assets…");
    compiler.run((error, stats) => {
      fs.writeFileSync("webpack-bundle-stats.json", JSON.stringify(stats.toJson()));
      const errors = stats.toJson().errors;
      if (errors.length) {
        errors.forEach((e) => {
          logger.error(e);
        });
        return;
      }

      logger.info("Assets have been prepared for production.");
      logger.info("Assets can be served from the \"/assets\" route but it is recommended that you serve the generated \"build\" folder from a Content Delivery Network");
    });
  }
};

<|endoftext|>


<commit_before>export default upgrade

import chalk from 'chalk'
import db from '../db'
import createEntryIndex from '../db/designEntryIndex'
import Entry from '../entry'
import _ from 'lodash'
import moment from 'moment'

function upgrade (yargs) {
  let argv = yargs
  .usage('Usage: tick upgrade')
  .help('h')
  .alias('h', 'help')
  .argv

  createEntryIndex(db)
  .then( () => console.log('index ensured'))
  .then(reparse)
}

function reparse () {
  return db.query('entry_index/by_version', {
    startkey: 0,
    endkey: 1,
    include_docs: true
  })
  .then(res => {
    let newDocs = _.chain(res.rows)
      .pluck('doc')
      .map(map0to1)
      .map(map1to2)
      .value()
    return db.bulkDocs(newDocs)
  })
  .then(res => {
    console.log(`updated ${res.length} documents`)
  })
}

function map0to1 (doc) {
  if (doc.version >= 1)
    return doc

  const date = moment(doc.from).toDate()
  const e = new Entry(doc.message, { date })
  let newDoc = {}
  Object.assign(newDoc, doc)

  newDoc.version = e.version

  return newDoc
}

function map1to2 (doc) {
  if (doc.version >= 2)
    return doc

  const date = moment(doc.from).toDate()
  const e = new Entry(doc.message, { date })
  let newDoc = {}
  Object.assign(newDoc, doc)

  newDoc.time = e.time

  return newDoc
}
<commit_msg>map1to2 needs to set version to 2<commit_after>export default upgrade

import chalk from 'chalk'
import db from '../db'
import createEntryIndex from '../db/designEntryIndex'
import Entry from '../entry'
import _ from 'lodash'
import moment from 'moment'

function upgrade (yargs) {
  let argv = yargs
  .usage('Usage: tick upgrade')
  .help('h')
  .alias('h', 'help')
  .argv

  createEntryIndex(db)
  .then( () => console.log('index ensured'))
  .then(reparse)
}

function reparse () {
  return db.query('entry_index/by_version', {
    startkey: 0,
    endkey: 1,
    include_docs: true
  })
  .then(res => {
    let newDocs = _.chain(res.rows)
      .pluck('doc')
      .map(map0to1)
      .map(map1to2)
      .value()
    return db.bulkDocs(newDocs)
  })
  .then(res => {
    console.log(`updated ${res.length} documents`)
  })
}

function map0to1 (doc) {
  if (doc.version >= 1)
    return doc

  const date = moment(doc.from).toDate()
  const e = new Entry(doc.message, { date })
  let newDoc = {}
  Object.assign(newDoc, doc)

  newDoc.version = e.version

  return newDoc
}

function map1to2 (doc) {
  if (doc.version >= 2)
    return doc

  const date = moment(doc.from).toDate()
  const e = new Entry(doc.message, { date })
  let newDoc = {}
  Object.assign(newDoc, doc)

  newDoc.time = e.time
  newDoc.version = 2

  return newDoc
}
<|endoftext|>