<commit_before>/* eslint-disable */

const log = {warn: ::console.warn};
import React, {Component} from 'react';

import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import 'rxjs/Rx';

      // const responseStream = Observable.create(observer => {
      //   console.warn('observer', observer, observer.prototype);
      //   window.fetch(requestUrl)
      //     .then(response => response.json())
      //     .then(observer._next)
      //     .catch(observer._error)
      //     .then(() => {
      //       observer.complete();
      //       console.warn('end');
      //     });
      // });

//  Rx.Observable.fromEvent(refreshButton, 'click');
function subjectFactory() {

  function subject(value) {
    // if (typeof mapFunction === 'function') {
    //   value = mapFunction.apply(undefined, arguments);
    // } else if (typeof mapFunction !== 'undefined') {
    //   value = mapFunction;
    // }
    subject.next(value);
    return value;
  }

  for (var key in Subject.prototype) {
    subject[key] = Subject.prototype[key];
  }
  // Object.assign(subject, Subject.prototype);

  Subject.apply(subject, []);

  return subject;
}

export default class FollowBox extends Component {
  componentDidMount() {
    console.warn('this', this);
    const responseStream = this.refreshClickStream
    .map((ev) => {
      log.warn('ev', ev);
      return ev;
    })
    .map((ev) => {
      console.warn('new stream', ev, ev.target);
      var randomOffset = Math.floor(Math.random()*500);
      return 'https://api.github.com/users?since=' + randomOffset;
    })
    .startWith('https://api.github.com/users')
    .flatMap(requestUrl =>
      Observable.fromPromise(window.fetch(requestUrl)
      .then(response => response.json()))
    )
    .map(function(userList) {
      return userList[Math.floor(Math.random()*userList.length)];
    });
    responseStream.subscribe(::console.log);
    // this.refreshClickStream.subscribe(::console.log);

// var suggestion1Stream = responseStream
//   .map(function(listUsers) {
//     // get one random user from the list
//     return listUsers[Math.floor(Math.random()*listUsers.length)];
//   });

    // const requestStream = Observable.of('https://api.github.com/users');
    // const responseStream = requestStream
    //   .flatMap(requestUrl => Observable.fromPromise(window.fetch(requestUrl).then(response => response.json())));
    // responseStream.subscribe(res => {
    //   log.warn('res', res);
    // });

    // var refreshClickStream = Rx.Observable.fromEvent(refreshButton, 'click');
  }

  refreshClickStream = subjectFactory();

  handleClick(ev) {
    log.warn('handleClick', ev.target);
  }

  render() {
    // const { todos, actions } = this.props
    return (

Who to follow?
•Refresh•View all
        FollowBox

    );
  }
}
<commit_msg>chore(cleanup): remove followbox rxjs test<commit_after><|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Error from '../components/Error';
import withIntl from '../lib/withIntl';
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import Member from './Member';
import { ButtonGroup, Button } from 'react-bootstrap';
import { FormattedMessage } from 'react-intl';

const MEMBERS_PER_PAGE = 10;

class MembersWithData extends React.Component {

  static propTypes = {
    collective: PropTypes.object,
    tier: PropTypes.object,
    limit: PropTypes.number,
    onChange: PropTypes.func,
    LoggedInUser: PropTypes.object
  }

  constructor(props) {
    super(props);
    this.fetchMore = this.fetchMore.bind(this);
    this.refetch = this.refetch.bind(this);
    this.onChange = this.onChange.bind(this);
    this.state = {
      role: null,
      loading: false
    };
  }

  onChange() {
    const { onChange } = this.props;
    onChange && this.node && onChange({ height: this.node.offsetHeight });
  }

  componentDidMount() {
    this.onChange();
  }

  fetchMore(e) {
    e.target.blur();
    this.setState({ loading: true });
    this.props.fetchMore().then(() => {
      this.setState({ loading: false });
      this.onChange();
    });
  }

  refetch(role) {
    this.setState({role});
    this.props.refetch({role});
  }

  render() {
    const { data, LoggedInUser, collective, tier, role, type } = this.props;

    if (data.error) {
      console.error("graphql error>>>", data.error.message);
      return (<Error message="GraphQL error" />)
    }
    if (!data.allMembers) {
      return (
);
    }
    const members = [...data.allMembers];
    if (members.length === 0) {
      return (
)
    }

    // need to sort by totalDonations and then date
    // browsers (chrome vs. firefox) appear to handle "0" return cases differently
    members.sort((a, b) => {
      if (b.stats.totalDonations !== a.stats.totalDonations) {
        return b.stats.totalDonations - a.stats.totalDonations;
      } else {
        const aDate = new Date(a.createdAt);
        const bDate = new Date(b.createdAt);
        return aDate - bDate;
      }
    });

    const size = members.length > 50 ? "small" : "large";
    let viewMode = (type && type.split(',')[0]) || "USER";
    if (tier && tier.name.match(/sponsor/i)) {
      viewMode = "ORGANIZATION";
    }
    const limit = this.props.limit || MEMBERS_PER_PAGE * 2;
    return (

 this.node = node}>

        { !role && !tier &&

            <ButtonGroup className="filterBtnGroup">
              <Button className="filterBtn" bsStyle={!this.state.role ? 'primary' : 'default'} onClick={() => this.refetch()}>
                <FormattedMessage id='members.all' defaultMessage='all' />
              </Button>
              <Button className="filterBtn" bsStyle={this.state.role === 'ADMIN' ? 'primary' : 'default'} onClick={() => this.refetch('ADMIN')}>
                <FormattedMessage id='members.admin' defaultMessage='administrators' />
              </Button>
              <Button className="filterBtn" bsStyle={this.state.role === 'MEMBER' ? 'primary' : 'default'} onClick={() => this.refetch('MEMBER')}>
                <FormattedMessage id='members.members' defaultMessage='members' />
              </Button>
              <Button className="filterBtn" bsStyle={this.state.role === 'BACKER' ? 'primary' : 'default'} onClick={() => this.refetch('BACKER')}>
                <FormattedMessage id='members.paid' defaultMessage='backers' />
              </Button>
            </ButtonGroup>

        }

          {members.map((member) =>
            (<Member
              key={member.id}
              member={member}
              className={classNames(this.props.className, size)}
              collective={collective}
              viewMode={viewMode}
              LoggedInUser={LoggedInUser}
              />)
          )}

        { members.length % 10 === 0 && members.length >= limit &&

            <Button bsStyle='default' onClick={this.fetchMore}>
              {this.state.loading && <FormattedMessage id='loading' defaultMessage='loading' />}
              {!this.state.loading && <FormattedMessage id='loadMore' defaultMessage='load more' />}
            </Button>

        }

    );
  }

}

const getMembersQuery = gql`
query Members($CollectiveId: Int!, $TierId: Int, $role: String, $type: String, $limit: Int, $offset: Int, $orderBy: String) {
  allMembers(CollectiveId: $CollectiveId, TierId: $TierId, role: $role, type: $type, limit: $limit, offset: $offset, orderBy: $orderBy) {
    id
    role
    createdAt
    stats {
      totalDonations
    }
    tier {
      id
      name
    }
    member {
      id
      type
      name
      company
      description
      slug
      image
      backgroundImage
      website
    }
  }
}
`;

export const addMembersData = graphql(getMembersQuery, {
  options(props) {
    return {
      variables: {
        CollectiveId: props.collective.id,
        TierId: props.tier && props.tier.id,
        offset: 0,
        type: props.type,
        role: props.role,
        orderBy: props.orderBy,
        limit: props.limit || MEMBERS_PER_PAGE * 2
      }
    }
  },
  props: ({ data }) => ({
    data,
    fetchMore: () => {
      return data.fetchMore({
        variables: {
          offset: data.allMembers.length,
          limit: MEMBERS_PER_PAGE
        },
        updateQuery: (previousResult, { fetchMoreResult }) => {
          if (!fetchMoreResult) {
            return previousResult
          }
          return Object.assign({}, previousResult, {
            // Append the new posts results to the old one
            allMembers: [...previousResult.allMembers, ...fetchMoreResult.allMembers]
          })
        }
      })
    }
  })
});

export default addMembersData(withIntl(MembersWithData));
<commit_msg>Make sure we display unique members<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Error from '../components/Error';
import withIntl from '../lib/withIntl';
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import Member from './Member';
import { ButtonGroup, Button } from 'react-bootstrap';
import { FormattedMessage } from 'react-intl';
import { uniqBy } from 'lodash';

const MEMBERS_PER_PAGE = 10;

class MembersWithData extends React.Component {

  static propTypes = {
    collective: PropTypes.object,
    tier: PropTypes.object,
    limit: PropTypes.number,
    onChange: PropTypes.func,
    LoggedInUser: PropTypes.object
  }

  constructor(props) {
    super(props);
    this.fetchMore = this.fetchMore.bind(this);
    this.refetch = this.refetch.bind(this);
    this.onChange = this.onChange.bind(this);
    this.state = {
      role: null,
      loading: false
    };
  }

  onChange() {
    const { onChange } = this.props;
    onChange && this.node && onChange({ height: this.node.offsetHeight });
  }

  componentDidMount() {
    this.onChange();
  }

  fetchMore(e) {
    e.target.blur();
    this.setState({ loading: true });
    this.props.fetchMore().then(() => {
      this.setState({ loading: false });
      this.onChange();
    });
  }

  refetch(role) {
    this.setState({role});
    this.props.refetch({role});
  }

  render() {
    const { data, LoggedInUser, collective, tier, role, type } = this.props;

    if (data.error) {
      console.error("graphql error>>>", data.error.message);
      return (<Error message="GraphQL error" />)
    }
    if (!data.allMembers) {
      return (
);
    }
    let members = [...data.allMembers];
    if (members.length === 0) {
      return (
)
    }

    // need to sort by totalDonations and then date
    // browsers (chrome vs. firefox) appear to handle "0" return cases differently
    members.sort((a, b) => {
      if (b.stats.totalDonations !== a.stats.totalDonations) {
        return b.stats.totalDonations - a.stats.totalDonations;
      } else {
        const aDate = new Date(a.createdAt);
        const bDate = new Date(b.createdAt);
        return bDate - aDate;
      }
    });

    // Make sure we display unique members
    // that should ultimately be addressed on the API side
    members = uniqBy(members, member => member.member.id);

    const size = members.length > 50 ? "small" : "large";
    let viewMode = (type && type.split(',')[0]) || "USER";
    if (tier && tier.name.match(/sponsor/i)) {
      viewMode = "ORGANIZATION";
    }
    const limit = this.props.limit || MEMBERS_PER_PAGE * 2;
    return (

 this.node = node}>

        { !role && !tier &&

            <ButtonGroup className="filterBtnGroup">
              <Button className="filterBtn" bsStyle={!this.state.role ? 'primary' : 'default'} onClick={() => this.refetch()}>
                <FormattedMessage id='members.all' defaultMessage='all' />
              </Button>
              <Button className="filterBtn" bsStyle={this.state.role === 'ADMIN' ? 'primary' : 'default'} onClick={() => this.refetch('ADMIN')}>
                <FormattedMessage id='members.admin' defaultMessage='administrators' />
              </Button>
              <Button className="filterBtn" bsStyle={this.state.role === 'MEMBER' ? 'primary' : 'default'} onClick={() => this.refetch('MEMBER')}>
                <FormattedMessage id='members.members' defaultMessage='members' />
              </Button>
              <Button className="filterBtn" bsStyle={this.state.role === 'BACKER' ? 'primary' : 'default'} onClick={() => this.refetch('BACKER')}>
                <FormattedMessage id='members.paid' defaultMessage='backers' />
              </Button>
            </ButtonGroup>

        }

          {members.map((member) =>
            (<Member
              key={member.id}
              member={member}
              className={classNames(this.props.className, size)}
              collective={collective}
              viewMode={viewMode}
              LoggedInUser={LoggedInUser}
              />)
          )}

        { members.length % 10 === 0 && members.length >= limit &&

            <Button bsStyle='default' onClick={this.fetchMore}>
              {this.state.loading && <FormattedMessage id='loading' defaultMessage='loading' />}
              {!this.state.loading && <FormattedMessage id='loadMore' defaultMessage='load more' />}
            </Button>

        }

    );
  }

}

const getMembersQuery = gql`
query Members($CollectiveId: Int!, $TierId: Int, $role: String, $type: String, $limit: Int, $offset: Int, $orderBy: String) {
  allMembers(CollectiveId: $CollectiveId, TierId: $TierId, role: $role, type: $type, limit: $limit, offset: $offset, orderBy: $orderBy) {
    id
    role
    createdAt
    stats {
      totalDonations
    }
    tier {
      id
      name
    }
    member {
      id
      type
      name
      company
      description
      slug
      image
      backgroundImage
      website
    }
  }
}
`;

export const addMembersData = graphql(getMembersQuery, {
  options(props) {
    return {
      variables: {
        CollectiveId: props.collective.id,
        TierId: props.tier && props.tier.id,
        offset: 0,
        type: props.type,
        role: props.role,
        orderBy: props.orderBy,
        limit: props.limit || MEMBERS_PER_PAGE * 2
      }
    }
  },
  props: ({ data }) => ({
    data,
    fetchMore: () => {
      return data.fetchMore({
        variables: {
          offset: data.allMembers.length,
          limit: MEMBERS_PER_PAGE
        },
        updateQuery: (previousResult, { fetchMoreResult }) => {
          if (!fetchMoreResult) {
            return previousResult
          }
          return Object.assign({}, previousResult, {
            // Append the new posts results to the old one
            allMembers: [...previousResult.allMembers, ...fetchMoreResult.allMembers]
          })
        }
      })
    }
  })
});

export default addMembersData(withIntl(MembersWithData));
<|endoftext|>


<commit_before>/* eslint-disable import/no-extraneous-dependencies */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { select } from 'd3-selection';
import _ from 'lodash';

class ObservableChart extends Component {
  componentDidMount() {
    this.createObservableChart();
    this.updateObservableChart();
  }

  componentDidUpdate() {
    this.updateObservableChart();
  }

  createObservableChart() {
    const node = this.node;
    const { width, height, paddingTop } = this.props;
    select(node)
      .append('rect')
      .attr('class', 'background')
      .attr('height', `${height - paddingTop}px`)
      .attr('width', `${width}px`)
      .attr('x', '0px')
      .attr('y', `${paddingTop}px`)
      .attr('fill', '#ffffff');

    renderHorizontalLine(paddingTop);
    _.range(0, 6).forEach((i) => {
      renderVerticalLine(i * 60, 0, height);
      renderText(`${i * 200} ms`, (i * 60) - 2, 10);
    });

    function renderHorizontalLine(y) {
      select(node)
        .append('rect')
        .attr('class', 'grid__horizontal-line')
        .attr('height', 1)
        .attr('width', width)
        .attr('x', 0)
        .attr('y', y)
        .attr('fill', '#d9d9d9');
    }

    function renderVerticalLine(x, y, h) {
      select(node)
        .append('rect')
        .attr('class', 'grid__vertical-line')
        .attr('height', h)
        .attr('width', 1)
        .attr('x', x)
        .attr('y', y)
        .attr('fill', '#d9d9d9');
    }

    function renderText(str, x, y) {
      select(node)
        .append('text')
        .attr('class', 'grid__text')
        .attr('x', x)
        .attr('y', y)
        .attr('text-anchor', 'end')
        .attr('fill', '#404040')
        .style('font-size', '11px')
        .text(str);
    }
  }

  updateObservableChart() {
    const { height, paddingTop } = this.props;
    const node = this.node;
    const barWidth = 3;

    // create a rect for new messages
    select(node)
      .selectAll('.message')
      .data(this.props.data)
      .enter()
      .append('rect')
      .attr('class', 'message')
      .attr('height', height - paddingTop)
      .attr('width', barWidth)
      .attr('y', paddingTop)
      .attr('fill', '#4a90e2');

    // remove rect for disappeared messages
    select(node)
      .selectAll('.message')
      .data(this.props.data)
      .exit()
      .remove();

    // update rect for every message
    select(node)
      .selectAll('.message')
      .data(this.props.data)
      .attr('x', d => d.frame - (barWidth / 2));
  }

  render() {
    const { width, height } = this.props;
    return (
      <svg ref={(node) => { this.node = node; }} width={width} height={height} />
    );
  }
}

const propTypes = {
  width: PropTypes.string.isRequired,
  height: PropTypes.string.isRequired,
  data: PropTypes.array.isRequired,
  paddingTop: PropTypes.number,
};
const defaultProps = {
  paddingTop: 14,
};
ObservableChart.propTypes = propTypes;
ObservableChart.defaultProps = defaultProps;

export default ObservableChart;
<commit_msg>Add line to show current time<commit_after>/* eslint-disable import/no-extraneous-dependencies */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { select } from 'd3-selection';
import _ from 'lodash';

class ObservableChart extends Component {
  componentDidMount() {
    this.createObservableChart();
    this.updateObservableChart();
  }

  componentDidUpdate() {
    this.updateObservableChart();
  }

  createObservableChart() {
    const node = this.node;
    const { width, height, paddingTop } = this.props;
    select(node)
      .append('rect')
      .attr('class', 'background')
      .attr('height', `${height - paddingTop}px`)
      .attr('width', `${width}px`)
      .attr('x', '0px')
      .attr('y', `${paddingTop}px`)
      .attr('fill', '#ffffff');

    renderHorizontalLine(paddingTop);
    _.range(0, 6).forEach((i) => {
      renderVerticalLine(i * 60, 0, height, 'grid__vertical-line', '#d9d9d9');
      renderText(`${i * 200} ms`, (i * 60) - 2, 10);
    });

    renderVerticalLine(0, 0, height, 'grid__current-time', '#d0021b');

    function renderHorizontalLine(y) {
      select(node)
        .append('rect')
        .attr('class', 'grid__horizontal-line')
        .attr('height', 1)
        .attr('width', width)
        .attr('x', 0)
        .attr('y', y)
        .attr('fill', '#d9d9d9');
    }

    function renderVerticalLine(x, y, h, className, color) {
      select(node)
        .append('rect')
        .attr('class', className)
        .attr('height', h)
        .attr('width', 1)
        .attr('x', x)
        .attr('y', y)
        .attr('fill', color);
    }

    function renderText(str, x, y) {
      select(node)
        .append('text')
        .attr('class', 'grid__text')
        .attr('x', x)
        .attr('y', y)
        .attr('text-anchor', 'end')
        .attr('fill', '#404040')
        .style('font-size', '11px')
        .text(str);
    }
  }

  updateObservableChart() {
    const { height, paddingTop } = this.props;
    const node = this.node;
    const barWidth = 3;

    // create a rect for new messages
    select(node)
      .selectAll('.message')
      .data(this.props.data)
      .enter()
      .append('rect')
      .attr('class', 'message')
      .attr('height', height - paddingTop)
      .attr('width', barWidth)
      .attr('y', paddingTop)
      .attr('fill', '#4a90e2');

    // remove rect for disappeared messages
    select(node)
      .selectAll('.message')
      .data(this.props.data)
      .exit()
      .remove();

    // update rect for every message
    select(node)
      .selectAll('.message')
      .data(this.props.data)
      .attr('x', d => d.frame - (barWidth / 2));
  }

  render() {
    const { width, height } = this.props;
    return (
      <svg ref={(node) => { this.node = node; }} width={width} height={height} />
    );
  }
}

const propTypes = {
  width: PropTypes.string.isRequired,
  height: PropTypes.string.isRequired,
  data: PropTypes.array.isRequired,
  paddingTop: PropTypes.number,
};
const defaultProps = {
  paddingTop: 14,
};
ObservableChart.propTypes = propTypes;
ObservableChart.defaultProps = defaultProps;

export default ObservableChart;
<|endoftext|>


<commit_before>import hoistStatics from 'hoist-non-react-statics'
import React, { useContext, useMemo, useRef, useReducer } from 'react'
import { isValidElementType, isContextConsumer } from 'react-is'
import Subscription from '../utils/Subscription'
import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect'

import { ReactReduxContext } from './Context'

// Define some constant arrays just to avoid re-creating these
const EMPTY_ARRAY = []
const NO_SUBSCRIPTION_ARRAY = [null, null]

const stringifyComponent = Comp => {
  try {
    return JSON.stringify(Comp)
  } catch (err) {
    return String(Comp)
  }
}

function storeStateUpdatesReducer(state, action) {
  const [, updateCount] = state
  return [action.payload, updateCount + 1]
}

const initStateUpdates = () => [null, 0]

export default function connectAdvanced(
  /*
    selectorFactory is a func that is responsible for returning the selector function used to
    compute new props from state, props, and dispatch. For example:

      export default connectAdvanced((dispatch, options) => (state, props) => ({
        thing: state.things[props.thingId],
        saveThing: fields => dispatch(actionCreators.saveThing(props.thingId, fields)),
      }))(YourComponent)

    Access to dispatch is provided to the factory so selectorFactories can bind actionCreators
    outside of their selector as an optimization. Options passed to connectAdvanced are passed to
    the selectorFactory, along with displayName and WrappedComponent, as the second argument.

    Note that selectorFactory is responsible for all caching/memoization of inbound and outbound
    props. Do not use connectAdvanced directly without memoizing results between calls to your
    selector, otherwise the Connect component will re-render on every state or props change.
  */
  selectorFactory,
  // options object:
  {
    // the func used to compute this HOC's displayName from the wrapped component's displayName.
    // probably overridden by wrapper functions such as connect()
    getDisplayName = name => `ConnectAdvanced(${name})`,

    // shown in error messages
    // probably overridden by wrapper functions such as connect()
    methodName = 'connectAdvanced',

    // REMOVED: if defined, the name of the property passed to the wrapped element indicating the number of
    // calls to render. useful for watching in react devtools for unnecessary re-renders.
    renderCountProp = undefined,

    // determines whether this HOC subscribes to store changes
    shouldHandleStateChanges = true,

    // REMOVED: the key of props/context to get the store
    storeKey = 'store',

    // REMOVED: expose the wrapped component via refs
    withRef = false,

    // use React's forwardRef to expose a ref of the wrapped component
    forwardRef = false,

    // the context consumer to use
    context = ReactReduxContext,

    // additional options are passed through to the selectorFactory
    ...connectOptions
  } = {}
) {
  if (process.env.NODE_ENV !== 'production') {
    if (renderCountProp !== undefined) {
      throw new Error(
        `renderCountProp is removed. render counting is built into the latest React Dev Tools profiling extension`
      )
    }
    if (withRef) {
      throw new Error(
        'withRef is removed. To access the wrapped instance, use a ref on the connected component'
      )
    }

    const customStoreWarningMessage =
      'To use a custom Redux store for specific components, create a custom React context with ' +
      "React.createContext(), and pass the context object to React Redux's Provider and specific components" +
      ' like: <Provider context={MyContext}><ConnectedComponent context={MyContext} /></Provider>. ' +
      'You may also pass a {context : MyContext} option to connect'

    if (storeKey !== 'store') {
      throw new Error(
        'storeKey has been removed and does not do anything. ' +
          customStoreWarningMessage
      )
    }
  }

  const Context = context

  return function wrapWithConnect(WrappedComponent) {
    if (
      process.env.NODE_ENV !== 'production' &&
      !isValidElementType(WrappedComponent)
    ) {
      throw new Error(
        `You must pass a component to the function returned by ` +
          `${methodName}. Instead received ${stringifyComponent(
            WrappedComponent
          )}`
      )
    }

    const wrappedComponentName =
      WrappedComponent.displayName || WrappedComponent.name || 'Component'

    const displayName = getDisplayName(wrappedComponentName)

    const selectorFactoryOptions = {
      ...connectOptions,
      getDisplayName,
      methodName,
      renderCountProp,
      shouldHandleStateChanges,
      storeKey,
      displayName,
      wrappedComponentName,
      WrappedComponent
    }

    const { pure } = connectOptions

    function createChildSelector(store) {
      return selectorFactory(store.dispatch, selectorFactoryOptions)
    }

    // If we aren't running in "pure" mode, we don't want to memoize values.
    // To avoid conditionally calling hooks, we fall back to a tiny wrapper
    // that just executes the given callback immediately.
    const usePureOnlyMemo = pure ? useMemo : callback => callback()

    function ConnectFunction(props) {
      const [propsContext, forwardedRef, wrapperProps] = useMemo(() => {
        // Distinguish between actual "data" props that were passed to the wrapper component,
        // and values needed to control behavior (forwarded refs, alternate context instances).
        // To maintain the wrapperProps object reference, memoize this destructuring.
        const { forwardedRef, ...wrapperProps } = props
        return [props.context, forwardedRef, wrapperProps]
      }, [props])

      const ContextToUse = useMemo(() => {
        // Users may optionally pass in a custom context instance to use instead of our ReactReduxContext.
        // Memoize the check that determines which context instance we should use.
        return propsContext &&
          propsContext.Consumer &&
          isContextConsumer(<propsContext.Consumer />)
          ? propsContext
          : Context
      }, [propsContext, Context])

      // Retrieve the store and ancestor subscription via context, if available
      const contextValue = useContext(ContextToUse)

      // The store _must_ exist as either a prop or in context.
      // We'll check to see if it _looks_ like a Redux store first.
      // This allows us to pass through a `store` prop that is just a plain value.
      const didStoreComeFromProps =
        Boolean(props.store) &&
        Boolean(props.store.getState) &&
        Boolean(props.store.dispatch)
      const didStoreComeFromContext =
        Boolean(contextValue) && Boolean(contextValue.store)

      if (
        process.env.NODE_ENV !== 'production' &&
        !didStoreComeFromProps &&
        !didStoreComeFromContext
      ) {
        throw new Error(
          `Could not find "store" in the context of ` +
            `"${displayName}". Either wrap the root component in a <Provider>, ` +
            `or pass a custom React context provider to <Provider> and the corresponding ` +
            `React context consumer to ${displayName} in connect options.`
        )
      }

      // Based on the previous check, one of these must be true
      const store = didStoreComeFromProps ? props.store : contextValue.store

      const childPropsSelector = useMemo(() => {
        // The child props selector needs the store reference as an input.
        // Re-create this selector whenever the store changes.
        return createChildSelector(store)
      }, [store])

      const [subscription, notifyNestedSubs] = useMemo(() => {
        if (!shouldHandleStateChanges) return NO_SUBSCRIPTION_ARRAY

        // This Subscription's source should match where store came from: props vs. context. A component
        // connected to the store via props shouldn't use subscription from context, or vice versa.
        const subscription = new Subscription(
          store,
          didStoreComeFromProps ? null : contextValue.subscription
        )

        // `notifyNestedSubs` is duplicated to handle the case where the component is unmounted in
        // the middle of the notification loop, where `subscription` will then be null. This can
        // probably be avoided if Subscription's listeners logic is changed to not call listeners
        // that have been unsubscribed in the  middle of the notification loop.
        const notifyNestedSubs = subscription.notifyNestedSubs.bind(
          subscription
        )

        return [subscription, notifyNestedSubs]
      }, [store, didStoreComeFromProps, contextValue])

      // Determine what {store, subscription} value should be put into nested context, if necessary,
      // and memoize that value to avoid unnecessary context updates.
      const overriddenContextValue = useMemo(() => {
        if (didStoreComeFromProps) {
          // This component is directly subscribed to a store from props.
          // We don't want descendants reading from this store - pass down whatever
          // the existing context value is from the nearest connected ancestor.
          return contextValue
        }

        // Otherwise, put this component's subscription instance into context, so that
        // connected descendants won't update until after this component is done
        return {
          ...contextValue,
          subscription
        }
      }, [didStoreComeFromProps, contextValue, subscription])

      // We need to force this wrapper component to re-render whenever a Redux store update
      // causes a change to the calculated child component props (or we caught an error in mapState)
      const [
        [previousStateUpdateResult],
        forceComponentUpdateDispatch
      ] = useReducer(storeStateUpdatesReducer, EMPTY_ARRAY, initStateUpdates)

      // Propagate any mapState/mapDispatch errors upwards
      if (previousStateUpdateResult && previousStateUpdateResult.error) {
        throw previousStateUpdateResult.error
      }

      // Set up refs to coordinate values between the subscription effect and the render logic
      const lastChildProps = useRef()
      const lastWrapperProps = useRef(wrapperProps)
      const childPropsFromStoreUpdate = useRef()
      const renderIsScheduled = useRef(false)

      const actualChildProps = usePureOnlyMemo(() => {
        // Tricky logic here:
        // - This render may have been triggered by a Redux store update that produced new child props
        // - However, we may have gotten new wrapper props after that
        // If we have new child props, and the same wrapper props, we know we should use the new child props as-is.
        // But, if we have new wrapper props, those might change the child props, so we have to recalculate things.
        // So, we'll use the child props from store update only if the wrapper props are the same as last time.
        if (
          childPropsFromStoreUpdate.current &&
          wrapperProps === lastWrapperProps.current
        ) {
          return childPropsFromStoreUpdate.current
        }

        // TODO We're reading the store directly in render() here. Bad idea?
        // This will likely cause Bad Things (TM) to happen in Concurrent Mode.
        // Note that we do this because on renders _not_ caused by store updates, we need the latest store state
        // to determine what the child props should be.
        return childPropsSelector(store.getState(), wrapperProps)
      }, [store, previousStateUpdateResult, wrapperProps])

      // We need this to execute synchronously every time we re-render. However, React warns
      // about useLayoutEffect in SSR, so we try to detect environment and fall back to
      // just useEffect instead to avoid the warning, since neither will run anyway.
      useIsomorphicLayoutEffect(() => {
        // We want to capture the wrapper props and child props we used for later comparisons
        lastWrapperProps.current = wrapperProps
        lastChildProps.current = actualChildProps
        renderIsScheduled.current = false

        // If the render was from a store update, clear out that reference and cascade the subscriber update
        if (childPropsFromStoreUpdate.current) {
          childPropsFromStoreUpdate.current = null
          notifyNestedSubs()
        }
      })

      // Our re-subscribe logic only runs when the store/subscription setup changes
      useIsomorphicLayoutEffect(() => {
        // If we're not subscribed to the store, nothing to do here
        if (!shouldHandleStateChanges) return

        // Capture values for checking if and when this component unmounts
        let didUnsubscribe = false
        let lastThrownError = null

        // We'll run this callback every time a store subscription update propagates to this component
        const checkForUpdates = () => {
          if (didUnsubscribe) {
            // Don't run stale listeners.
            // Redux doesn't guarantee unsubscriptions happen until next dispatch.
            return
          }

          const latestStoreState = store.getState()

          let newChildProps, error
          try {
            // Actually run the selector with the most recent store state and wrapper props
            // to determine what the child props should be
            newChildProps = childPropsSelector(
              latestStoreState,
              lastWrapperProps.current
            )
          } catch (e) {
            error = e
            lastThrownError = e
          }

          if (!error) {
            lastThrownError = null
          }

          // If the child props haven't changed, nothing to do here - cascade the subscription update
          if (newChildProps === lastChildProps.current) {
            if (!renderIsScheduled.current) {
              notifyNestedSubs()
            }
          } else {
            // Save references to the new child props.  Note that we track the "child props from store update"
            // as a ref instead of a useState/useReducer because we need a way to determine if that value has
            // been processed.  If this went into useState/useReducer, we couldn't clear out the value without
            // forcing another re-render, which we don't want.
            lastChildProps.current = newChildProps
            childPropsFromStoreUpdate.current = newChildProps
            renderIsScheduled.current = true

            // If the child props _did_ change (or we caught an error), this wrapper component needs to re-render
            forceComponentUpdateDispatch({
              type: 'STORE_UPDATED',
              payload: {
                error
              }
            })
          }
        }

        // Actually subscribe to the nearest connected ancestor (or store)
        subscription.onStateChange = checkForUpdates
        subscription.trySubscribe()

        // Pull data from the store after first render in case the store has
        // changed since we began.
        checkForUpdates()

        const unsubscribeWrapper = () => {
          didUnsubscribe = true
          subscription.tryUnsubscribe()
          subscription.onStateChange = null

          if (lastThrownError) {
            // It's possible that we caught an error due to a bad mapState function, but the
            // parent re-rendered without this component and we're about to unmount.
            // This shouldn't happen as long as we do top-down subscriptions correctly, but
            // if we ever do those wrong, this throw will surface the error in our tests.
            // In that case, throw the error from here so it doesn't get lost.
            throw lastThrownError
          }
        }

        return unsubscribeWrapper
      }, [store, subscription, childPropsSelector])

      // Now that all that's done, we can finally try to actually render the child component.
      // We memoize the elements for the rendered child component as an optimization.
      const renderedWrappedComponent = useMemo(
        () => <WrappedComponent {...actualChildProps} ref={forwardedRef} />,
        [forwardedRef, WrappedComponent, actualChildProps]
      )

      // If React sees the exact same element reference as last time, it bails out of re-rendering
      // that child, same as if it was wrapped in React.memo() or returned false from shouldComponentUpdate.
      const renderedChild = useMemo(() => {
        if (shouldHandleStateChanges) {
          // If this component is subscribed to store updates, we need to pass its own
          // subscription instance down to our descendants. That means rendering the same
          // Context instance, and putting a different value into the context.
          return (
            <ContextToUse.Provider value={overriddenContextValue}>
              {renderedWrappedComponent}
            </ContextToUse.Provider>
          )
        }

        return renderedWrappedComponent
      }, [ContextToUse, renderedWrappedComponent, overriddenContextValue])

      return renderedChild
    }

    // If we're in "pure" mode, ensure our wrapper component only re-renders when incoming props have changed.
    const Connect = pure ? React.memo(ConnectFunction) : ConnectFunction

    Connect.WrappedComponent = WrappedComponent
    Connect.displayName = displayName

    if (forwardRef) {
      const forwarded = React.forwardRef(function forwardConnectRef(
        props,
        ref
      ) {
        return <Connect {...props} forwardedRef={ref} />
      })

      forwarded.displayName = displayName
      forwarded.WrappedComponent = WrappedComponent
      return hoistStatics(forwarded, WrappedComponent)
    }

    return hoistStatics(Connect, WrappedComponent)
  }
}
<commit_msg>Fix memory leak issue with `UseEffect` (#1506)<commit_after>import hoistStatics from 'hoist-non-react-statics'
import React, { useContext, useMemo, useRef, useReducer } from 'react'
import { isValidElementType, isContextConsumer } from 'react-is'
import Subscription from '../utils/Subscription'
import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect'

import { ReactReduxContext } from './Context'

// Define some constant arrays just to avoid re-creating these
const EMPTY_ARRAY = []
const NO_SUBSCRIPTION_ARRAY = [null, null]

const stringifyComponent = Comp => {
  try {
    return JSON.stringify(Comp)
  } catch (err) {
    return String(Comp)
  }
}

function storeStateUpdatesReducer(state, action) {
  const [, updateCount] = state
  return [action.payload, updateCount + 1]
}

function useIsomorphicLayoutEffectWithArgs(
  effectFunc,
  effectArgs,
  dependencies
) {
  useIsomorphicLayoutEffect(() => effectFunc(...effectArgs), dependencies)
}

function captureWrapperProps(
  lastWrapperProps,
  lastChildProps,
  renderIsScheduled,
  wrapperProps,
  actualChildProps,
  childPropsFromStoreUpdate,
  notifyNestedSubs
) {
  // We want to capture the wrapper props and child props we used for later comparisons
  lastWrapperProps.current = wrapperProps
  lastChildProps.current = actualChildProps
  renderIsScheduled.current = false

  // If the render was from a store update, clear out that reference and cascade the subscriber update
  if (childPropsFromStoreUpdate.current) {
    childPropsFromStoreUpdate.current = null
    notifyNestedSubs()
  }
}

function subscribeUpdates(
  shouldHandleStateChanges,
  store,
  subscription,
  childPropsSelector,
  lastWrapperProps,
  lastChildProps,
  renderIsScheduled,
  childPropsFromStoreUpdate,
  notifyNestedSubs,
  forceComponentUpdateDispatch
) {
  // If we're not subscribed to the store, nothing to do here
  if (!shouldHandleStateChanges) return

  // Capture values for checking if and when this component unmounts
  let didUnsubscribe = false
  let lastThrownError = null

  // We'll run this callback every time a store subscription update propagates to this component
  const checkForUpdates = () => {
    if (didUnsubscribe) {
      // Don't run stale listeners.
      // Redux doesn't guarantee unsubscriptions happen until next dispatch.
      return
    }

    const latestStoreState = store.getState()

    let newChildProps, error
    try {
      // Actually run the selector with the most recent store state and wrapper props
      // to determine what the child props should be
      newChildProps = childPropsSelector(
        latestStoreState,
        lastWrapperProps.current
      )
    } catch (e) {
      error = e
      lastThrownError = e
    }

    if (!error) {
      lastThrownError = null
    }

    // If the child props haven't changed, nothing to do here - cascade the subscription update
    if (newChildProps === lastChildProps.current) {
      if (!renderIsScheduled.current) {
        notifyNestedSubs()
      }
    } else {
      // Save references to the new child props.  Note that we track the "child props from store update"
      // as a ref instead of a useState/useReducer because we need a way to determine if that value has
      // been processed.  If this went into useState/useReducer, we couldn't clear out the value without
      // forcing another re-render, which we don't want.
      lastChildProps.current = newChildProps
      childPropsFromStoreUpdate.current = newChildProps
      renderIsScheduled.current = true

      // If the child props _did_ change (or we caught an error), this wrapper component needs to re-render
      forceComponentUpdateDispatch({
        type: 'STORE_UPDATED',
        payload: {
          error
        }
      })
    }
  }

  // Actually subscribe to the nearest connected ancestor (or store)
  subscription.onStateChange = checkForUpdates
  subscription.trySubscribe()

  // Pull data from the store after first render in case the store has
  // changed since we began.
  checkForUpdates()

  const unsubscribeWrapper = () => {
    didUnsubscribe = true
    subscription.tryUnsubscribe()
    subscription.onStateChange = null

    if (lastThrownError) {
      // It's possible that we caught an error due to a bad mapState function, but the
      // parent re-rendered without this component and we're about to unmount.
      // This shouldn't happen as long as we do top-down subscriptions correctly, but
      // if we ever do those wrong, this throw will surface the error in our tests.
      // In that case, throw the error from here so it doesn't get lost.
      throw lastThrownError
    }
  }

  return unsubscribeWrapper
}

const initStateUpdates = () => [null, 0]

export default function connectAdvanced(
  /*
    selectorFactory is a func that is responsible for returning the selector function used to
    compute new props from state, props, and dispatch. For example:

      export default connectAdvanced((dispatch, options) => (state, props) => ({
        thing: state.things[props.thingId],
        saveThing: fields => dispatch(actionCreators.saveThing(props.thingId, fields)),
      }))(YourComponent)

    Access to dispatch is provided to the factory so selectorFactories can bind actionCreators
    outside of their selector as an optimization. Options passed to connectAdvanced are passed to
    the selectorFactory, along with displayName and WrappedComponent, as the second argument.

    Note that selectorFactory is responsible for all caching/memoization of inbound and outbound
    props. Do not use connectAdvanced directly without memoizing results between calls to your
    selector, otherwise the Connect component will re-render on every state or props change.
  */
  selectorFactory,
  // options object:
  {
    // the func used to compute this HOC's displayName from the wrapped component's displayName.
    // probably overridden by wrapper functions such as connect()
    getDisplayName = name => `ConnectAdvanced(${name})`,

    // shown in error messages
    // probably overridden by wrapper functions such as connect()
    methodName = 'connectAdvanced',

    // REMOVED: if defined, the name of the property passed to the wrapped element indicating the number of
    // calls to render. useful for watching in react devtools for unnecessary re-renders.
    renderCountProp = undefined,

    // determines whether this HOC subscribes to store changes
    shouldHandleStateChanges = true,

    // REMOVED: the key of props/context to get the store
    storeKey = 'store',

    // REMOVED: expose the wrapped component via refs
    withRef = false,

    // use React's forwardRef to expose a ref of the wrapped component
    forwardRef = false,

    // the context consumer to use
    context = ReactReduxContext,

    // additional options are passed through to the selectorFactory
    ...connectOptions
  } = {}
) {
  if (process.env.NODE_ENV !== 'production') {
    if (renderCountProp !== undefined) {
      throw new Error(
        `renderCountProp is removed. render counting is built into the latest React Dev Tools profiling extension`
      )
    }
    if (withRef) {
      throw new Error(
        'withRef is removed. To access the wrapped instance, use a ref on the connected component'
      )
    }

    const customStoreWarningMessage =
      'To use a custom Redux store for specific components, create a custom React context with ' +
      "React.createContext(), and pass the context object to React Redux's Provider and specific components" +
      ' like: <Provider context={MyContext}><ConnectedComponent context={MyContext} /></Provider>. ' +
      'You may also pass a {context : MyContext} option to connect'

    if (storeKey !== 'store') {
      throw new Error(
        'storeKey has been removed and does not do anything. ' +
          customStoreWarningMessage
      )
    }
  }

  const Context = context

  return function wrapWithConnect(WrappedComponent) {
    if (
      process.env.NODE_ENV !== 'production' &&
      !isValidElementType(WrappedComponent)
    ) {
      throw new Error(
        `You must pass a component to the function returned by ` +
          `${methodName}. Instead received ${stringifyComponent(
            WrappedComponent
          )}`
      )
    }

    const wrappedComponentName =
      WrappedComponent.displayName || WrappedComponent.name || 'Component'

    const displayName = getDisplayName(wrappedComponentName)

    const selectorFactoryOptions = {
      ...connectOptions,
      getDisplayName,
      methodName,
      renderCountProp,
      shouldHandleStateChanges,
      storeKey,
      displayName,
      wrappedComponentName,
      WrappedComponent
    }

    const { pure } = connectOptions

    function createChildSelector(store) {
      return selectorFactory(store.dispatch, selectorFactoryOptions)
    }

    // If we aren't running in "pure" mode, we don't want to memoize values.
    // To avoid conditionally calling hooks, we fall back to a tiny wrapper
    // that just executes the given callback immediately.
    const usePureOnlyMemo = pure ? useMemo : callback => callback()

    function ConnectFunction(props) {
      const [propsContext, forwardedRef, wrapperProps] = useMemo(() => {
        // Distinguish between actual "data" props that were passed to the wrapper component,
        // and values needed to control behavior (forwarded refs, alternate context instances).
        // To maintain the wrapperProps object reference, memoize this destructuring.
        const { forwardedRef, ...wrapperProps } = props
        return [props.context, forwardedRef, wrapperProps]
      }, [props])

      const ContextToUse = useMemo(() => {
        // Users may optionally pass in a custom context instance to use instead of our ReactReduxContext.
        // Memoize the check that determines which context instance we should use.
        return propsContext &&
          propsContext.Consumer &&
          isContextConsumer(<propsContext.Consumer />)
          ? propsContext
          : Context
      }, [propsContext, Context])

      // Retrieve the store and ancestor subscription via context, if available
      const contextValue = useContext(ContextToUse)

      // The store _must_ exist as either a prop or in context.
      // We'll check to see if it _looks_ like a Redux store first.
      // This allows us to pass through a `store` prop that is just a plain value.
      const didStoreComeFromProps =
        Boolean(props.store) &&
        Boolean(props.store.getState) &&
        Boolean(props.store.dispatch)
      const didStoreComeFromContext =
        Boolean(contextValue) && Boolean(contextValue.store)

      if (
        process.env.NODE_ENV !== 'production' &&
        !didStoreComeFromProps &&
        !didStoreComeFromContext
      ) {
        throw new Error(
          `Could not find "store" in the context of ` +
            `"${displayName}". Either wrap the root component in a <Provider>, ` +
            `or pass a custom React context provider to <Provider> and the corresponding ` +
            `React context consumer to ${displayName} in connect options.`
        )
      }

      // Based on the previous check, one of these must be true
      const store = didStoreComeFromProps ? props.store : contextValue.store

      const childPropsSelector = useMemo(() => {
        // The child props selector needs the store reference as an input.
        // Re-create this selector whenever the store changes.
        return createChildSelector(store)
      }, [store])

      const [subscription, notifyNestedSubs] = useMemo(() => {
        if (!shouldHandleStateChanges) return NO_SUBSCRIPTION_ARRAY

        // This Subscription's source should match where store came from: props vs. context. A component
        // connected to the store via props shouldn't use subscription from context, or vice versa.
        const subscription = new Subscription(
          store,
          didStoreComeFromProps ? null : contextValue.subscription
        )

        // `notifyNestedSubs` is duplicated to handle the case where the component is unmounted in
        // the middle of the notification loop, where `subscription` will then be null. This can
        // probably be avoided if Subscription's listeners logic is changed to not call listeners
        // that have been unsubscribed in the  middle of the notification loop.
        const notifyNestedSubs = subscription.notifyNestedSubs.bind(
          subscription
        )

        return [subscription, notifyNestedSubs]
      }, [store, didStoreComeFromProps, contextValue])

      // Determine what {store, subscription} value should be put into nested context, if necessary,
      // and memoize that value to avoid unnecessary context updates.
      const overriddenContextValue = useMemo(() => {
        if (didStoreComeFromProps) {
          // This component is directly subscribed to a store from props.
          // We don't want descendants reading from this store - pass down whatever
          // the existing context value is from the nearest connected ancestor.
          return contextValue
        }

        // Otherwise, put this component's subscription instance into context, so that
        // connected descendants won't update until after this component is done
        return {
          ...contextValue,
          subscription
        }
      }, [didStoreComeFromProps, contextValue, subscription])

      // We need to force this wrapper component to re-render whenever a Redux store update
      // causes a change to the calculated child component props (or we caught an error in mapState)
      const [
        [previousStateUpdateResult],
        forceComponentUpdateDispatch
      ] = useReducer(storeStateUpdatesReducer, EMPTY_ARRAY, initStateUpdates)

      // Propagate any mapState/mapDispatch errors upwards
      if (previousStateUpdateResult && previousStateUpdateResult.error) {
        throw previousStateUpdateResult.error
      }

      // Set up refs to coordinate values between the subscription effect and the render logic
      const lastChildProps = useRef()
      const lastWrapperProps = useRef(wrapperProps)
      const childPropsFromStoreUpdate = useRef()
      const renderIsScheduled = useRef(false)

      const actualChildProps = usePureOnlyMemo(() => {
        // Tricky logic here:
        // - This render may have been triggered by a Redux store update that produced new child props
        // - However, we may have gotten new wrapper props after that
        // If we have new child props, and the same wrapper props, we know we should use the new child props as-is.
        // But, if we have new wrapper props, those might change the child props, so we have to recalculate things.
        // So, we'll use the child props from store update only if the wrapper props are the same as last time.
        if (
          childPropsFromStoreUpdate.current &&
          wrapperProps === lastWrapperProps.current
        ) {
          return childPropsFromStoreUpdate.current
        }

        // TODO We're reading the store directly in render() here. Bad idea?
        // This will likely cause Bad Things (TM) to happen in Concurrent Mode.
        // Note that we do this because on renders _not_ caused by store updates, we need the latest store state
        // to determine what the child props should be.
        return childPropsSelector(store.getState(), wrapperProps)
      }, [store, previousStateUpdateResult, wrapperProps])

      // We need this to execute synchronously every time we re-render. However, React warns
      // about useLayoutEffect in SSR, so we try to detect environment and fall back to
      // just useEffect instead to avoid the warning, since neither will run anyway.
      useIsomorphicLayoutEffectWithArgs(captureWrapperProps, [
        lastWrapperProps,
        lastChildProps,
        renderIsScheduled,
        wrapperProps,
        actualChildProps,
        childPropsFromStoreUpdate,
        notifyNestedSubs
      ])

      // Our re-subscribe logic only runs when the store/subscription setup changes
      useIsomorphicLayoutEffectWithArgs(
        subscribeUpdates,
        [
          shouldHandleStateChanges,
          store,
          subscription,
          childPropsSelector,
          lastWrapperProps,
          lastChildProps,
          renderIsScheduled,
          childPropsFromStoreUpdate,
          notifyNestedSubs,
          forceComponentUpdateDispatch
        ],
        [store, subscription, childPropsSelector]
      )

      // Now that all that's done, we can finally try to actually render the child component.
      // We memoize the elements for the rendered child component as an optimization.
      const renderedWrappedComponent = useMemo(
        () => <WrappedComponent {...actualChildProps} ref={forwardedRef} />,
        [forwardedRef, WrappedComponent, actualChildProps]
      )

      // If React sees the exact same element reference as last time, it bails out of re-rendering
      // that child, same as if it was wrapped in React.memo() or returned false from shouldComponentUpdate.
      const renderedChild = useMemo(() => {
        if (shouldHandleStateChanges) {
          // If this component is subscribed to store updates, we need to pass its own
          // subscription instance down to our descendants. That means rendering the same
          // Context instance, and putting a different value into the context.
          return (
            <ContextToUse.Provider value={overriddenContextValue}>
              {renderedWrappedComponent}
            </ContextToUse.Provider>
          )
        }

        return renderedWrappedComponent
      }, [ContextToUse, renderedWrappedComponent, overriddenContextValue])

      return renderedChild
    }

    // If we're in "pure" mode, ensure our wrapper component only re-renders when incoming props have changed.
    const Connect = pure ? React.memo(ConnectFunction) : ConnectFunction

    Connect.WrappedComponent = WrappedComponent
    Connect.displayName = displayName

    if (forwardRef) {
      const forwarded = React.forwardRef(function forwardConnectRef(
        props,
        ref
      ) {
        return <Connect {...props} forwardedRef={ref} />
      })

      forwarded.displayName = displayName
      forwarded.WrappedComponent = WrappedComponent
      return hoistStatics(forwarded, WrappedComponent)
    }

    return hoistStatics(Connect, WrappedComponent)
  }
}
<|endoftext|>


<commit_before>import Icon from '../icon'
import Input from '../input'
import s from './dual-list.scss'

const Dual = {}

Dual.Group = {
  name: 'DualGroup',
  props: {
    items: {
      type: Object,
      default: () => {
        return {}
      }
    },
    selectedItems: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      listToAdd: this.items,
      listToRemove: this.selectedItems,
      highlightLeft: '',
      highlightRight: '',
      leftList: this.items,
      rightList: this.selectedItems
    }
  },
  mounted() {
    const { handleChange, handleClickOnX } = this
    this.listToAdd = Object.assign({}, this.listToAdd)
    this.listToRemove = Object.assign({}, this.listToRemove)
    this.$on('handleSingleDualListChange', handleChange)
    this.$on('handleClickOnX', handleClickOnX)
  },
  methods: {
    handleChange(list) {
      if (list[0] === 'add') {
        delete this.leftList[list[2]]
        this.$set(this.rightList, list[2], list[1])
        delete this.listToAdd[list[2]]
        this.$set(this.listToRemove, list[2], list[1])
      } else if (list[0] === 'remove') {
        delete this.rightList[list[2]]
        this.$set(this.leftList, list[2], list[1])
        delete this.listToRemove[list[2]]
        this.$set(this.listToAdd, list[2], list[1])
      }
      this.$emit('change', this.rightList)
    },
    handleClickOnX(data) {
      if (data === 'left') {
        this.listToAdd = this.leftList
        this.highlightLeft = ''
      } else if (data === 'right') {
        this.listToRemove = this.rightList
        this.highlightRight = ''
      }
    },
    handleSelectAll() {
      const keys = Object.keys(this.listToAdd)
      keys.map((key) => {
        delete this.leftList[key]
      })
      this.rightList = Object.assign({}, this.rightList, this.listToAdd)
      this.listToRemove = Object.assign({}, this.listToRemove, this.listToAdd)
      this.listToAdd = {}
      this.$emit('change', this.rightList)
    },
    handleUnselectAll() {
      const keys = Object.keys(this.listToRemove)
      keys.map((key) => {
        delete this.rightList[key]
      })
      this.leftList = Object.assign({}, this.leftList, this.listToRemove)
      this.listToAdd = Object.assign({}, this.listToAdd, this.listToRemove)
      this.listToRemove = {}
      this.$emit('change', this.rightList)
    },
    handleSearchListLeft(e) {
      if (e.charCode === 13) {
        const keys = Object.keys(this.leftList).filter((key) => {
          return this.leftList[key].includes(this.$refs.searchListToAdd.value)
        })
        this.listToAdd = keys.reduce((preVal, curVal) => {
          return Object.assign(preVal, { [curVal]: this.leftList[curVal] })
        }, {})
        this.highlightLeft = this.$refs.searchListToAdd.value
      }
    },
    handleSearchListRight(e) {
      if (e.charCode === 13) {
        const keys = Object.keys(this.rightList).filter((key) => {
          return this.rightList[key].includes(this.$refs.searchListToRemove.value)
        })
        this.listToRemove = keys.reduce((preVal, curVal) => {
          return Object.assign(preVal, { [curVal]: this.rightList[curVal] })
        }, {})
        this.highlightRight = this.$refs.searchListToRemove.value
      }
    }
  },
  render(h) {
    const { handleSelectAll, handleUnselectAll, handleSearchListLeft, handleSearchListRight, highlightLeft, highlightRight } = this
    return (

            <Input name="left" class={[s.input]} ref="searchListToAdd" icon={['search', '#919799']} x={true} />

            {
              Object.keys(this.listToAdd).map((label) => {
                return <Dual.List id={label} name={this.listToAdd[label]} highlight={highlightLeft} icon={['circle-add', '#b9e617']} />
              })
            }

            <Icon class={[s.doubleRight]} typ="double-right" size={20} fill="#b8bdbf" />

            <Icon class={[s.doubleLeft]} typ="double-left" size={20} fill="#b8bdbf" />

            <Input name="right" class={[s.input]} ref="searchListToRemove" icon={['search', '#919799']} x={true} />

            {
              Object.keys(this.listToRemove).map((label) => {
                return <Dual.List id={label} name={this.listToRemove[label]} highlight={highlightRight} icon={['circle-minus', '#e6175c']} />
              })
            }

    )
  }
}

Dual.List = {
  name: 'DualList',
  props: {
    highlight: {
      type: String,
      default: '',
    },
    id: {
      type: String,
      default: '',
    },
    name: {
      type: String,
      default: '',
    },
    icon: {
      type: Array,
      default: ['circle-add', '#b9e617']
    }
  },

  computed: {
    highlightText() {
      const { highlight, name } = this
      let highlightText = ''
      if (highlight) {
        const highlightReg = new RegExp(`${highlight}`, 'g')
        highlightText = `<span>${name}</span>`.replace(highlightReg, `<span class="${s.highlight}">${highlight}</span>`)
      }
      return highlightText
    }
  },

  methods: {
    handleClick() {
      const { $parent, name, id } = this
      const manipulation = (this.icon[0] === 'circle-add') ? 'add' : 'remove'
      const data = [manipulation, name, id]
      $parent.$emit('handleSingleDualListChange', data)
    },
  },

  render(h) {
    const { name, icon, highlight, handleClick, highlightText } = this
    return (

        {highlight
          ?
          :
        }
        <Icon class={[s.icon]} typ={icon[0]} size={18} fill={icon[1]} />

    )
  }
}

module.exports = Dual
<commit_msg>[DualList] add case insensitive search and highlight<commit_after>import Icon from '../icon'
import Input from '../input'
import s from './dual-list.scss'

const Dual = {}

Dual.Group = {
  name: 'DualGroup',
  props: {
    items: {
      type: Object,
      default: () => {
        return {}
      }
    },
    selectedItems: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      listToAdd: this.items,
      listToRemove: this.selectedItems,
      highlightLeft: '',
      highlightRight: '',
      leftList: this.items,
      rightList: this.selectedItems
    }
  },
  mounted() {
    const { handleChange, handleClickOnX } = this
    this.listToAdd = Object.assign({}, this.listToAdd)
    this.listToRemove = Object.assign({}, this.listToRemove)
    this.$on('handleSingleDualListChange', handleChange)
    this.$on('handleClickOnX', handleClickOnX)
  },
  methods: {
    handleChange(list) {
      if (list[0] === 'add') {
        delete this.leftList[list[2]]
        this.$set(this.rightList, list[2], list[1])
        delete this.listToAdd[list[2]]
        this.$set(this.listToRemove, list[2], list[1])
      } else if (list[0] === 'remove') {
        delete this.rightList[list[2]]
        this.$set(this.leftList, list[2], list[1])
        delete this.listToRemove[list[2]]
        this.$set(this.listToAdd, list[2], list[1])
      }
      this.$emit('change', this.rightList)
    },
    handleClickOnX(data) {
      if (data === 'left') {
        this.listToAdd = this.leftList
        this.highlightLeft = ''
      } else if (data === 'right') {
        this.listToRemove = this.rightList
        this.highlightRight = ''
      }
    },
    handleSelectAll() {
      const keys = Object.keys(this.listToAdd)
      keys.map((key) => {
        delete this.leftList[key]
      })
      this.rightList = Object.assign({}, this.rightList, this.listToAdd)
      this.listToRemove = Object.assign({}, this.listToRemove, this.listToAdd)
      this.listToAdd = {}
      this.$emit('change', this.rightList)
    },
    handleUnselectAll() {
      const keys = Object.keys(this.listToRemove)
      keys.map((key) => {
        delete this.rightList[key]
      })
      this.leftList = Object.assign({}, this.leftList, this.listToRemove)
      this.listToAdd = Object.assign({}, this.listToAdd, this.listToRemove)
      this.listToRemove = {}
      this.$emit('change', this.rightList)
    },
    handleSearchListLeft(e) {
      if (e.charCode === 13) {
        const keys = Object.keys(this.leftList).filter((key) => {
          return this.leftList[key].toLowerCase().includes(this.$refs.searchListToAdd.value.toLowerCase())
        })
        this.listToAdd = keys.reduce((preVal, curVal) => {
          return Object.assign(preVal, { [curVal]: this.leftList[curVal] })
        }, {})
        this.highlightLeft = this.$refs.searchListToAdd.value
      }
    },
    handleSearchListRight(e) {
      if (e.charCode === 13) {
        const keys = Object.keys(this.rightList).filter((key) => {
          return this.rightList[key].toLowerCase().includes(this.$refs.searchListToRemove.value.toLowerCase())
        })
        this.listToRemove = keys.reduce((preVal, curVal) => {
          return Object.assign(preVal, { [curVal]: this.rightList[curVal] })
        }, {})
        this.highlightRight = this.$refs.searchListToRemove.value
      }
    }
  },
  render(h) {
    const { handleSelectAll, handleUnselectAll, handleSearchListLeft, handleSearchListRight, highlightLeft, highlightRight } = this
    return (

          <Input nativeOn-keypress={handleSearchListLeft} name="left" class={[s.input]} ref="searchListToAdd" icon={['search', '#919799']} x={true} />

            {
              Object.keys(this.listToAdd).map((label) => {
                return <Dual.List id={label} name={this.listToAdd[label]} highlight={highlightLeft} icon={['circle-add', '#b9e617']} />
              })
            }

            <Icon class={[s.doubleRight]} typ="double-right" size={20} fill="#b8bdbf" />

            <Icon class={[s.doubleLeft]} typ="double-left" size={20} fill="#b8bdbf" />

          <Input nativeOn-keypress={handleSearchListRight} name="right" class={[s.input]} ref="searchListToRemove" icon={['search', '#919799']} x={true} />

            {
              Object.keys(this.listToRemove).map((label) => {
                return <Dual.List id={label} name={this.listToRemove[label]} highlight={highlightRight} icon={['circle-minus', '#e6175c']} />
              })
            }

    )
  }
}

Dual.List = {
  name: 'DualList',
  props: {
    highlight: {
      type: String,
      default: '',
    },
    id: {
      type: String,
      default: '',
    },
    name: {
      type: String,
      default: '',
    },
    icon: {
      type: Array,
      default: ['circle-add', '#b9e617']
    }
  },

  computed: {
    highlightText() {
      const { highlight, name } = this
      let highlightText = ''
      if (highlight) {
        const highlightReg = new RegExp(`${highlight}`, 'gi')
        highlightText = `<span>${name}</span>`.replace(highlightReg, (replacement) => {
          return `<span class="${s.highlight}">${replacement}</span>`
        })
      }
      return highlightText
    }
  },

  methods: {
    handleClick() {
      const { $parent, name, id } = this
      const manipulation = (this.icon[0] === 'circle-add') ? 'add' : 'remove'
      const data = [manipulation, name, id]
      $parent.$emit('handleSingleDualListChange', data)
    },
  },

  render(h) {
    const { name, icon, highlight, handleClick, highlightText } = this
    return (

        {highlight
          ?
          :
        }
        <Icon class={[s.icon]} typ={icon[0]} size={18} fill={icon[1]} />

    )
  }
}

module.exports = Dual
<|endoftext|>


<commit_before>/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Plotly = require('../../plotly');
var Lib = require('../../lib');
var setCursor = require('../../lib/setcursor');
var Snapshot = require('../../snapshot');
var Icons = require('../../../build/ploticon');

var modeBarButtons = module.exports = {};

/**
 * ModeBar buttons configuration
 *
 * @param {string} name
 *      name / id of the buttons (for tracking)
 * @param {string} title
 *      text that appears while hovering over the button,
 *      enter null, false or '' for no hover text
 * @param {string} icon
 *      svg icon object associated with the button
 *      can be linked to Plotly.Icons to use the default plotly icons
 * @param {string} [gravity]
 *      icon positioning
 * @param {function} click
 *      click handler associated with the button, a function of
 *      'gd' (the main graph object) and
 *      'ev' (the event object)
 * @param {string} [attr]
 *      attribute associated with button,
 *      use this with 'val' to keep track of the state
 * @param {*} [val]
 *      initial 'attr' value, can be a function of gd
 * @param {boolean} [toggle]
 *      is the button a toggle button?
 */

modeBarButtons.toImage = {
    name: 'toImage',
    title: 'Download plot as a png',
    icon: Icons.camera,
    click: function(gd) {
        var format = 'png';

        if(Lib.isIE()) {
            Lib.notifier('Snapshotting is unavailable in Internet Explorer. ' +
                         'Consider exporting your images using the Plotly Cloud', 'long');
            return;
        }

        if(gd._snapshotInProgress) {
            Lib.notifier('Snapshotting is still in progress - please hold', 'long');
            return;
        }

        gd._snapshotInProgress = true;
        Lib.notifier('Taking snapshot - this may take a few seconds', 'long');

        var ev = Snapshot.toImage(gd, {format: format});

        var filename = gd.fn || 'newplot';
        filename += '.' + format;

        ev.once('success', function(result) {
            gd._snapshotInProgress = false;

            var downloadLink = document.createElement('a');
            downloadLink.href = result;
            downloadLink.download = filename; // only supported by FF and Chrome

            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);

            ev.clean();
        });

        ev.once('error', function(err) {
            gd._snapshotInProgress = false;

            Lib.notifier('Sorry there was a problem downloading your ' + format, 'long');
            console.error(err);

            ev.clean();
        });
    }
};

modeBarButtons.sendDataToCloud = {
    name: 'sendDataToCloud',
    title: 'Save and edit plot in cloud',
    icon: Icons.disk,
    click: function(gd) {
        Plotly.Plots.sendDataToCloud(gd);
    }
};

modeBarButtons.zoom2d = {
    name: 'zoom2d',
    title: 'Zoom',
    attr: 'dragmode',
    val: 'zoom',
    icon: Icons.zoombox,
    click: handleCartesian
};

modeBarButtons.pan2d = {
    name: 'pan2d',
    title: 'Pan',
    attr: 'dragmode',
    val: 'pan',
    icon: Icons.pan,
    click: handleCartesian
};

modeBarButtons.select2d = {
    name: 'select2d',
    title: 'Box Select',
    attr: 'dragmode',
    val: 'select',
    icon: Icons.selectbox,
    click: handleCartesian
};

modeBarButtons.lasso2d = {
    name: 'lasso2d',
    title: 'Lasso Select',
    attr: 'dragmode',
    val: 'lasso',
    icon: Icons.lasso,
    click: handleCartesian
};

modeBarButtons.zoomIn2d = {
    name: 'zoomIn2d',
    title: 'Zoom in',
    attr: 'zoom',
    val: 'in',
    icon: Icons.zoom_plus,
    click: handleCartesian
};

modeBarButtons.zoomOut2d = {
    name: 'zoomOut2d',
    title: 'Zoom out',
    attr: 'zoom',
    val: 'out',
    icon: Icons.zoom_minus,
    click: handleCartesian
};

modeBarButtons.autoScale2d = {
    name: 'autoScale2d',
    title: 'Autoscale',
    attr: 'zoom',
    val: 'auto',
    icon: Icons.autoscale,
    click: handleCartesian
};

modeBarButtons.resetScale2d = {
    name: 'resetScale2d',
    title: 'Reset axes',
    attr: 'zoom',
    val: 'reset',
    icon: Icons.home,
    click: handleCartesian
};

modeBarButtons.hoverClosestCartesian = {
    name: 'hoverClosestCartesian',
    title: 'Show closest data on hover',
    attr: 'hovermode',
    val: 'closest',
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: handleCartesian
};

modeBarButtons.hoverCompareCartesian = {
    name: 'hoverCompareCartesian',
    title: 'Compare data on hover',
    attr: 'hovermode',
    val: function(gd) {
        return gd._fullLayout._isHoriz ? 'y' : 'x';
    },
    icon: Icons.tooltip_compare,
    gravity: 'ne',
    click: handleCartesian
};

var DRAGCURSORS = {
    pan: 'move',
    zoom: 'crosshair',
    select: 'crosshair',
    lasso: 'crosshair'
};

function handleCartesian(gd, ev) {
    var button = ev.currentTarget,
        astr = button.getAttribute('data-attr'),
        val = button.getAttribute('data-val') || true,
        fullLayout = gd._fullLayout,
        aobj = {};

    if(astr === 'zoom') {
        var mag = (val === 'in') ? 0.5 : 2,
            r0 = (1 + mag) / 2,
            r1 = (1 - mag) / 2,
            axList = Plotly.Axes.list(gd, null, true);

        var ax, axName;

        for(var i = 0; i < axList.length; i++) {
            ax = axList[i];

            if(!ax.fixedrange) {
                axName = ax._name;
                if(val === 'auto') aobj[axName + '.autorange'] = true;
                else if(val === 'reset') {
                    if(ax._rangeInitial === undefined) {
                        aobj[axName + '.autorange'] = true;
                    }
                    else {
                        var rangeInitial = ax._rangeInitial.slice();
                        aobj[axName + '.range[0]'] = rangeInitial[0];
                        aobj[axName + '.range[1]'] = rangeInitial[1];
                    }
                }
                else {
                    var rangeNow = ax.range;
                    aobj[axName + '.range[0]'] = r0 * rangeNow[0] + r1 * rangeNow[1];
                    aobj[axName + '.range[1]'] = r0 * rangeNow[1] + r1 * rangeNow[0];
                }
            }
        }
    }
    else {
        // if ALL traces have orientation 'h', 'hovermode': 'x' otherwise: 'y'
        if(astr==='hovermode' && (val==='x' || val==='y')) {
            val = fullLayout._isHoriz ? 'y' : 'x';
            button.setAttribute('data-val', val);
        }

        aobj[astr] = val;
    }

    console.log(aobj);

    Plotly.relayout(gd, aobj).then(function() {
        if(astr === 'dragmode') {
            if(fullLayout._hasCartesian) {
                setCursor(
                    fullLayout._paper.select('.nsewdrag'),
                    DRAGCURSORS[val]
                );
            }
            Plotly.Fx.supplyLayoutDefaults(gd.layout, fullLayout, gd._fullData);
            Plotly.Fx.init(gd);
        }
    });
}

modeBarButtons.zoom3d = {
    name: 'zoom3d',
    title: 'Zoom',
    attr: 'scene.dragmode',
    val: 'zoom',
    icon: Icons.zoombox,
    click: handleDrag3d
};

modeBarButtons.pan3d = {
    name: 'pan3d',
    title: 'Pan',
    attr: 'scene.dragmode',
    val: 'pan',
    icon: Icons.pan,
    click: handleDrag3d
};

modeBarButtons.orbitRotation = {
    name: 'orbitRotation',
    title: 'orbital rotation',
    attr: 'scene.dragmode',
    val: 'orbit',
    icon: Icons['3d_rotate'],
    click: handleDrag3d
};

modeBarButtons.tableRotation = {
    name: 'tableRotation',
    title: 'turntable rotation',
    attr: 'scene.dragmode',
    val: 'turntable',
    icon: Icons['z-axis'],
    click: handleDrag3d
};

function handleDrag3d(gd, ev) {
    var button = ev.currentTarget,
        attr = button.getAttribute('data-attr'),
        val = button.getAttribute('data-val') || true,
        fullLayout = gd._fullLayout,
        sceneIds = Plotly.Plots.getSubplotIds(fullLayout, 'gl3d'),
        layoutUpdate = {};

    var parts = attr.split('.');

    for(var i = 0; i < sceneIds.length; i++) {
        layoutUpdate[sceneIds[i] + '.' + parts[1]] = val;
    }

    Plotly.relayout(gd, layoutUpdate);
}

modeBarButtons.resetCameraDefault3d = {
    name: 'resetCameraDefault3d',
    title: 'Reset camera to default',
    attr: 'resetDefault',
    icon: Icons.home,
    click: handleCamera3d
};

modeBarButtons.resetCameraLastSave3d = {
    name: 'resetCameraLastSave3d',
    title: 'Reset camera to last save',
    attr: 'resetLastSave',
    icon: Icons.movie,
    click: handleCamera3d
};

function handleCamera3d(gd, ev) {
    var button = ev.currentTarget,
        attr = button.getAttribute('data-attr'),
        fullLayout = gd._fullLayout,
        sceneIds = Plotly.Plots.getSubplotIds(fullLayout, 'gl3d');

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneId = sceneIds[i],
            fullSceneLayout = fullLayout[sceneId],
            scene = fullSceneLayout._scene;

        if(attr === 'resetDefault') scene.setCameraToDefault();
        else if(attr === 'resetLastSave') {
            scene.setCamera(fullSceneLayout.camera);
        }
    }
}

modeBarButtons.hoverClosest3d = {
    name: 'hoverClosest3d',
    title: 'Toggle show closest data on hover',
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: handleHover3d
};

function handleHover3d(gd, ev) {
    var button = ev.currentTarget,
        val = button._previousVal || false,
        layout = gd.layout,
        fullLayout = gd._fullLayout,
        sceneIds = Plotly.Plots.getSubplotIds(fullLayout, 'gl3d');

    var axes = ['xaxis', 'yaxis', 'zaxis'],
        spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor'];

    // initialize 'current spike' object to be stored in the DOM
    var currentSpikes = {},
        axisSpikes = {},
        layoutUpdate = {};

    if(val) {
        layoutUpdate = Lib.extendDeep(layout, val);
        button._previousVal = null;
    }
    else {
        layoutUpdate = {
            'allaxes.showspikes': false
        };

        for(var i = 0; i < sceneIds.length; i++) {
            var sceneId = sceneIds[i],
                sceneLayout = fullLayout[sceneId],
                sceneSpikes = currentSpikes[sceneId] = {};

            sceneSpikes.hovermode = sceneLayout.hovermode;
            layoutUpdate[sceneId + '.hovermode'] = false;

            // copy all the current spike attrs
            for(var j = 0; j < 3; j++) {
                var axis = axes[j];
                axisSpikes = sceneSpikes[axis] = {};

                for(var k = 0; k < spikeAttrs.length; k++) {
                    var spikeAttr = spikeAttrs[k];
                    axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr];
                }
            }
        }

        button._previousVal = Lib.extendDeep({}, currentSpikes);
    }

    Plotly.relayout(gd, layoutUpdate);
}

modeBarButtons.zoomInGeo = {
    name: 'zoomInGeo',
    title: 'Zoom in',
    attr: 'zoom',
    val: 'in',
    icon: Icons.zoom_plus,
    click: handleGeo
};

modeBarButtons.zoomOutGeo = {
    name: 'zoomOutGeo',
    title: 'Zoom out',
    attr: 'zoom',
    val: 'out',
    icon: Icons.zoom_minus,
    click: handleGeo
};

modeBarButtons.resetGeo = {
    name: 'resetGeo',
    title: 'Reset',
    attr: 'reset',
    val: null,
    icon: Icons.autoscale,
    click: handleGeo
};

modeBarButtons.hoverClosestGeo = {
    name: 'hoverClosestGeo',
    title: 'Toggle show closest data on hover',
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

function handleGeo(gd, ev) {
    var button = ev.currentTarget,
        attr = button.getAttribute('data-attr'),
        val = button.getAttribute('data-val') || true,
        fullLayout = gd._fullLayout,
        geoIds = Plotly.Plots.getSubplotIds(fullLayout, 'geo');

    for(var i = 0; i < geoIds.length; i++) {
        var geo = fullLayout[geoIds[i]]._geo;

        if(attr === 'zoom') {
            var scale = geo.projection.scale();
            var newScale = (val === 'in') ? 2 * scale : 0.5 * scale;
            geo.projection.scale(newScale);
            geo.zoom.scale(newScale);
            geo.render();
        }
        else if(attr === 'reset') geo.zoomReset();
    }
}

modeBarButtons.hoverClosestGl2d = {
    name: 'hoverClosestGl2d',
    title: 'Toggle show closest data on hover',
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

modeBarButtons.hoverClosestPie = {
    name: 'hoverClosestPie',
    title: 'Toggle show closest data on hover',
    attr: 'hovermode',
    val: 'closest',
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

function toggleHover(gd) {
    var fullLayout = gd._fullLayout;

    var onHoverVal;
    if(fullLayout._hasCartesian) {
        onHoverVal = fullLayout._isHoriz ? 'y' : 'x';
    }
    else onHoverVal = 'closest';

    var newHover = gd._fullLayout.hovermode ? false : onHoverVal;

    Plotly.relayout(gd, 'hovermode', newHover);
}

// buttons when more then one plot types are present

modeBarButtons.toggleHover = {
    name: 'toggleHover',
    title: 'Toggle show closest data on hover',
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: function(gd, ev) {
        toggleHover(gd);

        // the 3d hovermode update must come
        // last so that layout.hovermode update does not
        // override scene?.hovermode?.layout.
        handleHover3d(gd, ev);
    }
};

modeBarButtons.resetViews = {
    name: 'resetViews',
    title: 'Reset views',
    icon: Icons.home,
    click: function(gd, ev) {
        var button = ev.currentTarget;

        button.setAttribute('data-attr', 'zoom');
        button.setAttribute('data-val', 'reset');
        handleCartesian(gd, ev);

        button.setAttribute('data-attr', 'resetLastSave');
        handleCamera3d(gd, ev);

        // N.B handleCamera3d also triggers a replot for
        // geo subplots.
    }
};
<commit_msg>:cow2: rm log<commit_after>/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Plotly = require('../../plotly');
var Lib = require('../../lib');
var setCursor = require('../../lib/setcursor');
var Snapshot = require('../../snapshot');
var Icons = require('../../../build/ploticon');

var modeBarButtons = module.exports = {};

/**
 * ModeBar buttons configuration
 *
 * @param {string} name
 *      name / id of the buttons (for tracking)
 * @param {string} title
 *      text that appears while hovering over the button,
 *      enter null, false or '' for no hover text
 * @param {string} icon
 *      svg icon object associated with the button
 *      can be linked to Plotly.Icons to use the default plotly icons
 * @param {string} [gravity]
 *      icon positioning
 * @param {function} click
 *      click handler associated with the button, a function of
 *      'gd' (the main graph object) and
 *      'ev' (the event object)
 * @param {string} [attr]
 *      attribute associated with button,
 *      use this with 'val' to keep track of the state
 * @param {*} [val]
 *      initial 'attr' value, can be a function of gd
 * @param {boolean} [toggle]
 *      is the button a toggle button?
 */

modeBarButtons.toImage = {
    name: 'toImage',
    title: 'Download plot as a png',
    icon: Icons.camera,
    click: function(gd) {
        var format = 'png';

        if(Lib.isIE()) {
            Lib.notifier('Snapshotting is unavailable in Internet Explorer. ' +
                         'Consider exporting your images using the Plotly Cloud', 'long');
            return;
        }

        if(gd._snapshotInProgress) {
            Lib.notifier('Snapshotting is still in progress - please hold', 'long');
            return;
        }

        gd._snapshotInProgress = true;
        Lib.notifier('Taking snapshot - this may take a few seconds', 'long');

        var ev = Snapshot.toImage(gd, {format: format});

        var filename = gd.fn || 'newplot';
        filename += '.' + format;

        ev.once('success', function(result) {
            gd._snapshotInProgress = false;

            var downloadLink = document.createElement('a');
            downloadLink.href = result;
            downloadLink.download = filename; // only supported by FF and Chrome

            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);

            ev.clean();
        });

        ev.once('error', function(err) {
            gd._snapshotInProgress = false;

            Lib.notifier('Sorry there was a problem downloading your ' + format, 'long');
            console.error(err);

            ev.clean();
        });
    }
};

modeBarButtons.sendDataToCloud = {
    name: 'sendDataToCloud',
    title: 'Save and edit plot in cloud',
    icon: Icons.disk,
    click: function(gd) {
        Plotly.Plots.sendDataToCloud(gd);
    }
};

modeBarButtons.zoom2d = {
    name: 'zoom2d',
    title: 'Zoom',
    attr: 'dragmode',
    val: 'zoom',
    icon: Icons.zoombox,
    click: handleCartesian
};

modeBarButtons.pan2d = {
    name: 'pan2d',
    title: 'Pan',
    attr: 'dragmode',
    val: 'pan',
    icon: Icons.pan,
    click: handleCartesian
};

modeBarButtons.select2d = {
    name: 'select2d',
    title: 'Box Select',
    attr: 'dragmode',
    val: 'select',
    icon: Icons.selectbox,
    click: handleCartesian
};

modeBarButtons.lasso2d = {
    name: 'lasso2d',
    title: 'Lasso Select',
    attr: 'dragmode',
    val: 'lasso',
    icon: Icons.lasso,
    click: handleCartesian
};

modeBarButtons.zoomIn2d = {
    name: 'zoomIn2d',
    title: 'Zoom in',
    attr: 'zoom',
    val: 'in',
    icon: Icons.zoom_plus,
    click: handleCartesian
};

modeBarButtons.zoomOut2d = {
    name: 'zoomOut2d',
    title: 'Zoom out',
    attr: 'zoom',
    val: 'out',
    icon: Icons.zoom_minus,
    click: handleCartesian
};

modeBarButtons.autoScale2d = {
    name: 'autoScale2d',
    title: 'Autoscale',
    attr: 'zoom',
    val: 'auto',
    icon: Icons.autoscale,
    click: handleCartesian
};

modeBarButtons.resetScale2d = {
    name: 'resetScale2d',
    title: 'Reset axes',
    attr: 'zoom',
    val: 'reset',
    icon: Icons.home,
    click: handleCartesian
};

modeBarButtons.hoverClosestCartesian = {
    name: 'hoverClosestCartesian',
    title: 'Show closest data on hover',
    attr: 'hovermode',
    val: 'closest',
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: handleCartesian
};

modeBarButtons.hoverCompareCartesian = {
    name: 'hoverCompareCartesian',
    title: 'Compare data on hover',
    attr: 'hovermode',
    val: function(gd) {
        return gd._fullLayout._isHoriz ? 'y' : 'x';
    },
    icon: Icons.tooltip_compare,
    gravity: 'ne',
    click: handleCartesian
};

var DRAGCURSORS = {
    pan: 'move',
    zoom: 'crosshair',
    select: 'crosshair',
    lasso: 'crosshair'
};

function handleCartesian(gd, ev) {
    var button = ev.currentTarget,
        astr = button.getAttribute('data-attr'),
        val = button.getAttribute('data-val') || true,
        fullLayout = gd._fullLayout,
        aobj = {};

    if(astr === 'zoom') {
        var mag = (val === 'in') ? 0.5 : 2,
            r0 = (1 + mag) / 2,
            r1 = (1 - mag) / 2,
            axList = Plotly.Axes.list(gd, null, true);

        var ax, axName;

        for(var i = 0; i < axList.length; i++) {
            ax = axList[i];

            if(!ax.fixedrange) {
                axName = ax._name;
                if(val === 'auto') aobj[axName + '.autorange'] = true;
                else if(val === 'reset') {
                    if(ax._rangeInitial === undefined) {
                        aobj[axName + '.autorange'] = true;
                    }
                    else {
                        var rangeInitial = ax._rangeInitial.slice();
                        aobj[axName + '.range[0]'] = rangeInitial[0];
                        aobj[axName + '.range[1]'] = rangeInitial[1];
                    }
                }
                else {
                    var rangeNow = ax.range;
                    aobj[axName + '.range[0]'] = r0 * rangeNow[0] + r1 * rangeNow[1];
                    aobj[axName + '.range[1]'] = r0 * rangeNow[1] + r1 * rangeNow[0];
                }
            }
        }
    }
    else {
        // if ALL traces have orientation 'h', 'hovermode': 'x' otherwise: 'y'
        if(astr==='hovermode' && (val==='x' || val==='y')) {
            val = fullLayout._isHoriz ? 'y' : 'x';
            button.setAttribute('data-val', val);
        }

        aobj[astr] = val;
    }

    Plotly.relayout(gd, aobj).then(function() {
        if(astr === 'dragmode') {
            if(fullLayout._hasCartesian) {
                setCursor(
                    fullLayout._paper.select('.nsewdrag'),
                    DRAGCURSORS[val]
                );
            }
            Plotly.Fx.supplyLayoutDefaults(gd.layout, fullLayout, gd._fullData);
            Plotly.Fx.init(gd);
        }
    });
}

modeBarButtons.zoom3d = {
    name: 'zoom3d',
    title: 'Zoom',
    attr: 'scene.dragmode',
    val: 'zoom',
    icon: Icons.zoombox,
    click: handleDrag3d
};

modeBarButtons.pan3d = {
    name: 'pan3d',
    title: 'Pan',
    attr: 'scene.dragmode',
    val: 'pan',
    icon: Icons.pan,
    click: handleDrag3d
};

modeBarButtons.orbitRotation = {
    name: 'orbitRotation',
    title: 'orbital rotation',
    attr: 'scene.dragmode',
    val: 'orbit',
    icon: Icons['3d_rotate'],
    click: handleDrag3d
};

modeBarButtons.tableRotation = {
    name: 'tableRotation',
    title: 'turntable rotation',
    attr: 'scene.dragmode',
    val: 'turntable',
    icon: Icons['z-axis'],
    click: handleDrag3d
};

function handleDrag3d(gd, ev) {
    var button = ev.currentTarget,
        attr = button.getAttribute('data-attr'),
        val = button.getAttribute('data-val') || true,
        fullLayout = gd._fullLayout,
        sceneIds = Plotly.Plots.getSubplotIds(fullLayout, 'gl3d'),
        layoutUpdate = {};

    var parts = attr.split('.');

    for(var i = 0; i < sceneIds.length; i++) {
        layoutUpdate[sceneIds[i] + '.' + parts[1]] = val;
    }

    Plotly.relayout(gd, layoutUpdate);
}

modeBarButtons.resetCameraDefault3d = {
    name: 'resetCameraDefault3d',
    title: 'Reset camera to default',
    attr: 'resetDefault',
    icon: Icons.home,
    click: handleCamera3d
};

modeBarButtons.resetCameraLastSave3d = {
    name: 'resetCameraLastSave3d',
    title: 'Reset camera to last save',
    attr: 'resetLastSave',
    icon: Icons.movie,
    click: handleCamera3d
};

function handleCamera3d(gd, ev) {
    var button = ev.currentTarget,
        attr = button.getAttribute('data-attr'),
        fullLayout = gd._fullLayout,
        sceneIds = Plotly.Plots.getSubplotIds(fullLayout, 'gl3d');

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneId = sceneIds[i],
            fullSceneLayout = fullLayout[sceneId],
            scene = fullSceneLayout._scene;

        if(attr === 'resetDefault') scene.setCameraToDefault();
        else if(attr === 'resetLastSave') {
            scene.setCamera(fullSceneLayout.camera);
        }
    }
}

modeBarButtons.hoverClosest3d = {
    name: 'hoverClosest3d',
    title: 'Toggle show closest data on hover',
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: handleHover3d
};

function handleHover3d(gd, ev) {
    var button = ev.currentTarget,
        val = button._previousVal || false,
        layout = gd.layout,
        fullLayout = gd._fullLayout,
        sceneIds = Plotly.Plots.getSubplotIds(fullLayout, 'gl3d');

    var axes = ['xaxis', 'yaxis', 'zaxis'],
        spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor'];

    // initialize 'current spike' object to be stored in the DOM
    var currentSpikes = {},
        axisSpikes = {},
        layoutUpdate = {};

    if(val) {
        layoutUpdate = Lib.extendDeep(layout, val);
        button._previousVal = null;
    }
    else {
        layoutUpdate = {
            'allaxes.showspikes': false
        };

        for(var i = 0; i < sceneIds.length; i++) {
            var sceneId = sceneIds[i],
                sceneLayout = fullLayout[sceneId],
                sceneSpikes = currentSpikes[sceneId] = {};

            sceneSpikes.hovermode = sceneLayout.hovermode;
            layoutUpdate[sceneId + '.hovermode'] = false;

            // copy all the current spike attrs
            for(var j = 0; j < 3; j++) {
                var axis = axes[j];
                axisSpikes = sceneSpikes[axis] = {};

                for(var k = 0; k < spikeAttrs.length; k++) {
                    var spikeAttr = spikeAttrs[k];
                    axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr];
                }
            }
        }

        button._previousVal = Lib.extendDeep({}, currentSpikes);
    }

    Plotly.relayout(gd, layoutUpdate);
}

modeBarButtons.zoomInGeo = {
    name: 'zoomInGeo',
    title: 'Zoom in',
    attr: 'zoom',
    val: 'in',
    icon: Icons.zoom_plus,
    click: handleGeo
};

modeBarButtons.zoomOutGeo = {
    name: 'zoomOutGeo',
    title: 'Zoom out',
    attr: 'zoom',
    val: 'out',
    icon: Icons.zoom_minus,
    click: handleGeo
};

modeBarButtons.resetGeo = {
    name: 'resetGeo',
    title: 'Reset',
    attr: 'reset',
    val: null,
    icon: Icons.autoscale,
    click: handleGeo
};

modeBarButtons.hoverClosestGeo = {
    name: 'hoverClosestGeo',
    title: 'Toggle show closest data on hover',
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

function handleGeo(gd, ev) {
    var button = ev.currentTarget,
        attr = button.getAttribute('data-attr'),
        val = button.getAttribute('data-val') || true,
        fullLayout = gd._fullLayout,
        geoIds = Plotly.Plots.getSubplotIds(fullLayout, 'geo');

    for(var i = 0; i < geoIds.length; i++) {
        var geo = fullLayout[geoIds[i]]._geo;

        if(attr === 'zoom') {
            var scale = geo.projection.scale();
            var newScale = (val === 'in') ? 2 * scale : 0.5 * scale;
            geo.projection.scale(newScale);
            geo.zoom.scale(newScale);
            geo.render();
        }
        else if(attr === 'reset') geo.zoomReset();
    }
}

modeBarButtons.hoverClosestGl2d = {
    name: 'hoverClosestGl2d',
    title: 'Toggle show closest data on hover',
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

modeBarButtons.hoverClosestPie = {
    name: 'hoverClosestPie',
    title: 'Toggle show closest data on hover',
    attr: 'hovermode',
    val: 'closest',
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

function toggleHover(gd) {
    var fullLayout = gd._fullLayout;

    var onHoverVal;
    if(fullLayout._hasCartesian) {
        onHoverVal = fullLayout._isHoriz ? 'y' : 'x';
    }
    else onHoverVal = 'closest';

    var newHover = gd._fullLayout.hovermode ? false : onHoverVal;

    Plotly.relayout(gd, 'hovermode', newHover);
}

// buttons when more then one plot types are present

modeBarButtons.toggleHover = {
    name: 'toggleHover',
    title: 'Toggle show closest data on hover',
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: function(gd, ev) {
        toggleHover(gd);

        // the 3d hovermode update must come
        // last so that layout.hovermode update does not
        // override scene?.hovermode?.layout.
        handleHover3d(gd, ev);
    }
};

modeBarButtons.resetViews = {
    name: 'resetViews',
    title: 'Reset views',
    icon: Icons.home,
    click: function(gd, ev) {
        var button = ev.currentTarget;

        button.setAttribute('data-attr', 'zoom');
        button.setAttribute('data-val', 'reset');
        handleCartesian(gd, ev);

        button.setAttribute('data-attr', 'resetLastSave');
        handleCamera3d(gd, ev);

        // N.B handleCamera3d also triggers a replot for
        // geo subplots.
    }
};
<|endoftext|>