<commit_before>/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @emails react-core
 */

'use strict';

var React = require('React');
var ReactDOM = require('ReactDOM');
var ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');

describe('ReactDOMFiber', () => {
  var container;

  beforeEach(() => {
    container = document.createElement('div');
  });

  it('should render strings as children', () => {
    const Box = ({value}) =>
{value}
;

    ReactDOM.render(
      <Box value="foo" />,
      container
    );
    expect(container.textContent).toEqual('foo');
  });

  it('should render numbers as children', () => {
    const Box = ({value}) =>
{value}
;

    ReactDOM.render(
      <Box value={10} />,
      container
    );

    expect(container.textContent).toEqual('10');
  });

  it('should be called a callback argument', () => {
    // mounting phase
    let called = false;
    ReactDOM.render(

Foo
,
      container,
      () => called = true
    );
    expect(called).toEqual(true);

    // updating phase
    called = false;
    ReactDOM.render(

Foo
,
      container,
      () => called = true
    );
    expect(called).toEqual(true);
  });

  if (ReactDOMFeatureFlags.useFiber) {
    it('should render a component returning strings directly from render', () => {
      const Text = ({value}) => value;

      ReactDOM.render(
        <Text value="foo" />,
        container
      );
      expect(container.textContent).toEqual('foo');
    });

    it('should render a component returning numbers directly from render', () => {
      const Text = ({value}) => value;

      ReactDOM.render(
        <Text value={10} />,
        container
      );

      expect(container.textContent).toEqual('10');
    });

    it('finds the DOM Text node of a string child', () => {
      class Text extends React.Component {
        render() {
          return this.props.value;
        }
      }

      let instance = null;
      ReactDOM.render(
        <Text value="foo" ref={ref => instance = ref} />,
        container
      );

      const textNode = ReactDOM.findDOMNode(instance);
      expect(textNode).toBe(container.firstChild);
      expect(textNode.nodeType).toBe(3);
      expect(textNode.nodeValue).toBe('foo');
    });

    it('finds the first child when a component returns a fragment', () => {
      class Fragment extends React.Component {
        render() {
          return [

,
            ,
          ];
        }
      }

      let instance = null;
      ReactDOM.render(
        <Fragment ref={ref => instance = ref} />,
        container
      );

      expect(container.childNodes.length).toBe(2);

      const firstNode = ReactDOM.findDOMNode(instance);
      expect(firstNode).toBe(container.firstChild);
      expect(firstNode.tagName).toBe('DIV');
    });

    it('finds the first child even when fragment is nested', () => {
      class Wrapper extends React.Component {
        render() {
          return this.props.children;
        }
      }

      class Fragment extends React.Component {
        render() {
          return [
            <Wrapper>
</Wrapper>,
            ,
          ];
        }
      }

      let instance = null;
      ReactDOM.render(
        <Fragment ref={ref => instance = ref} />,
        container
      );

      expect(container.childNodes.length).toBe(2);

      const firstNode = ReactDOM.findDOMNode(instance);
      expect(firstNode).toBe(container.firstChild);
      expect(firstNode.tagName).toBe('DIV');
    });

    it('finds the first child even when first child renders null', () => {
      class NullComponent extends React.Component {
        render() {
          return null;
        }
      }

      class Fragment extends React.Component {
        render() {
          return [
            <NullComponent />,

,
            ,
          ];
        }
      }

      let instance = null;
      ReactDOM.render(
        <Fragment ref={ref => instance = ref} />,
        container
      );

      expect(container.childNodes.length).toBe(2);

      const firstNode = ReactDOM.findDOMNode(instance);
      expect(firstNode).toBe(container.firstChild);
      expect(firstNode.tagName).toBe('DIV');
    });
  }

  if (ReactDOMFeatureFlags.useFiber) {
    it('should render one portal', () => {
      var portalContainer = document.createElement('div');

      ReactDOM.render(

          {ReactDOM.unstable_createPortal(

portal
,
            portalContainer
          )}

,
        container
      );
      expect(portalContainer.innerHTML).toBe('
portal
');
      expect(container.innerHTML).toBe('

');

      ReactDOM.unmountComponentAtNode(container);
      expect(portalContainer.innerHTML).toBe('');
      expect(container.innerHTML).toBe('');
    });

    it('should render many portals', () => {
      var portalContainer1 = document.createElement('div');
      var portalContainer2 = document.createElement('div');

      var ops = [];
      class Child extends React.Component {
        componentDidMount() {
          ops.push(`${this.props.name} componentDidMount`);
        }
        componentDidUpdate() {
          ops.push(`${this.props.name} componentDidUpdate`);
        }
        componentWillUnmount() {
          ops.push(`${this.props.name} componentWillUnmount`);
        }
        render() {
          return
{this.props.name}
;
        }
      }

      class Parent extends React.Component {
        componentDidMount() {
          ops.push(`Parent:${this.props.step} componentDidMount`);
        }
        componentDidUpdate() {
          ops.push(`Parent:${this.props.step} componentDidUpdate`);
        }
        componentWillUnmount() {
          ops.push(`Parent:${this.props.step} componentWillUnmount`);
        }
        render() {
          const {step} = this.props;
          return [
            <Child name={`normal[0]:${step}`} />,
            ReactDOM.unstable_createPortal(
              <Child name={`portal1[0]:${step}`} />,
              portalContainer1
            ),
            <Child name={`normal[1]:${step}`} />,
            ReactDOM.unstable_createPortal(
              [
                <Child name={`portal2[0]:${step}`} />,
                <Child name={`portal2[1]:${step}`} />,
              ],
              portalContainer2
            ),
          ];
        }
      }

      ReactDOM.render(<Parent step="a" />, container);
      expect(portalContainer1.innerHTML).toBe('
portal1[0]:a
');
      expect(portalContainer2.innerHTML).toBe('
portal2[0]:a

portal2[1]:a
');
      expect(container.innerHTML).toBe('
normal[0]:a

normal[1]:a
');
      expect(ops).toEqual([
        'normal[0]:a componentDidMount',
        'portal1[0]:a componentDidMount',
        'normal[1]:a componentDidMount',
        'portal2[0]:a componentDidMount',
        'portal2[1]:a componentDidMount',
        'Parent:a componentDidMount',
      ]);

      ops.length = 0;
      ReactDOM.render(<Parent step="b" />, container);
      expect(portalContainer1.innerHTML).toBe('
portal1[0]:b
');
      expect(portalContainer2.innerHTML).toBe('
portal2[0]:b

portal2[1]:b
');
      expect(container.innerHTML).toBe('
normal[0]:b

normal[1]:b
');
      expect(ops).toEqual([
        'normal[0]:b componentDidUpdate',
        'portal1[0]:b componentDidUpdate',
        'normal[1]:b componentDidUpdate',
        'portal2[0]:b componentDidUpdate',
        'portal2[1]:b componentDidUpdate',
        'Parent:b componentDidUpdate',
      ]);

      ops.length = 0;
      ReactDOM.unmountComponentAtNode(container);
      expect(portalContainer1.innerHTML).toBe('');
      expect(portalContainer2.innerHTML).toBe('');
      expect(container.innerHTML).toBe('');
      expect(ops).toEqual([
        'Parent:b componentWillUnmount',
        'normal[0]:b componentWillUnmount',
        'portal1[0]:b componentWillUnmount',
        'normal[1]:b componentWillUnmount',
        'portal2[0]:b componentWillUnmount',
        'portal2[1]:b componentWillUnmount',
      ]);
    });

    it('should render nested portals', () => {
      var portalContainer1 = document.createElement('div');
      var portalContainer2 = document.createElement('div');
      var portalContainer3 = document.createElement('div');

      ReactDOM.render([

normal[0]
,
        ReactDOM.unstable_createPortal([

portal1[0]
,
          ReactDOM.unstable_createPortal(

portal2[0]
,
            portalContainer2
          ),
          ReactDOM.unstable_createPortal(

portal3[0]
,
            portalContainer3
          ),

portal1[1]
,
        ], portalContainer1),

normal[1]
,
      ], container);
      expect(portalContainer1.innerHTML).toBe('
portal1[0]

portal1[1]
');
      expect(portalContainer2.innerHTML).toBe('
portal2[0]
');
      expect(portalContainer3.innerHTML).toBe('
portal3[0]
');
      expect(container.innerHTML).toBe('
normal[0]

normal[1]
');

      ReactDOM.unmountComponentAtNode(container);
      expect(portalContainer1.innerHTML).toBe('');
      expect(portalContainer2.innerHTML).toBe('');
      expect(portalContainer3.innerHTML).toBe('');
      expect(container.innerHTML).toBe('');
    });

    it('should pass portal context when rendering subtree elsewhere', () => {
      var portalContainer = document.createElement('div');

      class Component extends React.Component {
        static contextTypes = {
          foo: React.PropTypes.string.isRequired,
        };

        render() {
          return
{this.context.foo}
;
        }
      }

      class Parent extends React.Component {
        static childContextTypes = {
          foo: React.PropTypes.string.isRequired,
        };

        getChildContext() {
          return {
            foo: 'bar',
          };
        }

        render() {
          return ReactDOM.unstable_createPortal(
            <Component />,
            portalContainer
          );
        }
      }

      ReactDOM.render(<Parent />, container);
      expect(container.innerHTML).toBe('');
      expect(portalContainer.innerHTML).toBe('
bar
');
    });

    it('should update portal context if it changes due to setState', () => {
      var portalContainer = document.createElement('div');

      class Component extends React.Component {
        static contextTypes = {
          foo: React.PropTypes.string.isRequired,
          getFoo: React.PropTypes.func.isRequired,
        };

        render() {
          return
{this.context.foo + '-' + this.context.getFoo()}
;
        }
      }

      class Parent extends React.Component {
        static childContextTypes = {
          foo: React.PropTypes.string.isRequired,
          getFoo: React.PropTypes.func.isRequired,
        };

        state = {
          bar: 'initial',
        };

        getChildContext() {
          return {
            foo: this.state.bar,
            getFoo: () => this.state.bar,
          };
        }

        render() {
          return ReactDOM.unstable_createPortal(
            <Component />,
            portalContainer
          );
        }
      }

      var instance = ReactDOM.render(<Parent />, container);
      expect(portalContainer.innerHTML).toBe('
initial-initial
');
      expect(container.innerHTML).toBe('');
      instance.setState({bar: 'changed'});
      expect(portalContainer.innerHTML).toBe('
changed-changed
');
      expect(container.innerHTML).toBe('');
    });

    it('should update portal context if it changes due to re-render', () => {
      var portalContainer = document.createElement('div');

      class Component extends React.Component {
        static contextTypes = {
          foo: React.PropTypes.string.isRequired,
          getFoo: React.PropTypes.func.isRequired,
        };

        render() {
          return
{this.context.foo + '-' + this.context.getFoo()}
;
        }
      }

      class Parent extends React.Component {
        static childContextTypes = {
          foo: React.PropTypes.string.isRequired,
          getFoo: React.PropTypes.func.isRequired,
        };

        getChildContext() {
          return {
            foo: this.props.bar,
            getFoo: () => this.props.bar,
          };
        }

        render() {
          return ReactDOM.unstable_createPortal(
            <Component />,
            portalContainer
          );
        }
      }

      ReactDOM.render(<Parent bar="initial" />, container);
      expect(portalContainer.innerHTML).toBe('
initial-initial
');
      expect(container.innerHTML).toBe('');
      ReactDOM.render(<Parent bar="changed" />, container);
      expect(portalContainer.innerHTML).toBe('
changed-changed
');
      expect(container.innerHTML).toBe('');
    });

    it('findDOMNode should find dom element after expanding a fragment', () => {
      class MyNode extends React.Component {
        render() {
          return (
            !this.props.flag ?
            [
] :
            [,
]
          );
        }
      }

      var container = document.createElement('div');

      var myNodeA = ReactDOM.render(<MyNode />, container);
      var a = ReactDOM.findDOMNode(myNodeA);
      expect(a.tagName).toBe('DIV');

      var myNodeB = ReactDOM.render(<MyNode flag={true} />, container);
      expect(myNodeA === myNodeB).toBe(true);

      var b = ReactDOM.findDOMNode(myNodeB);
      expect(b.tagName).toBe('SPAN');
    });
  }
});
<commit_msg>Fix lint (#8489)<commit_after>/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @emails react-core
 */

'use strict';

var React = require('React');
var ReactDOM = require('ReactDOM');
var ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');

describe('ReactDOMFiber', () => {
  var container;

  beforeEach(() => {
    container = document.createElement('div');
  });

  it('should render strings as children', () => {
    const Box = ({value}) =>
{value}
;

    ReactDOM.render(
      <Box value="foo" />,
      container
    );
    expect(container.textContent).toEqual('foo');
  });

  it('should render numbers as children', () => {
    const Box = ({value}) =>
{value}
;

    ReactDOM.render(
      <Box value={10} />,
      container
    );

    expect(container.textContent).toEqual('10');
  });

  it('should be called a callback argument', () => {
    // mounting phase
    let called = false;
    ReactDOM.render(

Foo
,
      container,
      () => called = true
    );
    expect(called).toEqual(true);

    // updating phase
    called = false;
    ReactDOM.render(

Foo
,
      container,
      () => called = true
    );
    expect(called).toEqual(true);
  });

  if (ReactDOMFeatureFlags.useFiber) {
    it('should render a component returning strings directly from render', () => {
      const Text = ({value}) => value;

      ReactDOM.render(
        <Text value="foo" />,
        container
      );
      expect(container.textContent).toEqual('foo');
    });

    it('should render a component returning numbers directly from render', () => {
      const Text = ({value}) => value;

      ReactDOM.render(
        <Text value={10} />,
        container
      );

      expect(container.textContent).toEqual('10');
    });

    it('finds the DOM Text node of a string child', () => {
      class Text extends React.Component {
        render() {
          return this.props.value;
        }
      }

      let instance = null;
      ReactDOM.render(
        <Text value="foo" ref={ref => instance = ref} />,
        container
      );

      const textNode = ReactDOM.findDOMNode(instance);
      expect(textNode).toBe(container.firstChild);
      expect(textNode.nodeType).toBe(3);
      expect(textNode.nodeValue).toBe('foo');
    });

    it('finds the first child when a component returns a fragment', () => {
      class Fragment extends React.Component {
        render() {
          return [

,
            ,
          ];
        }
      }

      let instance = null;
      ReactDOM.render(
        <Fragment ref={ref => instance = ref} />,
        container
      );

      expect(container.childNodes.length).toBe(2);

      const firstNode = ReactDOM.findDOMNode(instance);
      expect(firstNode).toBe(container.firstChild);
      expect(firstNode.tagName).toBe('DIV');
    });

    it('finds the first child even when fragment is nested', () => {
      class Wrapper extends React.Component {
        render() {
          return this.props.children;
        }
      }

      class Fragment extends React.Component {
        render() {
          return [
            <Wrapper>
</Wrapper>,
            ,
          ];
        }
      }

      let instance = null;
      ReactDOM.render(
        <Fragment ref={ref => instance = ref} />,
        container
      );

      expect(container.childNodes.length).toBe(2);

      const firstNode = ReactDOM.findDOMNode(instance);
      expect(firstNode).toBe(container.firstChild);
      expect(firstNode.tagName).toBe('DIV');
    });

    it('finds the first child even when first child renders null', () => {
      class NullComponent extends React.Component {
        render() {
          return null;
        }
      }

      class Fragment extends React.Component {
        render() {
          return [
            <NullComponent />,

,
            ,
          ];
        }
      }

      let instance = null;
      ReactDOM.render(
        <Fragment ref={ref => instance = ref} />,
        container
      );

      expect(container.childNodes.length).toBe(2);

      const firstNode = ReactDOM.findDOMNode(instance);
      expect(firstNode).toBe(container.firstChild);
      expect(firstNode.tagName).toBe('DIV');
    });
  }

  if (ReactDOMFeatureFlags.useFiber) {
    it('should render one portal', () => {
      var portalContainer = document.createElement('div');

      ReactDOM.render(

          {ReactDOM.unstable_createPortal(

portal
,
            portalContainer
          )}

,
        container
      );
      expect(portalContainer.innerHTML).toBe('
portal
');
      expect(container.innerHTML).toBe('

');

      ReactDOM.unmountComponentAtNode(container);
      expect(portalContainer.innerHTML).toBe('');
      expect(container.innerHTML).toBe('');
    });

    it('should render many portals', () => {
      var portalContainer1 = document.createElement('div');
      var portalContainer2 = document.createElement('div');

      var ops = [];
      class Child extends React.Component {
        componentDidMount() {
          ops.push(`${this.props.name} componentDidMount`);
        }
        componentDidUpdate() {
          ops.push(`${this.props.name} componentDidUpdate`);
        }
        componentWillUnmount() {
          ops.push(`${this.props.name} componentWillUnmount`);
        }
        render() {
          return
{this.props.name}
;
        }
      }

      class Parent extends React.Component {
        componentDidMount() {
          ops.push(`Parent:${this.props.step} componentDidMount`);
        }
        componentDidUpdate() {
          ops.push(`Parent:${this.props.step} componentDidUpdate`);
        }
        componentWillUnmount() {
          ops.push(`Parent:${this.props.step} componentWillUnmount`);
        }
        render() {
          const {step} = this.props;
          return [
            <Child name={`normal[0]:${step}`} />,
            ReactDOM.unstable_createPortal(
              <Child name={`portal1[0]:${step}`} />,
              portalContainer1
            ),
            <Child name={`normal[1]:${step}`} />,
            ReactDOM.unstable_createPortal(
              [
                <Child name={`portal2[0]:${step}`} />,
                <Child name={`portal2[1]:${step}`} />,
              ],
              portalContainer2
            ),
          ];
        }
      }

      ReactDOM.render(<Parent step="a" />, container);
      expect(portalContainer1.innerHTML).toBe('
portal1[0]:a
');
      expect(portalContainer2.innerHTML).toBe('
portal2[0]:a

portal2[1]:a
');
      expect(container.innerHTML).toBe('
normal[0]:a

normal[1]:a
');
      expect(ops).toEqual([
        'normal[0]:a componentDidMount',
        'portal1[0]:a componentDidMount',
        'normal[1]:a componentDidMount',
        'portal2[0]:a componentDidMount',
        'portal2[1]:a componentDidMount',
        'Parent:a componentDidMount',
      ]);

      ops.length = 0;
      ReactDOM.render(<Parent step="b" />, container);
      expect(portalContainer1.innerHTML).toBe('
portal1[0]:b
');
      expect(portalContainer2.innerHTML).toBe('
portal2[0]:b

portal2[1]:b
');
      expect(container.innerHTML).toBe('
normal[0]:b

normal[1]:b
');
      expect(ops).toEqual([
        'normal[0]:b componentDidUpdate',
        'portal1[0]:b componentDidUpdate',
        'normal[1]:b componentDidUpdate',
        'portal2[0]:b componentDidUpdate',
        'portal2[1]:b componentDidUpdate',
        'Parent:b componentDidUpdate',
      ]);

      ops.length = 0;
      ReactDOM.unmountComponentAtNode(container);
      expect(portalContainer1.innerHTML).toBe('');
      expect(portalContainer2.innerHTML).toBe('');
      expect(container.innerHTML).toBe('');
      expect(ops).toEqual([
        'Parent:b componentWillUnmount',
        'normal[0]:b componentWillUnmount',
        'portal1[0]:b componentWillUnmount',
        'normal[1]:b componentWillUnmount',
        'portal2[0]:b componentWillUnmount',
        'portal2[1]:b componentWillUnmount',
      ]);
    });

    it('should render nested portals', () => {
      var portalContainer1 = document.createElement('div');
      var portalContainer2 = document.createElement('div');
      var portalContainer3 = document.createElement('div');

      ReactDOM.render([

normal[0]
,
        ReactDOM.unstable_createPortal([

portal1[0]
,
          ReactDOM.unstable_createPortal(

portal2[0]
,
            portalContainer2
          ),
          ReactDOM.unstable_createPortal(

portal3[0]
,
            portalContainer3
          ),

portal1[1]
,
        ], portalContainer1),

normal[1]
,
      ], container);
      expect(portalContainer1.innerHTML).toBe('
portal1[0]

portal1[1]
');
      expect(portalContainer2.innerHTML).toBe('
portal2[0]
');
      expect(portalContainer3.innerHTML).toBe('
portal3[0]
');
      expect(container.innerHTML).toBe('
normal[0]

normal[1]
');

      ReactDOM.unmountComponentAtNode(container);
      expect(portalContainer1.innerHTML).toBe('');
      expect(portalContainer2.innerHTML).toBe('');
      expect(portalContainer3.innerHTML).toBe('');
      expect(container.innerHTML).toBe('');
    });

    it('should pass portal context when rendering subtree elsewhere', () => {
      var portalContainer = document.createElement('div');

      class Component extends React.Component {
        static contextTypes = {
          foo: React.PropTypes.string.isRequired,
        };

        render() {
          return
{this.context.foo}
;
        }
      }

      class Parent extends React.Component {
        static childContextTypes = {
          foo: React.PropTypes.string.isRequired,
        };

        getChildContext() {
          return {
            foo: 'bar',
          };
        }

        render() {
          return ReactDOM.unstable_createPortal(
            <Component />,
            portalContainer
          );
        }
      }

      ReactDOM.render(<Parent />, container);
      expect(container.innerHTML).toBe('');
      expect(portalContainer.innerHTML).toBe('
bar
');
    });

    it('should update portal context if it changes due to setState', () => {
      var portalContainer = document.createElement('div');

      class Component extends React.Component {
        static contextTypes = {
          foo: React.PropTypes.string.isRequired,
          getFoo: React.PropTypes.func.isRequired,
        };

        render() {
          return
{this.context.foo + '-' + this.context.getFoo()}
;
        }
      }

      class Parent extends React.Component {
        static childContextTypes = {
          foo: React.PropTypes.string.isRequired,
          getFoo: React.PropTypes.func.isRequired,
        };

        state = {
          bar: 'initial',
        };

        getChildContext() {
          return {
            foo: this.state.bar,
            getFoo: () => this.state.bar,
          };
        }

        render() {
          return ReactDOM.unstable_createPortal(
            <Component />,
            portalContainer
          );
        }
      }

      var instance = ReactDOM.render(<Parent />, container);
      expect(portalContainer.innerHTML).toBe('
initial-initial
');
      expect(container.innerHTML).toBe('');
      instance.setState({bar: 'changed'});
      expect(portalContainer.innerHTML).toBe('
changed-changed
');
      expect(container.innerHTML).toBe('');
    });

    it('should update portal context if it changes due to re-render', () => {
      var portalContainer = document.createElement('div');

      class Component extends React.Component {
        static contextTypes = {
          foo: React.PropTypes.string.isRequired,
          getFoo: React.PropTypes.func.isRequired,
        };

        render() {
          return
{this.context.foo + '-' + this.context.getFoo()}
;
        }
      }

      class Parent extends React.Component {
        static childContextTypes = {
          foo: React.PropTypes.string.isRequired,
          getFoo: React.PropTypes.func.isRequired,
        };

        getChildContext() {
          return {
            foo: this.props.bar,
            getFoo: () => this.props.bar,
          };
        }

        render() {
          return ReactDOM.unstable_createPortal(
            <Component />,
            portalContainer
          );
        }
      }

      ReactDOM.render(<Parent bar="initial" />, container);
      expect(portalContainer.innerHTML).toBe('
initial-initial
');
      expect(container.innerHTML).toBe('');
      ReactDOM.render(<Parent bar="changed" />, container);
      expect(portalContainer.innerHTML).toBe('
changed-changed
');
      expect(container.innerHTML).toBe('');
    });

    it('findDOMNode should find dom element after expanding a fragment', () => {
      class MyNode extends React.Component {
        render() {
          return (
            !this.props.flag ?
            [
] :
            [,
]
          );
        }
      }

      var myNodeA = ReactDOM.render(<MyNode />, container);
      var a = ReactDOM.findDOMNode(myNodeA);
      expect(a.tagName).toBe('DIV');

      var myNodeB = ReactDOM.render(<MyNode flag={true} />, container);
      expect(myNodeA === myNodeB).toBe(true);

      var b = ReactDOM.findDOMNode(myNodeB);
      expect(b.tagName).toBe('SPAN');
    });
  }
});
<|endoftext|>


<commit_before>//Do this as soon as the DOM is ready
$(document).ready(function() {

    $.getJSON("http://demos.fmeserver.com.s3.amazonaws.com/server-demo-config.json", function(config) {
        $('#loadingImage').hide();
        initialize(config);
    });

});

var initialize = function (config) {
	FMEServer.init(config);

  BuildForm.token = config.token;
  BuildForm.host = config.server;

	//Call server and get the session ID and path
	FMEServer.getSession(BuildForm.repository, BuildForm.workspaceName, function(json){
		BuildForm.session = json.serviceResponse.session;
		BuildForm.path = json.serviceResponse.files.folder[0].path;

		//Call server to get list of parameters and potential values
		FMEServer.getWorkspaceParameters(BuildForm.repository, BuildForm.workspaceName, BuildForm.buildParams);

		//Build up the form
		BuildForm.init();

	});

};

var BuildForm = {
	repository : 'Demos',
	workspaceName : 'validate-direct.fmw',
	session : null,
	path : null,

	init : function() {

		//hide navigation buttons
		$('#back').hide();

		$('#back').click(function(){
			if (! $('#submissionPage').hasClass('active')){
				$('#back').hide();
				//clear the results page
				$('#resultStatus').remove();
				$('#loadingImage').show();
			}
		})

		//--------------------------------------------------------------
		//Initialize the drag and drop file upload area
		//--------------------------------------------------------------
		//control behaviour of the fileuploader
		$('#fileupload').fileupload({
			url : BuildForm.host + '/fmedataupload/' + BuildForm.repository + '/' +  BuildForm.workspaceName + ';jsessionid=' + BuildForm.session,
			dropzone : $('#dropzone'),
			autoUpload : true,

			//when a new file is added either through drag and drop or
			//file selection dialog
			add : function(e, data){
				//displays filename and progress bar for any uploading files
				$('#fileTable').show();
				data.context = $('#fileTable');
				$.each(data.files, function(index, file) {
					if (!index) {
						var elemName = file.name;
						elemName = elemName.replace(/[.\(\)]/g,'');
						elemName = elemName.split(' ').join('');

						var row = $("
");

						var name = $("
" + file.name + '
');
						var progressBar = $("
");
						progressBar.append("
");
						var progress = $("
").append(progressBar);
					}

					name.appendTo(row);
					progress.appendTo(row);
				 	row.appendTo(data.context);
          $('#dropText').hide();
          $('.fileinput-button').hide();
				})

				data.submit();
			},

			done : function(e, data){
				//update list of uploaded files with button to select
				//them as source datasets for translation
				var elemName = data.files[0].name;
				elemName = elemName.replace(/[.\(\)]/g, '');
				elemName = elemName.split(' ').join('');

				var test = 'stop';
        BuildForm.submit();
			},

			fail : function(e, data) {
				$.each(data.result.files, function(index, file) {
					var error = $('').text(file.error);
					$(data.context.children()[index])
						.append('
')
						.append(error);
				});
			},

	        dragover : function(e, data){
	      		//going to use this to change look of 'dropzone'
	      		//when someone drags a file onto the page
				var dropZone = $('#dropzone');
				var timeout = window.dropZoneTimeout;

				if (!timeout){
					dropZone.addClass('in');
				}
				else{
					clearTimeout(timeout);
				}

				var found = false;
				var node = e.target;
				do {
					if (node == dropZone[0]){
						found = true;
						break;
					}
					node = node.parentNode;
				}
				while (node != null);
				if (found){

					dropZone.addClass('hover');
				}
				else {

					dropZone.removeClass('hover');
				}
				window.dropZoneTimeout = setTimeout(function(){
					window.dropZoneTimeout = null;

					dropZone.removeClass('in hover');
				}, 100);
			},

			//give updates on upload progress of each file
			progress : function(e, data){
				var progress = parseInt(data.loaded / data.total * 100, 10);

				var name = data.files[0].name
				name = name.replace(/[.\(\)]/g, '');
				name = name.split(' ').join('');

				var progressId = '#progress' + name + ' .bar';
				$(progressId).css('width', progress + '%');

			}
		});
	},

	submit : function() {

    var files = '"';
		var fileList = $('.fileRow');

		//check a file has been uploaded and at least one is selected
		if (fileList.length == 0){
			//put out an alert and don't continue with submission
			$('#dropzone').prepend('
 Please upload a file. <button type="button" class="close" data-dismiss="alert">×</button>
');
		}

		else{
				$('#loadingImage').fadeIn();

				for (var i = 0; i < fileList.length; i++){
          files = files + '"' + BuildForm.path + '/' + fileList[i].firstChild.textContent + '" ';
				}

				files = files + '"';

				//build url
				var submitUrl = BuildForm.host + '/fmedatastreaming/' + BuildForm.repository + '/' +  BuildForm.workspaceName + '?SourceDataset_ACAD=' + files;
        submitUrl += '&token='+BuildForm.token;
        submitUrl += '&opt_responseformat=json';

				//submit
				$.ajax(submitUrl)
					.done(function(result){
						 BuildForm.displayResults(result, true);
					})
					.fail(function(textStatus){
						var error = textStatus;
					});

		}
	},

	displayResults : function(result, isSuccess){
		//hide loading image
		$('#loadingImage').hide();

    //hide upload area
    $('#dropzone').hide();
    $('#submitToServer').hide();

		//show back button
		$('#back').show();

		//get the JSON response from the Server and displays information on the page
		var resultStatus = $('
');

		if (isSuccess){;

			resultStatus.append(result);
		}
		else{
			var FMEError = result.responseJSON.serviceResponse.fmeTransformationResult.fmeEngineResponse.statusMessage;
			resultStatus.append("
There was an error submitting your request
");
			resultStatus.append('
');
			resultStatus.append('
Error ' + result.status + ': ' + result.statusText + '
');
			if (FMEError == "Translation Successful"){
				resultStatus.append('
No features were read from the source dataset
');
			}
			else{
				resultStatus.append('
' + FMEError + '
');
			}
			resultStatus.append('
');
			resultStatus.append('
Use the back arrow to return to the start page.
');
		}

		$('#results').append(resultStatus);
	},

	buildParams : function(json){
		//parse JSON response
		//add in drop down menu options from workspace
		var paramArray = json;
		var elements = [ 'SourceFormat', 'DestinationFormat' ];
		for (var i = 0; i < paramArray.length; i++){
			//populate drop-down options for choice-type parameters
			if (elements.indexOf(paramArray[i].name) != -1){
				//populate drop-down options on page
				if(paramArray[i].listOptions){
					var optionArray = paramArray[i].listOptions;
					for (var x = 0; x < optionArray.length; x++){
						if (optionArray[x].value != 'SDF3' && optionArray[x].value != 'SQLITE3FDO'){
							var option = $('<option />', {value: optionArray[x].value, text: optionArray[x].caption});
							$('#' + paramArray[i].name).append(option);
						}
					}
				}
			}
		}
	}

}<commit_msg>update<commit_after>//Do this as soon as the DOM is ready
$(document).ready(function() {

    $.getJSON("http://demos.fmeserver.com.s3.amazonaws.com/server-demo-config.json", function(config) {
        $('#loadingImage').hide();
        initialize(config.initObject);
    });

});

var initialize = function (config) {
	FMEServer.init(config);

  BuildForm.token = config.token;
  BuildForm.host = config.server;

	//Call server and get the session ID and path
	FMEServer.getSession(BuildForm.repository, BuildForm.workspaceName, function(json){
		BuildForm.session = json.serviceResponse.session;
		BuildForm.path = json.serviceResponse.files.folder[0].path;

		//Call server to get list of parameters and potential values
		FMEServer.getWorkspaceParameters(BuildForm.repository, BuildForm.workspaceName, BuildForm.buildParams);

		//Build up the form
		BuildForm.init();

	});

};

var BuildForm = {
	repository : 'Demos',
	workspaceName : 'validate-direct.fmw',
	session : null,
	path : null,

	init : function() {

		//hide navigation buttons
		$('#back').hide();

		$('#back').click(function(){
			if (! $('#submissionPage').hasClass('active')){
				$('#back').hide();
				//clear the results page
				$('#resultStatus').remove();
				$('#loadingImage').show();
			}
		})

		//--------------------------------------------------------------
		//Initialize the drag and drop file upload area
		//--------------------------------------------------------------
		//control behaviour of the fileuploader
		$('#fileupload').fileupload({
			url : BuildForm.host + '/fmedataupload/' + BuildForm.repository + '/' +  BuildForm.workspaceName + ';jsessionid=' + BuildForm.session,
			dropzone : $('#dropzone'),
			autoUpload : true,

			//when a new file is added either through drag and drop or
			//file selection dialog
			add : function(e, data){
				//displays filename and progress bar for any uploading files
				$('#fileTable').show();
				data.context = $('#fileTable');
				$.each(data.files, function(index, file) {
					if (!index) {
						var elemName = file.name;
						elemName = elemName.replace(/[.\(\)]/g,'');
						elemName = elemName.split(' ').join('');

						var row = $("
");

						var name = $("
" + file.name + '
');
						var progressBar = $("
");
						progressBar.append("
");
						var progress = $("
").append(progressBar);
					}

					name.appendTo(row);
					progress.appendTo(row);
				 	row.appendTo(data.context);
          $('#dropText').hide();
          $('.fileinput-button').hide();
				})

				data.submit();
			},

			done : function(e, data){
				//update list of uploaded files with button to select
				//them as source datasets for translation
				var elemName = data.files[0].name;
				elemName = elemName.replace(/[.\(\)]/g, '');
				elemName = elemName.split(' ').join('');

				var test = 'stop';
        BuildForm.submit();
			},

			fail : function(e, data) {
				$.each(data.result.files, function(index, file) {
					var error = $('').text(file.error);
					$(data.context.children()[index])
						.append('
')
						.append(error);
				});
			},

	        dragover : function(e, data){
	      		//going to use this to change look of 'dropzone'
	      		//when someone drags a file onto the page
				var dropZone = $('#dropzone');
				var timeout = window.dropZoneTimeout;

				if (!timeout){
					dropZone.addClass('in');
				}
				else{
					clearTimeout(timeout);
				}

				var found = false;
				var node = e.target;
				do {
					if (node == dropZone[0]){
						found = true;
						break;
					}
					node = node.parentNode;
				}
				while (node != null);
				if (found){

					dropZone.addClass('hover');
				}
				else {

					dropZone.removeClass('hover');
				}
				window.dropZoneTimeout = setTimeout(function(){
					window.dropZoneTimeout = null;

					dropZone.removeClass('in hover');
				}, 100);
			},

			//give updates on upload progress of each file
			progress : function(e, data){
				var progress = parseInt(data.loaded / data.total * 100, 10);

				var name = data.files[0].name
				name = name.replace(/[.\(\)]/g, '');
				name = name.split(' ').join('');

				var progressId = '#progress' + name + ' .bar';
				$(progressId).css('width', progress + '%');

			}
		});
	},

	submit : function() {

    var files = '"';
		var fileList = $('.fileRow');

		//check a file has been uploaded and at least one is selected
		if (fileList.length == 0){
			//put out an alert and don't continue with submission
			$('#dropzone').prepend('
 Please upload a file. <button type="button" class="close" data-dismiss="alert">×</button>
');
		}

		else{
				$('#loadingImage').fadeIn();

				for (var i = 0; i < fileList.length; i++){
          files = files + '"' + BuildForm.path + '/' + fileList[i].firstChild.textContent + '" ';
				}

				files = files + '"';

				//build url
				var submitUrl = BuildForm.host + '/fmedatastreaming/' + BuildForm.repository + '/' +  BuildForm.workspaceName + '?SourceDataset_ACAD=' + files;
        submitUrl += '&token='+BuildForm.token;
        submitUrl += '&opt_responseformat=json';

				//submit
				$.ajax(submitUrl)
					.done(function(result){
						 BuildForm.displayResults(result, true);
					})
					.fail(function(textStatus){
						var error = textStatus;
					});

		}
	},

	displayResults : function(result, isSuccess){
		//hide loading image
		$('#loadingImage').hide();

    //hide upload area
    $('#dropzone').hide();
    $('#submitToServer').hide();

		//show back button
		$('#back').show();

		//get the JSON response from the Server and displays information on the page
		var resultStatus = $('
');

		if (isSuccess){;

			resultStatus.append(result);
		}
		else{
			var FMEError = result.responseJSON.serviceResponse.fmeTransformationResult.fmeEngineResponse.statusMessage;
			resultStatus.append("
There was an error submitting your request
");
			resultStatus.append('
');
			resultStatus.append('
Error ' + result.status + ': ' + result.statusText + '
');
			if (FMEError == "Translation Successful"){
				resultStatus.append('
No features were read from the source dataset
');
			}
			else{
				resultStatus.append('
' + FMEError + '
');
			}
			resultStatus.append('
');
			resultStatus.append('
Use the back arrow to return to the start page.
');
		}

		$('#results').append(resultStatus);
	},

	buildParams : function(json){
		//parse JSON response
		//add in drop down menu options from workspace
		var paramArray = json;
		var elements = [ 'SourceFormat', 'DestinationFormat' ];
		for (var i = 0; i < paramArray.length; i++){
			//populate drop-down options for choice-type parameters
			if (elements.indexOf(paramArray[i].name) != -1){
				//populate drop-down options on page
				if(paramArray[i].listOptions){
					var optionArray = paramArray[i].listOptions;
					for (var x = 0; x < optionArray.length; x++){
						if (optionArray[x].value != 'SDF3' && optionArray[x].value != 'SQLITE3FDO'){
							var option = $('<option />', {value: optionArray[x].value, text: optionArray[x].caption});
							$('#' + paramArray[i].name).append(option);
						}
					}
				}
			}
		}
	}

}<|endoftext|>


<commit_before>// Copyright (c) 2019, Frappe Technologies and contributors
// For license information, please see license.txt

frappe.provide('frappe.dashboards.chart_sources');

frappe.ui.form.on('Dashboard Chart', {
	setup: function(frm) {
		// fetch timeseries from source
		frm.add_fetch('source', 'timeseries', 'timeseries');
	},

	refresh: function(frm) {
		frm.chart_filters = null;
		frm.set_df_property("filters_section", "hidden", 1);
		frm.trigger('update_options');
	},

	source: function(frm) {
		frm.trigger("show_filters");
	},

	chart_type: function(frm) {
		// set timeseries based on chart type
		if (['Count', 'Average', 'Sum'].includes(frm.doc.chart_type)) {
			frm.set_value('timeseries', 1);
		}
		frm.set_value('document_type', '');
	},

	document_type: function(frm) {
		// update `based_on` options based on date / datetime fields
		frm.set_value('source', '');
		frm.set_value('based_on', '');
		frm.set_value('value_based_on', '');
		frm.set_value('filters_json', '{}');
		frm.trigger('update_options');
	},

	update_options: function(frm) {
		let doctype = frm.doc.document_type;
		let date_fields = [
			{label: __('Created On'), value: 'creation'},
			{label: __('Last Modified On'), value: 'modified'}
		];
		let value_fields = [];
		let update_form = function() {
			// update select options
			frm.set_df_property('based_on', 'options', date_fields);
			frm.set_df_property('value_based_on', 'options', value_fields);
			frm.trigger("show_filters");
		}

		if (doctype) {
			frappe.model.with_doctype(doctype, () => {
				// get all date and datetime fields
				frappe.get_meta(doctype).fields.map(df => {
					if (['Date', 'Datetime'].includes(df.fieldtype)) {
						date_fields.push({label: df.label, value: df.fieldname});
					}
					if (['Int', 'Float', 'Currency', 'Percent'].includes(df.fieldtype)) {
						value_fields.push({label: df.label, value: df.fieldname});
					}
				});
				update_form();
			});
		} else {
			// update select options
			update_form();
		}

	},

	show_filters: function(frm) {
		if (frm.chart_filters && frm.chart_filters.length) {
			frm.trigger('render_filters_table');
		} else {
			if (frm.doc.chart_type==='Custom') {
				if (frm.doc.source) {
					frappe.xcall('frappe.desk.doctype.dashboard_chart_source.dashboard_chart_source.get_config', {name: frm.doc.source})
						.then(config => {
							frappe.dom.eval(config);
							frm.chart_filters = frappe.dashboards.chart_sources[frm.doc.source].filters;
							frm.trigger('render_filters_table');
						});
				} else {
					frm.chart_filters = [];
					frm.trigger('render_filters_table');
				}
			} else {
				// standard filters
				if (frm.doc.document_type) {
					// allow all link and select fields as filters
					frm.chart_filters = [];
					frappe.model.with_doctype(frm.doc.document_type, () => {
						frappe.get_meta(frm.doc.document_type).fields.map(df => {
							if (['Link', 'Select'].includes(df.fieldtype)) {
								let _df = copy_dict(df);

								// nothing is mandatory
								_df.reqd = 0;
								_df.default = null;

								frm.chart_filters.push(_df);
							}
							frm.trigger('render_filters_table');
						});
					});
				}
			}

		}
	},

	render_filters_table: function(frm) {
		frm.set_df_property("filters_section", "hidden", 0);
		let fields = frm.chart_filters;

		let wrapper = $(frm.get_field('filters_json').wrapper).empty();
		let table = $(`

					${__('Filter')}
					${__('Value')}

`).appendTo(wrapper);
		$(`<p class="text-muted small">${__("Click table to edit")}</p>`).appendTo(wrapper);

		let filters = JSON.parse(frm.doc.filters_json || '{}');
		var filters_set = false;
		fields.map( f => {
			if (filters[f.fieldname]) {
				const filter_row = $(`<tr><td>${f.label}</td><td>${filters[f.fieldname] || ""}</td></tr>`);
				table.find('tbody').append(filter_row);
				filters_set = true;
			}
		});

		if (!filters_set) {
			const filter_row = $(`

				${__("Click to Set Filters")}
`);
			table.find('tbody').append(filter_row);
		}

		table.on('click', () => {
			let dialog = new frappe.ui.Dialog({
				title: __('Set Filters'),
				fields: fields,
				primary_action: function() {
					let values = this.get_values();
					if(values) {
						this.hide();
						frm.set_value('filters_json', JSON.stringify(values));
						frm.trigger('show_filters');
					}
				},
				primary_action_label: "Set"
			});
			dialog.show();
			dialog.set_values(filters);
			frappe.dashboards.filters_dialog = dialog;
		});
	}
});

<commit_msg>fix(minor): filter selection for dashboard chart, even if hidden / readonly<commit_after>// Copyright (c) 2019, Frappe Technologies and contributors
// For license information, please see license.txt

frappe.provide('frappe.dashboards.chart_sources');

frappe.ui.form.on('Dashboard Chart', {
	setup: function(frm) {
		// fetch timeseries from source
		frm.add_fetch('source', 'timeseries', 'timeseries');
	},

	refresh: function(frm) {
		frm.chart_filters = null;
		frm.set_df_property("filters_section", "hidden", 1);
		frm.trigger('update_options');
	},

	source: function(frm) {
		frm.trigger("show_filters");
	},

	chart_type: function(frm) {
		// set timeseries based on chart type
		if (['Count', 'Average', 'Sum'].includes(frm.doc.chart_type)) {
			frm.set_value('timeseries', 1);
		}
		frm.set_value('document_type', '');
	},

	document_type: function(frm) {
		// update `based_on` options based on date / datetime fields
		frm.set_value('source', '');
		frm.set_value('based_on', '');
		frm.set_value('value_based_on', '');
		frm.set_value('filters_json', '{}');
		frm.trigger('update_options');
	},

	update_options: function(frm) {
		let doctype = frm.doc.document_type;
		let date_fields = [
			{label: __('Created On'), value: 'creation'},
			{label: __('Last Modified On'), value: 'modified'}
		];
		let value_fields = [];
		let update_form = function() {
			// update select options
			frm.set_df_property('based_on', 'options', date_fields);
			frm.set_df_property('value_based_on', 'options', value_fields);
			frm.trigger("show_filters");
		}

		if (doctype) {
			frappe.model.with_doctype(doctype, () => {
				// get all date and datetime fields
				frappe.get_meta(doctype).fields.map(df => {
					if (['Date', 'Datetime'].includes(df.fieldtype)) {
						date_fields.push({label: df.label, value: df.fieldname});
					}
					if (['Int', 'Float', 'Currency', 'Percent'].includes(df.fieldtype)) {
						value_fields.push({label: df.label, value: df.fieldname});
					}
				});
				update_form();
			});
		} else {
			// update select options
			update_form();
		}

	},

	show_filters: function(frm) {
		if (frm.chart_filters && frm.chart_filters.length) {
			frm.trigger('render_filters_table');
		} else {
			if (frm.doc.chart_type==='Custom') {
				if (frm.doc.source) {
					frappe.xcall('frappe.desk.doctype.dashboard_chart_source.dashboard_chart_source.get_config', {name: frm.doc.source})
						.then(config => {
							frappe.dom.eval(config);
							frm.chart_filters = frappe.dashboards.chart_sources[frm.doc.source].filters;
							frm.trigger('render_filters_table');
						});
				} else {
					frm.chart_filters = [];
					frm.trigger('render_filters_table');
				}
			} else {
				// standard filters
				if (frm.doc.document_type) {
					// allow all link and select fields as filters
					frm.chart_filters = [];
					frappe.model.with_doctype(frm.doc.document_type, () => {
						frappe.get_meta(frm.doc.document_type).fields.map(df => {
							if (['Link', 'Select'].includes(df.fieldtype)) {
								let _df = copy_dict(df);

								// nothing is mandatory
								_df.reqd = 0;
								_df.default = null;
								_df.read_only = 0;
								_df.permlevel = 1;
								_df.hidden = 0;

								frm.chart_filters.push(_df);
							}
							frm.trigger('render_filters_table');
						});
					});
				}
			}

		}
	},

	render_filters_table: function(frm) {
		frm.set_df_property("filters_section", "hidden", 0);
		let fields = frm.chart_filters;

		let wrapper = $(frm.get_field('filters_json').wrapper).empty();
		let table = $(`

					${__('Filter')}
					${__('Value')}

`).appendTo(wrapper);
		$(`<p class="text-muted small">${__("Click table to edit")}</p>`).appendTo(wrapper);

		let filters = JSON.parse(frm.doc.filters_json || '{}');
		var filters_set = false;
		fields.map( f => {
			if (filters[f.fieldname]) {
				const filter_row = $(`<tr><td>${f.label}</td><td>${filters[f.fieldname] || ""}</td></tr>`);
				table.find('tbody').append(filter_row);
				filters_set = true;
			}
		});

		if (!filters_set) {
			const filter_row = $(`

				${__("Click to Set Filters")}
`);
			table.find('tbody').append(filter_row);
		}

		table.on('click', () => {
			let dialog = new frappe.ui.Dialog({
				title: __('Set Filters'),
				fields: fields,
				primary_action: function() {
					let values = this.get_values();
					if(values) {
						this.hide();
						frm.set_value('filters_json', JSON.stringify(values));
						frm.trigger('show_filters');
					}
				},
				primary_action_label: "Set"
			});
			dialog.show();
			dialog.set_values(filters);
			frappe.dashboards.filters_dialog = dialog;
		});
	}
});

<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React from 'react'
import SongList from '../SongList'
import Icon from 'components/Icon'
import Highlighter from 'react-highlight-words'
import './ArtistItem.css'

const ArtistItem = (props) => {
  let isChildQueued = false

  props.artistSongIds.forEach(songId => {
    if (props.queuedSongIds.includes(songId)) {
      isChildQueued = true
    }
  })

  return (

          <Icon icon='FOLDER' size={44} styleName='folderIcon' />
          {props.isExpanded &&

<Icon icon='EXPAND_LESS' size={24} />

          }
          {!props.isExpanded &&

{props.artistSongIds.length}

          }

          <Highlighter autoEscape textToHighlight={props.name} searchWords={props.filterKeywords} />

      {props.isExpanded &&
        <SongList
          songIds={props.artistSongIds}
          showArtist={false}
          filterKeywords={props.filterKeywords}
        />
      }

  )
}

ArtistItem.propTypes = {
  artistSongIds: PropTypes.array.isRequired,
  queuedSongIds: PropTypes.array.isRequired,
  name: PropTypes.string.isRequired,
  isExpanded: PropTypes.bool.isRequired,
  filterKeywords: PropTypes.array.isRequired,
  style: PropTypes.object,
  // actions
  onArtistClick: PropTypes.func.isRequired,
}

export default ArtistItem
<commit_msg>Simplify queued child detection<commit_after>import PropTypes from 'prop-types'
import React from 'react'
import SongList from '../SongList'
import Icon from 'components/Icon'
import Highlighter from 'react-highlight-words'
import './ArtistItem.css'

const ArtistItem = (props) => {
  const isChildQueued = props.artistSongIds.some(songId => props.queuedSongIds.includes(songId))

  return (

          <Icon icon='FOLDER' size={44} styleName='folderIcon' />
          {props.isExpanded &&

<Icon icon='EXPAND_LESS' size={24} />

          }
          {!props.isExpanded &&

{props.artistSongIds.length}

          }

          <Highlighter autoEscape textToHighlight={props.name} searchWords={props.filterKeywords} />

      {props.isExpanded &&
        <SongList
          songIds={props.artistSongIds}
          showArtist={false}
          filterKeywords={props.filterKeywords}
        />
      }

  )
}

ArtistItem.propTypes = {
  artistSongIds: PropTypes.array.isRequired,
  queuedSongIds: PropTypes.array.isRequired,
  name: PropTypes.string.isRequired,
  isExpanded: PropTypes.bool.isRequired,
  filterKeywords: PropTypes.array.isRequired,
  style: PropTypes.object,
  // actions
  onArtistClick: PropTypes.func.isRequired,
}

export default ArtistItem
<|endoftext|>


<commit_before>import $ from 'jquery';
import { clipboard } from 'electron';
import renderjson from '../../../../lib/renderjson';
import '../../../../utils/lib/velocity';
import loadTemplate from '../../../../utils/loadTemplate';
import BaseVw from '../../../baseVw';

export default class extends BaseVw {
  constructor(options = {}) {
    const opts = {
      ...options,
      initialState: {
        heading: '',
        errors: [],
        ...options.initialState || {},
      },
    };

    super(options);

    if (!options.contract) {
      throw new Error('Please provide a contract.');
    }

    this.contract = options.contract;
    this.options = opts;
  }

  tagName() {
    return 'section';
  }

  events() {
    return {
      'click .js-copyContract': 'onClickCopyContract',
    };
  }

  onClickCopyContract() {
    clipboard.writeText(JSON.stringify(this.contract));
    // Fade the link and make it unclickable, but maintain its position in the DOM.
    this.getCachedEl('.js-copyContract')
      .addClass('unclickable')
      .velocity('stop')
      .velocity({ opacity: 0 })
      .velocity({ opacity: 1 }, {
        delay: 5000,
        complete: (els) => {
          $(els[0]).removeClass('unclickable');
        },
      });
    this.getCachedEl('.js-copyContractDone')
      .velocity('stop')
      .velocity({ opacity: 1 })
      .velocity({ opacity: 0 }, { delay: 5000 });
  }

  render() {
    super.render();

    let renderjsonEl;

    if (this.rendered) {
      // On re-renders, reuse the renderjson el so it's state (e.g.
      // what is expanded/collapsed) is maintained.
      renderjsonEl = this.$('.js-jsonContractContainer')
        .children()[0];
    }

    loadTemplate('modals/orderDetail/contractTab/contract.html', t => {
      this.$el.html(t({
        ...this.getState(),
      }));

      this.$('.js-jsonContractContainer')
        .html(renderjsonEl || renderjson.set_show_to_level('1')(this.contract));
    });

    this.rendered = true;
    return this;
  }
}
<commit_msg>format the copied json<commit_after>import $ from 'jquery';
import { clipboard } from 'electron';
import renderjson from '../../../../lib/renderjson';
import '../../../../utils/lib/velocity';
import loadTemplate from '../../../../utils/loadTemplate';
import BaseVw from '../../../baseVw';

export default class extends BaseVw {
  constructor(options = {}) {
    const opts = {
      ...options,
      initialState: {
        heading: '',
        errors: [],
        ...options.initialState || {},
      },
    };

    super(options);

    if (!options.contract) {
      throw new Error('Please provide a contract.');
    }

    this.contract = options.contract;
    this.options = opts;
  }

  tagName() {
    return 'section';
  }

  events() {
    return {
      'click .js-copyContract': 'onClickCopyContract',
    };
  }

  onClickCopyContract() {
    clipboard.writeText(JSON.stringify(this.contract, null, 2));
    // Fade the link and make it unclickable, but maintain its position in the DOM.
    this.getCachedEl('.js-copyContract')
      .addClass('unclickable')
      .velocity('stop')
      .velocity({ opacity: 0 })
      .velocity({ opacity: 1 }, {
        delay: 5000,
        complete: (els) => {
          $(els[0]).removeClass('unclickable');
        },
      });
    this.getCachedEl('.js-copyContractDone')
      .velocity('stop')
      .velocity({ opacity: 1 })
      .velocity({ opacity: 0 }, { delay: 5000 });
  }

  render() {
    super.render();

    let renderjsonEl;

    if (this.rendered) {
      // On re-renders, reuse the renderjson el so it's state (e.g.
      // what is expanded/collapsed) is maintained.
      renderjsonEl = this.$('.js-jsonContractContainer')
        .children()[0];
    }

    loadTemplate('modals/orderDetail/contractTab/contract.html', t => {
      this.$el.html(t({
        ...this.getState(),
      }));

      this.$('.js-jsonContractContainer')
        .html(renderjsonEl || renderjson.set_show_to_level('1')(this.contract));
    });

    this.rendered = true;
    return this;
  }
}
<|endoftext|>


<commit_before>// This is a CLI tool, using console is OK
/* eslint no-console: 0 */
const {spawn, exec} = require('child_process');
const {isAbsolute, resolve} = require('path');
const {existsSync} = require('fs');
const pify = require('pify');
const args = require('args');
const chalk = require('chalk');
const opn = require('opn');
const columnify = require('columnify');
const got = require('got');
const ora = require('ora');
const api = require('./api');

const PLUGIN_PREFIX = 'hyper-';

let commandPromise;

const assertPluginName = pluginName => {
  if (!pluginName) {
    console.error(chalk.red('Plugin name is required'));
    process.exit(1);
  }
};

const getPluginName = arg => {
  if (arg.indexOf(PLUGIN_PREFIX) !== 0) {
    return `${PLUGIN_PREFIX}${arg}`;
  }
  return arg;
};

const checkConfig = () => {
  if (api.exists()) {
    return true;
  }
  let msg = chalk.red(`Error! Config file not found: ${api.configPath}\n`);
  msg += 'Please launch Hyper and retry.';
  console.error(msg);
  process.exit(1);
};

args.command(['i', 'install'], 'Install a plugin', (name, args_) => {
  checkConfig();
  assertPluginName(args_[0]);
  const plugin = getPluginName(args_[0]);
  commandPromise = api
    .install(plugin)
    .then(() => console.log(chalk.green(`${plugin} installed successfully!`)))
    .catch(err => console.error(chalk.red(err)));
});

args.command(['u', 'uninstall', 'rm', 'remove'], 'Uninstall a plugin', (name, args_) => {
  checkConfig();
  assertPluginName(args_[0]);
  const plugin = getPluginName(args_[0]);
  commandPromise = api
    .uninstall(plugin)
    .then(() => console.log(chalk.green(`${plugin} uninstalled successfully!`)))
    .catch(err => console.log(chalk.red(err)));
});

args.command(['ls', 'list'], 'List installed plugins', () => {
  checkConfig();
  let plugins = api.list();

  if (plugins) {
    console.log(plugins);
  } else {
    console.log(chalk.red(`No plugins installed yet.`));
  }
  process.exit(0);
});

const lsRemote = pattern => {
  // note that no errors are catched by this function
  const URL = `https://api.npms.io/v2/search?q=${(pattern && `${pattern}+`) || ''}keywords:hyper-plugin,hyper-theme`;
  return got(URL)
    .then(response => JSON.parse(response.body).results)
    .then(entries => entries.map(entry => entry.package))
    .then(entries => entries.filter(entry => entry.name.indexOf(PLUGIN_PREFIX) === 0))
    .then(entries =>
      entries.map(({name, description}) => {
        return {name, description};
      })
    )
    .then(entries =>
      entries.map(entry => {
        entry.name = chalk.green(entry.name);
        return entry;
      })
    );
};

args.command(['s', 'search'], 'Search for plugins on npm', (name, args_) => {
  const spinner = ora('Searching').start();
  const query = args_[0] ? args_[0].toLowerCase() : '';

  commandPromise = lsRemote(query)
    .then(entries => {
      if (entries.length === 0) {
        spinner.fail();
        console.error(chalk.red(`Your search '${query}' did not match any plugins`));
        console.error(`${chalk.red('Try')} ${chalk.green('hyper ls-remote')}`);
        process.exit(1);
      } else {
        let msg = columnify(entries);
        spinner.succeed();
        msg = msg.substring(msg.indexOf('\n') + 1); // remove header
        console.log(msg);
      }
    })
    .catch(err => {
      spinner.fail();
      console.error(chalk.red(err)); // TODO
    });
});

args.command(['lsr', 'list-remote', 'ls-remote'], 'List plugins available on npm', () => {
  const spinner = ora('Searching').start();

  commandPromise = lsRemote()
    .then(entries => {
      let msg = columnify(entries);

      spinner.succeed();
      msg = msg.substring(msg.indexOf('\n') + 1); // remove header
      console.log(msg);
    })
    .catch(err => {
      spinner.fail();
      console.error(chalk.red(err)); // TODO
    });
});

args.command(['d', 'docs', 'h', 'home'], 'Open the npm page of a plugin', (name, args_) => {
  assertPluginName(args_[0]);
  const plugin = getPluginName(args_[0]);
  opn(`http://ghub.io/${plugin}`, {wait: false});
  process.exit(0);
});

args.command(['<default>'], 'Launch Hyper');

args.option(['v', 'verbose'], 'Verbose mode', false);

const main = argv => {
  const flags = args.parse(argv, {
    name: 'hyper',
    version: false,
    mri: {
      boolean: ['v', 'verbose']
    }
  });

  if (commandPromise) {
    return commandPromise;
  }

  const env = Object.assign({}, process.env, {
    // this will signal Hyper that it was spawned from this module
    HYPER_CLI: '1',
    ELECTRON_NO_ATTACH_CONSOLE: '1'
  });

  delete env['ELECTRON_RUN_AS_NODE'];

  if (flags.verbose) {
    env['ELECTRON_ENABLE_LOGGING'] = '1';
  }

  const options = {
    detached: true,
    env
  };

  const args_ = args.sub.map(arg => {
    const cwd = isAbsolute(arg) ? arg : resolve(process.cwd(), arg);
    if (!existsSync(cwd)) {
      console.error(chalk.red(`Error! Directory or file does not exist: ${cwd}`));
      process.exit(1);
    }
    return cwd;
  });

  if (!flags.verbose) {
    options['stdio'] = 'ignore';
    if (process.platform === 'darwin') {
      //Use `open` to prevent multiple Hyper process
      const cmd = `open -b co.zeit.hyper ${args_}`;
      const opts = {
        env
      };
      return pify(exec)(cmd, opts);
    }
  }

  const child = spawn(process.execPath, args_, options);

  if (flags.verbose) {
    child.stdout.on('data', data => console.log(data.toString('utf8')));
    child.stderr.on('data', data => console.error(data.toString('utf8')));
  }
  if (flags.verbose) {
    return new Promise(c => child.once('exit', () => c(null)));
  }
  child.unref();
  return Promise.resolve();
};

function eventuallyExit(code) {
  setTimeout(() => process.exit(code), 100);
}

main(process.argv)
  .then(() => eventuallyExit(0))
  .catch(err => {
    console.error(err.stack ? err.stack : err);
    eventuallyExit(1);
  });
<commit_msg>Remove auto prefix plugin name (#2757)<commit_after>// This is a CLI tool, using console is OK
/* eslint no-console: 0 */
const {spawn, exec} = require('child_process');
const {isAbsolute, resolve} = require('path');
const {existsSync} = require('fs');
const pify = require('pify');
const args = require('args');
const chalk = require('chalk');
const opn = require('opn');
const columnify = require('columnify');
const got = require('got');
const ora = require('ora');
const api = require('./api');

const PLUGIN_PREFIX = 'hyper-';

let commandPromise;

const assertPluginName = pluginName => {
  if (!pluginName) {
    console.error(chalk.red('Plugin name is required'));
    process.exit(1);
  }
};

const checkConfig = () => {
  if (api.exists()) {
    return true;
  }
  let msg = chalk.red(`Error! Config file not found: ${api.configPath}\n`);
  msg += 'Please launch Hyper and retry.';
  console.error(msg);
  process.exit(1);
};

args.command(['i', 'install'], 'Install a plugin', (name, args_) => {
  checkConfig();
  const pluginName = args_[0];
  assertPluginName(pluginName);
  commandPromise = api
    .install(pluginName)
    .then(() => console.log(chalk.green(`${pluginName} installed successfully!`)))
    .catch(err => console.error(chalk.red(err)));
});

args.command(['u', 'uninstall', 'rm', 'remove'], 'Uninstall a plugin', (name, args_) => {
  checkConfig();
  const pluginName = args_[0];
  assertPluginName(pluginName);
  commandPromise = api
    .uninstall(pluginName)
    .then(() => console.log(chalk.green(`${pluginName} uninstalled successfully!`)))
    .catch(err => console.log(chalk.red(err)));
});

args.command(['ls', 'list'], 'List installed plugins', () => {
  checkConfig();
  let plugins = api.list();

  if (plugins) {
    console.log(plugins);
  } else {
    console.log(chalk.red(`No plugins installed yet.`));
  }
  process.exit(0);
});

const lsRemote = pattern => {
  // note that no errors are catched by this function
  const URL = `https://api.npms.io/v2/search?q=${(pattern && `${pattern}+`) || ''}keywords:hyper-plugin,hyper-theme`;
  return got(URL)
    .then(response => JSON.parse(response.body).results)
    .then(entries => entries.map(entry => entry.package))
    .then(entries => entries.filter(entry => entry.name.indexOf(PLUGIN_PREFIX) === 0))
    .then(entries =>
      entries.map(({name, description}) => {
        return {name, description};
      })
    )
    .then(entries =>
      entries.map(entry => {
        entry.name = chalk.green(entry.name);
        return entry;
      })
    );
};

args.command(['s', 'search'], 'Search for plugins on npm', (name, args_) => {
  const spinner = ora('Searching').start();
  const query = args_[0] ? args_[0].toLowerCase() : '';

  commandPromise = lsRemote(query)
    .then(entries => {
      if (entries.length === 0) {
        spinner.fail();
        console.error(chalk.red(`Your search '${query}' did not match any plugins`));
        console.error(`${chalk.red('Try')} ${chalk.green('hyper ls-remote')}`);
        process.exit(1);
      } else {
        let msg = columnify(entries);
        spinner.succeed();
        msg = msg.substring(msg.indexOf('\n') + 1); // remove header
        console.log(msg);
      }
    })
    .catch(err => {
      spinner.fail();
      console.error(chalk.red(err)); // TODO
    });
});

args.command(['lsr', 'list-remote', 'ls-remote'], 'List plugins available on npm', () => {
  const spinner = ora('Searching').start();

  commandPromise = lsRemote()
    .then(entries => {
      let msg = columnify(entries);

      spinner.succeed();
      msg = msg.substring(msg.indexOf('\n') + 1); // remove header
      console.log(msg);
    })
    .catch(err => {
      spinner.fail();
      console.error(chalk.red(err)); // TODO
    });
});

args.command(['d', 'docs', 'h', 'home'], 'Open the npm page of a plugin', (name, args_) => {
  const pluginName = args_[0];
  assertPluginName(pluginName);
  opn(`http://ghub.io/${pluginName}`, {wait: false});
  process.exit(0);
});

args.command(['<default>'], 'Launch Hyper');

args.option(['v', 'verbose'], 'Verbose mode', false);

const main = argv => {
  const flags = args.parse(argv, {
    name: 'hyper',
    version: false,
    mri: {
      boolean: ['v', 'verbose']
    }
  });

  if (commandPromise) {
    return commandPromise;
  }

  const env = Object.assign({}, process.env, {
    // this will signal Hyper that it was spawned from this module
    HYPER_CLI: '1',
    ELECTRON_NO_ATTACH_CONSOLE: '1'
  });

  delete env['ELECTRON_RUN_AS_NODE'];

  if (flags.verbose) {
    env['ELECTRON_ENABLE_LOGGING'] = '1';
  }

  const options = {
    detached: true,
    env
  };

  const args_ = args.sub.map(arg => {
    const cwd = isAbsolute(arg) ? arg : resolve(process.cwd(), arg);
    if (!existsSync(cwd)) {
      console.error(chalk.red(`Error! Directory or file does not exist: ${cwd}`));
      process.exit(1);
    }
    return cwd;
  });

  if (!flags.verbose) {
    options['stdio'] = 'ignore';
    if (process.platform === 'darwin') {
      //Use `open` to prevent multiple Hyper process
      const cmd = `open -b co.zeit.hyper ${args_}`;
      const opts = {
        env
      };
      return pify(exec)(cmd, opts);
    }
  }

  const child = spawn(process.execPath, args_, options);

  if (flags.verbose) {
    child.stdout.on('data', data => console.log(data.toString('utf8')));
    child.stderr.on('data', data => console.error(data.toString('utf8')));
  }
  if (flags.verbose) {
    return new Promise(c => child.once('exit', () => c(null)));
  }
  child.unref();
  return Promise.resolve();
};

function eventuallyExit(code) {
  setTimeout(() => process.exit(code), 100);
}

main(process.argv)
  .then(() => eventuallyExit(0))
  .catch(err => {
    console.error(err.stack ? err.stack : err);
    eventuallyExit(1);
  });
<|endoftext|>


<commit_before>import {test} from '../utils'
import {RuleTester} from 'eslint'
import rule from 'rules/no-mutable-exports'

const ruleTester = new RuleTester()

ruleTester.run('no-mutable-exports', rule, {
  valid: [
    test({ code: 'export const count = 1'}),
    test({ code: 'export function getCount() {}'}),
    test({ code: 'export class Counter {}'}),
    test({ code: 'export default count = 1'}),
    test({ code: 'export default function getCount() {}'}),
    test({ code: 'export default class Counter {}'}),
    test({ code: 'const count = 1\nexport { count }'}),
    test({ code: 'const count = 1\nexport { count as counter }'}),
    test({ code: 'const count = 1\nexport default count'}),
    test({ code: 'const count = 1\nexport { count as default }'}),
    test({ code: 'function getCount() {}\nexport { getCount }'}),
    test({ code: 'function getCount() {}\nexport { getCount as getCounter }'}),
    test({ code: 'function getCount() {}\nexport default getCount'}),
    test({ code: 'function getCount() {}\nexport { getCount as default }'}),
    test({ code: 'class Counter {}\nexport { Counter }'}),
    test({ code: 'class Counter {}\nexport { Counter as Count }'}),
    test({ code: 'class Counter {}\nexport default Counter'}),
    test({ code: 'class Counter {}\nexport { Counter as default }'}),
    test({
      parser: 'babel-eslint',
      code: 'export Something from "./something";',
    }),
  ],
  invalid: [
    test({
      code: 'export let count = 1',
      errors: ['Exporting mutable \'let\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'export var count = 1',
      errors: ['Exporting mutable \'var\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'let count = 1\nexport { count }',
      errors: ['Exporting mutable \'let\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'var count = 1\nexport { count }',
      errors: ['Exporting mutable \'var\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'let count = 1\nexport { count as counter }',
      errors: ['Exporting mutable \'let\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'var count = 1\nexport { count as counter }',
      errors: ['Exporting mutable \'var\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'let count = 1\nexport default count',
      errors: ['Exporting mutable \'let\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'var count = 1\nexport default count',
      errors: ['Exporting mutable \'var\' binding, use \'const\' instead.'],
    }),

    // todo: undeclared globals
    // test({
    //   code: 'count = 1\nexport { count }',
    //   errors: ['Exporting mutable global binding, use \'const\' instead.'],
    // }),
    // test({
    //   code: 'count = 1\nexport default count',
    //   errors: ['Exporting mutable global binding, use \'const\' instead.'],
    // }),
  ],
})
<commit_msg>Add test for flow type export (#835)<commit_after>import {test} from '../utils'
import {RuleTester} from 'eslint'
import rule from 'rules/no-mutable-exports'

const ruleTester = new RuleTester()

ruleTester.run('no-mutable-exports', rule, {
  valid: [
    test({ code: 'export const count = 1'}),
    test({ code: 'export function getCount() {}'}),
    test({ code: 'export class Counter {}'}),
    test({ code: 'export default count = 1'}),
    test({ code: 'export default function getCount() {}'}),
    test({ code: 'export default class Counter {}'}),
    test({ code: 'const count = 1\nexport { count }'}),
    test({ code: 'const count = 1\nexport { count as counter }'}),
    test({ code: 'const count = 1\nexport default count'}),
    test({ code: 'const count = 1\nexport { count as default }'}),
    test({ code: 'function getCount() {}\nexport { getCount }'}),
    test({ code: 'function getCount() {}\nexport { getCount as getCounter }'}),
    test({ code: 'function getCount() {}\nexport default getCount'}),
    test({ code: 'function getCount() {}\nexport { getCount as default }'}),
    test({ code: 'class Counter {}\nexport { Counter }'}),
    test({ code: 'class Counter {}\nexport { Counter as Count }'}),
    test({ code: 'class Counter {}\nexport default Counter'}),
    test({ code: 'class Counter {}\nexport { Counter as default }'}),
    test({
      parser: 'babel-eslint',
      code: 'export Something from "./something";',
    }),
    test({
      parser: 'babel-eslint',
      code: 'type Foo = {}\nexport type {Foo}',
    }),
  ],
  invalid: [
    test({
      code: 'export let count = 1',
      errors: ['Exporting mutable \'let\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'export var count = 1',
      errors: ['Exporting mutable \'var\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'let count = 1\nexport { count }',
      errors: ['Exporting mutable \'let\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'var count = 1\nexport { count }',
      errors: ['Exporting mutable \'var\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'let count = 1\nexport { count as counter }',
      errors: ['Exporting mutable \'let\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'var count = 1\nexport { count as counter }',
      errors: ['Exporting mutable \'var\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'let count = 1\nexport default count',
      errors: ['Exporting mutable \'let\' binding, use \'const\' instead.'],
    }),
    test({
      code: 'var count = 1\nexport default count',
      errors: ['Exporting mutable \'var\' binding, use \'const\' instead.'],
    }),

    // todo: undeclared globals
    // test({
    //   code: 'count = 1\nexport { count }',
    //   errors: ['Exporting mutable global binding, use \'const\' instead.'],
    // }),
    // test({
    //   code: 'count = 1\nexport default count',
    //   errors: ['Exporting mutable global binding, use \'const\' instead.'],
    // }),
  ],
})
<|endoftext|>


<commit_before>define(['text!templates/events.html', 'views/event'], function(tpl, EventView){
    var EventsView = Backbone.View.extend({
        template: _.template(tpl),
        goals: null,
        initialize: function(){
            // Инициализируем модели
            this.goals = new Backbone.Collection();
            this.goals.on('add', this.addOne, this);
            var that = this;
            $.each(window.kicker_goals, function(index, value){
                that.goals.add(new Backbone.Model(value));
            });

        },
        render: function(){
            return this;
        },
        addOne: function(item){
            var view = new EventView({model: item});
            this.$el.append(view.render().el);
        }
    });
    return EventsView;
});<commit_msg>Отображаем голы в обратном порядке<commit_after>define(['text!templates/events.html', 'views/event'], function(tpl, EventView){
    var EventsView = Backbone.View.extend({
        template: _.template(tpl),
        goals: null,
        initialize: function(){
            // Инициализируем модели
            this.goals = new Backbone.Collection();
            this.goals.on('add', this.addOne, this);
            var that = this;
            $.each(window.kicker_goals, function(index, value){
                that.goals.add(new Backbone.Model(value));
            });

        },
        render: function(){
            return this;
        },
        addOne: function(item){
            var view = new EventView({model: item});
            this.$el.prepend(view.render().el);
        }
    });
    return EventsView;
});<|endoftext|>