<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import cookie from 'react-cookie';
import SwitchButton from 'react-switch-button';
import styled from 'styled-components';
import Slider from 'react-slick';
import Modal from '../template/modal';
import * as actions from '../../actions/article';

const ArticleItem = styled.div`{
  border-radius: 6px;
  padding: 10px;
  &:hover {
    background: rgb(222,222,222);
    transition: background .2s ease;
    & > .imgContainer img {
      opacity: .7;
      transition: opacity .2s linear;
    }
  }
  & > .imgContainer img {
    width: 100%;
    border-radius: 6px;
    opacity: 1;
  }
  & > .articleInfo {
    display: flex;
    padding: 5px;
    justify-content: space-between;
    & > .caption {
      color: #444;
      font-weight: bold;
      padding-right: 10px
    }
    & > .pubDate {
      color: #888;
      font-size: 12px;
    }
  }
}
`;
const SwiperContainer = styled.div`{
    width: 450px;
    padding: 20px;
    background: red;
    text-align: center;
    color: white;
  }
`;
const NextArrow = styled.div`{

    padding: 20px;

  }
`;
class ArticleList extends Component {
  state = {
    isModalOpen: false,
    selectedArticle: {},
    isToggled: false,
  }
  componentWillMount() {
    // Fetch user data prior to component mounting
    this.props.fetchArticles();
  }
  openModal = (article) => {
    this.setState({ isModalOpen: true });
    const articleTemp = Object.assign({}, article);
    this.setState({ selectedArticle: articleTemp });
  }
  closeModal = () => {
    this.setState({ isModalOpen: false });
  }
  helperEncoding = (str) => {
    const Base64 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", encode: function(e) {var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}
    const encodedString = Base64.encode(str);
    return encodedString;
  }
  handleSwitch = () => {
    this.setState({ isToggled: !this.state.isToggled });
  }
  OnVote = () => {
    const { selectedArticle, isToggled } = this.state;
    const user = cookie.load('user');
    const votedArticle = {
      profile: user,
      _id: this.helperEncoding(selectedArticle.title),
      title: selectedArticle.title,
      pubdate: selectedArticle.pubdate,
      mediaImageURL: selectedArticle.mediaImageURL,
      link: selectedArticle.link,
      voted: isToggled
    }
    this.props.voteArticle(votedArticle);
  }

  render() {
    const { articles } = this.props;
    const { isModalOpen, selectedArticle, isToggled } = this.state;
    const sliderSettings = {
      infinite: false,
      speed: 500,
      slidesToShow: 1,
      initialSlide: 1,
      slidesToScroll: 1
    };
    const articleList = articles.map((article, index) => {
      return (

 this.openModal(article)}>
            <ArticleItem >

{article.title}

{article.pubdate}

            </ArticleItem>

      );
    });
    return (

        { articleList }
        <Modal isOpen={isModalOpen} closeModal={this.closeModal} heading="Voting">

 { selectedArticle.title }

 { selectedArticle.pubdate }

 { selectedArticle.summary }

 { selectedArticle.description }

          <SwitchButton
            name="switch-8"
            label="Switch mode"
            mode="select"
            labelRight="Factual"
            labelLeft="Sensationalized"
            onChange={this.handleSwitch}
          />
          <SwiperContainer>
          <Slider {...sliderSettings}>

Slide 1

Slide 2

Slide 3

          </Slider>
          </SwiperContainer>

          <button onClick={this.OnVote}>Vote now </button>
        </Modal>

    );
  }
}

function mapStateToProps(state) {
  return {
    articles: state.article.articles,
    profile: state.user.profile,
  };
}

export default connect(mapStateToProps, actions)(ArticleList);
<commit_msg>Relevant Article List Page Update<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import cookie from 'react-cookie';
import SwitchButton from 'react-switch-button';
import styled from 'styled-components';
import Slider from 'react-slick';
import Modal from '../template/modal';
import * as actions from '../../actions/article';

const ArticleItem = styled.div`{
  border-radius: 6px;
  padding: 10px;
  &:hover {
    background: rgb(222,222,222);
    transition: background .2s ease;
    & > .imgContainer img {
      opacity: .7;
      transition: opacity .2s linear;
    }
  }
  & > .imgContainer img {
    width: 100%;
    border-radius: 6px;
    opacity: 1;
  }
  & > .articleInfo {
    display: flex;
    padding: 5px;
    justify-content: space-between;
    & > .caption {
      color: #444;
      font-weight: bold;
      padding-right: 10px
    }
    & > .pubDate {
      color: #888;
      font-size: 12px;
    }
  }
}
`;
const SwiperContainer = styled.div`{
    width: 410px;
    text-align: center;
    color: white;
  }
`;
const BoardSlider = styled.div`{
    font-family: Lato, "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 24px;
    font-weight: 300;
    letter-spacing: 1px;
    padding:  10px;
    & > div {
      padding: 20px;
      border-radius: 4px;
      cursor: pointer;
    }
    & > .FactualBoard {
      background: #8bc34a;
      -webkit-box-shadow: 0px 0px 10px 0px rgba(124, 179, 66, .7);
      -moz-box-shadow:    0px 0px 10px 0px rgba(124, 179, 66, .7);
      box-shadow:         0px 0px 10px 0px rgba(124, 179, 66, .7);
    }
    & > .SensationalizedBoard {
      background: #ffc107;
      -webkit-box-shadow: 0px 0px 10px 0px rgba(255, 179, 0, .7);
      -moz-box-shadow:    0px 0px 10px 0px rgba(255, 179, 0, .7);
      box-shadow:         0px 0px 10px 0px rgba(255, 179, 0, .7);
    }
    & > .NotVotedBoard {
      background: #03a9f4;
      -webkit-box-shadow: 0px 0px 10px 0px rgba(15, 101, 212, .7);
      -moz-box-shadow:    0px 0px 10px 0px rgba(15, 101, 212, .7);
      box-shadow:         0px 0px 10px 0px rgba(15, 101, 212, .7);
    }
  }
`;

class ArticleList extends Component {
  state = {
    isModalOpen: false,
    selectedArticle: {},
    isToggled: false,
    votingResult: 0,
  }
  componentWillMount() {
    // Fetch user data prior to component mounting
    this.props.fetchArticles();
  }
  openModal = (article) => {
    this.setState({ isModalOpen: true });
    const articleTemp = Object.assign({}, article);
    this.setState({ selectedArticle: articleTemp });
  }
  closeModal = () => {
    this.setState({ isModalOpen: false });
  }
  helperEncoding = (str) => {
    const Base64 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", encode: function(e) {var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}
    const encodedString = Base64.encode(str);
    return encodedString;
  }
  handleSwitch = () => {
    this.setState({ isToggled: !this.state.isToggled });
  }
  OnVote = () => {
    const { selectedArticle, isToggled, votingResult } = this.state;
    const user = cookie.load('user');
    console.log(votingResult);
    const votedArticle = {
      profile: user,
      _id: this.helperEncoding(selectedArticle.title),
      title: selectedArticle.title,
      pubdate: selectedArticle.pubdate,
      mediaImageURL: selectedArticle.mediaImageURL,
      link: selectedArticle.link,
      voted: votingResult
    }
    this.props.voteArticle(votedArticle);
  }
  afterChange = (cur) => {
    this.setState({ votingResult: cur-1 });
  }
  render() {
    const { articles } = this.props;
    const { isModalOpen, selectedArticle, isToggled, votingResult } = this.state;
    const sliderSettings = {
      infinite: false,
      speed: 500,
      slidesToShow: 1,
      initialSlide: 1,
      slidesToScroll: 1,
      afterChange: this.afterChange
    };
    const articleList = articles.map((article, index) => {
      return (

 this.openModal(article)}>
            <ArticleItem >

{article.title}

{article.pubdate}

            </ArticleItem>

      );
    });
    return (

        { articleList }
        <Modal isOpen={isModalOpen} closeModal={this.closeModal} heading="Voting">

 { selectedArticle.title }

 { selectedArticle.pubdate }

 { selectedArticle.summary }

 { selectedArticle.description }

          <SwitchButton
            name="switch-8"
            label="Switch mode"
            mode="select"
            labelRight="Factual"
            labelLeft="Sensationalized"
            onChange={this.handleSwitch}
          />
          <SwiperContainer>
          <Slider {...sliderSettings}>
            <BoardSlider>
Sensationalized
</BoardSlider>
            <BoardSlider>
No idea
</BoardSlider>
            <BoardSlider>
Factual
</BoardSlider>
          </Slider>
          </SwiperContainer>

          <button onClick={this.OnVote}>Vote now </button>
        </Modal>

    );
  }
}

function mapStateToProps(state) {
  return {
    articles: state.article.articles,
    profile: state.user.profile,
  };
}

export default connect(mapStateToProps, actions)(ArticleList);
<|endoftext|>


<commit_before>import { Route } from 'react-router-dom'

// Top Level Containers
import Home from './app/containers/Home'
import Invited from './agents/containers/Invited'
import MyProfilePage from './agents/containers/MyProfile'
import MyGroupsPage from './agents/containers/MyGroups'
import TasksPage from './tasks/containers/TasksPage'
import TaskWorker from './tasks/containers/TaskWorker'
import OrdersPage from './ordering/containers/OrdersPage'
import OrderPage from './ordering/containers/OrderPage'
import OrderSummary from './ordering/containers/OrderSummary'

import {
  Register,
  SignIn,
  LogOut
} from 'dogstack-agents/components'
import {
  UserIsAuthenticated,
  UserIsNotAuthenticated
} from 'dogstack-agents/hoc'
import {
  getIsAuthenticated,
  getIsNotAuthenticated
} from 'dogstack-agents/getters'

export default [
  {
    name: 'home',
    path: '/',
    exact: true,
    Component: Home,
    selector: getIsNotAuthenticated,
    navigation: {
      title: 'app.home',
      icon: 'fa fa-home'
    }
  },
  {
    name: 'order',
    path: '/o/:orderId',
    Component: OrderPage,
    selector: getIsAuthenticated
  },
  {
    name: 'signIn',
    path: '/sign-in',
    Component: UserIsNotAuthenticated(SignIn),
    navigation: {
      title: 'agents.signIn',
      selector: getIsNotAuthenticated,
      icon: 'fa fa-sign-in'
    }
  },
  {
    name: 'logOut',
    navigation: {
      Component: LogOut,
      selector: getIsAuthenticated,
      icon: 'fa fa-sign-out'
    }
  },
  {
    name: 'register',
    path: '/register',
    Component: UserIsNotAuthenticated(Register),
    navigation: {
      title: 'agents.register',
      selector: getIsNotAuthenticated,
      icon: 'fa fa-heart'
    }
  },
  {
    name: 'invited',
    path: '/invited/:jwt/:orderId',
    Component: UserIsNotAuthenticated(Invited)
  },
  {
    name: 'orders',
    path: '/',
    exact: true,
    Component: OrdersPage,
    selector: getIsAuthenticated,
    navigation: {
      title: 'app.orders',
      icon: 'fa fa-shopping-basket'
    }
  },
  {
    name: 'tasks',
    path: '/tasks',
    exact: true,
    Component: UserIsAuthenticated(TasksPage),
    navigation: {
      title: 'tasks.tasks',
      selector: getIsAuthenticated,
      icon: 'fa fa-check-circle'
    }
  },
  {
    name: 'task',
    path: '/tasks/:taskPlanId',
    Component: UserIsAuthenticated(TaskWorker)
  },
  {
    name: 'orderSummary',
    path: '/ordersummary',
    Component: OrderSummary
  },
  {
    name: 'my-profile',
    path: '/my-profile',
    Component: MyProfilePage,
    selector: getIsAuthenticated,
    navigation: {
      title: 'app.myProfile',
      icon: 'fa fa-user'
    }
  },
  {
    name: 'my-groups',
    path: '/my-groups',
    Component: MyGroupsPage,
    selector: getIsAuthenticated,
    navigation: {
      title: 'agents.myGroups',
      icon: 'fa fa-users'
    }
  },
]
<commit_msg>feat(profile): added new route for viewing individual profile<commit_after>import { Route } from 'react-router-dom'

// Top Level Containers
import Home from './app/containers/Home'
import Invited from './agents/containers/Invited'
import MyProfilePage from './agents/containers/MyProfile'
import MyGroupsPage from './agents/containers/MyGroups'
import ProfilePage from './agents/containers/Profile'
import TasksPage from './tasks/containers/TasksPage'
import TaskWorker from './tasks/containers/TaskWorker'
import OrdersPage from './ordering/containers/OrdersPage'
import OrderPage from './ordering/containers/OrderPage'
import OrderSummary from './ordering/containers/OrderSummary'

import {
  Register,
  SignIn,
  LogOut
} from 'dogstack-agents/components'
import {
  UserIsAuthenticated,
  UserIsNotAuthenticated
} from 'dogstack-agents/hoc'
import {
  getIsAuthenticated,
  getIsNotAuthenticated
} from 'dogstack-agents/getters'

export default [
  {
    name: 'home',
    path: '/',
    exact: true,
    Component: Home,
    selector: getIsNotAuthenticated,
    navigation: {
      title: 'app.home',
      icon: 'fa fa-home'
    }
  },
  {
    name: 'order',
    path: '/o/:orderId',
    Component: OrderPage,
    selector: getIsAuthenticated
  },
  {
    name: 'signIn',
    path: '/sign-in',
    Component: UserIsNotAuthenticated(SignIn),
    navigation: {
      title: 'agents.signIn',
      selector: getIsNotAuthenticated,
      icon: 'fa fa-sign-in'
    }
  },
  {
    name: 'logOut',
    navigation: {
      Component: LogOut,
      selector: getIsAuthenticated,
      icon: 'fa fa-sign-out'
    }
  },
  {
    name: 'register',
    path: '/register',
    Component: UserIsNotAuthenticated(Register),
    navigation: {
      title: 'agents.register',
      selector: getIsNotAuthenticated,
      icon: 'fa fa-heart'
    }
  },
  {
    name: 'invited',
    path: '/invited/:jwt/:orderId',
    Component: UserIsNotAuthenticated(Invited)
  },
  {
    name: 'orders',
    path: '/',
    exact: true,
    Component: OrdersPage,
    selector: getIsAuthenticated,
    navigation: {
      title: 'app.orders',
      icon: 'fa fa-shopping-basket'
    }
  },
  {
    name: 'tasks',
    path: '/tasks',
    exact: true,
    Component: UserIsAuthenticated(TasksPage),
    navigation: {
      title: 'tasks.tasks',
      selector: getIsAuthenticated,
      icon: 'fa fa-check-circle'
    }
  },
  {
    name: 'task',
    path: '/tasks/:taskPlanId',
    Component: UserIsAuthenticated(TaskWorker)
  },
  {
    name: 'orderSummary',
    path: '/ordersummary',
    Component: OrderSummary
  },
  {
    name: 'my-profile',
    path: '/my-profile',
    Component: MyProfilePage,
    selector: getIsAuthenticated,
    navigation: {
      title: 'app.myProfile',
      icon: 'fa fa-user'
    }
  },
  {
    name: 'my-groups',
    path: '/my-groups',
    Component: MyGroupsPage,
    selector: getIsAuthenticated,
    navigation: {
      title: 'agents.myGroups',
      icon: 'fa fa-users'
    }
  },
  {
    name: 'profile',
    path: '/profiles/:profileId',
    Component: ProfilePage,
    selector: getIsAuthenticated
  },
]
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import classnames from 'classnames';
import { themr } from 'react-css-themr';
import { APP_BAR } from '../identifiers';
import InjectIconButton from '../button/IconButton';

const factory = (IconButton) => {
  class AppBar extends React.Component {
    static propTypes = {
      children: PropTypes.node,
      className: PropTypes.string,
      fixed: PropTypes.bool,
      flat: PropTypes.bool,
      leftIcon: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.element,
      ]),
      onLeftIconClick: PropTypes.func,
      onRightIconClick: PropTypes.func,
      rightIcon: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.element,
      ]),
      scrollHide: PropTypes.bool,
      theme: PropTypes.shape({
        appBar: PropTypes.string,
        inner: PropTypes.string,
        fixed: PropTypes.string,
        flat: PropTypes.string,
        leftIcon: PropTypes.string,
        rightIcon: PropTypes.string,
        scrollHide: PropTypes.string,
        title: PropTypes.string,
      }),
      title: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.element,
      ]),
    };

    static defaultProps = {
      className: '',
      fixed: false,
      flat: false,
      scrollHide: false,
    };

    state = { hidden: false, height: 0 };

    componentDidMount() {
      if (this.props.scrollHide) {
        this.initializeScroll();
      }
    }

    componentWillReceiveProps(nextProps) {
      if (!this.props.scrollHide && nextProps.scrollHide) {
        this.initializeScroll();
      }

      if (this.props.scrollHide && !nextProps.scrollHide) {
        this.endScroll();
      }
    }

    componentWillUnmount() {
      if (this.props.scrollHide) {
        this.endScroll();
      }
    }

    initializeScroll() {
      window.addEventListener('scroll', this.handleScroll);
      const { height } = this.rootNode.getBoundingClientRect();
      this.curScroll = window.scrollY;
      this.setState({ height });
    }

    endScroll() {
      window.removeEventListener('scroll', this.handleScroll);
    }

    handleScroll() {
      const scrollDiff = this.curScroll - window.scrollY;
      const hidden = scrollDiff < 0
        && window.scrollY !== undefined
        && window.scrollY > this.state.height;
      this.setState({ hidden });
      this.curScroll = window.scrollY;
    }

    renderTitle() {
      const { props } = this;
      const { title, theme } = props;
      if (!title) return undefined;

      return typeof (title) === 'string'
        ?
{title}

        : React.createElement(title, props);
    }

    render() {
      const { props, renderTitle } = this;
      const {
        children,
        leftIcon,
        onLeftIconClick,
        onRightIconClick,
        rightIcon,
        theme,
        title,
      } = props;
      const className = classnames(theme.appBar, {
        [theme.fixed]: this.props.fixed,
        [theme.flat]: this.props.flat,
        [theme.scrollHide]: this.state.hidden,
      }, this.props.className);

      return (
         { this.rootNode = node; }}
        >

            {leftIcon && <IconButton
              inverse
              className={classnames(theme.leftIcon)}
              onClick={onLeftIconClick}
              icon={leftIcon}
            />
            }
            {renderTitle(title)}
            {children}
            {rightIcon && <IconButton
              inverse
              className={classnames(theme.rightIcon)}
              onClick={onRightIconClick}
              icon={rightIcon}
            />
            }

      );
    }
  }

  return AppBar;
};

const AppBar = factory(InjectIconButton);
export default themr(APP_BAR)(AppBar);
export { factory as appBarFactory };
export { AppBar };
<commit_msg>Small fixes<commit_after>import React, { PropTypes } from 'react';
import cn from 'classnames';
import { themr } from 'react-css-themr';
import { APP_BAR } from '../identifiers';
import InjectIconButton from '../button/IconButton';

const factory = (IconButton) => {
  class AppBar extends React.Component {
    static propTypes = {
      children: PropTypes.node,
      className: PropTypes.string,
      fixed: PropTypes.bool,
      flat: PropTypes.bool,
      leftIcon: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.element,
      ]),
      onLeftIconClick: PropTypes.func,
      onRightIconClick: PropTypes.func,
      rightIcon: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.element,
      ]),
      scrollHide: PropTypes.bool,
      theme: PropTypes.shape({
        appBar: PropTypes.string,
        inner: PropTypes.string,
        fixed: PropTypes.string,
        flat: PropTypes.string,
        leftIcon: PropTypes.string,
        rightIcon: PropTypes.string,
        scrollHide: PropTypes.string,
        title: PropTypes.string,
      }),
      title: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.element,
      ]),
    };

    static defaultProps = {
      className: '',
      fixed: false,
      flat: false,
      scrollHide: false,
    };

    state = { hidden: false, height: 0 };

    componentDidMount() {
      if (this.props.scrollHide) {
        this.initializeScroll();
      }
    }

    componentWillReceiveProps(nextProps) {
      if (!this.props.scrollHide && nextProps.scrollHide) {
        this.initializeScroll();
      }

      if (this.props.scrollHide && !nextProps.scrollHide) {
        this.endScroll();
      }
    }

    componentWillUnmount() {
      if (this.props.scrollHide) {
        this.endScroll();
      }
    }

    initializeScroll() {
      window.addEventListener('scroll', this.handleScroll);
      const { height } = this.rootNode.getBoundingClientRect();
      this.curScroll = window.scrollY;
      this.setState({ height });
    }

    endScroll() {
      window.removeEventListener('scroll', this.handleScroll);
    }

    handleScroll = () => {
      const scrollDiff = this.curScroll - window.scrollY;
      const hidden = scrollDiff < 0
        && window.scrollY !== undefined
        && window.scrollY > this.state.height;
      this.setState({ hidden });
      this.curScroll = window.scrollY;
    };

    render() {
      const {
        children,
        leftIcon,
        onLeftIconClick,
        onRightIconClick,
        rightIcon,
        theme,
        title,
      } = this.props;

      const className = cn(theme.appBar, {
        [theme.fixed]: this.props.fixed,
        [theme.flat]: this.props.flat,
        [theme.scrollHide]: this.state.hidden,
      }, this.props.className);

      const renderedTitle = typeof title === 'string'
        ?
{title}

        : title;

      const renderedLeftIcon = leftIcon && (
        <IconButton
          inverse
          className={cn(theme.leftIcon)}
          onClick={onLeftIconClick}
          icon={leftIcon}
        />
      );

      const renderedRightIcon = rightIcon && (
        <IconButton
          inverse
          className={cn(theme.rightIcon)}
          onClick={onRightIconClick}
          icon={rightIcon}
        />
      );

      return (
         { this.rootNode = node; }}
        >

            {renderedLeftIcon}
            {renderedTitle}
            {children}
            {renderedRightIcon}

      );
    }
  }

  return AppBar;
};

const AppBar = factory(InjectIconButton);
export default themr(APP_BAR)(AppBar);
export { factory as appBarFactory };
export { AppBar };
<|endoftext|>


<commit_before>'use strict';
import Webpack from 'webpack';
import Merge from 'webpack-merge';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import HTMLWebpackPlugin from 'html-webpack-plugin';
import Path from 'path';
import PostCSS from './postcss.config';

const isProdEnv = (process.env.NODE_EV === 'production');
  console.log(`Node environment:\t${isProdEnv}`);

const VENDOR_LIBS = [
  'body-parser',
  'lodash',
  'react',
  'react-dom',
  'react-redux',
  'react-router',
  'react-router-redux',
  'redux'
];

const BASE_CONFIG = {
  entry: {
    // 'webpack/hot/dev-server',
    bundle: Path.resolve(__dirname, 'src/App'),
    vendor: VENDOR_LIBS
  },
  output: {
    path: Path.join(__dirname, 'dist'),
    filename: '[name].[hash].js'
    // publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/i,
        exclude: /(node_modules|bower_components)/,
        use: 'babel'
      }, {
        test: /\.css$/i,
        loader: ExtractTextPlugin.extract({
          fallbackLoader: 'style',
          loader: 'css'
        })
      }, {
        test: /\.(scss|sass)$/i,
        loaders: ExtractTextPlugin.extract({
          fallbackLoader: 'style',
          loader: ['css', 'postcss', 'sass']
        })
        // [
        //   'style',
        //   'css',
        //   'autoprefixer?browsers=last 3 versions',
        //   'sass?outputStyle=expanded'
        // ]
      }, {
        test: /\.json$/i,
        use: 'json'
      }, {
        test: /\.(bmp|gif|jpe?g|png|svg|ttif)$/i,
        use: [
          // {
          //   loader: 'url',
          //   options: { limit: 40000 }
          // },
          'file?name=/images/[name].[ext]',
          'image-webpack'
        ]
      }, {
        test: /\.(pdf|doc[mstx]?|ppt[mstx]?|od[fpst])$/i,
        use: 'file?name=/docs/[name].[ext]'
      }
    ]
  },
  plugins: [
    new Webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest'],
      minChunks: Infinity
    }),
    new Webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
      }
    }),
    new Webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
      options: {
        postcss: { PostCSS }
      }
    }),
    new ExtractTextPlugin('styles.css'),
    new HTMLWebpackPlugin({
      template: 'assets/index.html'
    })
  ],
  node: {
    console: false,
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  },
  cache: true,
  watch: true,
  devtool: `${isProdEnv ? 'inline' : 'cheap-eval'}-source-map`,
  resolve: {
    extensions: ['.js', '.jsx']
  },
  resolveLoader: {
    moduleExtensions: ['-loader']
  }
};

const DEV_SERVER = {
  plugins: [
    new Webpack.HotModuleReplacementPlugin()
  ],
  devServer: {
    // contentBase: __dirname,
    historyApiFallback: true,
    host: 'localhost',
    hot: true,
    inline: true,
    noInfo: false,
    port: 3000
  },
  stats: {
    assets: true,
    children: false,
    chunks: false,
    colors: {
      bold: '\u001b[1m',
      cyan: '\u001b[1m\u001b[36m',
      green: '\u001b[1m\u001b[32m',
      magenta: '\u001b[1m\u001b[35m',
      red: '\u001b[1m\u001b[31m',
      yellow: '\u001b[1m\u001b[33m'
    },
    errorDetails: true,
    hash: false,
    modules: false,
    publicPath: false,
    reasons: true,
    timings: true,
    version: false,
    warnings: true
  }
};

const AGGREGATE_CONFIG = isProdEnv
  ? BASE_CONFIG
  : Merge(BASE_CONFIG, DEV_SERVER);

export default AGGREGATE_CONFIG;

//     new Webpack.optimize.DedupePlugin(),
//     new Webpack.optimize.UglifyJsPlugin({
//       compress: { warnings: false },
//       output: { comments: false },
//       sourceMap: false
//     })
<commit_msg>config (Webpack): Set entry point to Routes.jsx<commit_after>'use strict';
import Webpack from 'webpack';
import Merge from 'webpack-merge';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import HTMLWebpackPlugin from 'html-webpack-plugin';
import Path from 'path';
import PostCSS from './postcss.config';

const isProdEnv = (process.env.NODE_EV === 'production');
  console.log(`Node environment:\t${isProdEnv}`);

const VENDOR_LIBS = [
  'body-parser',
  'lodash',
  'react',
  'react-dom',
  'react-redux',
  'react-router',
  'react-router-redux',
  'redux'
];

const BASE_CONFIG = {
  entry: {
    // 'webpack/hot/dev-server',
    bundle: Path.resolve(__dirname, 'src/Routes'),
    vendor: VENDOR_LIBS
  },
  output: {
    path: Path.join(__dirname, 'dist'),
    filename: '[name].[hash].js'
    // publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/i,
        exclude: /(node_modules|bower_components)/,
        use: 'babel'
      }, {
        test: /\.css$/i,
        loader: ExtractTextPlugin.extract({
          fallbackLoader: 'style',
          loader: 'css'
        })
      }, {
        test: /\.(scss|sass)$/i,
        loaders: ExtractTextPlugin.extract({
          fallbackLoader: 'style',
          loader: ['css', 'postcss', 'sass']
        })
        // [
        //   'style',
        //   'css',
        //   'autoprefixer?browsers=last 3 versions',
        //   'sass?outputStyle=expanded'
        // ]
      }, {
        test: /\.json$/i,
        use: 'json'
      }, {
        test: /\.(bmp|gif|jpe?g|png|svg|ttif)$/i,
        use: [
          // {
          //   loader: 'url',
          //   options: { limit: 40000 }
          // },
          'file?name=/images/[name].[ext]',
          'image-webpack'
        ]
      }, {
        test: /\.(pdf|doc[mstx]?|ppt[mstx]?|od[fpst])$/i,
        use: 'file?name=/docs/[name].[ext]'
      }
    ]
  },
  plugins: [
    new Webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest'],
      minChunks: Infinity
    }),
    new Webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
      }
    }),
    new Webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
      options: {
        postcss: { PostCSS }
      }
    }),
    new ExtractTextPlugin('styles.css'),
    new HTMLWebpackPlugin({
      template: 'assets/index.html'
    })
  ],
  node: {
    console: false,
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  },
  cache: true,
  watch: true,
  devtool: `${isProdEnv ? 'inline' : 'cheap-eval'}-source-map`,
  resolve: {
    extensions: ['.js', '.jsx']
  },
  resolveLoader: {
    moduleExtensions: ['-loader']
  }
};

const DEV_SERVER = {
  plugins: [
    new Webpack.HotModuleReplacementPlugin()
  ],
  devServer: {
    // contentBase: __dirname,
    historyApiFallback: true,
    host: 'localhost',
    hot: true,
    inline: true,
    noInfo: false,
    port: 3000
  },
  stats: {
    assets: true,
    children: false,
    chunks: false,
    colors: {
      bold: '\u001b[1m',
      cyan: '\u001b[1m\u001b[36m',
      green: '\u001b[1m\u001b[32m',
      magenta: '\u001b[1m\u001b[35m',
      red: '\u001b[1m\u001b[31m',
      yellow: '\u001b[1m\u001b[33m'
    },
    errorDetails: true,
    hash: false,
    modules: false,
    publicPath: false,
    reasons: true,
    timings: true,
    version: false,
    warnings: true
  }
};

const AGGREGATE_CONFIG = isProdEnv
  ? BASE_CONFIG
  : Merge(BASE_CONFIG, DEV_SERVER);

export default AGGREGATE_CONFIG;

//     new Webpack.optimize.DedupePlugin(),
//     new Webpack.optimize.UglifyJsPlugin({
//       compress: { warnings: false },
//       output: { comments: false },
//       sourceMap: false
//     })
<|endoftext|>


<commit_before>import Backbone from 'backbone'

// Module to deal with authentication
// Should handle any Single sign on requests and deal with login/logout actions
const auth = {
  namespaced: true,
  state: {
    type: 'cas',
    cas_sso: false,
    cas_url: '',
    token: '',
  },
  mutations: {
      //
      // Authorisation status
      //
      authSuccess(state, token){
        state.token = token
        sessionStorage.setItem('token', token)
        // Preserve legacy app
        app.token = state.token
      },
      authError(state){
        console.log("store.auth - error trying to authenticate")
        state.token = ''
        sessionStorage.removeItem('token')
        // Preserve legacy app
        delete app.token
      },
      // Mutation to set state info back to defaults after successful logout action
      logout(state){
        state.token = ''
        sessionStorage.removeItem('token')
        // Preserve legacy app
        delete app.token
      },
  },
  actions: {
    checkAuth({state, rootState}, ticket) {
      console.log("Store checkAuth Ticket: " + ticket)
      return new Promise( (resolve) => {
        // If we have a token return
        if (state.token) resolve(true)
        else {
          Backbone.ajax({
              url: rootState.apiUrl+'/authenticate/check',
              type: 'GET',
              success: function(response) {
                console.log("Store checkAuth success: " + JSON.stringify(response))
                const token = response.jwt
                commit('authSuccess', token)
                resolve(true)
              },
              error: function(response) {
                console.log("Store check auth warning - no previous session")
                resolve(false)
              }
          })
        }
      })
    },

    validate({state, rootState}, ticket) {
      console.log("Store validate Ticket: " + ticket)
      return new Promise( (resolve) => {
        // If we have a token return
        if (state.token) resolve(true)

        Backbone.ajax({
            url: rootState.apiUrl+'/authenticate/check',
            type: 'GET',
            success: function(response) {
              console.log("Store validate success: " + JSON.stringify(response))
              const token = response.jwt
              commit('authSuccess', token)
              resolve(true)
            },
            error: function(response) {
              console.log("Store validate warning - no previous session")
              resolve(false)
            }
        })
      })
    },

    login({state, commit, rootState}, credentials) {
      return new Promise((resolve, reject) => {
        commit('loading', true, { root: true })

        Backbone.ajax({
          url: rootState.apiUrl+'/authenticate',
          data: credentials,
          type: 'POST',
          success: function(resp) {
            const token = resp.jwt
            console.log("Authentication success for " + credentials.login) // Using passed fed id at the moment
            commit('authSuccess', token)
            commit('loading', false, { root: true })
            resolve(resp)
          },
          error: function(req, status, error) {
            commit('authError')
            commit('loading', false, { root: true })
            reject(error)
          }})
        })
    },

    logout({commit, rootState}){
      return new Promise((resolve, reject) => {
        // If sso need to call the logout URL
        Backbone.ajax({
          url: rootState.apiUrl+'/authenticate/logout',
          type: 'GET',
          success: function(resp) {
            console.log("Logout successful")
            commit('logout')
            commit('proposal/setProposal', null)
            commit('user/updateUser', {})
            resolve()
          },
          error: function(req, status, error) {
            // Even if an error we can set our local properties to logged out
            console.log("Error returned from logout URL")
            commit('logout')
            commit('proposal/setProposal', null)
            commit('user/updateUser', {})
            reject()
        }})
      })
    },
  },
  getters: {
    isLoggedIn: function(state) {
      return state.token !== ''
    },
    token: function(state) {
      if (!state.token) {
        // Any in storage?
        state.token = sessionStorage.getItem('token')
      }
      return state.token
    },
  }
}

export default auth
<commit_msg>Fix use of global mutations in auth module<commit_after>import Backbone from 'backbone'

// Module to deal with authentication
// Should handle any Single sign on requests and deal with login/logout actions
const auth = {
  namespaced: true,
  state: {
    type: 'cas',
    cas_sso: false,
    cas_url: '',
    token: '',
  },
  mutations: {
      //
      // Authorisation status
      //
      authSuccess(state, token){
        state.token = token
        sessionStorage.setItem('token', token)
        // Preserve legacy app
        app.token = state.token
      },
      authError(state){
        console.log("store.auth - error trying to authenticate")
        state.token = ''
        sessionStorage.removeItem('token')
        // Preserve legacy app
        delete app.token
      },
      // Mutation to set state info back to defaults after successful logout action
      logout(state){
        state.token = ''
        sessionStorage.removeItem('token')
        // Preserve legacy app
        delete app.token
      },
  },
  actions: {
    checkAuth({state, rootState}, ticket) {
      console.log("Store checkAuth Ticket: " + ticket)
      return new Promise( (resolve) => {
        // If we have a token return
        if (state.token) resolve(true)
        else {
          Backbone.ajax({
              url: rootState.apiUrl+'/authenticate/check',
              type: 'GET',
              success: function(response) {
                console.log("Store checkAuth success: " + JSON.stringify(response))
                const token = response.jwt
                commit('authSuccess', token)
                resolve(true)
              },
              error: function(response) {
                console.log("Store check auth warning - no previous session")
                resolve(false)
              }
          })
        }
      })
    },

    validate({state, rootState}, ticket) {
      console.log("Store validate Ticket: " + ticket)
      return new Promise( (resolve) => {
        // If we have a token return
        if (state.token) resolve(true)

        Backbone.ajax({
            url: rootState.apiUrl+'/authenticate/check',
            type: 'GET',
            success: function(response) {
              console.log("Store validate success: " + JSON.stringify(response))
              const token = response.jwt
              commit('authSuccess', token)
              resolve(true)
            },
            error: function(response) {
              console.log("Store validate warning - no previous session")
              resolve(false)
            }
        })
      })
    },

    login({state, commit, rootState}, credentials) {
      return new Promise((resolve, reject) => {
        commit('loading', true, { root: true })

        Backbone.ajax({
          url: rootState.apiUrl+'/authenticate',
          data: credentials,
          type: 'POST',
          success: function(resp) {
            const token = resp.jwt
            console.log("Authentication success for " + credentials.login) // Using passed fed id at the moment
            commit('authSuccess', token)
            commit('loading', false, { root: true })
            resolve(resp)
          },
          error: function(req, status, error) {
            commit('authError')
            commit('loading', false, { root: true })
            reject(error)
          }})
        })
    },

    logout({commit, rootState}){
      return new Promise((resolve, reject) => {
        // If sso need to call the logout URL
        Backbone.ajax({
          url: rootState.apiUrl+'/authenticate/logout',
          type: 'GET',
          success: function(resp) {
            console.log("Logout successful")
            commit('logout')
            commit('proposal/setProposal', null, {root: true})
            commit('user/updateUser', {}, {root: true})
            resolve()
          },
          error: function(req, status, error) {
            // Even if an error we can set our local properties to logged out
            console.log("Error returned from logout URL")
            commit('logout')
            commit('proposal/setProposal', null, {root: true})
            commit('user/updateUser', {}, {root: true})
            reject()
        }})
      })
    },
  },
  getters: {
    isLoggedIn: function(state) {
      return state.token !== ''
    },
    token: function(state) {
      if (!state.token) {
        // Any in storage?
        state.token = sessionStorage.getItem('token')
      }
      return state.token
    },
  }
}

export default auth
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');

var devFlagPlugin = new webpack.DefinePlugin({
  __DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false'))
});

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    './frontend/index'
  ],
  output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    devFlagPlugin
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: ['babel'],
      exclude: /node_modules/,
      include: __dirname
    }]
  }
};

// When inside Redux repo, prefer src to compiled version.
// You can safely delete these lines in your project.
var reduxSrc = path.join(__dirname, '..', '..', 'src');
var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules');
var fs = require('fs');
if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) {
  // Resolve Redux to source
  module.exports.resolve = { alias: { 'redux': reduxSrc } };
  // Compile Redux from source
  module.exports.module.loaders.push({
    test: /\.js$/,
    loaders: ['babel'],
    include: reduxSrc
  });
}
<commit_msg>Reconfigure webpack to use eslint<commit_after>var path = require('path');
var webpack = require('webpack');

var devFlagPlugin = new webpack.DefinePlugin({
  __DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false'))
});

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    './frontend/index'
  ],
  output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    devFlagPlugin
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: ['babel', 'eslint-loader'],
      exclude: [/node_modules/,/scripts/],
      include: __dirname
    }]
  }
  eslint: {
    configFile: './.eslintrc'
  }
};

// When inside Redux repo, prefer src to compiled version.
// You can safely delete these lines in your project.
var reduxSrc = path.join(__dirname, '..', '..', 'src');
var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules');
var fs = require('fs');
if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) {
  // Resolve Redux to source
  module.exports.resolve = { alias: { 'redux': reduxSrc } };
  // Compile Redux from source
  module.exports.module.loaders.push({
    test: /\.js$/,
    loaders: ['babel'],
    include: reduxSrc
  });
}
<|endoftext|>


<commit_before>import path from 'path'

const library = 'style-script'
const srcPath = path.resolve(__dirname, 'src')
const libPath = path.resolve(__dirname, 'lib')

export default {
  devtool: 'source-map',

  context: srcPath,

  entry: 'index.js',

  resolve: {
    root: srcPath,
  },

  output: {
    library,
    libraryTarget: 'commonjs2',
    filename: `${ library }.js`,
    path: libPath,
  },

  module: {
    loaders: [
      {
        test: /\.js$/,
        include: srcPath,
        loader: 'babel',
      },
    ],
  },
}
<commit_msg>Add `lodash` to `externals` option of webpack<commit_after>import path from 'path'

const library = 'style-script'
const srcPath = path.resolve(__dirname, 'src')
const libPath = path.resolve(__dirname, 'lib')

export default {
  devtool: 'source-map',

  context: srcPath,

  entry: 'index.js',

  resolve: {
    root: srcPath,
  },

  output: {
    library,
    libraryTarget: 'commonjs2',
    filename: `${ library }.js`,
    path: libPath,
  },

  module: {
    loaders: [
      {
        test: /\.js$/,
        include: srcPath,
        loader: 'babel',
      },
    ],
  },

  externals: {
    lodash: '_',
  },
}
<|endoftext|>


<commit_before>define( [
            'dojo/_base/declare',
            'dojo/_base/lang',
            'dojo/_base/array',
            'dojo/_base/url',
            'JBrowse/Model/DataView',
            'JBrowse/has',
            'JBrowse/Errors',
            'JBrowse/Store/SeqFeature',
            'JBrowse/Store/DeferredStatsMixin',
            'JBrowse/Store/DeferredFeaturesMixin',
            './BigWig/Window',
            'JBrowse/Util',
            'JBrowse/Model/XHRBlob'
        ],
        function(
            declare,
            lang,
            array,
            urlObj,
            jDataView,
            has,
            JBrowseErrors,
            SeqFeatureStore,
            DeferredFeaturesMixin,
            DeferredStatsMixin,
            Window,
            Util,
            XHRBlob
        ) {
return declare([ SeqFeatureStore, DeferredFeaturesMixin, DeferredStatsMixin ],

 /**
  * @lends JBrowse.Store.SeqFeature.BigWig
  */
{

    BIG_WIG_MAGIC: -2003829722,
    BIG_BED_MAGIC: -2021002517,

    BIG_WIG_TYPE_GRAPH: 1,
    BIG_WIG_TYPE_VSTEP: 2,
    BIG_WIG_TYPE_FSTEP: 3,

    _littleEndian: true,

    /**
     * Data backend for reading wiggle data from BigWig or BigBed files.
     *
     * Adapted by Robert Buels from bigwig.js in the Dalliance Genome
     * Explorer which is copyright Thomas Down 2006-2010
     * @constructs
     */
    constructor: function( args ) {

        this.data = args.blob || new XHRBlob( this.resolveUrl(args.urlTemplate || 'data.bigwig'), { expectRanges: true });

        this.name = args.name || ( this.data.url && new urlObj( this.data.url ).path.replace(/^.+\//,'') ) || 'anonymous';

        this._load();
    },

    _defaultConfig: function() {
        return Util.deepUpdate(
            dojo.clone( this.inherited(arguments) ),
            {
                chunkSizeLimit: 30000000 // 30mb
            });
    },

    _getGlobalStats: function( successCallback, errorCallback ) {
        var s = this._globalStats || {};

        // calc mean and standard deviation if necessary
        if( !( 'scoreMean' in s ))
            s.scoreMean = s.basesCovered ? s.scoreSum / s.basesCovered : 0;
        if( !( 'scoreStdDev' in s ))
            s.scoreStdDev = this._calcStdFromSums( s.scoreSum, s.scoreSumSquares, s.basesCovered );

        successCallback( s );
    },

     /**
      * Read from the bbi file, respecting the configured chunkSizeLimit.
      */
    _read: function( start, size, callback, errorcallback ) {
        if( size > this.config.chunkSizeLimit )
            errorcallback( new JBrowseErrors.DataOverflow('Too much data. Chunk size '+Util.commifyNumber(size)+' bytes exceeds chunkSizeLimit of '+Util.commifyNumber(this.config.chunkSizeLimit)+'.' ) );
        else
            this.data.read.apply( this.data, arguments );
    },

    _load: function() {
        var thisB = this;
        this._read( 0, 2000, lang.hitch( this, function( bytes ) {
            if( ! bytes ) {
                this._failAllDeferred( 'BBI header not readable' );
                return;
            }

            var data = this.newDataView( bytes );

            // check magic numbers
            var magic = data.getInt32();
            if( magic != this.BIG_WIG_MAGIC && magic != this.BIG_BED_MAGIC ) {
                // try the other endianness if no magic
                this._littleEndian = false;
                data = this.newDataView( bytes );
                if( data.getInt32() != this.BIG_WIG_MAGIC && magic != this.BIG_BED_MAGIC) {
                    console.error('Not a BigWig or BigBed file');
                    this._failAllDeferred('Not a BigWig or BigBed file');
                    return;
                }
            }
            this.type = magic == this.BIG_BED_MAGIC ? 'bigbed' : 'bigwig';

            this.fileSize = bytes.fileSize;
            if( ! this.fileSize )
                console.warn("cannot get size of BigWig/BigBed file, widest zoom level not available");

            this.version = data.getUint16();
            this.numZoomLevels = data.getUint16();
            this.chromTreeOffset = data.getUint64();
            this.unzoomedDataOffset = data.getUint64();
            this.unzoomedIndexOffset = data.getUint64();
            this.fieldCount = data.getUint16();
            this.definedFieldCount = data.getUint16();
            this.asOffset = data.getUint64();
            this.totalSummaryOffset = data.getUint64();
            this.uncompressBufSize = data.getUint32();

            // dlog('bigType: ' + this.type);
            // dlog('chromTree at: ' + this.chromTreeOffset);
            // dlog('uncompress: ' + this.uncompressBufSize);
            // dlog('data at: ' + this.unzoomedDataOffset);
            // dlog('index at: ' + this.unzoomedIndexOffset);
            // dlog('field count: ' + this.fieldCount);
            // dlog('defined count: ' + this.definedFieldCount);

            this.zoomLevels = [];
            for (var zl = 0; zl < this.numZoomLevels; ++zl) {
                var zlReduction = data.getUint32( 4*(zl*6 + 16) );
                var zlData = data.getUint64( 4*(zl*6 + 18) );
                var zlIndex = data.getUint64( 4*(zl*6 + 20) );

                //          dlog('zoom(' + zl + '): reduction=' + zlReduction + '; data=' + zlData + '; index=' + zlIndex);
                this.zoomLevels.push({reductionLevel: zlReduction, dataOffset: zlData, indexOffset: zlIndex});
            }

            // parse the autoSql if present (bigbed)
            if( this.asOffset ) {
                (function() {
                     var d = this.newDataView( bytes, this.asOffset );
                     var string = "";
                     var c;
                     while((c = d.getChar()) && c.charCodeAt() != 0) {
                         string += c;
                     }
                     thisB.parseAutoSql(string);
                 }).call(this);
            }

            // parse the totalSummary if present (summary of all data in the file)
            if( this.totalSummaryOffset ) {
                (function() {
                     var d = this.newDataView( bytes, this.totalSummaryOffset );
                     var s = {
                         basesCovered: d.getUint64(),
                         scoreMin: d.getFloat64(),
                         scoreMax: d.getFloat64(),
                         scoreSum: d.getFloat64(),
                         scoreSumSquares: d.getFloat64()
                     };
                     this._globalStats = s;
                     // rest of stats will be calculated on demand in getGlobalStats
                 }).call(this);
            } else {
                    console.warn("BigWig "+this.data.url+ " has no total summary data.");
            }

            this._readChromTree(
                function() {
                    this._deferred.features.resolve({success: true});
                    this._deferred.stats.resolve({success: true});
                },
                lang.hitch( this, '_failAllDeferred' )
            );
        }),
        lang.hitch( this, '_failAllDeferred' )
       );
    },

    newDataView: function( bytes, offset, length ) {
        return new jDataView( bytes, offset, length, this._littleEndian );
    },

    /**
     * @private
     */
    _readChromTree: function( callback, errorCallback ) {
        var thisB = this;
        this.refsByNumber = {};
        this.refsByName = {};

        var udo = this.unzoomedDataOffset;
        while ((udo % 4) != 0) {
            ++udo;
        }

        this._read( this.chromTreeOffset, udo - this.chromTreeOffset, function(bpt) {
                       if( ! has('typed-arrays') ) {
                           thisB._failAllDeferred( 'Web browser does not support typed arrays' );
                           return;
                       }
                       var data = thisB.newDataView( bpt );

                       if( data.getUint32() !== 2026540177 )
                           throw "parse error: not a Kent bPlusTree";
                       var blockSize = data.getUint32();
                       var keySize = data.getUint32();
                       var valSize = data.getUint32();
                       var itemCount = data.getUint64();
                       var rootNodeOffset = 32;

                       //dlog('blockSize=' + blockSize + '    keySize=' + keySize + '   valSize=' + valSize + '    itemCount=' + itemCount);

                       var bptReadNode = function(offset) {
                           if( offset >= bpt.length )
                               throw "reading beyond end of buffer";
                           var isLeafNode = data.getUint8( offset );
                           var cnt = data.getUint16( offset+2 );
                           //dlog('ReadNode: ' + offset + '     type=' + isLeafNode + '   count=' + cnt);
                           offset += 4;
                           for (var n = 0; n < cnt; ++n) {
                               if( isLeafNode ) {
                                   // parse leaf node
                                   var key = '';
                                   for (var ki = 0; ki < keySize; ++ki) {
                                       var charCode = data.getUint8( offset++ );
                                       if (charCode != 0) {
                                           key += String.fromCharCode(charCode);
                                       }
                                   }
                                   var refId = data.getUint32( offset );
                                   var refSize = data.getUint32( offset+4 );
                                   offset += 8;

                                   var refRec = { name: key, id: refId, length: refSize };

                                   //dlog(key + ':' + refId + ',' + refSize);
                                   thisB.refsByName[ thisB.browser.regularizeReferenceName(key) ] = refRec;
                                   thisB.refsByNumber[refId] = refRec;
                               } else {
                                   // parse index node
                                   offset += keySize;
                                   var childOffset = data.getUint64( offset );
                                   offset += 8;
                                   childOffset -= thisB.chromTreeOffset;
                                   bptReadNode(childOffset);
                               }
                           }
                       };
                       bptReadNode(rootNodeOffset);

                       callback.call( thisB, thisB );
            }, errorCallback );
    },

    /**
     * Interrogate whether a store has data for a given reference
     * sequence.  Calls the given callback with either true or false.
     *
     * Implemented as a binary interrogation because some stores are
     * smart enough to regularize reference sequence names, while
     * others are not.
     */
    hasRefSeq: function( seqName, callback, errorCallback ) {
        var thisB = this;
        seqName = thisB.browser.regularizeReferenceName( seqName );
        this._deferred.features.then(function() {
            callback( seqName in thisB.refsByName );
        }, errorCallback );
    },

    _getFeatures: function( query, featureCallback, endCallback, errorCallback ) {

        var chrName = this.browser.regularizeReferenceName( query.ref );
        var min = query.start;
        var max = query.end;

        var v = query.basesPerSpan ? this.getView( 1/query.basesPerSpan ) :
                       query.scale ? this.getView( query.scale )          :
                                     this.getView( 1 );

        if( !v ) {
            endCallback();
            return;
        }

        v.readWigData( chrName, min, max, dojo.hitch( this, function( features ) {
            array.forEach( features || [], featureCallback );
            endCallback();
        }), errorCallback );
    },

    getUnzoomedView: function() {
        if (!this.unzoomedView) {
            var cirLen = 4000;
            var nzl = this.zoomLevels[0];
            if (nzl) {
                cirLen = this.zoomLevels[0].dataOffset - this.unzoomedIndexOffset;
            }
            this.unzoomedView = new Window( this, this.unzoomedIndexOffset, cirLen, false, this.autoSql );
        }
        return this.unzoomedView;
    },

    getView: function( scale ) {
        if( ! this.zoomLevels || ! this.zoomLevels.length )
            return null;

        if( !this._viewCache || this._viewCache.scale != scale ) {
            this._viewCache = {
                scale: scale,
                view: this._getView( scale )
            };
        }
        return this._viewCache.view;
    },

    _getView: function( scale ) {
        var basesPerPx = 1/scale;
        //console.log('getting view for '+basesPerSpan+' bases per span');
        var maxLevel = this.zoomLevels.length;
        if( ! this.fileSize ) // if we don't know the file size, we can't fetch the highest zoom level :-(
            maxLevel--;
        for( var i = maxLevel; i >= 0; i-- ) {
            var zh = this.zoomLevels[i];
            if( zh && zh.reductionLevel <= 2*basesPerPx ) {
                var indexLength = i < this.zoomLevels.length - 1
                    ? this.zoomLevels[i + 1].dataOffset - zh.indexOffset
                    : this.fileSize - 4 - zh.indexOffset;
                //console.log( 'using zoom level '+i);
                return new Window( this, zh.indexOffset, indexLength, true );
            }
        }
        //console.log( 'using unzoomed level');
        return this.getUnzoomedView();
    },

    getTagMetadata(tagName) {
        if (this.autoSql) {
            const lcTagName = tagName.replace(/_/g,'').toLowerCase()
            const fieldDefinition = this.autoSql.fields.find(
                field => field.name.toLowerCase() === lcTagName
            )
            if (fieldDefinition)
                return fieldDefinition
        }
    },

    parseAutoSql: function(string) {
        string = string.trim();
        var res = string.split('\n');
        this.autoSql = {
            name: /table\s+(\w+)/.exec(res[0])[1],
            description: /"(.*)"/.exec(res[1])[1],
            fields: []
        };
        var i = 3;
        var field;
        while(res[i].trim() != ')') {
            if(field = /([\w\[\]0-9]+)\s*(\w+)\s*;\s*"(.*)"/.exec(res[i].trim())) {
                this.autoSql.fields.push({
                    type: field[1],
                    name: field[2],
                    description: field[3]
                });
            } else {
                console.warn('autosql line not parsed', res[i]);
            }
            i++;
        }
    },

    saveStore: function() {
        return {
            urlTemplate: this.config.blob.url
        };
    }

});

});
<commit_msg>Get filesize from a stat call for bigwig<commit_after>define( [
            'dojo/_base/declare',
            'dojo/_base/lang',
            'dojo/_base/array',
            'dojo/_base/url',
            'JBrowse/Model/DataView',
            'JBrowse/has',
            'JBrowse/Errors',
            'JBrowse/Store/SeqFeature',
            'JBrowse/Store/DeferredStatsMixin',
            'JBrowse/Store/DeferredFeaturesMixin',
            './BigWig/Window',
            'JBrowse/Util',
            'JBrowse/Model/XHRBlob'
        ],
        function(
            declare,
            lang,
            array,
            urlObj,
            jDataView,
            has,
            JBrowseErrors,
            SeqFeatureStore,
            DeferredFeaturesMixin,
            DeferredStatsMixin,
            Window,
            Util,
            XHRBlob
        ) {
return declare([ SeqFeatureStore, DeferredFeaturesMixin, DeferredStatsMixin ],

 /**
  * @lends JBrowse.Store.SeqFeature.BigWig
  */
{

    BIG_WIG_MAGIC: -2003829722,
    BIG_BED_MAGIC: -2021002517,

    BIG_WIG_TYPE_GRAPH: 1,
    BIG_WIG_TYPE_VSTEP: 2,
    BIG_WIG_TYPE_FSTEP: 3,

    _littleEndian: true,

    /**
     * Data backend for reading wiggle data from BigWig or BigBed files.
     *
     * Adapted by Robert Buels from bigwig.js in the Dalliance Genome
     * Explorer which is copyright Thomas Down 2006-2010
     * @constructs
     */
    constructor: function( args ) {

        this.data = args.blob || new XHRBlob( this.resolveUrl(args.urlTemplate || 'data.bigwig'), { expectRanges: true });

        this.name = args.name || ( this.data.url && new urlObj( this.data.url ).path.replace(/^.+\//,'') ) || 'anonymous';

        this._load();
    },

    _defaultConfig: function() {
        return Util.deepUpdate(
            dojo.clone( this.inherited(arguments) ),
            {
                chunkSizeLimit: 30000000 // 30mb
            });
    },

    _getGlobalStats: function( successCallback, errorCallback ) {
        var s = this._globalStats || {};

        // calc mean and standard deviation if necessary
        if( !( 'scoreMean' in s ))
            s.scoreMean = s.basesCovered ? s.scoreSum / s.basesCovered : 0;
        if( !( 'scoreStdDev' in s ))
            s.scoreStdDev = this._calcStdFromSums( s.scoreSum, s.scoreSumSquares, s.basesCovered );

        successCallback( s );
    },

     /**
      * Read from the bbi file, respecting the configured chunkSizeLimit.
      */
    _read: function( start, size, callback, errorcallback ) {
        if( size > this.config.chunkSizeLimit )
            errorcallback( new JBrowseErrors.DataOverflow('Too much data. Chunk size '+Util.commifyNumber(size)+' bytes exceeds chunkSizeLimit of '+Util.commifyNumber(this.config.chunkSizeLimit)+'.' ) );
        else
            this.data.read.apply( this.data, arguments );
    },

    _load: function() {
        this._read( 0, 2000, async ( bytes ) => {
            const res = await this.data.statPromise()
            if( ! bytes ) {
                this._failAllDeferred( 'BBI header not readable' );
                return;
            }

            var data = this.newDataView( bytes );

            // check magic numbers
            var magic = data.getInt32();
            if( magic != this.BIG_WIG_MAGIC && magic != this.BIG_BED_MAGIC ) {
                // try the other endianness if no magic
                this._littleEndian = false;
                data = this.newDataView( bytes );
                if( data.getInt32() != this.BIG_WIG_MAGIC && magic != this.BIG_BED_MAGIC) {
                    console.error('Not a BigWig or BigBed file');
                    this._failAllDeferred('Not a BigWig or BigBed file');
                    return;
                }
            }
            this.type = magic == this.BIG_BED_MAGIC ? 'bigbed' : 'bigwig';

            this.fileSize = (res||{}).size
            if( ! this.fileSize )
                console.warn("cannot get size of BigWig/BigBed file, widest zoom level not available");

            this.version = data.getUint16();
            this.numZoomLevels = data.getUint16();
            this.chromTreeOffset = data.getUint64();
            this.unzoomedDataOffset = data.getUint64();
            this.unzoomedIndexOffset = data.getUint64();
            this.fieldCount = data.getUint16();
            this.definedFieldCount = data.getUint16();
            this.asOffset = data.getUint64();
            this.totalSummaryOffset = data.getUint64();
            this.uncompressBufSize = data.getUint32();

            // dlog('bigType: ' + this.type);
            // dlog('chromTree at: ' + this.chromTreeOffset);
            // dlog('uncompress: ' + this.uncompressBufSize);
            // dlog('data at: ' + this.unzoomedDataOffset);
            // dlog('index at: ' + this.unzoomedIndexOffset);
            // dlog('field count: ' + this.fieldCount);
            // dlog('defined count: ' + this.definedFieldCount);

            this.zoomLevels = [];
            for (var zl = 0; zl < this.numZoomLevels; ++zl) {
                var zlReduction = data.getUint32( 4*(zl*6 + 16) );
                var zlData = data.getUint64( 4*(zl*6 + 18) );
                var zlIndex = data.getUint64( 4*(zl*6 + 20) );

                //          dlog('zoom(' + zl + '): reduction=' + zlReduction + '; data=' + zlData + '; index=' + zlIndex);
                this.zoomLevels.push({reductionLevel: zlReduction, dataOffset: zlData, indexOffset: zlIndex});
            }

            // parse the autoSql if present (bigbed)
            if( this.asOffset ) {
                (function() {
                     var d = this.newDataView( bytes, this.asOffset );
                     var string = "";
                     var c;
                     while((c = d.getChar()) && c.charCodeAt() != 0) {
                         string += c;
                     }
                     thisB.parseAutoSql(string);
                 }).call(this);
            }

            // parse the totalSummary if present (summary of all data in the file)
            if( this.totalSummaryOffset ) {
                (function() {
                     var d = this.newDataView( bytes, this.totalSummaryOffset );
                     var s = {
                         basesCovered: d.getUint64(),
                         scoreMin: d.getFloat64(),
                         scoreMax: d.getFloat64(),
                         scoreSum: d.getFloat64(),
                         scoreSumSquares: d.getFloat64()
                     };
                     this._globalStats = s;
                     // rest of stats will be calculated on demand in getGlobalStats
                 }).call(this);
            } else {
                    console.warn("BigWig "+this.data.url+ " has no total summary data.");
            }

            this._readChromTree(
                function() {
                    this._deferred.features.resolve({success: true});
                    this._deferred.stats.resolve({success: true});
                },
                lang.hitch( this, '_failAllDeferred' )
            );
        },
        lang.hitch( this, '_failAllDeferred' )
       );
    },

    newDataView: function( bytes, offset, length ) {
        return new jDataView( bytes, offset, length, this._littleEndian );
    },

    /**
     * @private
     */
    _readChromTree: function( callback, errorCallback ) {
        var thisB = this;
        this.refsByNumber = {};
        this.refsByName = {};

        var udo = this.unzoomedDataOffset;
        while ((udo % 4) != 0) {
            ++udo;
        }

        this._read( this.chromTreeOffset, udo - this.chromTreeOffset, function(bpt) {
                       if( ! has('typed-arrays') ) {
                           thisB._failAllDeferred( 'Web browser does not support typed arrays' );
                           return;
                       }
                       var data = thisB.newDataView( bpt );

                       if( data.getUint32() !== 2026540177 )
                           throw "parse error: not a Kent bPlusTree";
                       var blockSize = data.getUint32();
                       var keySize = data.getUint32();
                       var valSize = data.getUint32();
                       var itemCount = data.getUint64();
                       var rootNodeOffset = 32;

                       //dlog('blockSize=' + blockSize + '    keySize=' + keySize + '   valSize=' + valSize + '    itemCount=' + itemCount);

                       var bptReadNode = function(offset) {
                           if( offset >= bpt.length )
                               throw "reading beyond end of buffer";
                           var isLeafNode = data.getUint8( offset );
                           var cnt = data.getUint16( offset+2 );
                           //dlog('ReadNode: ' + offset + '     type=' + isLeafNode + '   count=' + cnt);
                           offset += 4;
                           for (var n = 0; n < cnt; ++n) {
                               if( isLeafNode ) {
                                   // parse leaf node
                                   var key = '';
                                   for (var ki = 0; ki < keySize; ++ki) {
                                       var charCode = data.getUint8( offset++ );
                                       if (charCode != 0) {
                                           key += String.fromCharCode(charCode);
                                       }
                                   }
                                   var refId = data.getUint32( offset );
                                   var refSize = data.getUint32( offset+4 );
                                   offset += 8;

                                   var refRec = { name: key, id: refId, length: refSize };

                                   //dlog(key + ':' + refId + ',' + refSize);
                                   thisB.refsByName[ thisB.browser.regularizeReferenceName(key) ] = refRec;
                                   thisB.refsByNumber[refId] = refRec;
                               } else {
                                   // parse index node
                                   offset += keySize;
                                   var childOffset = data.getUint64( offset );
                                   offset += 8;
                                   childOffset -= thisB.chromTreeOffset;
                                   bptReadNode(childOffset);
                               }
                           }
                       };
                       bptReadNode(rootNodeOffset);

                       callback.call( thisB, thisB );
            }, errorCallback );
    },

    /**
     * Interrogate whether a store has data for a given reference
     * sequence.  Calls the given callback with either true or false.
     *
     * Implemented as a binary interrogation because some stores are
     * smart enough to regularize reference sequence names, while
     * others are not.
     */
    hasRefSeq: function( seqName, callback, errorCallback ) {
        var thisB = this;
        seqName = thisB.browser.regularizeReferenceName( seqName );
        this._deferred.features.then(function() {
            callback( seqName in thisB.refsByName );
        }, errorCallback );
    },

    _getFeatures: function( query, featureCallback, endCallback, errorCallback ) {

        var chrName = this.browser.regularizeReferenceName( query.ref );
        var min = query.start;
        var max = query.end;

        var v = query.basesPerSpan ? this.getView( 1/query.basesPerSpan ) :
                       query.scale ? this.getView( query.scale )          :
                                     this.getView( 1 );

        if( !v ) {
            endCallback();
            return;
        }

        v.readWigData( chrName, min, max, dojo.hitch( this, function( features ) {
            array.forEach( features || [], featureCallback );
            endCallback();
        }), errorCallback );
    },

    getUnzoomedView: function() {
        if (!this.unzoomedView) {
            var cirLen = 4000;
            var nzl = this.zoomLevels[0];
            if (nzl) {
                cirLen = this.zoomLevels[0].dataOffset - this.unzoomedIndexOffset;
            }
            this.unzoomedView = new Window( this, this.unzoomedIndexOffset, cirLen, false, this.autoSql );
        }
        return this.unzoomedView;
    },

    getView: function( scale ) {
        if( ! this.zoomLevels || ! this.zoomLevels.length )
            return null;

        if( !this._viewCache || this._viewCache.scale != scale ) {
            this._viewCache = {
                scale: scale,
                view: this._getView( scale )
            };
        }
        return this._viewCache.view;
    },

    _getView: function( scale ) {
        var basesPerPx = 1/scale;
        //console.log('getting view for '+basesPerSpan+' bases per span');
        var maxLevel = this.zoomLevels.length;
        if( ! this.fileSize ) // if we don't know the file size, we can't fetch the highest zoom level :-(
            maxLevel--;
        for( var i = maxLevel; i >= 0; i-- ) {
            var zh = this.zoomLevels[i];
            if( zh && zh.reductionLevel <= 2*basesPerPx ) {
                var indexLength = i < this.zoomLevels.length - 1
                    ? this.zoomLevels[i + 1].dataOffset - zh.indexOffset
                    : this.fileSize - 4 - zh.indexOffset;
                //console.log( 'using zoom level '+i);
                return new Window( this, zh.indexOffset, indexLength, true );
            }
        }
        //console.log( 'using unzoomed level');
        return this.getUnzoomedView();
    },

    getTagMetadata(tagName) {
        if (this.autoSql) {
            const lcTagName = tagName.replace(/_/g,'').toLowerCase()
            const fieldDefinition = this.autoSql.fields.find(
                field => field.name.toLowerCase() === lcTagName
            )
            if (fieldDefinition)
                return fieldDefinition
        }
    },

    parseAutoSql: function(string) {
        string = string.trim();
        var res = string.split('\n');
        this.autoSql = {
            name: /table\s+(\w+)/.exec(res[0])[1],
            description: /"(.*)"/.exec(res[1])[1],
            fields: []
        };
        var i = 3;
        var field;
        while(res[i].trim() != ')') {
            if(field = /([\w\[\]0-9]+)\s*(\w+)\s*;\s*"(.*)"/.exec(res[i].trim())) {
                this.autoSql.fields.push({
                    type: field[1],
                    name: field[2],
                    description: field[3]
                });
            } else {
                console.warn('autosql line not parsed', res[i]);
            }
            i++;
        }
    },

    saveStore: function() {
        return {
            urlTemplate: this.config.blob.url
        };
    }

});

});
<|endoftext|>


<commit_before>import path from "path";
import webpack from "webpack";
import { webpack as ClosureCompiler } from "google-closure-compiler-js";
import HtmlWebpackPlugin from "html-webpack-plugin";
import ExtractTextPlugin from "extract-text-webpack-plugin";
import CopyWebpackPlugin from "copy-webpack-plugin";
import autoprefixer from "autoprefixer";

const isProduction = process.env.NODE_ENV === "production";

export default {
  context: path.resolve(__dirname, "src"),
  devtool: isProduction ? "source-map" : false,
  entry: {
    /*    polyfills: ["./setup"],
    panel: ["./setupPanel"],
    injector: ["./prompt-injector"],
    background: ["./background"],
    prompt: ["./prompt"],
    record: ["./record"],
    escape: ["./escape"],*/
    atoms: ["./selenium/javascript/atoms/bot", "./selenium/javascript/atoms/error", "./selenium/javascript/atoms/response"]
  },
  output: {
    path: path.resolve(__dirname, "build/assets"),
    filename: "[name].js",
    publicPath: "/assets/",
    libraryTarget: "umd"
  },
  resolve: {
    extensions: [".js", ".jsx", ".json"]
  },
  module: {
    rules: [
      {
        // "oneOf" will traverse all following loaders until one will
        // match the requirements. When no loader matches it will fall
        // back to the "file" loader at the end of the loader list.
        oneOf: [
          // "url" loader works just like "file" loader but it also embeds
          // assets smaller than specified size as data URLs to avoid requests.
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: "url-loader",
            options: {
              limit: 10000,
              name: "media/[name].[hash:8].[ext]"
            }
          },
          // Process JS with Babel.
          {
            test: /\.(jsx?)$/,
            include: [
              path.resolve(__dirname, "src")
            ],
            use: [{
              loader: "babel-loader",
              options: {
                compact: true
              }
            },
            {
              loader: "closure-compiler-loader",
              options: {
                languageIn: "ECMASCRIPT6",
                languageOut: "ECMASCRIPT5",
                compilationLevel: "SIMPLE",
                warningLevel: "VERBOSE"
              }
            }]
          },
          // The notation here is somewhat confusing.
          // "postcss" loader applies autoprefixer to our CSS.
          // "css" loader resolves paths in CSS and adds assets as dependencies.
          // "style" loader normally turns CSS into JS modules injecting <style>,
          // but unlike in development configuration, we do something different.
          // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
          // (second argument), then grabs the result CSS and puts it into a
          // separate file in our build process. This way we actually ship
          // a single CSS file in production instead of JS code injecting <style>
          // tags. If you use code splitting, however, any async bundles will still
          // use the "style" loader inside the async code so CSS from them won't be
          // in the main CSS file.
          {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract(
              {
                fallback: "style-loader",
                use: [
                  {
                    loader: "css-loader",
                    options: {
                      importLoaders: 1,
                      minimize: true,
                      sourceMap: isProduction
                    }
                  },
                  {
                    loader: "postcss-loader",
                    options: {
                      // Necessary for external CSS imports to work
                      // https://github.com/facebookincubator/create-react-app/issues/2677
                      ident: "postcss",
                      plugins: () => [
                        require("postcss-flexbugs-fixes"),
                        autoprefixer({
                          browsers: [
                            ">1%",
                            "last 4 versions",
                            "Firefox ESR",
                            "not ie < 9" // React doesn't support IE8 anyway
                          ],
                          flexbox: "no-2009"
                        })
                      ]
                    }
                  }
                ]
              }
            )
            // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
          },
          // "file" loader makes sure assets end up in the `build` folder.
          // When you `import` an asset, you get its filename.
          // This loader don't uses a "test" so it will catch all modules
          // that fall through the other loaders.
          {
            loader: "file-loader",
            // Exclude `js` files to keep "css" loader working as it injects
            // it's runtime that would otherwise processed through "file" loader.
            // Also exclude `html` and `json` extensions so they get processed
            // by webpacks internal loaders.
            exclude: [/\.jsx?$/, /\.html$/, /\.json$/],
            options: {
              name: "media/[name].[hash:8].[ext]"
            }
          }
          // ** STOP ** Are you adding a new loader?
          // Make sure to add the new loader(s) before the "file" loader.
        ]
      }
    ]
  },
  plugins: [
    // Compile whatever possible using Closure Compiler
    /*new ClosureCompiler({
      options: {
        languageIn: "ECMASCRIPT6",
        languageOut: "ECMASCRIPT5",
        compilationLevel: "ADVANCED",
        processCommonJsModules: true,
        warningLevel: "VERBOSE"
      }
    }),*/
    // Copy non-umd assets to vendor
    new CopyWebpackPlugin([
      { from: "", to: "vendor", ignore: ["selenium/*"] }
    ]),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      filename: "panel.html",
      inject: "head",
      template: path.resolve(__dirname, "src/panel.html"),
      chunks: [],
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true
      }
    }),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin({
      "process.env": {
        "NODE_ENV": JSON.stringify(process.env.NODE_ENV)
      }
    }),
    // Minify the code.
    /*new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        // Disabled because of an issue with Uglify breaking seemingly valid code:
        // https://github.com/facebookincubator/create-react-app/issues/2376
        // Pending further investigation:
        // https://github.com/mishoo/UglifyJS2/issues/2011
        comparisons: false
      },
      output: {
        comments: false,
        // Turned on because emoji and regex is not minified properly using default
        // https://github.com/facebookincubator/create-react-app/issues/2488
        ascii_only: true
      },
      sourceMap: isProduction
    }),*/
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: "css/[name].[hash:8].css"
    }),
    // Moment.js is an extremely popular library that bundles large locale files
    // by default due to how Webpack interprets its code. This is a practical
    // solution that requires the user to opt into importing specific locales.
    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
    // You can remove this if you don't use Moment.js:
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
  ]
};
<commit_msg>changed the paths to their new location<commit_after>import path from "path";
import webpack from "webpack";
import { webpack as ClosureCompiler } from "google-closure-compiler-js";
import HtmlWebpackPlugin from "html-webpack-plugin";
import ExtractTextPlugin from "extract-text-webpack-plugin";
import CopyWebpackPlugin from "copy-webpack-plugin";
import autoprefixer from "autoprefixer";

const isProduction = process.env.NODE_ENV === "production";

export default {
  context: path.resolve(__dirname, "src"),
  devtool: isProduction ? "source-map" : false,
  entry: {
    /*    polyfills: ["./setup"],
    panel: ["./setupPanel"],
    injector: ["./prompt-injector"],
    background: ["./background"],
    prompt: ["./prompt"],
    record: ["./record"],
    escape: ["./escape"],*/
    atoms: ["./atoms/bot", "./atoms/error", "./atoms/response"]
  },
  output: {
    path: path.resolve(__dirname, "build/assets"),
    filename: "[name].js",
    publicPath: "/assets/",
    libraryTarget: "umd"
  },
  resolve: {
    extensions: [".js", ".jsx", ".json"]
  },
  module: {
    rules: [
      {
        // "oneOf" will traverse all following loaders until one will
        // match the requirements. When no loader matches it will fall
        // back to the "file" loader at the end of the loader list.
        oneOf: [
          // "url" loader works just like "file" loader but it also embeds
          // assets smaller than specified size as data URLs to avoid requests.
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: "url-loader",
            options: {
              limit: 10000,
              name: "media/[name].[hash:8].[ext]"
            }
          },
          // Process JS with Babel.
          {
            test: /\.(jsx?)$/,
            include: [
              path.resolve(__dirname, "src")
            ],
            use: [{
              loader: "babel-loader",
              options: {
                compact: true
              }
            },
            {
              loader: "closure-compiler-loader",
              options: {
                languageIn: "ECMASCRIPT6",
                languageOut: "ECMASCRIPT5",
                compilationLevel: "SIMPLE",
                warningLevel: "VERBOSE"
              }
            }]
          },
          // The notation here is somewhat confusing.
          // "postcss" loader applies autoprefixer to our CSS.
          // "css" loader resolves paths in CSS and adds assets as dependencies.
          // "style" loader normally turns CSS into JS modules injecting <style>,
          // but unlike in development configuration, we do something different.
          // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
          // (second argument), then grabs the result CSS and puts it into a
          // separate file in our build process. This way we actually ship
          // a single CSS file in production instead of JS code injecting <style>
          // tags. If you use code splitting, however, any async bundles will still
          // use the "style" loader inside the async code so CSS from them won't be
          // in the main CSS file.
          {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract(
              {
                fallback: "style-loader",
                use: [
                  {
                    loader: "css-loader",
                    options: {
                      importLoaders: 1,
                      minimize: true,
                      sourceMap: isProduction
                    }
                  },
                  {
                    loader: "postcss-loader",
                    options: {
                      // Necessary for external CSS imports to work
                      // https://github.com/facebookincubator/create-react-app/issues/2677
                      ident: "postcss",
                      plugins: () => [
                        require("postcss-flexbugs-fixes"),
                        autoprefixer({
                          browsers: [
                            ">1%",
                            "last 4 versions",
                            "Firefox ESR",
                            "not ie < 9" // React doesn't support IE8 anyway
                          ],
                          flexbox: "no-2009"
                        })
                      ]
                    }
                  }
                ]
              }
            )
            // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
          },
          // "file" loader makes sure assets end up in the `build` folder.
          // When you `import` an asset, you get its filename.
          // This loader don't uses a "test" so it will catch all modules
          // that fall through the other loaders.
          {
            loader: "file-loader",
            // Exclude `js` files to keep "css" loader working as it injects
            // it's runtime that would otherwise processed through "file" loader.
            // Also exclude `html` and `json` extensions so they get processed
            // by webpacks internal loaders.
            exclude: [/\.jsx?$/, /\.html$/, /\.json$/],
            options: {
              name: "media/[name].[hash:8].[ext]"
            }
          }
          // ** STOP ** Are you adding a new loader?
          // Make sure to add the new loader(s) before the "file" loader.
        ]
      }
    ]
  },
  plugins: [
    // Compile whatever possible using Closure Compiler
    /*new ClosureCompiler({
      options: {
        languageIn: "ECMASCRIPT6",
        languageOut: "ECMASCRIPT5",
        compilationLevel: "ADVANCED",
        processCommonJsModules: true,
        warningLevel: "VERBOSE"
      }
    }),*/
    // Copy non-umd assets to vendor
    new CopyWebpackPlugin([
      { from: "", to: "vendor", ignore: ["selenium/*"] }
    ]),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      filename: "panel.html",
      inject: "head",
      template: path.resolve(__dirname, "src/panel.html"),
      chunks: [],
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true
      }
    }),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin({
      "process.env": {
        "NODE_ENV": JSON.stringify(process.env.NODE_ENV)
      }
    }),
    // Minify the code.
    /*new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        // Disabled because of an issue with Uglify breaking seemingly valid code:
        // https://github.com/facebookincubator/create-react-app/issues/2376
        // Pending further investigation:
        // https://github.com/mishoo/UglifyJS2/issues/2011
        comparisons: false
      },
      output: {
        comments: false,
        // Turned on because emoji and regex is not minified properly using default
        // https://github.com/facebookincubator/create-react-app/issues/2488
        ascii_only: true
      },
      sourceMap: isProduction
    }),*/
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: "css/[name].[hash:8].css"
    }),
    // Moment.js is an extremely popular library that bundles large locale files
    // by default due to how Webpack interprets its code. This is a practical
    // solution that requires the user to opt into importing specific locales.
    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
    // You can remove this if you don't use Moment.js:
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
  ]
};
<|endoftext|>