<commit_before>import React from 'react';
import TestUtils from 'react-dom/test-utils';
import Rainbow from './rainbow';
import Immutable from 'immutable';
import { shallow } from 'enzyme';
import { elementsTagTest, rootTagTest } from '../../utils/helpers/tags/tags-specs';

describe('Rainbow', () => {
  let instance, data, chart;

  function render(props={}) {
    instance = TestUtils.renderIntoDocument(
      <Rainbow title="My Title" data={ data } { ...props } />
    );

    chart = instance._chart;
  };

  beforeEach(() => {
    data = Immutable.fromJS([
      {
        y: 30,
        name: 'First Bit',
        label: 'label for first bit',
        tooltip: 'more info about this bit'
      }, {
        y: 70,
        name: 'Second Bit',
        label: 'label for second bit',
        tooltip: 'more info about this bit'
      }
    ]);

    render();
  });

  describe('shouldComponentUpdate', () => {
    beforeEach(() => {
      spyOn(chart, 'setTitle');
      spyOn(chart.series[0], 'setData');
    });

    describe('when title changes', () => {
      it("calls setTitle", () => {
        instance.shouldComponentUpdate({ title: "different title", data: instance.props.data });
        expect(chart.setTitle).toHaveBeenCalledWith({ text: "different title" });
      });
    });

    describe('when data changes', () => {
      it("calls setData", () => {
        let newData = Immutable.fromJS({ foo: "bar" });
        instance.shouldComponentUpdate({ title: instance.props.title, data: newData  });
        expect(chart.series[0].setData).toHaveBeenCalledWith(newData.toJS());
      });
    });

    describe('when nothing has changed', () => {
      it("calls neither set methods", () => {
        instance.shouldComponentUpdate({ title: instance.props.title, data: instance.props.data  });
        expect(chart.setTitle).not.toHaveBeenCalled();
        expect(chart.series[0].setData).not.toHaveBeenCalled();
      });
    });
  });

  describe('mainClasses', () => {
    it('returns the base class', () => {
      expect(instance.mainClasses).toEqual('carbon-rainbow');
    });

    describe('when a custom class is passed', () => {
      it('returns base and custom class', () => {
        render({ className: 'customClass' });
        expect(instance.mainClasses).toEqual('carbon-rainbow customClass');
      });
    });
  });

  describe('highcharts config', () => {
    it("sets the config to use the data", () => {
      expect(chart.userOptions.series[0].data).toEqual(instance.props.data.toJS());
    });

    it("sets the config to use the title", () => {
      expect(chart.userOptions.title.text).toEqual(instance.props.title);
    });

    it("calls zIndexSetter when triggering mouse over on a segment", () => {
      let point = chart.series[0].data[0];
      let graphic = point.graphic;

      spyOn(graphic, 'zIndexSetter');
      point.onMouseOver();

      expect(graphic.zIndexSetter).toHaveBeenCalledWith(1);
    });

    it("calls zIndexSetter when triggering mouse over on a segment", () => {
      let point = chart.series[0].data[0];
      let graphic = point.graphic;

      spyOn(graphic, 'zIndexSetter');
      point.onMouseOut();

      expect(graphic.zIndexSetter).toHaveBeenCalledWith(0);
    });

    it("positions the tooltip correctly", () => {
      let opts = {
        plotX: 100,
        plotY: 200
      };
      expect(chart.userOptions.tooltip.positioner(50, 100, opts)).toEqual({ x: 75, y: 105 });
    });

    it("sets the label to be display block if the pointer is visible", () => {
      chart.series[0].setData([{
        y: 30,
        name: 'First Bit',
        label: 'label for first bit',
        tooltip: 'more info about this bit',
        visible: true
      }]);
      let display = chart.series[0].points[0].dataLabel.div.children[0].children[0].style["display"];
      expect(display).toEqual('block');
    });

    it("sets the label to be display none if the pointer is not visible", () => {
      chart.series[0].setData([{
        y: 30,
        name: 'First Bit',
        label: 'label for first bit',
        tooltip: 'more info about this bit',
        visible: false
      }]);
      let display = chart.series[0].points[0].dataLabel.div.children[0].children[0].style["display"];
      expect(display).toEqual('none');
    });

    describe('config property', () => {
      describe('uses some default chart config when no config is passed', () => {
        it("can use the config property to override some chart properties", () => {
          expect(chart.options.chart.backgroundColor).toEqual(null);
          expect(chart.options.credits.enabled).toEqual(false);
        });
      });

      describe('it is possible to override the chart properties using the config props', () => {
        let config = {
          credits: {
            enabled: true
          },
          chart: {
            backgroundColor: '#ff00cc'
          }
        };

        beforeEach(() => {
          render({config});
        });

        it("can use the config property to override some chart properties", () => {
          expect(chart.options.chart.backgroundColor).toEqual('#ff00cc');
          expect(chart.options.credits.enabled).toEqual(true);
        });
      });
    });
  });

  describe("tags on component", () => {
    let wrapper = shallow(
      <Rainbow
        data-element='bar'
        data-role='baz'
        data={ {} }/>
      );

    it('include correct component, element and role data tags', () => {
      rootTagTest(wrapper, 'rainbow', 'bar', 'baz');
    });
  });
});
<commit_msg>Override global.Highcharts for rainbow specs<commit_after>import React from 'react';
import TestUtils from 'react-dom/test-utils';
import Rainbow from './rainbow';
import Immutable from 'immutable';
import { shallow, mount } from 'enzyme';
import { elementsTagTest, rootTagTest } from '../../utils/helpers/tags/tags-specs';

/* global jest */

describe('Rainbow', () => {
  global.Highcharts = {
    chart() {
      return {
        setTitle() {},
        series: [
          { setData() {} }
        ]
      };
    }
  };

  let wrapper, data, chart;

  function render(props={}) {
    wrapper = mount(
      <Rainbow title="My Title" data={ data } { ...props } />
    );
  };

  beforeEach(() => {
    data = Immutable.fromJS([
      {
        y: 30,
        name: 'First Bit',
        label: 'label for first bit',
        tooltip: 'more info about this bit'
      }, {
        y: 70,
        name: 'Second Bit',
        label: 'label for second bit',
        tooltip: 'more info about this bit'
      }
    ]);

    render();

    const instance = wrapper.instance();
    chart = instance._chart;
  });

  describe('shouldComponentUpdate', () => {
    beforeEach(() => {
      chart.setTitle = jest.fn();
      chart.series[0].setData = jest.fn();
      // spyOn(chart, 'setTitle');
      // spyOn(chart.series[0], 'setData');
    });

    describe('when title changes', () => {
      test("calls setTitle", () => {
        wrapper.setProps({ title: 'different title', data: wrapper.props().data });
        expect(chart.setTitle).toHaveBeenCalledWith({ text: "different title" });
      });
    });

    describe('when data changes', () => {
      it("calls setData", () => {
        const newData = Immutable.fromJS({ foo: "bar" });
        wrapper.setProps({ title: wrapper.props().title, data: newData });
        expect(chart.series[0].setData).toHaveBeenCalledWith(newData.toJS());
      });
    });

    describe('when nothing has changed', () => {
      it("calls neither set methods", () => {
        const theProps = wrapper.props();
        wrapper.setProps({ title: theProps.title, data: theProps.data });
        expect(chart.setTitle).not.toHaveBeenCalled();
        expect(chart.series[0].setData).not.toHaveBeenCalled();
      });
    });
  });

  describe('mainClasses', () => {
    it('returns the base class', () => {
      expect(wrapper.instance().mainClasses).toEqual('carbon-rainbow');
    });

    describe('when a custom class is passed', () => {
      it('returns base and custom class', () => {
        render({ className: 'customClass' });
        expect(wrapper.instance().mainClasses).toEqual('carbon-rainbow customClass');
      });
    });
  });

  xdescribe('highcharts config', () => {
    it("sets the config to use the data", () => {
      expect(chart.userOptions.series[0].data).toEqual(wrapper.instance().props.data.toJS());
    });

    it("sets the config to use the title", () => {
      expect(chart.userOptions.title.text).toEqual(wrapper.instance().props.title);
    });

    it("calls zIndexSetter when triggering mouse over on a segment", () => {
      let point = chart.series[0].data[0];
      let graphic = point.graphic;

      spyOn(graphic, 'zIndexSetter');
      point.onMouseOver();

      expect(graphic.zIndexSetter).toHaveBeenCalledWith(1);
    });

    it("calls zIndexSetter when triggering mouse over on a segment", () => {
      let point = chart.series[0].data[0];
      let graphic = point.graphic;

      spyOn(graphic, 'zIndexSetter');
      point.onMouseOut();

      expect(graphic.zIndexSetter).toHaveBeenCalledWith(0);
    });

    it("positions the tooltip correctly", () => {
      let opts = {
        plotX: 100,
        plotY: 200
      };
      expect(chart.userOptions.tooltip.positioner(50, 100, opts)).toEqual({ x: 75, y: 105 });
    });

    it("sets the label to be display block if the pointer is visible", () => {
      chart.series[0].setData([{
        y: 30,
        name: 'First Bit',
        label: 'label for first bit',
        tooltip: 'more info about this bit',
        visible: true
      }]);
      let display = chart.series[0].points[0].dataLabel.div.children[0].children[0].style["display"];
      expect(display).toEqual('block');
    });

    it("sets the label to be display none if the pointer is not visible", () => {
      chart.series[0].setData([{
        y: 30,
        name: 'First Bit',
        label: 'label for first bit',
        tooltip: 'more info about this bit',
        visible: false
      }]);
      let display = chart.series[0].points[0].dataLabel.div.children[0].children[0].style["display"];
      expect(display).toEqual('none');
    });

    describe('config property', () => {
      describe('uses some default chart config when no config is passed', () => {
        it("can use the config property to override some chart properties", () => {
          expect(chart.options.chart.backgroundColor).toEqual(null);
          expect(chart.options.credits.enabled).toEqual(false);
        });
      });

      describe('it is possible to override the chart properties using the config props', () => {
        let config = {
          credits: {
            enabled: true
          },
          chart: {
            backgroundColor: '#ff00cc'
          }
        };

        beforeEach(() => {
          render({config});
        });

        it("can use the config property to override some chart properties", () => {
          expect(chart.options.chart.backgroundColor).toEqual('#ff00cc');
          expect(chart.options.credits.enabled).toEqual(true);
        });
      });
    });
  });

  describe("tags on component", () => {
    let wrapper = shallow(
      <Rainbow
        data-element='bar'
        data-role='baz'
        data={ {} }/>
      );

    it('include correct component, element and role data tags', () => {
      rootTagTest(wrapper, 'rainbow', 'bar', 'baz');
    });
  });
});
<|endoftext|>


<commit_before>(function(cobalt){
    var plugin={
        name:"location",
        onError:undefined,
        onSuccess:undefined,
        defaultHandlers :{
            onLocationChanged:function(obj){
                cobalt.log('LocationPlugin location changed ', obj)
            },
            onStatusChanged:function(obj){
                cobalt.log('LocationPlugin status changed', obj && obj.status)
            }
        },
        init:function(options){
            cobalt.log('LocationPlugin initialization', options)

            //install plugin in cobalt scope
            cobalt.location={
                start:this.startLocation.bind(this),
                stop:this.stopLocation.bind(this),
                onLocationChanged : this.defaultHandlers.onLocationChanged,
                onStatusChanged : this.defaultHandlers.onStatusChanged
            };
            this.defineCallbacks(options);
        },
        defineCallbacks:function(options){
            if (options){
                if ( typeof options.onLocationChanged == "function"){
                    cobalt.location.onLocationChanged=options.onLocationChanged;
                }
                if ( typeof options.onStatusChanged == "function"){
                    cobalt.location.onStatusChanged=options.onStatusChanged;
                }
            }
        },
        startLocation:function(options){
            if (!options || !options.mode){
                cobalt.log('LocationPlugin startLocation invalid parameters : missing mode parameter');
                return
            }
            this.defineCallbacks(options);

            cobalt.log('LocationPlugin sending startLocation with options', options);
            this.send('startLocation',options);
        },
        stopLocation:function(){
            cobalt.log('LocationPlugin sending stopLocation');
            this.send('stopLocation');
        },
        handleEvent:function(json){
            cobalt.log('LocationPlugin received plugin event', json);
            switch (json && json.action){
                case "onLocationChanged":
                    cobalt.location.onLocationChanged(json.data);
                    break;
                case "onStatusChanged":
                    cobalt.location.onStatusChanged(json.data);
                    break;
            }
        },
        send:function(action, data, callback){
            cobalt.send({ type : "plugin", name : "location", action : action, data : data }, callback);
        }
    };
    cobalt.plugins.register(plugin);

})(cobalt || {});<commit_msg>Add status enum<commit_after>(function (cobalt) {
    var plugin = {
        name: "location",

        defaultHandlers: {
            onLocationChanged: function (obj) {
                cobalt.log(this.name, ': location changed: ', obj);
            },
            onStatusChanged: function (obj) {
                cobalt.log(this.name, ': status changed: ', obj && obj.status);
            }
        },

        status: {
            REFUSED: 'refused',
            DISABLED: 'disabled',
            TIMEOUT: 'timeout'
        },

        init: function (options) {
            cobalt.location = {
                start: this.startLocation.bind(this),
                stop: this.stopLocation.bind(this),
                onLocationChanged: this.defaultHandlers.onLocationChanged,
                onStatusChanged: this.defaultHandlers.onStatusChanged,
                status: this.status
            };

            this.defineCallbacks(options);
        },

        defineCallbacks: function (options) {
            if (options) {
                if (typeof options.onLocationChanged == 'function') {
                    cobalt.location.onLocationChanged = options.onLocationChanged;
                }

                if (typeof options.onStatusChanged == 'function') {
                    cobalt.location.onStatusChanged = options.onStatusChanged;
                }
            }
        },

        startLocation: function (options) {
            this.defineCallbacks(options);

            this.send('startLocation', options || {});
        },

        stopLocation: function () {
            this.send('stopLocation');
        },

        handleEvent: function (json) {
            cobalt.log(this.name, ': received plugin event: ', json);

            switch (json && json.action) {
                case 'onLocationChanged':
                    cobalt.location.onLocationChanged(json.data);
                    break;

                case 'onStatusChanged':
                    cobalt.location.onStatusChanged(json.data);
                    break;

                default:
                    cobalt.log(this.name, ': unknown action: ', json.action);
                    break;
            }
        },

        send: function (action, data, callback) {
            cobalt.send({
                type: 'plugin',
                name: this.name,
                action: action,
                data: data
            }, callback);
        }
    };

    cobalt.plugins.register(plugin);
})(cobalt || {});
<|endoftext|>


<commit_before>import React from 'react';
import TestUtils from 'react-dom/test-utils';
import Rainbow from './rainbow';
import Immutable from 'immutable';
import { shallow, mount } from 'enzyme';
import { elementsTagTest, rootTagTest } from '../../utils/helpers/tags/tags-specs';

/* global jest */

describe('Rainbow', () => {
  global.Highcharts = {
    chart() {
      return {
        setTitle() {},
        series: [
          { setData() {} }
        ]
      };
    }
  };

  let wrapper, data, chart;

  function render(props={}) {
    wrapper = mount(
      <Rainbow title="My Title" data={ data } { ...props } />
    );
  };

  beforeEach(() => {
    data = Immutable.fromJS([
      {
        y: 30,
        name: 'First Bit',
        label: 'label for first bit',
        tooltip: 'more info about this bit'
      }, {
        y: 70,
        name: 'Second Bit',
        label: 'label for second bit',
        tooltip: 'more info about this bit'
      }
    ]);

    render();

    const instance = wrapper.instance();
    chart = instance._chart;
  });

  describe('shouldComponentUpdate', () => {
    beforeEach(() => {
      chart.setTitle = jest.fn();
      chart.series[0].setData = jest.fn();
      // spyOn(chart, 'setTitle');
      // spyOn(chart.series[0], 'setData');
    });

    describe('when title changes', () => {
      test("calls setTitle", () => {
        wrapper.setProps({ title: 'different title', data: wrapper.props().data });
        expect(chart.setTitle).toHaveBeenCalledWith({ text: "different title" });
      });
    });

    describe('when data changes', () => {
      it("calls setData", () => {
        const newData = Immutable.fromJS({ foo: "bar" });
        wrapper.setProps({ title: wrapper.props().title, data: newData });
        expect(chart.series[0].setData).toHaveBeenCalledWith(newData.toJS());
      });
    });

    describe('when nothing has changed', () => {
      it("calls neither set methods", () => {
        const theProps = wrapper.props();
        wrapper.setProps({ title: theProps.title, data: theProps.data });
        expect(chart.setTitle).not.toHaveBeenCalled();
        expect(chart.series[0].setData).not.toHaveBeenCalled();
      });
    });
  });

  describe('mainClasses', () => {
    it('returns the base class', () => {
      expect(wrapper.instance().mainClasses).toEqual('carbon-rainbow');
    });

    describe('when a custom class is passed', () => {
      it('returns base and custom class', () => {
        render({ className: 'customClass' });
        expect(wrapper.instance().mainClasses).toEqual('carbon-rainbow customClass');
      });
    });
  });

  xdescribe('highcharts config', () => {
    it("sets the config to use the data", () => {
      expect(chart.userOptions.series[0].data).toEqual(wrapper.instance().props.data.toJS());
    });

    it("sets the config to use the title", () => {
      expect(chart.userOptions.title.text).toEqual(wrapper.instance().props.title);
    });

    it("calls zIndexSetter when triggering mouse over on a segment", () => {
      let point = chart.series[0].data[0];
      let graphic = point.graphic;

      spyOn(graphic, 'zIndexSetter');
      point.onMouseOver();

      expect(graphic.zIndexSetter).toHaveBeenCalledWith(1);
    });

    it("calls zIndexSetter when triggering mouse over on a segment", () => {
      let point = chart.series[0].data[0];
      let graphic = point.graphic;

      spyOn(graphic, 'zIndexSetter');
      point.onMouseOut();

      expect(graphic.zIndexSetter).toHaveBeenCalledWith(0);
    });

    it("positions the tooltip correctly", () => {
      let opts = {
        plotX: 100,
        plotY: 200
      };
      expect(chart.userOptions.tooltip.positioner(50, 100, opts)).toEqual({ x: 75, y: 105 });
    });

    it("sets the label to be display block if the pointer is visible", () => {
      chart.series[0].setData([{
        y: 30,
        name: 'First Bit',
        label: 'label for first bit',
        tooltip: 'more info about this bit',
        visible: true
      }]);
      let display = chart.series[0].points[0].dataLabel.div.children[0].children[0].style["display"];
      expect(display).toEqual('block');
    });

    it("sets the label to be display none if the pointer is not visible", () => {
      chart.series[0].setData([{
        y: 30,
        name: 'First Bit',
        label: 'label for first bit',
        tooltip: 'more info about this bit',
        visible: false
      }]);
      let display = chart.series[0].points[0].dataLabel.div.children[0].children[0].style["display"];
      expect(display).toEqual('none');
    });

    describe('config property', () => {
      describe('uses some default chart config when no config is passed', () => {
        it("can use the config property to override some chart properties", () => {
          expect(chart.options.chart.backgroundColor).toEqual(null);
          expect(chart.options.credits.enabled).toEqual(false);
        });
      });

      describe('it is possible to override the chart properties using the config props', () => {
        let config = {
          credits: {
            enabled: true
          },
          chart: {
            backgroundColor: '#ff00cc'
          }
        };

        beforeEach(() => {
          render({config});
        });

        it("can use the config property to override some chart properties", () => {
          expect(chart.options.chart.backgroundColor).toEqual('#ff00cc');
          expect(chart.options.credits.enabled).toEqual(true);
        });
      });
    });
  });

  describe("tags on component", () => {
    let wrapper = shallow(
      <Rainbow
        data-element='bar'
        data-role='baz'
        data={ {} }/>
      );

    it('include correct component, element and role data tags', () => {
      rootTagTest(wrapper, 'rainbow', 'bar', 'baz');
    });
  });
});
<commit_msg>Remove highcharts config tests<commit_after>import React from 'react';
import TestUtils from 'react-dom/test-utils';
import Rainbow from './rainbow';
import Immutable from 'immutable';
import { shallow, mount } from 'enzyme';
import { elementsTagTest, rootTagTest } from '../../utils/helpers/tags/tags-specs';

/* global jest */

describe('Rainbow', () => {
  global.Highcharts = {
    chart() {
      return {
        setTitle() {},
        series: [
          { setData() {} }
        ]
      };
    }
  };

  let wrapper, data, chart;

  function render(props={}) {
    wrapper = mount(
      <Rainbow title="My Title" data={ data } { ...props } />
    );
  };

  beforeEach(() => {
    data = Immutable.fromJS([
      {
        y: 30,
        name: 'First Bit',
        label: 'label for first bit',
        tooltip: 'more info about this bit'
      }, {
        y: 70,
        name: 'Second Bit',
        label: 'label for second bit',
        tooltip: 'more info about this bit'
      }
    ]);

    render();

    const instance = wrapper.instance();
    chart = instance._chart;
  });

  describe('shouldComponentUpdate', () => {
    beforeEach(() => {
      chart.setTitle = jest.fn();
      chart.series[0].setData = jest.fn();
    });

    describe('when title changes', () => {
      test("calls setTitle", () => {
        wrapper.setProps({ title: 'different title', data: wrapper.props().data });
        expect(chart.setTitle).toHaveBeenCalledWith({ text: "different title" });
      });
    });

    describe('when data changes', () => {
      it("calls setData", () => {
        const newData = Immutable.fromJS({ foo: "bar" });
        wrapper.setProps({ title: wrapper.props().title, data: newData });
        expect(chart.series[0].setData).toHaveBeenCalledWith(newData.toJS());
      });
    });

    describe('when nothing has changed', () => {
      it("calls neither set methods", () => {
        const theProps = wrapper.props();
        wrapper.setProps({ title: theProps.title, data: theProps.data });
        expect(chart.setTitle).not.toHaveBeenCalled();
        expect(chart.series[0].setData).not.toHaveBeenCalled();
      });
    });
  });

  describe('mainClasses', () => {
    it('returns the base class', () => {
      expect(wrapper.instance().mainClasses).toEqual('carbon-rainbow');
    });

    describe('when a custom class is passed', () => {
      it('returns base and custom class', () => {
        render({ className: 'customClass' });
        expect(wrapper.instance().mainClasses).toEqual('carbon-rainbow customClass');
      });
    });
  });

  describe("tags on component", () => {
    let wrapper = shallow(
      <Rainbow
        data-element='bar'
        data-role='baz'
        data={ {} }/>
      );

    it('include correct component, element and role data tags', () => {
      rootTagTest(wrapper, 'rainbow', 'bar', 'baz');
    });
  });
});
<|endoftext|>


<commit_before>import React from 'react';

import dateFormat from 'dateformat';

export default class ResultContainer extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        var {apiResult} = this.props;

        return (

download-url: {apiResult.downloadUrl}

expires on {dateFormat(apiResult.expirationDate)}

        );
    }
}<commit_msg>fixed missing dependency to "dateformat" switched date format to momentjs formating<commit_after>import React from 'react';
import moment from 'moment';

export default class ResultContainer extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        var {apiResult} = this.props;

        return (

download-url: {apiResult.downloadUrl}

expires on {moment(apiResult.expirationDate).format('LLL')}

        );
    }
}<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.weather', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/weather', {
    templateUrl: 'weather/weather.html',
    controller: 'WeatherCtrl'
  });
}])

.controller('WeatherCtrl', [function() {
      $(".menu-item").removeClass("active");
      $("#weather").addClass("active");
}]);<commit_msg>copied over controller from weather project<commit_after>'use strict';

angular.module('myApp.weather', ['ngRoute'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/weather', {
            templateUrl: 'weather/weather.html',
            controller: 'WeatherCtrl',
            resolve: {
                weatherData: ['$q', 'weatherSvc', function ($q, weatherSvc) {
                    var deferred = $q.defer();

                    navigator.geolocation.getCurrentPosition(
                        deferred.resolve,
                        deferred.reject);

                    return deferred.promise.then(function (position) {
                            return weatherSvc.query(position.coords.latitude, position.coords.longitude);
                        }
                    );
                }]
            }
        });
    }])

    .controller('WeatherCtrl', ['$scope', '$animate', '$timeout', 'weatherData', function ($scope, $animate, $timeout, weatherData) {
        $(".menu-item").removeClass("active");
        $("#twitter").addClass("active");

        $scope.weatherData = weatherData.data;
        $scope.day = 0;
        $scope.tempMode = 'C';

        // todo remove
        console.log($scope.weatherData);

        var getBG = function (day) {
            var id = $scope.weatherData.list[day].weather[0].id;

            // http://openweathermap.org/weather-conditions
            switch (true) {
                case (id >= 200 && id < 300):
                    return "https://static.pexels.com/photos/799/city-lights-night-clouds.jpg";
                case (id >= 300 && id < 400):
                    return "https://static.pexels.com/photos/1551/field-thunderstorm-rainy-meadow.jpg";
                case (id >= 500 && id < 600):
                    return "https://static.pexels.com/photos/639/clouds-rainy-rain-asia-large.jpg";
                case (id >= 600 && id < 700):
                    return "https://static.pexels.com/photos/374/snow-dawn-sunset-winter-large.jpg";
                case (id === 701):
                    return "https://static.pexels.com/photos/5052/road-fog-bend-foggy-large.jpg";
                case (id >= 702 && id < 800):
                    return "https://static.pexels.com/photos/4241/cold-snow-black-and-white-road-large.jpg";
                case (id === 800):
                    return "https://static.pexels.com/photos/180/wood-sea-landscape-nature-large.jpg";
                case (id >= 801 && id < 804):
                    return "https://static.pexels.com/photos/215/road-sky-clouds-cloudy.jpg";
                case (id >= 804 && id < 900):
                    return "https://static.pexels.com/photos/1679/sea-nature-beach-clouds-large.jpg";
                case (id === 900): // tornado
                    return "";
                case (id === 901):
                    return "https://static.pexels.com/photos/6648/sea-water-ocean-storm-large.jpg";
                case (id === 902):
                    return "https://static.pexels.com/photos/3927/storm-hotel-waves-windy-large.jpeg";
                case (id === 903):
                    return "https://static.pexels.com/photos/2969/climate-cold-glacier-iceberg-large.jpg";
                case (id === 904):
                    return "https://static.pexels.com/photos/607/sea-beach-sand-ocean-large.jpg";
                case (id === 905):
                    return "https://static.pexels.com/photos/1549/nature-fashion-person-red-large.jpg";
                case (id === 906):
                    return "https://static.pexels.com/photos/3935/cold-snow-black-and-white-train-large.jpeg";

                case (id === 951):
                    return "https://static.pexels.com/photos/6643/sea-dawn-sunset-cloudy-large.jpg";
                case (id >= 952 && id < 956):
                    return "https://static.pexels.com/photos/1206/person-woman-girl-blonde-large.jpg";
                case (id >= 956 && id < 960):
                    return "https://static.pexels.com/photos/2635/sea-beach-storm-tree-large.jpg";
                case (id >= 960 && id < 963):
                    return "https://static.pexels.com/photos/2271/clouds-cloudy-field-meadow-large.jpg";
            }
        };

        var activeImg = '.bgImgOne';
        var inactiveImg = '.bgImgTwo';
        $scope.bgOne = getBG($scope.day);
        $scope.bgTwo = getBG($scope.day);
        $scope.btnDisabled = false;

        var toggleImg = function () {
            if ($scope.btnDisabled) return;

            if (activeImg === '.bgImgOne') {
                $scope.bgTwo = getBG($scope.day);
            } else {
                $scope.bgOne = getBG($scope.day);
            }

            if ($scope.bgOne !== $scope.bgTwo) {
                $scope.btnDisabled = true;
                $animate.addClass(angular.element(activeImg), 'transparent', {});
                $animate.removeClass(angular.element(inactiveImg), 'transparent', {});

                var tmp = activeImg;
                activeImg = inactiveImg;
                inactiveImg = tmp;

                $timeout(function () {
                    $scope.btnDisabled = false;
                }, 1000);
            }
        };

        $scope.next = function () {
            if ($scope.btnDisabled) return;
            $scope.day = (++$scope.day < $scope.weatherData.list.length) ? $scope.day : $scope.weatherData.list.length - 1;
            toggleImg();
        };
        $scope.prev = function () {
            if ($scope.btnDisabled) return;
            $scope.day = (--$scope.day >= 0) ? $scope.day : 0;
            toggleImg();
        };

        var kelvinToCelsius = function (k) {
            return k - 273.15;
        };
        var kelvinToFahrenheit = function (k) {
            return ((k - 273.15) * 9 / 5) + 32;
        };
        $scope.degToCompassDir = function (deg) {
            var dir = Math.round(deg / 45);

            switch (dir) {
                case 0:
                    return 'N';
                case 1:
                    return 'NE';
                case 2:
                    return 'E';
                case 3:
                    return 'SE';
                case 4:
                    return 'S';
                case 5:
                    return 'SW';
                case 6:
                    return 'W';
                case 7:
                    return 'NW';
                case 8:
                    return 'N';
            }
        };
        $scope.mpsToKph = function (mps) {
            return mps * 3.6;
        };
        $scope.tempMin = function (day, mode) {
            switch (mode) {
                case 'C':
                    return kelvinToCelsius($scope.weatherData.list[day].temp.min);
                case 'K':
                    return $scope.weatherData.list[day].temp.min;
                case 'F':
                    return kelvinToFahrenheit($scope.weatherData.list[day].temp.min);
            }
        };
        $scope.tempMax = function (day, mode) {
            switch (mode) {
                case 'C':
                    return kelvinToCelsius($scope.weatherData.list[day].temp.max);
                case 'K':
                    return $scope.weatherData.list[day].temp.max;
                case 'F':
                    return kelvinToFahrenheit($scope.weatherData.list[day].temp.max);
            }
        };
        $scope.toTitleCase = function (str) {
            return str.replace(/\w\S*/g, function (txt) {
                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
            });
        };

    }]);

<|endoftext|>


<commit_before>/**
 * @file PopupProvider component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component, cloneElement, Fragment, createRef} from 'react';
import PropTypes from 'prop-types';
import {findDOMNode} from 'react-dom';

// components
import Popup from '../Popup';

// statics
import Theme from '../Theme';
import Position from '../_statics/Position';

// vendors
import Util from '../_vendors/Util';
import ComponentUtil from '../_vendors/ComponentUtil';

class PopupProvider extends Component {

    static Position = Position;
    static Theme = Theme;

    static getDerivedStateFromProps(props, state) {
        return {
            prevProps: props,
            value: ComponentUtil.getDerivedState(props, state, 'visible')
        };
    }

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.trigger = createRef();
        this.triggerEl = null;

        this.state = {
            visible: props.visible
        };

    }

    /**
     * public
     */
    toggle = () => {
        this.setState({
            visible: !this.state.visible
        }, () => {
            if (!this.state.visible) {
                const {onRequestClose} = this.props;
                onRequestClose && onRequestClose();
            } else {
                const {onRequestOpen} = this.props;
                onRequestOpen && onRequestOpen();
            }
        });
    };

    /**
     * public
     */
    hide = () => {
        this.setState({
            visible: false
        }, () => {
            const {onRequestClose} = this.props;
            onRequestClose && onRequestClose();
        });
    };

    handleClick = e => {

        const {children} = this.props;

        if (children && children.props && children.props.onClick
            && typeof children.props.onClick === 'function') {
            children.props.onClick(e);
        }

        this.toggle();

    };

    componentDidMount() {
        this.triggerEl = this.trigger && this.trigger.current && findDOMNode(this.trigger.current);
    }

    render() {

        const {

                children, popupContent,

                // not passing down these props
                onRequestOpen, onRequestClose,

                ...restProps

            } = this.props,
            {visible} = this.state;

        if (!popupContent) {
            return children;
        }

        return (
            <Fragment>

                {
                    cloneElement(children, {
                        ref: this.trigger,
                        onClick: this.handleClick
                    })
                }

                <Popup {...restProps}
                       triggerEl={this.triggerEl}
                       visible={visible}
                       onRequestClose={this.hide}>
                    {popupContent}
                </Popup>

            </Fragment>
        );
    }

}

PopupProvider.propTypes = {

    children: PropTypes.any,

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * The CSS class name of the content element.
     */
    contentClassName: PropTypes.string,

    modalClassName: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The popup theme.Can be primary,highlight,success,warning,error.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    parentEl: PropTypes.object,

    /**
     * This is the DOM element that will be used to set the position of the popup.
     */
    triggerEl: PropTypes.object,

    /**
     * If true,the popup is visible.
     */
    visible: PropTypes.bool,

    /**
     * If true,the popup will have a triangle on the top of the DOM element.
     */
    hasTriangle: PropTypes.bool,

    triangle: PropTypes.element,

    /**
     * The popup alignment.
     */
    position: PropTypes.oneOf(Util.enumerateValue(Position)),

    /**
     * If true,popup will have animation effects.
     */
    isAnimated: PropTypes.bool,

    /**
     * The depth of Paper component.
     */
    depth: PropTypes.number,

    isBlurClose: PropTypes.bool,
    isEscClose: PropTypes.bool,

    shouldFollowScroll: PropTypes.bool,
    scrollEl: PropTypes.object,

    resetPositionWait: PropTypes.number,
    showModal: PropTypes.bool,

    /**
     * The function of popup event handler.
     */
    triggerHandler: PropTypes.func,

    /**
     * The function of popup render.
     */
    onRender: PropTypes.func,

    /**
     * The function of popup rendered.
     */
    onRendered: PropTypes.func,

    /**
     * The function of popup destroy.
     */
    onDestroy: PropTypes.func,

    /**
     * The function of popup destroyed.
     */
    onDestroyed: PropTypes.func,

    /**
     * Callback function fired when the popup is requested to be opened.
     */
    onRequestOpen: PropTypes.func,

    /**
     * Callback function fired when the popup is requested to be closed.
     */
    onRequestClose: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func,

    popupContent: PropTypes.any

};

PopupProvider.defaultProps = {

    parentEl: document.body,

    visible: false,
    hasTriangle: true,
    position: Position.BOTTOM,
    isAnimated: true,

    isBlurClose: true,
    isEscClose: true,
    shouldFollowScroll: false,
    resetPositionWait: 250,
    showModal: false

};

export default PopupProvider;
<commit_msg>optimize PopupProvider<commit_after>/**
 * @file PopupProvider component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component, cloneElement, Fragment, createRef} from 'react';
import PropTypes from 'prop-types';
import {findDOMNode} from 'react-dom';

// components
import Popup from '../Popup';

// statics
import Theme from '../Theme';
import Position from '../_statics/Position';

// vendors
import Util from '../_vendors/Util';
import ComponentUtil from '../_vendors/ComponentUtil';

class PopupProvider extends Component {

    static Position = Position;
    static Theme = Theme;

    static getDerivedStateFromProps(props, state) {
        return {
            prevProps: props,
            value: ComponentUtil.getDerivedState(props, state, 'visible')
        };
    }

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.trigger = createRef();
        this.triggerEl = null;

        this.state = {
            visible: props.visible
        };

    }

    /**
     * public
     */
    toggle = () => {
        this.setState({
            visible: !this.state.visible
        }, () => {
            if (!this.state.visible) {
                const {onRequestClose} = this.props;
                onRequestClose && onRequestClose();
            } else {
                const {onRequestOpen} = this.props;
                onRequestOpen && onRequestOpen();
            }
        });
    };

    /**
     * public
     */
    hide = () => {

        if (!this.state.visible) {
            return;
        }

        this.setState({
            visible: false
        }, () => {
            const {onRequestClose} = this.props;
            onRequestClose && onRequestClose();
        });

    };

    handleClick = e => {

        const {children} = this.props;

        if (children && children.props && children.props.onClick
            && typeof children.props.onClick === 'function') {
            children.props.onClick(e);
        }

        this.toggle();

    };

    componentDidMount() {
        this.triggerEl = this.trigger && this.trigger.current && findDOMNode(this.trigger.current);
    }

    render() {

        const {

                children, popupContent,

                // not passing down these props
                onRequestOpen, onRequestClose,

                ...restProps

            } = this.props,
            {visible} = this.state;

        if (!popupContent) {
            return children;
        }

        return (
            <Fragment>

                {
                    cloneElement(children, {
                        ref: this.trigger,
                        onClick: this.handleClick
                    })
                }

                <Popup {...restProps}
                       triggerEl={this.triggerEl}
                       visible={visible}
                       onRequestClose={this.hide}>
                    {popupContent}
                </Popup>

            </Fragment>
        );
    }

}

PopupProvider.propTypes = {

    children: PropTypes.any,

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * The CSS class name of the content element.
     */
    contentClassName: PropTypes.string,

    modalClassName: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The popup theme.Can be primary,highlight,success,warning,error.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    parentEl: PropTypes.object,

    /**
     * This is the DOM element that will be used to set the position of the popup.
     */
    triggerEl: PropTypes.object,

    /**
     * If true,the popup is visible.
     */
    visible: PropTypes.bool,

    /**
     * If true,the popup will have a triangle on the top of the DOM element.
     */
    hasTriangle: PropTypes.bool,

    triangle: PropTypes.element,

    /**
     * The popup alignment.
     */
    position: PropTypes.oneOf(Util.enumerateValue(Position)),

    /**
     * If true,popup will have animation effects.
     */
    isAnimated: PropTypes.bool,

    /**
     * The depth of Paper component.
     */
    depth: PropTypes.number,

    isBlurClose: PropTypes.bool,
    isEscClose: PropTypes.bool,

    shouldFollowScroll: PropTypes.bool,
    scrollEl: PropTypes.object,

    resetPositionWait: PropTypes.number,
    showModal: PropTypes.bool,

    /**
     * The function of popup event handler.
     */
    triggerHandler: PropTypes.func,

    /**
     * The function of popup render.
     */
    onRender: PropTypes.func,

    /**
     * The function of popup rendered.
     */
    onRendered: PropTypes.func,

    /**
     * The function of popup destroy.
     */
    onDestroy: PropTypes.func,

    /**
     * The function of popup destroyed.
     */
    onDestroyed: PropTypes.func,

    /**
     * Callback function fired when the popup is requested to be opened.
     */
    onRequestOpen: PropTypes.func,

    /**
     * Callback function fired when the popup is requested to be closed.
     */
    onRequestClose: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func,

    popupContent: PropTypes.any

};

PopupProvider.defaultProps = {

    parentEl: document.body,

    visible: false,
    hasTriangle: true,
    position: Position.BOTTOM,
    isAnimated: true,

    isBlurClose: true,
    isEscClose: true,
    shouldFollowScroll: false,
    resetPositionWait: 250,
    showModal: false

};

export default PopupProvider;
<|endoftext|>


<commit_before>import React from 'react';
import MonacoEditor from 'react-monaco-editor';
import './styles.css';

export default class TextEditor extends React.Component {

    state = { value: '', language: '', editor: null };

    editor = null;

    options = {
        minimap: false,
        selectOnLineNumbers: true,
        theme: 'vs-dark'
    };

    get visible() {
        return !(this.state.value && this.state.language);
    }

    editorDidMount(editor, monaco) {
        editor.focus();
        this.editor = editor;
    }

    loadCode(value, language) {
        const { body } = this.props;
        this.setState({ value, language });
        this.editor.layout(body);
    }

    onChange(value, e) {
        this.setState({ value }, () => {
            this.props.onChange && this.props.onChange(value, e);
        });
    }

    render() {
        return (

                <MonacoEditor
                    {...this.state}
                    options={this.options}
                    onChange={(newValue, e) => this.onChange(newValue, e)}
                    editorDidMount={(editor, monaco) => this.editorDidMount(editor, monaco)}
                />

        );
    }
}<commit_msg>Disabling minimap<commit_after>import React from 'react';
import MonacoEditor from 'react-monaco-editor';
import './styles.css';

export default class TextEditor extends React.Component {

    state = { value: '', language: '', editor: null };

    editor = null;

    options = {
        minimap: { enabled: false },
        selectOnLineNumbers: true,
        theme: 'vs-dark'
    };

    get visible() {
        return !(this.state.value && this.state.language);
    }

    editorDidMount(editor, monaco) {
        editor.focus();
        this.editor = editor;
    }

    loadCode(value, language) {
        const { body } = this.props;
        this.setState({ value, language });
        this.editor.layout(body);
    }

    onChange(value, e) {
        this.setState({ value }, () => {
            this.props.onChange && this.props.onChange(value, e);
        });
    }

    render() {
        return (

                <MonacoEditor
                    {...this.state}
                    options={this.options}
                    onChange={(newValue, e) => this.onChange(newValue, e)}
                    editorDidMount={(editor, monaco) => this.editorDidMount(editor, monaco)}
                />

        );
    }
}<|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 d3 = require('d3');

var Plotly = require('../../plotly');
var Plots = require('../../plots/plots');
var Lib = require('../../lib');
var Color = require('../color');
var Drawing = require('../drawing');
var svgTextUtils = require('../../lib/svg_text_utils');
var anchorUtils = require('../legend/anchor_utils');

var constants = require('./constants');

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout,
        menuData = makeMenuData(fullLayout);

    /* Update menu data is bound to the header-group.
     * The items in the header group are always present.
     *
     * Upon clicking on a header its corresponding button
     * data is bound to the button-group.
     *
     * We draw all headers in one group before all buttons
     * so that the buttons *always* appear above the headers.
     *
     * Note that only one set of buttons are visible at once.
     *
     * <g container />
     *
     *     <g header-group />
     *         <g item header />
     *         <text item header-arrow />
     *     <g header-group />
     *         <g item header />
     *         <text item header-arrow />
     *     ...
     *
     *     <g button-group />
     *         <g item button />
     *         <g item button />
     *         ...
     */

    // draw update menu container
    var menus = fullLayout._infolayer
        .selectAll('g.' + constants.containerClassName)
        .data(menuData.length > 0 ? [0] : []);

    menus.enter().append('g')
        .classed(constants.containerClassName, true)
        .style('cursor', 'pointer');

    menus.exit().remove();

    // return early if no update menus are visible
    if(menuData.length === 0) return;

    // join header group
    var headerGroups = menus.selectAll('g.' + constants.headerGroupClassName)
        .data(menuData, keyFunction);

    headerGroups.enter().append('g')
        .classed(constants.headerGroupClassName, true);

    // draw button container
    var gButton = menus.selectAll('g.' + constants.buttonGroupClassName)
        .data([0]);

    gButton.enter().append('g')
        .classed(constants.buttonGroupClassName, true)
        .style('pointer-events', 'all');

    // whenever we add new menu, attach 'state' variable to node
    // to keep track of the active menu ('-1' means no menu is active)
    // and remove all dropped buttons (if any)
    if(headerGroups.enter().size()) {
        gButton
            .call(removeAllButtons)
            .attr(constants.menuIndexAttrName, '-1');
    }

    // remove exiting header, remove dropped buttons and reset margins
    headerGroups.exit().each(function(menuOpts) {
        d3.select(this).remove();

        gButton
            .call(removeAllButtons)
            .attr(constants.menuIndexAttrName, '-1');

        Plots.autoMargin(gd, constants.autoMarginIdRoot + menuOpts._index);
    });

    // find dimensions before plotting anything (this mutates menuOpts)
    for(var i = 0; i < menuData.length; i++) {
        var menuOpts = menuData[i];

        // often more convenient than playing with two arguments
        menuOpts._index = i;
        findDimenstions(gd, menuOpts);
    }

    // draw headers!
    headerGroups.each(function(menuOpts) {
        var gHeader = d3.select(this);
        drawHeader(gd, gHeader, gButton, menuOpts);

        // update buttons if they are dropped
        if(areMenuButtonsDropped(gButton, menuOpts)) {
            drawButtons(gd, gHeader, gButton, menuOpts);
        }
    });
};

function makeMenuData(fullLayout) {
    var contOpts = fullLayout[constants.name],
        menuData = [];

    for(var i = 0; i < contOpts.length; i++) {
        var item = contOpts[i];

        if(item.visible) menuData.push(item);
    }

    return menuData;
}

function keyFunction(opts, i) {
    return opts.visible + i;
}

function areMenuButtonsDropped(gButton, menuOpts) {
    var droppedIndex = +gButton.attr(constants.menuIndexAttrName);

    return droppedIndex === menuOpts._index;
}

function drawHeader(gd, gHeader, gButton, menuOpts) {
    var header = gHeader.selectAll('g.' + constants.headerClassName)
        .data([0]);

    header.enter().append('g')
        .classed(constants.headerClassName, true)
        .style('pointer-events', 'all');

    var active = menuOpts.active,
        headerOpts = menuOpts.buttons[active] || constants.blankHeaderOpts,
        posOpts = { y: 0, yPad: 0 };

    header
        .call(drawItem, menuOpts, headerOpts)
        .call(setItemPosition, menuOpts, posOpts);

    // draw drop arrow at the right edge
    var arrow = gHeader.selectAll('text.' + constants.headerArrowClassName)
        .data([0]);

    arrow.enter().append('text')
        .classed(constants.headerArrowClassName, true)
        .classed('user-select-none', true)
        .attr('text-anchor', 'end')
        .call(Drawing.font, menuOpts.font)
        .text('▼');

    arrow.attr({
        x: menuOpts.width - constants.arrowOffsetX,
        y: menuOpts.height1 / 2 + constants.textOffsetY
    });

    header.on('click', function() {
        gButton.call(removeAllButtons);

        // if clicked index is same as dropped index => fold
        // otherwise => drop buttons associated with header
        gButton.attr(
            constants.menuIndexAttrName,
            areMenuButtonsDropped(gButton, menuOpts) ? '-1' : String(menuOpts._index)
        );

        drawButtons(gd, gHeader, gButton, menuOpts);
    });

    header.on('mouseover', function() {
        header.call(styleOnMouseOver);
    });

    header.on('mouseout', function() {
        header.call(styleOnMouseOut, menuOpts);
    });

    // translate header group
    Lib.setTranslate(gHeader, menuOpts.lx, menuOpts.ly);
}

function drawButtons(gd, gHeader, gButton, menuOpts) {
    var buttonData = gButton.attr(constants.menuIndexAttrName) !== '-1' ?
        menuOpts.buttons :
        [];

    var buttons = gButton.selectAll('g.' + constants.buttonClassName)
        .data(buttonData);

    buttons.enter().append('g')
        .classed(constants.buttonClassName, true)
        .attr('opacity', '0')
        .transition()
        .attr('opacity', '1');

    buttons.exit()
        .transition()
        .attr('opacity', '0')
        .remove();

    var posOpts = {
        y: menuOpts.height1 + constants.gapButtonHeader,
        yPad: constants.gapButton
    };

    buttons.each(function(buttonOpts, buttonIndex) {
        var button = d3.select(this);

        button
            .call(drawItem, menuOpts, buttonOpts)
            .call(setItemPosition, menuOpts, posOpts);

        button.on('click', function() {
            // update 'active' attribute in menuOpts
            menuOpts._input.active = menuOpts.active = buttonIndex;

            // fold up buttons and redraw header
            gButton.attr(constants.menuIndexAttrName, '-1');
            drawHeader(gd, gHeader, gButton, menuOpts);
            drawButtons(gd, gHeader, gButton, menuOpts);

            // call button method
            var args = buttonOpts.args;
            Plotly[buttonOpts.method](gd, args[0], args[1], args[2]);
        });

        button.on('mouseover', function() {
            button.call(styleOnMouseOver);
        });

        button.on('mouseout', function() {
            button.call(styleOnMouseOut, menuOpts);
            buttons.call(styleButtons, menuOpts);
        });
    });

    buttons.call(styleButtons, menuOpts);

    // translate button group
    Lib.setTranslate(gButton, menuOpts.lx, menuOpts.ly);
}

function drawItem(item, menuOpts, itemOpts) {
    item.call(drawItemRect, menuOpts)
        .call(drawItemText, menuOpts, itemOpts);
}

function drawItemRect(item, menuOpts) {
    var rect = item.selectAll('rect')
        .data([0]);

    rect.enter().append('rect')
        .classed(constants.itemRectClassName, true)
        .attr({
            rx: constants.rx,
            ry: constants.ry,
            'shape-rendering': 'crispEdges'
        });

    rect.call(Color.stroke, menuOpts.bordercolor)
        .call(Color.fill, menuOpts.bgcolor)
        .style('stroke-width', menuOpts.borderwidth + 'px');
}

function drawItemText(item, menuOpts, itemOpts) {
    var text = item.selectAll('text')
        .data([0]);

    text.enter().append('text')
        .classed(constants.itemTextClassName, true)
        .classed('user-select-none', true)
        .attr('text-anchor', 'start');

    text.call(Drawing.font, menuOpts.font)
        .text(itemOpts.label)
        .call(svgTextUtils.convertToTspans);
}

function styleButtons(buttons, menuOpts) {
    var active = menuOpts.active;

    buttons.each(function(buttonOpts, i) {
        var button = d3.select(this);

        if(i === active) {
            button.select('rect.' + constants.itemRectClassName)
                .call(Color.fill, constants.activeColor);
        }
    });
}

function styleOnMouseOver(item) {
    item.select('rect.' + constants.itemRectClassName)
        .call(Color.fill, constants.hoverColor);
}

function styleOnMouseOut(item, menuOpts) {
    item.select('rect.' + constants.itemRectClassName)
        .call(Color.fill, menuOpts.bgcolor);
}

// find item dimensions (this mutates menuOpts)
function findDimenstions(gd, menuOpts) {
    menuOpts.width = 0;
    menuOpts.height = 0;
    menuOpts.height1 = 0;
    menuOpts.lx = 0;
    menuOpts.ly = 0;

    var fakeButtons = gd._tester.selectAll('g.' + constants.buttonClassName)
        .data(menuOpts.buttons);

    fakeButtons.enter().append('g')
        .classed(constants.buttonClassName, true);

    // loop over fake buttons to find width / height
    fakeButtons.each(function(buttonOpts) {
        var button = d3.select(this);

        button.call(drawItem, menuOpts, buttonOpts);

        var text = button.select('.' + constants.itemTextClassName),
            tspans = text.selectAll('tspan');

        // width is given by max width of all buttons
        var tWidth = text.node() && Drawing.bBox(text.node()).width,
            wEff = Math.max(tWidth + constants.textPadX, constants.minWidth);

        // height is determined by item text
        var tHeight = menuOpts.font.size * constants.fontSizeToHeight,
            tLines = tspans[0].length || 1,
            hEff = Math.max(tHeight * tLines, constants.minHeight) + constants.textOffsetY;

        menuOpts.width = Math.max(menuOpts.width, wEff);
        menuOpts.height1 = Math.max(menuOpts.height1, hEff);
        menuOpts.height += menuOpts.height1;
    });

    fakeButtons.remove();

    var graphSize = gd._fullLayout._size;
    menuOpts.lx = graphSize.l + graphSize.w * menuOpts.x;
    menuOpts.ly = graphSize.t + graphSize.h * (1 - menuOpts.y);

    var xanchor = 'left';
    if(anchorUtils.isRightAnchor(menuOpts)) {
        menuOpts.lx -= menuOpts.width;
        xanchor = 'right';
    }
    if(anchorUtils.isCenterAnchor(menuOpts)) {
        menuOpts.lx -= menuOpts.width / 2;
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(anchorUtils.isBottomAnchor(menuOpts)) {
        menuOpts.ly -= menuOpts.height;
        yanchor = 'bottom';
    }
    if(anchorUtils.isMiddleAnchor(menuOpts)) {
        menuOpts.ly -= menuOpts.height / 2;
        yanchor = 'middle';
    }

    menuOpts.width = Math.ceil(menuOpts.width);
    menuOpts.height = Math.ceil(menuOpts.height);
    menuOpts.lx = Math.round(menuOpts.lx);
    menuOpts.ly = Math.round(menuOpts.ly);

    Plots.autoMargin(gd, constants.autoMarginIdRoot + menuOpts._index, {
        x: menuOpts.x,
        y: menuOpts.y,
        l: menuOpts.width * ({right: 1, center: 0.5}[xanchor] || 0),
        r: menuOpts.width * ({left: 1, center: 0.5}[xanchor] || 0),
        b: menuOpts.height * ({top: 1, middle: 0.5}[yanchor] || 0),
        t: menuOpts.height * ({bottom: 1, middle: 0.5}[yanchor] || 0)
    });
}

// set item positions (mutates posOpts)
function setItemPosition(item, menuOpts, posOpts) {
    var rect = item.select('.' + constants.itemRectClassName),
        text = item.select('.' + constants.itemTextClassName),
        tspans = text.selectAll('tspan'),
        borderWidth = menuOpts.borderwidth;

    Lib.setTranslate(item, borderWidth, borderWidth + posOpts.y);

    rect.attr({
        x: 0,
        y: 0,
        width: menuOpts.width,
        height: menuOpts.height1
    });

    var tHeight = menuOpts.font.size * constants.fontSizeToHeight,
        tLines = tspans[0].length || 1,
        spanOffset = ((tLines - 1) * tHeight / 4);

    var textAttrs = {
        x: constants.textOffsetX,
        y: menuOpts.height1 / 2 - spanOffset + constants.textOffsetY
    };

    text.attr(textAttrs);
    tspans.attr(textAttrs);

    posOpts.y += menuOpts.height1 + posOpts.yPad;
}

function removeAllButtons(gButton) {
    gButton.selectAll('g.' + constants.buttonClassName).remove();
}
<commit_msg>clear all push margins objects if all menus get removed<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 d3 = require('d3');

var Plotly = require('../../plotly');
var Plots = require('../../plots/plots');
var Lib = require('../../lib');
var Color = require('../color');
var Drawing = require('../drawing');
var svgTextUtils = require('../../lib/svg_text_utils');
var anchorUtils = require('../legend/anchor_utils');

var constants = require('./constants');

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout,
        menuData = makeMenuData(fullLayout);

    /* Update menu data is bound to the header-group.
     * The items in the header group are always present.
     *
     * Upon clicking on a header its corresponding button
     * data is bound to the button-group.
     *
     * We draw all headers in one group before all buttons
     * so that the buttons *always* appear above the headers.
     *
     * Note that only one set of buttons are visible at once.
     *
     * <g container />
     *
     *     <g header-group />
     *         <g item header />
     *         <text item header-arrow />
     *     <g header-group />
     *         <g item header />
     *         <text item header-arrow />
     *     ...
     *
     *     <g button-group />
     *         <g item button />
     *         <g item button />
     *         ...
     */

    // draw update menu container
    var menus = fullLayout._infolayer
        .selectAll('g.' + constants.containerClassName)
        .data(menuData.length > 0 ? [0] : []);

    menus.enter().append('g')
        .classed(constants.containerClassName, true)
        .style('cursor', 'pointer');

    menus.exit().remove();

    // remove push margin object(s)
    if(menus.exit().size()) clearPushMargins(gd);

    // return early if no update menus are visible
    if(menuData.length === 0) return;

    // join header group
    var headerGroups = menus.selectAll('g.' + constants.headerGroupClassName)
        .data(menuData, keyFunction);

    headerGroups.enter().append('g')
        .classed(constants.headerGroupClassName, true);

    // draw button container
    var gButton = menus.selectAll('g.' + constants.buttonGroupClassName)
        .data([0]);

    gButton.enter().append('g')
        .classed(constants.buttonGroupClassName, true)
        .style('pointer-events', 'all');

    // whenever we add new menu, attach 'state' variable to node
    // to keep track of the active menu ('-1' means no menu is active)
    // and remove all dropped buttons (if any)
    if(headerGroups.enter().size()) {
        gButton
            .call(removeAllButtons)
            .attr(constants.menuIndexAttrName, '-1');
    }

    // remove exiting header, remove dropped buttons and reset margins
    headerGroups.exit().each(function(menuOpts) {
        d3.select(this).remove();

        gButton
            .call(removeAllButtons)
            .attr(constants.menuIndexAttrName, '-1');

        Plots.autoMargin(gd, constants.autoMarginIdRoot + menuOpts._index);
    });

    // find dimensions before plotting anything (this mutates menuOpts)
    for(var i = 0; i < menuData.length; i++) {
        var menuOpts = menuData[i];

        // often more convenient than playing with two arguments
        menuOpts._index = i;
        findDimenstions(gd, menuOpts);
    }

    // draw headers!
    headerGroups.each(function(menuOpts) {
        var gHeader = d3.select(this);
        drawHeader(gd, gHeader, gButton, menuOpts);

        // update buttons if they are dropped
        if(areMenuButtonsDropped(gButton, menuOpts)) {
            drawButtons(gd, gHeader, gButton, menuOpts);
        }
    });
};

function makeMenuData(fullLayout) {
    var contOpts = fullLayout[constants.name],
        menuData = [];

    for(var i = 0; i < contOpts.length; i++) {
        var item = contOpts[i];

        if(item.visible) menuData.push(item);
    }

    return menuData;
}

function keyFunction(opts, i) {
    return opts.visible + i;
}

function areMenuButtonsDropped(gButton, menuOpts) {
    var droppedIndex = +gButton.attr(constants.menuIndexAttrName);

    return droppedIndex === menuOpts._index;
}

function drawHeader(gd, gHeader, gButton, menuOpts) {
    var header = gHeader.selectAll('g.' + constants.headerClassName)
        .data([0]);

    header.enter().append('g')
        .classed(constants.headerClassName, true)
        .style('pointer-events', 'all');

    var active = menuOpts.active,
        headerOpts = menuOpts.buttons[active] || constants.blankHeaderOpts,
        posOpts = { y: 0, yPad: 0 };

    header
        .call(drawItem, menuOpts, headerOpts)
        .call(setItemPosition, menuOpts, posOpts);

    // draw drop arrow at the right edge
    var arrow = gHeader.selectAll('text.' + constants.headerArrowClassName)
        .data([0]);

    arrow.enter().append('text')
        .classed(constants.headerArrowClassName, true)
        .classed('user-select-none', true)
        .attr('text-anchor', 'end')
        .call(Drawing.font, menuOpts.font)
        .text('▼');

    arrow.attr({
        x: menuOpts.width - constants.arrowOffsetX,
        y: menuOpts.height1 / 2 + constants.textOffsetY
    });

    header.on('click', function() {
        gButton.call(removeAllButtons);

        // if clicked index is same as dropped index => fold
        // otherwise => drop buttons associated with header
        gButton.attr(
            constants.menuIndexAttrName,
            areMenuButtonsDropped(gButton, menuOpts) ? '-1' : String(menuOpts._index)
        );

        drawButtons(gd, gHeader, gButton, menuOpts);
    });

    header.on('mouseover', function() {
        header.call(styleOnMouseOver);
    });

    header.on('mouseout', function() {
        header.call(styleOnMouseOut, menuOpts);
    });

    // translate header group
    Lib.setTranslate(gHeader, menuOpts.lx, menuOpts.ly);
}

function drawButtons(gd, gHeader, gButton, menuOpts) {
    var buttonData = gButton.attr(constants.menuIndexAttrName) !== '-1' ?
        menuOpts.buttons :
        [];

    var buttons = gButton.selectAll('g.' + constants.buttonClassName)
        .data(buttonData);

    buttons.enter().append('g')
        .classed(constants.buttonClassName, true)
        .attr('opacity', '0')
        .transition()
        .attr('opacity', '1');

    buttons.exit()
        .transition()
        .attr('opacity', '0')
        .remove();

    var posOpts = {
        y: menuOpts.height1 + constants.gapButtonHeader,
        yPad: constants.gapButton
    };

    buttons.each(function(buttonOpts, buttonIndex) {
        var button = d3.select(this);

        button
            .call(drawItem, menuOpts, buttonOpts)
            .call(setItemPosition, menuOpts, posOpts);

        button.on('click', function() {
            // update 'active' attribute in menuOpts
            menuOpts._input.active = menuOpts.active = buttonIndex;

            // fold up buttons and redraw header
            gButton.attr(constants.menuIndexAttrName, '-1');
            drawHeader(gd, gHeader, gButton, menuOpts);
            drawButtons(gd, gHeader, gButton, menuOpts);

            // call button method
            var args = buttonOpts.args;
            Plotly[buttonOpts.method](gd, args[0], args[1], args[2]);
        });

        button.on('mouseover', function() {
            button.call(styleOnMouseOver);
        });

        button.on('mouseout', function() {
            button.call(styleOnMouseOut, menuOpts);
            buttons.call(styleButtons, menuOpts);
        });
    });

    buttons.call(styleButtons, menuOpts);

    // translate button group
    Lib.setTranslate(gButton, menuOpts.lx, menuOpts.ly);
}

function drawItem(item, menuOpts, itemOpts) {
    item.call(drawItemRect, menuOpts)
        .call(drawItemText, menuOpts, itemOpts);
}

function drawItemRect(item, menuOpts) {
    var rect = item.selectAll('rect')
        .data([0]);

    rect.enter().append('rect')
        .classed(constants.itemRectClassName, true)
        .attr({
            rx: constants.rx,
            ry: constants.ry,
            'shape-rendering': 'crispEdges'
        });

    rect.call(Color.stroke, menuOpts.bordercolor)
        .call(Color.fill, menuOpts.bgcolor)
        .style('stroke-width', menuOpts.borderwidth + 'px');
}

function drawItemText(item, menuOpts, itemOpts) {
    var text = item.selectAll('text')
        .data([0]);

    text.enter().append('text')
        .classed(constants.itemTextClassName, true)
        .classed('user-select-none', true)
        .attr('text-anchor', 'start');

    text.call(Drawing.font, menuOpts.font)
        .text(itemOpts.label)
        .call(svgTextUtils.convertToTspans);
}

function styleButtons(buttons, menuOpts) {
    var active = menuOpts.active;

    buttons.each(function(buttonOpts, i) {
        var button = d3.select(this);

        if(i === active) {
            button.select('rect.' + constants.itemRectClassName)
                .call(Color.fill, constants.activeColor);
        }
    });
}

function styleOnMouseOver(item) {
    item.select('rect.' + constants.itemRectClassName)
        .call(Color.fill, constants.hoverColor);
}

function styleOnMouseOut(item, menuOpts) {
    item.select('rect.' + constants.itemRectClassName)
        .call(Color.fill, menuOpts.bgcolor);
}

// find item dimensions (this mutates menuOpts)
function findDimenstions(gd, menuOpts) {
    menuOpts.width = 0;
    menuOpts.height = 0;
    menuOpts.height1 = 0;
    menuOpts.lx = 0;
    menuOpts.ly = 0;

    var fakeButtons = gd._tester.selectAll('g.' + constants.buttonClassName)
        .data(menuOpts.buttons);

    fakeButtons.enter().append('g')
        .classed(constants.buttonClassName, true);

    // loop over fake buttons to find width / height
    fakeButtons.each(function(buttonOpts) {
        var button = d3.select(this);

        button.call(drawItem, menuOpts, buttonOpts);

        var text = button.select('.' + constants.itemTextClassName),
            tspans = text.selectAll('tspan');

        // width is given by max width of all buttons
        var tWidth = text.node() && Drawing.bBox(text.node()).width,
            wEff = Math.max(tWidth + constants.textPadX, constants.minWidth);

        // height is determined by item text
        var tHeight = menuOpts.font.size * constants.fontSizeToHeight,
            tLines = tspans[0].length || 1,
            hEff = Math.max(tHeight * tLines, constants.minHeight) + constants.textOffsetY;

        menuOpts.width = Math.max(menuOpts.width, wEff);
        menuOpts.height1 = Math.max(menuOpts.height1, hEff);
        menuOpts.height += menuOpts.height1;
    });

    fakeButtons.remove();

    var graphSize = gd._fullLayout._size;
    menuOpts.lx = graphSize.l + graphSize.w * menuOpts.x;
    menuOpts.ly = graphSize.t + graphSize.h * (1 - menuOpts.y);

    var xanchor = 'left';
    if(anchorUtils.isRightAnchor(menuOpts)) {
        menuOpts.lx -= menuOpts.width;
        xanchor = 'right';
    }
    if(anchorUtils.isCenterAnchor(menuOpts)) {
        menuOpts.lx -= menuOpts.width / 2;
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(anchorUtils.isBottomAnchor(menuOpts)) {
        menuOpts.ly -= menuOpts.height;
        yanchor = 'bottom';
    }
    if(anchorUtils.isMiddleAnchor(menuOpts)) {
        menuOpts.ly -= menuOpts.height / 2;
        yanchor = 'middle';
    }

    menuOpts.width = Math.ceil(menuOpts.width);
    menuOpts.height = Math.ceil(menuOpts.height);
    menuOpts.lx = Math.round(menuOpts.lx);
    menuOpts.ly = Math.round(menuOpts.ly);

    Plots.autoMargin(gd, constants.autoMarginIdRoot + menuOpts._index, {
        x: menuOpts.x,
        y: menuOpts.y,
        l: menuOpts.width * ({right: 1, center: 0.5}[xanchor] || 0),
        r: menuOpts.width * ({left: 1, center: 0.5}[xanchor] || 0),
        b: menuOpts.height * ({top: 1, middle: 0.5}[yanchor] || 0),
        t: menuOpts.height * ({bottom: 1, middle: 0.5}[yanchor] || 0)
    });
}

// set item positions (mutates posOpts)
function setItemPosition(item, menuOpts, posOpts) {
    var rect = item.select('.' + constants.itemRectClassName),
        text = item.select('.' + constants.itemTextClassName),
        tspans = text.selectAll('tspan'),
        borderWidth = menuOpts.borderwidth;

    Lib.setTranslate(item, borderWidth, borderWidth + posOpts.y);

    rect.attr({
        x: 0,
        y: 0,
        width: menuOpts.width,
        height: menuOpts.height1
    });

    var tHeight = menuOpts.font.size * constants.fontSizeToHeight,
        tLines = tspans[0].length || 1,
        spanOffset = ((tLines - 1) * tHeight / 4);

    var textAttrs = {
        x: constants.textOffsetX,
        y: menuOpts.height1 / 2 - spanOffset + constants.textOffsetY
    };

    text.attr(textAttrs);
    tspans.attr(textAttrs);

    posOpts.y += menuOpts.height1 + posOpts.yPad;
}

function removeAllButtons(gButton) {
    gButton.selectAll('g.' + constants.buttonClassName).remove();
}

function clearPushMargins(gd) {
    var pushMargins = gd._fullLayout._pushmargin || {},
        keys = Object.keys(pushMargins);

    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];

        if(k.indexOf(constants.autoMarginIdRoot) !== -1) {
            Plots.autoMargin(gd, k);
        }
    }
}
<|endoftext|>


<commit_before>
import React from 'react';
import { Toolbar } from 'Schemas';

export default function TestToolbar(props) {
	return (
		<Toolbar {...props} />
	);
}
<commit_msg>update schema toolbar<commit_after>
import React from 'react';
import { Toolbar } from 'Schemas';

export default function TestToolbar() {
	return (
		<Toolbar />
	);
}
<|endoftext|>


<commit_before>/**
* Editable jQuery UI Tooltip
* ---------------------
* requires jquery ui 1.9.x
*/
(function ($) {
    "use strict";

    //extend methods
    $.extend($.fn.editableContainer.Popup.prototype, {
        containerName: 'tooltip',  //jQuery method, aplying the widget
        containerDataName: 'uiTooltip', //object name in elements .data() (e.g. uiTooltip for tooltip)
        innerCss: '.ui-tooltip-content',

        //split options on containerOptions and formOptions
        splitOptions: function() {
            this.containerOptions = {};
            this.formOptions = {};
            //defaults for tooltip
            var cDef = $.ui[this.containerName].prototype.options;
            for(var k in this.options) {
              if(k in cDef) {
                 this.containerOptions[k] = this.options[k];
              } else {
                 this.formOptions[k] = this.options[k];
              }
            }
        },

        initContainer: function(){
            this.handlePlacement();
            $.extend(this.containerOptions, {
                items: '*',
                content: ' ',
                track:  false,
                open: $.proxy(function() {
                        //disable events hiding tooltip by default
                        this.container()._on(this.container().element, {
                            mouseleave: function(e){ e.stopImmediatePropagation(); },
                            focusout: function(e){ e.stopImmediatePropagation(); }
                        });
                    }, this)
            });

            this.call(this.containerOptions);

            //disable standart triggering tooltip event
            //for some versions of jQueryUI it gives error:
            //TypeError: this.container(...)._off is not a function
            //see: https://github.com/vitalets/x-editable/issues/32
            if(this.container()._off) {
                this.container()._off(this.container().element, 'mouseover focusin');
            } else {
                $.error('this.container()._off is not a function. jQuery UI: ' + $.ui.version);
            }
        },

        tip: function() {
            return this.container() ? this.container()._find(this.container().element) : null;
        },

        innerShow: function() {
            this.call('open');
            var label = this.options.title || this.$element.data( "ui-tooltip-title") || this.$element.data( "originalTitle");
            this.tip().find(this.innerCss).empty().append($('<label>').text(label));
        },

        innerHide: function() {
            this.call('close');
        },

        innerDestroy: function() {
            /* tooltip destroys itself on hide */
        },

        setPosition: function() {
            this.tip().position( $.extend({
                of: this.$element
            }, this.containerOptions.position ) );
        },

        handlePlacement: function() {
           var pos;
           switch(this.options.placement) {
               case 'top':
                      pos = {
                          my: "center bottom-5",
                          at: "center top",
                          collision: 'flipfit'
                      };
               break;
               case 'right':
                      pos = {
                          my: "left+5 center",
                          at: "right center",
                          collision: 'flipfit'
                      };
               break;
               case 'bottom':
                      pos = {
                          my: "center top+5",
                          at: "center bottom",
                          collision: 'flipfit'
                      };
               break;
               case 'left':
                      pos = {
                          my: "right-5 center",
                          at: "left center",
                          collision: 'flipfit'
                      };
               break;
           }

           this.containerOptions.position = pos;
        }

    });

}(window.jQuery));
<commit_msg>add check for tooltip presence in jqueryUI build<commit_after>/**
* Editable jQuery UI Tooltip
* ---------------------
* requires jquery ui 1.9.x
*/
(function ($) {
    "use strict";

    //extend methods
    $.extend($.fn.editableContainer.Popup.prototype, {
        containerName: 'tooltip',  //jQuery method, aplying the widget
        containerDataName: 'uiTooltip', //object name in elements .data() (e.g. uiTooltip for tooltip)
        innerCss: '.ui-tooltip-content',

        //split options on containerOptions and formOptions
        splitOptions: function() {
            this.containerOptions = {};
            this.formOptions = {};

            //check that jQueryUI build contains tooltip widget
            if(!$.ui[this.containerName]) {
                $.error('Please use jQueryUI with "tooltip" widget! http://jqueryui.com/download');
                return;
            }
            //defaults for tooltip
            var cDef = $.ui[this.containerName].prototype.options;
            for(var k in this.options) {
              if(k in cDef) {
                 this.containerOptions[k] = this.options[k];
              } else {
                 this.formOptions[k] = this.options[k];
              }
            }
        },

        initContainer: function(){
            this.handlePlacement();
            $.extend(this.containerOptions, {
                items: '*',
                content: ' ',
                track:  false,
                open: $.proxy(function() {
                        //disable events hiding tooltip by default
                        this.container()._on(this.container().element, {
                            mouseleave: function(e){ e.stopImmediatePropagation(); },
                            focusout: function(e){ e.stopImmediatePropagation(); }
                        });
                    }, this)
            });

            this.call(this.containerOptions);

            //disable standart triggering tooltip event
            //for some versions of jQueryUI it gives error:
            //TypeError: this.container(...)._off is not a function
            //see: https://github.com/vitalets/x-editable/issues/32
            if(this.container()._off) {
                this.container()._off(this.container().element, 'mouseover focusin');
            } else {
                $.error('this.container()._off is not a function. jQuery UI: ' + $.ui.version);
            }
        },

        tip: function() {
            return this.container() ? this.container()._find(this.container().element) : null;
        },

        innerShow: function() {
            this.call('open');
            var label = this.options.title || this.$element.data( "ui-tooltip-title") || this.$element.data( "originalTitle");
            this.tip().find(this.innerCss).empty().append($('<label>').text(label));
        },

        innerHide: function() {
            this.call('close');
        },

        innerDestroy: function() {
            /* tooltip destroys itself on hide */
        },

        setPosition: function() {
            this.tip().position( $.extend({
                of: this.$element
            }, this.containerOptions.position ) );
        },

        handlePlacement: function() {
           var pos;
           switch(this.options.placement) {
               case 'top':
                      pos = {
                          my: "center bottom-5",
                          at: "center top",
                          collision: 'flipfit'
                      };
               break;
               case 'right':
                      pos = {
                          my: "left+5 center",
                          at: "right center",
                          collision: 'flipfit'
                      };
               break;
               case 'bottom':
                      pos = {
                          my: "center top+5",
                          at: "center bottom",
                          collision: 'flipfit'
                      };
               break;
               case 'left':
                      pos = {
                          my: "right-5 center",
                          at: "left center",
                          collision: 'flipfit'
                      };
               break;
           }

           this.containerOptions.position = pos;
        }

    });

}(window.jQuery));
<|endoftext|>