<commit_before>define(["cm/tests/media/common"], function() {

  var tests = {

    'play/stop/release': function(assert, Media, source) {
      assert.expect(41);
      var done = assert.async();

      var media = new Media();
      var el = media.getElement();
      var events = {};

      media.on('media', function(eventName) {
        events[eventName] = events[eventName] ? events[eventName] + 1 : 1;
      });

      assert.equal(el.networkState, HTMLMediaElement.NETWORK_EMPTY);
      assert.equal(el.readyState, HTMLMediaElement.HAVE_NOTHING);
      assert.equal(media.isPlaying(), false);
      assert.equal(media.getPromiseLoaded().isFulfilled(), false);

      media
        .getPromiseLoaded()
        .then(function() {
          assert.equal(events['media:setSource'], 1);
          assert.equal(el.networkState, HTMLMediaElement.NETWORK_IDLE);
          assert.equal(el.readyState, HTMLMediaElement.HAVE_ENOUGH_DATA);
          assert.equal(media.isPlaying(), false);
          return media.play();
        })
        .then(function() {
          assert.equal(events['media:play'], 1);
          assert.equal(events['media:playing'], 1);
          // desktop: el.networkState == HTMLMediaElement.NETWORK_IDLE
          // mobile: el.networkState == HTMLMediaElement.NETWORK_LOADING
          assert.ok(
            el.networkState == HTMLMediaElement.NETWORK_IDLE ||
            el.networkState == HTMLMediaElement.NETWORK_LOADING
          );
          assert.equal(el.readyState, HTMLMediaElement.HAVE_ENOUGH_DATA);
          assert.equal(media.isPlaying(), true);
          return media.stop();
        })
        .then(function() {
          assert.equal(events['media:play'], 1);
          assert.equal(events['media:playing'], 1);
          assert.equal(events['media:stop'], 1);
          assert.equal(events['media:stopped'], 1);
          // desktop: el.networkState == HTMLMediaElement.NETWORK_IDLE
          // mobile: el.networkState == HTMLMediaElement.NETWORK_LOADING
          assert.ok(
            el.networkState == HTMLMediaElement.NETWORK_IDLE ||
            el.networkState == HTMLMediaElement.NETWORK_LOADING
          );
          // firefox: el.readyState == HTMLMediaElement.HAVE_ENOUGH_DATA
          //  chrome: el.readyState == HTMLMediaElement.HAVE_METADATA
          assert.ok(
            el.readyState == HTMLMediaElement.HAVE_METADATA ||
            el.readyState == HTMLMediaElement.HAVE_ENOUGH_DATA
          );
          assert.equal(media.isPlaying(), false);
          return media.play();
        })
        .then(function() {
          assert.equal(events['media:play'], 2);
          assert.equal(events['media:playing'], 2);
          assert.equal(events['media:stop'], 1);
          assert.equal(events['media:stopped'], 1);
          // desktop: el.networkState == HTMLMediaElement.NETWORK_IDLE
          // mobile: el.networkState == HTMLMediaElement.NETWORK_LOADING
          assert.ok(
            el.networkState == HTMLMediaElement.NETWORK_IDLE ||
            el.networkState == HTMLMediaElement.NETWORK_LOADING
          );

          // firefox: el.readyState == HTMLMediaElement.HAVE_METADATA
          //  chrome: el.readyState == HTMLMediaElement.HAVE_ENOUGH_DATA
          assert.ok(
            el.readyState == HTMLMediaElement.HAVE_METADATA ||
            el.readyState == HTMLMediaElement.HAVE_ENOUGH_DATA
          );
          assert.equal(media.isPlaying(), true);
          return media.release();
        })
        .then(function() {
          assert.equal(events['media:play'], 2);
          assert.equal(events['media:playing'], 2);
          assert.equal(events['media:stop'], 2);
          assert.equal(events['media:stopped'], 2);
          assert.equal(events['media:release'], 1);
          assert.equal(events['media:released'], 1);
          assert.equal(el.networkState, HTMLMediaElement.NETWORK_NO_SOURCE);
          assert.equal(el.readyState, HTMLMediaElement.HAVE_NOTHING);
          assert.equal(media.isPlaying(), false);
          assert.equal(media.getPromiseLoaded().isFulfilled(), false);
        })
        .finally(function() {
          media.release();
          done();
        });

      media.setSource(source);

      // useful to run these tests on mobile (gesture required to play a media...)
      $('body').on('click', function() {
        media.play();
      });

      assert.equal(el.networkState, HTMLMediaElement.NETWORK_NO_SOURCE);
      assert.equal(el.readyState, HTMLMediaElement.HAVE_NOTHING);
      assert.equal(media.isPlaying(), false);
      assert.equal(media.getPromiseLoaded().isFulfilled(), false);
    },

    'options loop:true': function(assert, Media, source) {
      var done = assert.async();

      var media = new Media();
      media.setOptions({
        loop: true
      });
      var el = media.getElement();

      var seeking = 0;
      var seeked = 0;
      var error = null;

      media.setSource(source);

      media
        .play()
        .then(function() {
          el.addEventListener('seeking', function() {
            seeking++;
          });
          el.addEventListener('seeked', function() {
            seeked++;
          });
          return media
            .getPromisePlaying()
            .timeout(2000);
        })
        .catch(function(reason) {
          error = reason;
        })
        .finally(function() {
          assert.equal(seeking, 1);
          assert.equal(seeked, 1);
          assert.equal(error, null);
          media.release();
          done();
        });
    },

    'options loop:false': function(assert, Media, source) {
      var done = assert.async();

      var media = new Media();
      media.setOptions({
        loop: false
      });
      var el = media.getElement();

      var seeking = 0;
      var seeked = 0;
      var error = null;

      media.setSource(source);

      media
        .play()
        .then(function() {
          return new Promise(function(resolve, reject) {
            el.addEventListener('seeking', function() {
              reject(new Error('media seek in loop:false mode.'));
            });
            el.addEventListener('ended', resolve);
          }).timeout(2000)
        })
        .catch(function(reason) {
          error = reason;
        })
        .finally(function() {
          assert.equal(error, null);
          media.release();
          done();
        });
    }
  };

  return {
    test: function(Media, source) {
      QUnit.config.testTimeout = 5000;
      _.each(tests, function(fn, name) {
        QUnit.test(name, function(assert) {
          fn(assert, Media, source);
        });
      });
    },
    skip: function() {
      _.each(tests, function(fn, name) {
        QUnit.skip(name);
      });
    }
  };
});
<commit_msg>Fix media tests<commit_after>define(["cm/tests/media/common"], function() {

  var tests = {

    'play/stop/release': function(assert, Media, source) {
      assert.expect(41);
      var done = assert.async();

      var media = new Media();
      var el = media.getElement();
      var events = {};

      media.on('media', function(eventName) {
        events[eventName] = events[eventName] ? events[eventName] + 1 : 1;
      });

      assert.equal(el.networkState, HTMLMediaElement.NETWORK_EMPTY);
      assert.equal(el.readyState, HTMLMediaElement.HAVE_NOTHING);
      assert.equal(media.isPlaying(), false);
      assert.equal(media.getPromiseLoaded().isFulfilled(), false);

      media
        .getPromiseLoaded()
        .then(function() {
          assert.equal(events['media:setSource'], 1);
          assert.ok(
            el.networkState == HTMLMediaElement.NETWORK_IDLE ||
            el.networkState == HTMLMediaElement.NETWORK_LOADING
          );
          assert.equal(el.readyState, HTMLMediaElement.HAVE_ENOUGH_DATA);
          assert.equal(media.isPlaying(), false);
          return media.play();
        })
        .then(function() {
          assert.equal(events['media:play'], 1);
          assert.equal(events['media:playing'], 1);
          // desktop: el.networkState == HTMLMediaElement.NETWORK_IDLE
          // mobile: el.networkState == HTMLMediaElement.NETWORK_LOADING
          assert.ok(
            el.networkState == HTMLMediaElement.NETWORK_IDLE ||
            el.networkState == HTMLMediaElement.NETWORK_LOADING
          );
          assert.equal(el.readyState, HTMLMediaElement.HAVE_ENOUGH_DATA);
          assert.equal(media.isPlaying(), true);
          return media.stop();
        })
        .then(function() {
          assert.equal(events['media:play'], 1);
          assert.equal(events['media:playing'], 1);
          assert.equal(events['media:stop'], 1);
          assert.equal(events['media:stopped'], 1);
          // desktop: el.networkState == HTMLMediaElement.NETWORK_IDLE
          // mobile: el.networkState == HTMLMediaElement.NETWORK_LOADING
          assert.ok(
            el.networkState == HTMLMediaElement.NETWORK_IDLE ||
            el.networkState == HTMLMediaElement.NETWORK_LOADING
          );
          // firefox: el.readyState == HTMLMediaElement.HAVE_ENOUGH_DATA
          //  chrome: el.readyState == HTMLMediaElement.HAVE_METADATA
          assert.ok(
            el.readyState == HTMLMediaElement.HAVE_METADATA ||
            el.readyState == HTMLMediaElement.HAVE_ENOUGH_DATA
          );
          assert.equal(media.isPlaying(), false);
          return media.play();
        })
        .then(function() {
          assert.equal(events['media:play'], 2);
          assert.equal(events['media:playing'], 2);
          assert.equal(events['media:stop'], 1);
          assert.equal(events['media:stopped'], 1);
          // desktop: el.networkState == HTMLMediaElement.NETWORK_IDLE
          // mobile: el.networkState == HTMLMediaElement.NETWORK_LOADING
          assert.ok(
            el.networkState == HTMLMediaElement.NETWORK_IDLE ||
            el.networkState == HTMLMediaElement.NETWORK_LOADING
          );

          // firefox: el.readyState == HTMLMediaElement.HAVE_METADATA
          //  chrome: el.readyState == HTMLMediaElement.HAVE_ENOUGH_DATA
          assert.ok(
            el.readyState == HTMLMediaElement.HAVE_METADATA ||
            el.readyState == HTMLMediaElement.HAVE_ENOUGH_DATA
          );
          assert.equal(media.isPlaying(), true);
          return media.release();
        })
        .then(function() {
          assert.equal(events['media:play'], 2);
          assert.equal(events['media:playing'], 2);
          assert.equal(events['media:stop'], 2);
          assert.equal(events['media:stopped'], 2);
          assert.equal(events['media:release'], 1);
          assert.equal(events['media:released'], 1);
          assert.equal(el.networkState, HTMLMediaElement.NETWORK_NO_SOURCE);
          assert.equal(el.readyState, HTMLMediaElement.HAVE_NOTHING);
          assert.equal(media.isPlaying(), false);
          assert.equal(media.getPromiseLoaded().isFulfilled(), false);
        })
        .finally(function() {
          media.release();
          done();
        });

      media.setSource(source);

      // useful to run these tests on mobile (gesture required to play a media...)
      $('body').on('click', function() {
        media.play();
      });

      assert.equal(el.networkState, HTMLMediaElement.NETWORK_NO_SOURCE);
      assert.equal(el.readyState, HTMLMediaElement.HAVE_NOTHING);
      assert.equal(media.isPlaying(), false);
      assert.equal(media.getPromiseLoaded().isFulfilled(), false);
    },

    'options loop:true': function(assert, Media, source) {
      var done = assert.async();

      var media = new Media();
      media.setOptions({
        loop: true
      });
      var el = media.getElement();

      var seeking = 0;
      var seeked = 0;
      var error = null;

      media.setSource(source);

      media
        .play()
        .then(function() {
          el.addEventListener('seeking', function() {
            seeking++;
          });
          el.addEventListener('seeked', function() {
            seeked++;
          });
          return media
            .getPromisePlaying()
            .timeout(2000);
        })
        .catch(function(reason) {
          error = reason;
        })
        .finally(function() {
          assert.equal(seeking, 1);
          assert.equal(seeked, 1);
          assert.equal(error, null);
          media.release();
          done();
        });
    },

    'options loop:false': function(assert, Media, source) {
      var done = assert.async();

      var media = new Media();
      media.setOptions({
        loop: false
      });
      var el = media.getElement();

      var seeking = 0;
      var seeked = 0;
      var error = null;

      media.setSource(source);

      media
        .play()
        .then(function() {
          return new Promise(function(resolve, reject) {
            el.addEventListener('seeking', function() {
              reject(new Error('media seek in loop:false mode.'));
            });
            el.addEventListener('ended', resolve);
          }).timeout(2000)
        })
        .catch(function(reason) {
          error = reason;
        })
        .finally(function() {
          assert.equal(error, null);
          media.release();
          done();
        });
    }
  };

  return {
    test: function(Media, source) {
      QUnit.config.testTimeout = 5000;
      _.each(tests, function(fn, name) {
        QUnit.test(name, function(assert) {
          fn(assert, Media, source);
        });
      });
    },
    skip: function() {
      _.each(tests, function(fn, name) {
        QUnit.skip(name);
      });
    }
  };
});
<|endoftext|>


<commit_before>(function() {
    /**
     * Navigation Controller
     * @param $scope
     * @param $location
     * @constructor
     */
    var NavController = function($scope, $location) {
        $scope.isActive = function (viewLocation) {
            return viewLocation === $location.path();
        };
    };
    angular.module('App').controller('NavController', ['$scope', '$location', NavController]);

    /**
     * Main Controller
     * @param $scope
     * @param $location
     * @constructor
     */
    var MainController = function($routeParams, mainFactory) {
        mainFactory.useTestData = $routeParams['debug'] === 'true';
    };
    angular.module('App').controller('MainController', ['$routeParams', 'mainFactory', MainController]);

    /**
     * Search Controller
     * @param $scope
     * @constructor
     */
    var SearchController = function($scope, $rootScope, searchFactory) {
        $scope.tabs = searchFactory.tabs;

        $scope.populate = function (tab_name) {
            switch (tab_name) {
                case $scope.tabs[0].name:
                    searchFactory.getDrugs()
                        .then(function (results) {
                            $scope.drug_list = results
                        }, function (error) {
                            // TODO show alert
                            console.log("got an error, ", error)
                        });
                    break;
                case $scope.tabs[1].name:
                    searchFactory.getStates()
                        .then(function (results) {
                            $scope.state_list = results
                        }, function (error) {
                            // TODO show alert
                            console.log("got an error, ", error)
                        });
                    break;
                case $scope.tabs[2].name:
                    searchFactory.getManufacturers()
                        .then(function (results) {
                            $scope.maker_list = results
                        }, function (error) {
                            // TODO show alert
                            console.log("got an error, ", error)
                        });
                    break;
                default:
                    break;
            }
        };

        $scope.dropdown = {
            isopen : false
        };

        $scope.toggleDropdown = function() {
            $scope.dropdown.isopen = this.search.drug_name.length
        };

        $scope.toggleMakerDropdown = function() {
            $scope.dropdown.isopen = this.search.maker_name.length
        };

        $scope.reset = function() {
            $rootScope.$broadcast('reset-update', [])
            $scope.selected_drug = null
            $scope.selected_maker = null
            $rootScope.all_drugs = null
        };

        $scope.getDrugData = function(drug) {
            this.search.drug_name = drug
            searchFactory.getDrugLabelInfo(drug)
                .then( function( data ) {
                    $scope.selected_drug = drug;
                    setLabelInfo( data.results[0] )
                }, function( error ) {
                    console.log("got an error: ", error);
                    $scope.selected_drug = null
                });
            searchFactory.getDrugRecallInfo(drug)
                .then( function( data ) {
                    setRecallInfo( data.results )
                }, function( error ) {
                    console.log("got an error: ", error);
                    $scope.selected_drug = null
                });
        };

        $scope.getManufacturerData = function(maker) {
           this.search.maker_name = maker
            searchFactory.getManufacturerInfo(maker)
                .then( function( data ) {
                    $scope.selected_maker = maker;
                    setManufacturerInfo( data )
                }, function( error ) {
                    console.log("got an error: ", error);
                    $scope.selected_maker = null
                });
        };

        $scope.update = function(state){
            $rootScope.$broadcast('state-update', state)
        };

        function setLabelInfo( info ){
            if( info.purpose ){
                $scope.selected_drug_purpose = info.purpose[0].replace("PURPOSES ", "")
            }
            $scope.selected_drug_usage = info.indications_and_usage[0].replace("USES ", "")
            $scope.manufacturer_name = info.openfda.manufacturer_name[0]

            var length = info.openfda.substance_name.length;
            var active_ingredients= [];
            for(var i= 0; i<length; i++){
                active_ingredients.push({name: info.openfda.substance_name[i]})
            }
            $scope.active_ingredients = active_ingredients
        }

        function setRecallInfo( results ){
            var length = results.length
            // fix the dates
            var regions = []
            for(var i= 0; i<length; i++){
                var date = results[i].recall_initiation_date;
                results[i].recall_initiation_date = new Date(date.substring(0,4), date.substring(4,6), date.substring(6,8)).toDateString();
                // grab all recall areas
                for( var j=0; j< results[i].recall_area.length; j++ ) {
                    regions.push( results[i].recall_area[j])
                }
            }
            // helper method
            function contains(a, obj) {
                for (var i = 0; i < a.length; i++) {
                    if (a[i] === obj) { return true; }
                }
                return false;
            }
            console.log(regions)
            if( contains(regions, "Nationwide") ) {
                regions = ["Nationwide"]
            } else {
                // remove duplicates by sorting and checking repeated regions
                regions = regions.sort().filter(function(item, pos, ary) {
                    return !pos || item != ary[pos - 1];
                });
            }
            console.log(regions)
            $rootScope.$broadcast('drug-update', regions)
            $scope.recalls = results
            $rootScope.$broadcast('length-update', ($scope.recalls).length)
        }

        function setManufacturerInfo( response ){
            $scope.manufacturer_city = response.city
            $scope.manufacturer_state = response.state
            var drug_length = response.brand_names.length;
            $scope.maker_drug_recalls = [];
            for(var i= 0; i<drug_length; i++){
                $scope.maker_drug_recalls.push({name: response.brand_names[i]})
            }
            $rootScope.$broadcast('length-update', ($scope.maker_drug_recalls).length)

            var state_length = response.results.length;
            var maker_state_recalls = [];
            var maker_state_count = [];
            $scope.manufacturer_count = 0;
            for(var j= 0; j<state_length; j++){
                maker_state_recalls.push(response.results[j].state)
                maker_state_count.push(response.results[j])
                $scope.manufacturer_count = response.results[j].count + $scope.manufacturer_count
            }
            // helper method
            function contains(a, obj) {
                for (var i = 0; i < a.length; i++) {
                    if (a[i] === obj) { return true; }
                }
                return false;
            }
            if( contains(maker_state_recalls, "Nationwide") ) {
                maker_state_recalls = ["Nationwide"]
            } else {
                // remove duplicates by sorting and checking repeated regions
                maker_state_recalls = maker_state_recalls.sort().filter(function(item, pos, ary) {
                    return !pos || item != ary[pos - 1];
                });
            }

            $rootScope.$broadcast('manufacturer-update', maker_state_recalls)
            $scope.manufacturer_states = maker_state_recalls
            $rootScope.manufacturer_state_count = maker_state_count
        }

    };
    angular.module('App').controller('SearchController', ['$scope', '$rootScope', 'searchFactory', SearchController]);

    /**
     * Map Controller
     * @param $scope
     * @constructor
     */

    var MapController = function($scope, $http, $rootScope, mapFactory) {

        var tab;

     /*   $scope.$on("leafletDirectiveGeoJson.click", function(event, args){
             if (tab == "state"){
                mapFactory.getRecallsCountByState(args.leafletObject.feature.properties.name)
                    .then(function (results) {
                        $scope.state_count = results
                    });

                mapFactory.getRecallsCountByState("Nationwide")
                    .then(function (results) {
                        $scope.nationwide_count = results
                    });
                $scope.total_recalls = $scope.state_count + $scope.nationwide_count
                $scope.total_recalls_state = args.leafletObject.feature.properties.name
            }
        }); */

        $scope.$on("leafletDirectiveGeoJson.mouseover", function(event, args){
            if (tab != "maker") {
                var layer = args.leafletEvent.target
                layer.setStyle({
                    fillColor: '#ee7600'
                })
            }
        });

        angular.extend($scope, {
            center: {
                lat: 39,
                lng: -100,
                zoom: 4
            }
        });

        $scope.$on('drug-update', function(event, args) {
            tab = "drug";
            var all_locations = [];
            $http.get("data/us-states.json").success(function(response, status) {
                state_location = response.features
                recall_location = args
                    angular.forEach(recall_location, function (recall_locale) {
                        angular.forEach(state_location, function (state_locale) {
                            if (recall_locale == state_locale.properties.name || recall_locale == "Nationwide") {
                                all_locations.push(state_locale);
                            }
                        });
                    });
            });

            $scope.geojson = {
                data: all_locations,
                style: {
                    fillColor: 'orange',
                    weight: 1,
                    opacity: 1,
                    color: 'white',
                    dashArray: '3',
                    fillOpacity: 0.7
                },
                resetStyleOnMouseout: true
            }

        });

        function style(feature) {
            var vals = getColor(feature.properties.name)
            return {
                fillColor: vals,
                weight: 1,
                opacity: 1,
                color: 'white',
                dashArray: '3',
                fillOpacity: 0.7
            };
        }

        function getColor(name) {

            var d = 0;

            for(var i= 0; i<($rootScope.manufacturer_state_count).length; i++){

                state = ($rootScope.manufacturer_state_count)[i].state
                count = ($rootScope.manufacturer_state_count)[i].count

                if ( name == state ) {
                    d = d + count
                }
                if ( state == "Nationwide" ) {
                    d = d + count
                }
            }

            return  d > 40 ? '#FF410F' :
                    d > 35 ? '#FF5423' :
                    d > 30 ? '#FF6838' :
                    d > 25 ? '#FF7C4C' :
                    d > 20 ? '#FF9061' :
                    d > 15 ? '#FFA375' :
                    d > 10 ? '#FFB78A' :
                    d > 5 ? '#FFCB9E' :
                    d > 1 ? '#FFDBAE' :
                '#FFDFB3';
        }

        $scope.$on('manufacturer-update', function(event, args) {
            tab = "maker";
            var maker_locations = [];
            $http.get("data/us-states.json").success(function(response, status) {
                state_location = response.features
                recall_location = args
                angular.forEach(recall_location, function (recall_locale) {
                    angular.forEach(state_location, function (state_locale) {
                        if (recall_locale == state_locale.properties.name || recall_locale == "Nationwide") {
                            maker_locations.push(state_locale);
                        }
                    });
                });
            });

            $scope.geojson = {
                data: maker_locations,
                style: style,
                resetStyleOnMouseout: false
            }

        });

        $scope.$on('reset-update', function(event, args) {
             angular.extend($scope, {
                geojson: {
                    data: args
                }
            });

            $scope.total_recalls = null;

        });

        $scope.$on('state-update', function(event, args) {

            tab = "state";

            selected_state = args;
            $rootScope.all_drugs = []

            mapFactory.getRecallsByState("Nationwide")
                .then(function (results) {
                    angular.forEach(results, function(drug_name){
                        $rootScope.all_drugs.push(drug_name);
                    });
                }, function (error) {
                    // TODO show alert
                    console.log("got an error, ", error)
                });

            mapFactory.getRecallsByState(selected_state)
                .then(function (results) {
                    angular.forEach(results, function(drug_name){
                        $rootScope.all_drugs.push(drug_name);
                    });
                    $rootScope.$broadcast('length-update', ($rootScope.all_drugs).length)
                }, function (error) {
                    // TODO show alert
                    console.log("got an error, ", error)
                });

            var one_location = []
            $http.get("data/us-states.json").success(function (response, status) {
                state_location = response.features
                angular.forEach(state_location, function (state_locale) {
                    if (state_locale.properties.name == selected_state) {
                        one_location.push(state_locale)
                    }
                });
            });

            $scope.geojson = {
                data: one_location,
                style: {
                    fillColor: 'orange',
                    weight: 1,
                    opacity: 1,
                    color: 'white',
                    dashArray: '3',
                    fillOpacity: 0.7
                },
                resetStyleOnMouseout: true
            }
        });

    };
    angular.module('App').controller('MapController', ["$scope", "$http", "$rootScope", "mapFactory", MapController]);

    var PaginationCtrl = function ($scope, $rootScope, $log) {

        $scope.$on('length-update', function(event, args){
            $scope.totalItems = args
        });

        $scope.currentPage = 1
        $scope.itemsPerPage = 3
        $scope.maxSize = 5

        $scope.setPage = function (pageNo) {
            $scope.currentPage = pageNo
        };

        $scope.pageChanged = function() {
            $log.log('Page changed to: ' + $scope.currentPage)
        };

    };
    angular.module('App').controller('PaginationCtrl', ["$scope", "$rootScope", '$log', PaginationCtrl]);

}());<commit_msg>fixed minor bugs<commit_after>(function() {
    /**
     * Navigation Controller
     * @param $scope
     * @param $location
     * @constructor
     */
    var NavController = function($scope, $location) {
        $scope.isActive = function (viewLocation) {
            return viewLocation === $location.path();
        };
    };
    angular.module('App').controller('NavController', ['$scope', '$location', NavController]);

    /**
     * Main Controller
     * @param $scope
     * @param $location
     * @constructor
     */
    var MainController = function($routeParams, mainFactory) {
        mainFactory.useTestData = $routeParams['debug'] === 'true';
    };
    angular.module('App').controller('MainController', ['$routeParams', 'mainFactory', MainController]);

    /**
     * Search Controller
     * @param $scope
     * @constructor
     */
    var SearchController = function($scope, $rootScope, searchFactory) {
        $scope.tabs = searchFactory.tabs;

        $scope.populate = function (tab_name) {
            switch (tab_name) {
                case $scope.tabs[0].name:
                    searchFactory.getDrugs()
                        .then(function (results) {
                            $scope.drug_list = results
                        }, function (error) {
                            // TODO show alert
                            console.log("got an error, ", error)
                        });
                    break;
                case $scope.tabs[1].name:
                    searchFactory.getStates()
                        .then(function (results) {
                            $scope.state_list = results
                        }, function (error) {
                            // TODO show alert
                            console.log("got an error, ", error)
                        });
                    break;
                case $scope.tabs[2].name:
                    searchFactory.getManufacturers()
                        .then(function (results) {
                            $scope.maker_list = results
                        }, function (error) {
                            // TODO show alert
                            console.log("got an error, ", error)
                        });
                    break;
                default:
                    break;
            }
        };

        $scope.dropdown = {
            isopen : false
        };

        $scope.toggleDropdown = function() {
            $scope.dropdown.isopen = this.search.drug_name.length
        };

        $scope.toggleMakerDropdown = function() {
            $scope.dropdown.isopen = this.search.maker_name.length
        };

        $scope.reset = function() {
            $rootScope.$broadcast('reset-update', [])
            $scope.selected_drug = null
            $scope.selected_maker = null
            $rootScope.all_drugs = null
        };

        $scope.getDrugData = function(drug) {
            this.search.drug_name = drug
            searchFactory.getDrugLabelInfo(drug)
                .then( function( data ) {
                    $scope.selected_drug = drug;
                    setLabelInfo( data.results[0] )
                }, function( error ) {
                    console.log("got an error: ", error);
                    $scope.selected_drug = null
                });
            searchFactory.getDrugRecallInfo(drug)
                .then( function( data ) {
                    setRecallInfo( data.results )
                }, function( error ) {
                    console.log("got an error: ", error);
                    $scope.selected_drug = null
                });
        };

        $scope.getManufacturerData = function(maker) {
           this.search.maker_name = maker
            searchFactory.getManufacturerInfo(maker)
                .then( function( data ) {
                    $scope.selected_maker = maker;
                    setManufacturerInfo( data )
                }, function( error ) {
                    console.log("got an error: ", error);
                    $scope.selected_maker = null
                });
        };

        $scope.update = function(state){
            $rootScope.$broadcast('state-update', state)
        };

        function setLabelInfo( info ){
            if( info.purpose ){
                $scope.selected_drug_purpose = info.purpose[0].replace("PURPOSES ", "")
            } else {
                $scope.selected_drug_purpose = ""
            }
            $scope.selected_drug_usage = info.indications_and_usage[0].replace("USES ", "")
            $scope.manufacturer_name = info.openfda.manufacturer_name[0]

            var length = info.openfda.substance_name.length;
            var active_ingredients= [];
            for(var i= 0; i<length; i++){
                active_ingredients.push({name: info.openfda.substance_name[i]})
            }
            $scope.active_ingredients = active_ingredients
        }

        function setRecallInfo( results ){
            var length = results.length
            // fix the dates
            var regions = []
            for(var i= 0; i<length; i++){
                var date = results[i].recall_initiation_date;
                results[i].recall_initiation_date = new Date(date.substring(0,4), date.substring(4,6), date.substring(6,8)).toDateString();
                // grab all recall areas
                for( var j=0; j< results[i].recall_area.length; j++ ) {
                    regions.push( results[i].recall_area[j])
                }
            }
            // helper method
            function contains(a, obj) {
                for (var i = 0; i < a.length; i++) {
                    if (a[i] === obj) { return true; }
                }
                return false;
            }
            console.log(regions)
            if( contains(regions, "Nationwide") ) {
                regions = ["Nationwide"]
            } else {
                // remove duplicates by sorting and checking repeated regions
                regions = regions.sort().filter(function(item, pos, ary) {
                    return !pos || item != ary[pos - 1];
                });
            }
            console.log(regions)
            $rootScope.$broadcast('drug-update', regions)
            $scope.recalls = results
            $rootScope.$broadcast('length-update', ($scope.recalls).length)
        }

        function setManufacturerInfo( response ){
            $scope.manufacturer_city = response.city
            $scope.manufacturer_state = response.state
            var drug_length = response.brand_names.length;
            $scope.maker_drug_recalls = [];
            for(var i= 0; i<drug_length; i++){
                $scope.maker_drug_recalls.push({name: response.brand_names[i]})
            }
            $rootScope.$broadcast('length-update', ($scope.maker_drug_recalls).length)

            var state_length = response.results.length;
            var maker_state_recalls = [];
            var maker_state_count = [];
            $scope.manufacturer_count = 0;
            for(var j= 0; j<state_length; j++){
                maker_state_recalls.push(response.results[j].state)
                maker_state_count.push(response.results[j])
                $scope.manufacturer_count = response.results[j].count + $scope.manufacturer_count
            }
            // helper method
            function contains(a, obj) {
                for (var i = 0; i < a.length; i++) {
                    if (a[i] === obj) { return true; }
                }
                return false;
            }
            if( contains(maker_state_recalls, "Nationwide") ) {
                maker_state_recalls = ["Nationwide"]
            } else {
                // remove duplicates by sorting and checking repeated regions
                maker_state_recalls = maker_state_recalls.sort().filter(function(item, pos, ary) {
                    return !pos || item != ary[pos - 1];
                });
            }

            $rootScope.$broadcast('manufacturer-update', maker_state_recalls)
            $scope.manufacturer_states = maker_state_recalls
            $rootScope.manufacturer_state_count = maker_state_count
        }

    };
    angular.module('App').controller('SearchController', ['$scope', '$rootScope', 'searchFactory', SearchController]);

    /**
     * Map Controller
     * @param $scope
     * @constructor
     */

    var MapController = function($scope, $http, $rootScope, mapFactory) {

        var tab;

     /*   $scope.$on("leafletDirectiveGeoJson.click", function(event, args){
             if (tab == "state"){
                mapFactory.getRecallsCountByState(args.leafletObject.feature.properties.name)
                    .then(function (results) {
                        $scope.state_count = results
                    });

                mapFactory.getRecallsCountByState("Nationwide")
                    .then(function (results) {
                        $scope.nationwide_count = results
                    });
                $scope.total_recalls = $scope.state_count + $scope.nationwide_count
                $scope.total_recalls_state = args.leafletObject.feature.properties.name
            }
        }); */

        $scope.$on("leafletDirectiveGeoJson.mouseover", function(event, args){
            if (tab != "maker") {
                var layer = args.leafletEvent.target
                layer.setStyle({
                    fillColor: '#ee7600'
                })
            }
        });

        angular.extend($scope, {
            center: {
                lat: 39,
                lng: -100,
                zoom: 4
            }
        });

        $scope.$on('drug-update', function(event, args) {
            tab = "drug";
            var all_locations = [];
            $http.get("data/us-states.json").success(function(response, status) {
                state_location = response.features
                recall_location = args
                    angular.forEach(recall_location, function (recall_locale) {
                        angular.forEach(state_location, function (state_locale) {
                            if (recall_locale == state_locale.properties.name || recall_locale == "Nationwide") {
                                all_locations.push(state_locale);
                            }
                        });
                    });
            });

            $scope.geojson = {
                data: all_locations,
                style: {
                    fillColor: 'orange',
                    weight: 1,
                    opacity: 1,
                    color: 'white',
                    dashArray: '3',
                    fillOpacity: 0.7
                },
                resetStyleOnMouseout: true
            }

        });

        function style(feature) {
            var vals = getColor(feature.properties.name)
            return {
                fillColor: vals,
                weight: 1,
                opacity: 1,
                color: 'white',
                dashArray: '3',
                fillOpacity: 0.7
            };
        }

        function getColor(name) {

            var d = 0;

            for(var i= 0; i<($rootScope.manufacturer_state_count).length; i++){

                state = ($rootScope.manufacturer_state_count)[i].state
                count = ($rootScope.manufacturer_state_count)[i].count

                if ( name == state ) {
                    d = d + count
                }
                if ( state == "Nationwide" ) {
                    d = d + count
                }
            }

            return  d > 40 ? '#FF410F' :
                    d > 35 ? '#FF5423' :
                    d > 30 ? '#FF6838' :
                    d > 25 ? '#FF7C4C' :
                    d > 20 ? '#FF9061' :
                    d > 15 ? '#FFA375' :
                    d > 10 ? '#FFB78A' :
                    d > 5 ? '#FFCB9E' :
                    d > 1 ? '#FFDBAE' :
                '#FFDFB3';
        }

        $scope.$on('manufacturer-update', function(event, args) {
            tab = "maker";
            var maker_locations = [];
            $http.get("data/us-states.json").success(function(response, status) {
                state_location = response.features
                recall_location = args
                angular.forEach(recall_location, function (recall_locale) {
                    angular.forEach(state_location, function (state_locale) {
                        if (recall_locale == state_locale.properties.name || recall_locale == "Nationwide") {
                            maker_locations.push(state_locale);
                        }
                    });
                });
            });

            $scope.geojson = {
                data: maker_locations,
                style: style,
                resetStyleOnMouseout: false
            }

        });

        $scope.$on('reset-update', function(event, args) {
             angular.extend($scope, {
                geojson: {
                    data: args
                }
            });

            $scope.total_recalls = null;

        });

        $scope.$on('state-update', function(event, args) {

            tab = "state";

            selected_state = args;
            $rootScope.all_drugs = []

            mapFactory.getRecallsByState("Nationwide")
                .then(function (results) {
                    angular.forEach(results, function(drug_name){
                        $rootScope.all_drugs.push(drug_name);
                    });
                    $rootScope.$broadcast('length-update', ($rootScope.all_drugs).length)
                }, function (error) {
                    // TODO show alert
                    console.log("got an error, ", error)
                });

            mapFactory.getRecallsByState(selected_state)
                .then(function (results) {
                    angular.forEach(results, function(drug_name){
                        $rootScope.all_drugs.push(drug_name);
                    });
                    $rootScope.$broadcast('length-update', ($rootScope.all_drugs).length)
                }, function (error) {
                    // TODO show alert
                    console.log("got an error, ", error)
                });

            var one_location = []
            $http.get("data/us-states.json").success(function (response, status) {
                state_location = response.features
                angular.forEach(state_location, function (state_locale) {
                    if (state_locale.properties.name == selected_state) {
                        one_location.push(state_locale)
                    }
                });
            });

            $scope.geojson = {
                data: one_location,
                style: {
                    fillColor: 'orange',
                    weight: 1,
                    opacity: 1,
                    color: 'white',
                    dashArray: '3',
                    fillOpacity: 0.7
                },
                resetStyleOnMouseout: true
            }
        });

    };
    angular.module('App').controller('MapController', ["$scope", "$http", "$rootScope", "mapFactory", MapController]);

    var PaginationCtrl = function ($scope, $rootScope, $log) {

        $scope.$on('length-update', function(event, args){
            $scope.totalItems = args
        });

        $scope.currentPage = 1
        $scope.itemsPerPage = 3
        $scope.maxSize = 5

        $scope.setPage = function (pageNo) {
            $scope.currentPage = pageNo
        };

        $scope.pageChanged = function() {
            $log.log('Page changed to: ' + $scope.currentPage)
        };

    };
    angular.module('App').controller('PaginationCtrl', ["$scope", "$rootScope", '$log', PaginationCtrl]);

}());<|endoftext|>


<commit_before>'use strict';

const URL = 'foo.png';
const NAME = 'foo';
const NAME2 = 'bar';

function cleanCache()
{
    delete PIXI.utils.BaseTextureCache[URL];
    delete PIXI.utils.BaseTextureCache[NAME];
    delete PIXI.utils.BaseTextureCache[NAME2];

    delete PIXI.utils.TextureCache[URL];
    delete PIXI.utils.TextureCache[NAME];
    delete PIXI.utils.TextureCache[NAME2];
}

describe('PIXI.Texture', function ()
{
    it('should register Texture from Loader', function ()
    {
        cleanCache();

        const image = new Image();

        const texture = PIXI.Texture.fromLoader(image, URL, NAME);

        expect(texture.baseTexture.imageUrl).to.equal('foo.png');
        expect(PIXI.utils.TextureCache[NAME]).to.equal(texture);
        expect(PIXI.utils.BaseTextureCache[NAME]).to.equal(texture.baseTexture);
        expect(PIXI.utils.TextureCache[URL]).to.equal(texture);
        expect(PIXI.utils.BaseTextureCache[URL]).to.equal(texture.baseTexture);
    });

    it('should remove Texture from cache on destroy', function ()
    {
        cleanCache();

        const texture = new PIXI.Texture(new PIXI.BaseTexture());

        PIXI.Texture.addToCache(texture, NAME);
        PIXI.Texture.addToCache(texture, NAME2);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(1);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(texture);
        expect(PIXI.utils.TextureCache[NAME2]).to.equal(texture);
        texture.destroy();
        expect(texture.textureCacheIds).to.equal(null);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(undefined);
        expect(PIXI.utils.TextureCache[NAME2]).to.equal(undefined);
    });

    it('should be added to the texture cache correctly, '
     + 'and should remove only itself, not effecting the base texture and its cache', function ()
    {
        cleanCache();

        const texture = new PIXI.Texture(new PIXI.BaseTexture());

        PIXI.BaseTexture.addToCache(texture.baseTexture, NAME);
        PIXI.Texture.addToCache(texture, NAME);
        expect(texture.baseTexture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(PIXI.utils.BaseTextureCache[NAME]).to.equal(texture.baseTexture);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(texture);
        PIXI.Texture.removeFromCache(NAME);
        expect(texture.baseTexture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(-1);
        expect(PIXI.utils.BaseTextureCache[NAME]).to.equal(texture.baseTexture);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(undefined);
    });

    it('should be added to the texture cache correctly using legacy addTextureToCache, '
     + 'and should remove also remove the base texture from its cache with removeTextureFromCache', function ()
    {
        cleanCache();

        const texture = new PIXI.Texture(new PIXI.BaseTexture());

        PIXI.BaseTexture.addToCache(texture.baseTexture, NAME);
        PIXI.Texture.addTextureToCache(texture, NAME);
        expect(texture.baseTexture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(PIXI.utils.BaseTextureCache[NAME]).to.equal(texture.baseTexture);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(texture);
        PIXI.Texture.removeTextureFromCache(NAME);
        expect(texture.baseTexture.textureCacheIds.indexOf(NAME)).to.equal(-1);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(-1);
        expect(PIXI.utils.BaseTextureCache[NAME]).to.equal(undefined);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(undefined);
    });

    it('should remove Texture from entire cache using removeFromCache (by Texture instance)', function ()
    {
        cleanCache();

        const texture = new PIXI.Texture(new PIXI.BaseTexture());

        PIXI.Texture.addToCache(texture, NAME);
        PIXI.Texture.addToCache(texture, NAME2);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(1);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(texture);
        expect(PIXI.utils.TextureCache[NAME2]).to.equal(texture);
        PIXI.Texture.removeFromCache(texture);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(-1);
        expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(-1);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(undefined);
        expect(PIXI.utils.TextureCache[NAME2]).to.equal(undefined);
    });

    it('should remove Texture from single cache entry using removeFromCache (by id)', function ()
    {
        cleanCache();

        const texture = new PIXI.Texture(new PIXI.BaseTexture());

        PIXI.Texture.addToCache(texture, NAME);
        PIXI.Texture.addToCache(texture, NAME2);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(1);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(texture);
        expect(PIXI.utils.TextureCache[NAME2]).to.equal(texture);
        PIXI.Texture.removeFromCache(NAME);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(-1);
        expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(0);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(undefined);
        expect(PIXI.utils.TextureCache[NAME2]).to.equal(texture);
    });

    it('destroying a destroyed texture should not throw an error', function ()
    {
        const texture = new PIXI.Texture(new PIXI.BaseTexture());

        texture.destroy(true);
        texture.destroy(true);
    });
});
<commit_msg>Removed unit test for deprecated Texture cache functions (#3970)<commit_after>'use strict';

const URL = 'foo.png';
const NAME = 'foo';
const NAME2 = 'bar';

function cleanCache()
{
    delete PIXI.utils.BaseTextureCache[URL];
    delete PIXI.utils.BaseTextureCache[NAME];
    delete PIXI.utils.BaseTextureCache[NAME2];

    delete PIXI.utils.TextureCache[URL];
    delete PIXI.utils.TextureCache[NAME];
    delete PIXI.utils.TextureCache[NAME2];
}

describe('PIXI.Texture', function ()
{
    it('should register Texture from Loader', function ()
    {
        cleanCache();

        const image = new Image();

        const texture = PIXI.Texture.fromLoader(image, URL, NAME);

        expect(texture.baseTexture.imageUrl).to.equal('foo.png');
        expect(PIXI.utils.TextureCache[NAME]).to.equal(texture);
        expect(PIXI.utils.BaseTextureCache[NAME]).to.equal(texture.baseTexture);
        expect(PIXI.utils.TextureCache[URL]).to.equal(texture);
        expect(PIXI.utils.BaseTextureCache[URL]).to.equal(texture.baseTexture);
    });

    it('should remove Texture from cache on destroy', function ()
    {
        cleanCache();

        const texture = new PIXI.Texture(new PIXI.BaseTexture());

        PIXI.Texture.addToCache(texture, NAME);
        PIXI.Texture.addToCache(texture, NAME2);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(1);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(texture);
        expect(PIXI.utils.TextureCache[NAME2]).to.equal(texture);
        texture.destroy();
        expect(texture.textureCacheIds).to.equal(null);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(undefined);
        expect(PIXI.utils.TextureCache[NAME2]).to.equal(undefined);
    });

    it('should be added to the texture cache correctly, '
     + 'and should remove only itself, not effecting the base texture and its cache', function ()
    {
        cleanCache();

        const texture = new PIXI.Texture(new PIXI.BaseTexture());

        PIXI.BaseTexture.addToCache(texture.baseTexture, NAME);
        PIXI.Texture.addToCache(texture, NAME);
        expect(texture.baseTexture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(PIXI.utils.BaseTextureCache[NAME]).to.equal(texture.baseTexture);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(texture);
        PIXI.Texture.removeFromCache(NAME);
        expect(texture.baseTexture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(-1);
        expect(PIXI.utils.BaseTextureCache[NAME]).to.equal(texture.baseTexture);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(undefined);
    });

    it('should remove Texture from entire cache using removeFromCache (by Texture instance)', function ()
    {
        cleanCache();

        const texture = new PIXI.Texture(new PIXI.BaseTexture());

        PIXI.Texture.addToCache(texture, NAME);
        PIXI.Texture.addToCache(texture, NAME2);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(1);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(texture);
        expect(PIXI.utils.TextureCache[NAME2]).to.equal(texture);
        PIXI.Texture.removeFromCache(texture);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(-1);
        expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(-1);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(undefined);
        expect(PIXI.utils.TextureCache[NAME2]).to.equal(undefined);
    });

    it('should remove Texture from single cache entry using removeFromCache (by id)', function ()
    {
        cleanCache();

        const texture = new PIXI.Texture(new PIXI.BaseTexture());

        PIXI.Texture.addToCache(texture, NAME);
        PIXI.Texture.addToCache(texture, NAME2);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
        expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(1);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(texture);
        expect(PIXI.utils.TextureCache[NAME2]).to.equal(texture);
        PIXI.Texture.removeFromCache(NAME);
        expect(texture.textureCacheIds.indexOf(NAME)).to.equal(-1);
        expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(0);
        expect(PIXI.utils.TextureCache[NAME]).to.equal(undefined);
        expect(PIXI.utils.TextureCache[NAME2]).to.equal(texture);
    });

    it('destroying a destroyed texture should not throw an error', function ()
    {
        const texture = new PIXI.Texture(new PIXI.BaseTexture());

        texture.destroy(true);
        texture.destroy(true);
    });
});
<|endoftext|>


<commit_before>import path from 'path'
import mkdirp from 'mkdirp'
import fse from 'fs-extra'
import moment from 'moment'

import {
  abeExtend,
  coreUtils,
  cmsData,
  config
} from '../../'

export function getAbeMeta(fileObject, json) {
  if(json.abe_meta.latest.date != null) {
    fileObject.date = json.abe_meta.latest.date
    fileObject.cleanDate = moment(json.abe_meta.latest.date).format('YYYY/MM/DD HH:MM:ss')
  }

  if(json.abe_meta != null) {
    var date = null
    if (json.abe_meta.latest.date !== null) {
      date = json.abe_meta.latest.date
    } else if (json.abe_meta.date !== null) {
      date = json.abe_meta.date
    }
    fileObject.abe_meta = {
      date: date,
      type: (json.abe_meta.type != null) ? json.abe_meta.type : null,
      link: (json.abe_meta.link != null) ? json.abe_meta.link : null,
      template: (json.abe_meta.template != null) ? json.abe_meta.template : null,
      status: (json.abe_meta.status != null) ? json.abe_meta.status : null,
      cleanName: (json.abe_meta.cleanName != null) ? json.abe_meta.cleanName : null,
      cleanFilename: (json.abe_meta.cleanFilename != null) ? json.abe_meta.cleanFilename : null
    }
  }

  return fileObject
}

export function getAllWithKeys(withKeys) {
  const pathData = path.join(config.root, config.data.url)
  const extension = '.json'
  const files = coreUtils.file.getFilesSync(pathData, true, extension)

  let filesArr = []

  Array.prototype.forEach.call(files, (pathFile) => {
    let fileObject = cmsData.file.getFileObject(pathFile)
    const json = cmsData.file.get(pathFile)

    fileObject = cmsData.file.getAbeMeta(fileObject, json)

    Array.prototype.forEach.call(withKeys, (key) => {
      var keyFirst = key.split('.')[0]
      fileObject[keyFirst] = json[keyFirst]
    })

    filesArr.push(fileObject)
  })

  var merged = cmsData.revision.getFilesMerged(filesArr)
  abeExtend.hooks.instance.trigger('afterGetAllFiles', merged)

  return merged
}

export function get(pathJson) {
  var json = {}
  pathJson = abeExtend.hooks.instance.trigger('beforeGetJson', pathJson)

  try {
    var stat = fse.statSync(pathJson)
    if (stat) {
      json = fse.readJsonSync(pathJson)
    }
  }catch(e) {
  }

  json = abeExtend.hooks.instance.trigger('afterGetJson', json)
  return json
}

export function fromUrl(url) {
  var res = {
    root: '',
    draft: {
      dir: '',
      file: '',
      path: ''
    },
    publish: {
      dir: '',
      file: '',
      link: '',
      path: '',
      json: ''
    },
    json: {
      path: '',
      file: ''
    }
  }

  if(url != null) {

    var dir = path.dirname(url).replace(config.root, '')
    var filename = path.basename(url)
    var link = url.replace(config.root, '')
    link = link.replace(/^\//, '').split('/')
    link.shift()
    link = cmsData.fileAttr.delete('/' + link.join('/').replace(/\/$/, ''))

    let draft = config.draft.url
    let publish = config.publish.url
    let data = config.data.url

    res.root = config.root

    // set dir path draft/json
    res.draft.dir = coreUtils.file.changePath(dir, draft)
    res.json.dir = coreUtils.file.changePath(dir, data)
    res.publish.dir = coreUtils.file.changePath(dir, publish)
    res.publish.json = res.json.dir

    // set filename draft/json
    res.draft.file = filename
    res.publish.file = cmsData.fileAttr.delete(filename)
    res.publish.link = link
    res.json.file = filename.replace(`.${config.files.templates.extension}`, '.json')
    res.publish.json = path.join(res.json.dir, cmsData.fileAttr.delete(res.json.file))

    // set filename draft/json
    res.draft.path = path.join(res.draft.dir, res.draft.file)
    res.publish.path = path.join(res.publish.dir, res.publish.file)
    res.json.path = path.join(res.json.dir, res.json.file)
  }
  return res
}

export function getFilesByType(pathFile, type = null) {
  const extension = '.' + config.files.templates.extension
  let result = []

  try {
    var directory = fse.lstatSync(pathFile)
    if (!directory.isDirectory()) {
      mkdirp.sync(pathFile)
    }
  } catch (e) {
    mkdirp.sync(pathFile)
  }
  const files = coreUtils.file.getFilesSync(pathFile, true, extension)

  Array.prototype.forEach.call(files, (file) => {
    var val = cmsData.fileAttr.get(file).s
    if(type === null || val === type) result.push(file)
  })

  return result
}

export function getFileObject(pathFile) {
  const pathData = path.join(config.root, config.data.url)
  const extension = '.json'

  const name = path.basename(pathFile)
  const nameNoExt = path.basename(pathFile, extension)
  const relativePath = pathFile.replace(pathData + '/', '')

  const parentName = cmsData.fileAttr.delete(name)
  const parentPath = cmsData.fileAttr.delete(pathFile)
  const parentRelativePath = cmsData.fileAttr.delete(pathFile).replace(config.root, '').replace(/^\/?.+?\//, '')

  const fileData = cmsData.fileAttr.get(name)

  let date
  if (fileData.d) {
    date = fileData.d
  }else {
    const stat = fse.statSync(pathFile)
    date = stat.mtime
  }

  const fileDate = moment(date)
  const duration = moment.duration(moment(fileDate).diff(new Date())).humanize(true)

  let fileObject = {
    'name': name,
    'cleanNameNoExt': nameNoExt,
    'path': pathFile,
    'cleanPath': relativePath,
    'filePath': relativePath,
    'date': date,
    'cleanDate': fileDate.format('YYYY/MM/DD HH:MM:ss'),
    'duration': duration,
    'cleanName': parentName,
    'cleanPathName': parentPath,
    'cleanFilePath': parentRelativePath
  }

  return fileObject
}
<commit_msg>fix:linting<commit_after>import path from 'path'
import mkdirp from 'mkdirp'
import fse from 'fs-extra'
import moment from 'moment'

import {
  abeExtend,
  coreUtils,
  cmsData,
  config
} from '../../'

export function getAbeMeta(fileObject, json) {
  if(json.abe_meta.latest.date != null) {
    fileObject.date = json.abe_meta.latest.date
    fileObject.cleanDate = moment(json.abe_meta.latest.date).format('YYYY/MM/DD HH:MM:ss')
  }

  if(json.abe_meta != null) {
    var date = null
    if (json.abe_meta.latest.date !== null) {
      date = json.abe_meta.latest.date
    } else if (json.abe_meta.date !== null) {
      date = json.abe_meta.date
    }
    fileObject.abe_meta = {
      date: date,
      type: (json.abe_meta.type != null) ? json.abe_meta.type : null,
      link: (json.abe_meta.link != null) ? json.abe_meta.link : null,
      template: (json.abe_meta.template != null) ? json.abe_meta.template : null,
      status: (json.abe_meta.status != null) ? json.abe_meta.status : null,
      cleanName: (json.abe_meta.cleanName != null) ? json.abe_meta.cleanName : null,
      cleanFilename: (json.abe_meta.cleanFilename != null) ? json.abe_meta.cleanFilename : null
    }
  }

  return fileObject
}

export function getAllWithKeys(withKeys) {
  const pathData = path.join(config.root, config.data.url)
  const extension = '.json'
  const files = coreUtils.file.getFilesSync(pathData, true, extension)

  let filesArr = []

  Array.prototype.forEach.call(files, (pathFile) => {
    let fileObject = cmsData.file.getFileObject(pathFile)
    const json = cmsData.file.get(pathFile)

    fileObject = cmsData.file.getAbeMeta(fileObject, json)

    Array.prototype.forEach.call(withKeys, (key) => {
      var keyFirst = key.split('.')[0]
      fileObject[keyFirst] = json[keyFirst]
    })

    filesArr.push(fileObject)
  })

  var merged = cmsData.revision.getFilesMerged(filesArr)
  abeExtend.hooks.instance.trigger('afterGetAllFiles', merged)

  return merged
}

export function get(pathJson) {
  let json
  pathJson = abeExtend.hooks.instance.trigger('beforeGetJson', pathJson)

  try {
    var stat = fse.statSync(pathJson)
    if (stat) {
      json = fse.readJsonSync(pathJson)
    }
  }catch(e) {
    json = {}
  }

  json = abeExtend.hooks.instance.trigger('afterGetJson', json)
  return json
}

export function fromUrl(url) {
  var res = {
    root: '',
    draft: {
      dir: '',
      file: '',
      path: ''
    },
    publish: {
      dir: '',
      file: '',
      link: '',
      path: '',
      json: ''
    },
    json: {
      path: '',
      file: ''
    }
  }

  if(url != null) {

    var dir = path.dirname(url).replace(config.root, '')
    var filename = path.basename(url)
    var link = url.replace(config.root, '')
    link = link.replace(/^\//, '').split('/')
    link.shift()
    link = cmsData.fileAttr.delete('/' + link.join('/').replace(/\/$/, ''))

    let draft = config.draft.url
    let publish = config.publish.url
    let data = config.data.url

    res.root = config.root

    // set dir path draft/json
    res.draft.dir = coreUtils.file.changePath(dir, draft)
    res.json.dir = coreUtils.file.changePath(dir, data)
    res.publish.dir = coreUtils.file.changePath(dir, publish)
    res.publish.json = res.json.dir

    // set filename draft/json
    res.draft.file = filename
    res.publish.file = cmsData.fileAttr.delete(filename)
    res.publish.link = link
    res.json.file = filename.replace(`.${config.files.templates.extension}`, '.json')
    res.publish.json = path.join(res.json.dir, cmsData.fileAttr.delete(res.json.file))

    // set filename draft/json
    res.draft.path = path.join(res.draft.dir, res.draft.file)
    res.publish.path = path.join(res.publish.dir, res.publish.file)
    res.json.path = path.join(res.json.dir, res.json.file)
  }
  return res
}

export function getFilesByType(pathFile, type = null) {
  const extension = '.' + config.files.templates.extension
  let result = []

  try {
    var directory = fse.lstatSync(pathFile)
    if (!directory.isDirectory()) {
      mkdirp.sync(pathFile)
    }
  } catch (e) {
    mkdirp.sync(pathFile)
  }
  const files = coreUtils.file.getFilesSync(pathFile, true, extension)

  Array.prototype.forEach.call(files, (file) => {
    var val = cmsData.fileAttr.get(file).s
    if(type === null || val === type) result.push(file)
  })

  return result
}

export function getFileObject(pathFile) {
  const pathData = path.join(config.root, config.data.url)
  const extension = '.json'

  const name = path.basename(pathFile)
  const nameNoExt = path.basename(pathFile, extension)
  const relativePath = pathFile.replace(pathData + '/', '')

  const parentName = cmsData.fileAttr.delete(name)
  const parentPath = cmsData.fileAttr.delete(pathFile)
  const parentRelativePath = cmsData.fileAttr.delete(pathFile).replace(config.root, '').replace(/^\/?.+?\//, '')

  const fileData = cmsData.fileAttr.get(name)

  let date
  if (fileData.d) {
    date = fileData.d
  }else {
    const stat = fse.statSync(pathFile)
    date = stat.mtime
  }

  const fileDate = moment(date)
  const duration = moment.duration(moment(fileDate).diff(new Date())).humanize(true)

  let fileObject = {
    'name': name,
    'cleanNameNoExt': nameNoExt,
    'path': pathFile,
    'cleanPath': relativePath,
    'filePath': relativePath,
    'date': date,
    'cleanDate': fileDate.format('YYYY/MM/DD HH:MM:ss'),
    'duration': duration,
    'cleanName': parentName,
    'cleanPathName': parentPath,
    'cleanFilePath': parentRelativePath
  }

  return fileObject
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import UnauthenticatedRouteMixin from 'ember-simple-auth/mixins/unauthenticated-route-mixin';

export default Ember.Route.extend(UnauthenticatedRouteMixin);
<commit_msg>Create a user record for validation purposes.<commit_after>import Ember from 'ember';
import UnauthenticatedRouteMixin from 'ember-simple-auth/mixins/unauthenticated-route-mixin';

export default Ember.Route.extend(UnauthenticatedRouteMixin, {
  model() {
    return this.store.createRecord('user');
  }
});
<|endoftext|>


<commit_before>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var should = require('should');

var testutil = require('./util');
var azure = testutil.libRequire('azure');
var Validate = azure.Validate;

suite('servicesettings-tests', function () {
  describe('isValidUri', function () {
    it('should work', function () {
      Validate.isValidUri('http://www.microsoft.com').should.be.ok;
      Validate.isValidUri('http://www.microsoft.com').should.equal(true);

      (function() {
        Validate.isValidUri('something');
      }).should.throw('The provided URI "something" is invalid.');
    });
  });

  describe('isBase64Encoded', function () {
    it('should work', function () {
      Validate.isBase64Encoded('AhlzsbLRkjfwObuqff3xrhB2yWJNh1EMptmcmxFJ6fvPTVX3PZXwrG2YtYWf5DPMVgNsteKStM5iBLlknYFVoA==').should.be.ok;

      var key = '__A&*INVALID-@Key';
      (function() {
        Validate.isBase64Encoded(key);
      }).should.throw('The provided account key ' + key + ' is not a valid base64 string.');
    });
  });

  describe('Namespace validation', function () {
    it('should pass on valid name', function() {
      (function() { Validate.namespaceNameIsValid('aValidNamespace'); })
        .should.not.throw();
    });

    it('should fail if name is too short', function () {
      (function() { Validate.namespaceNameIsValid("a"); })
        .should.throw(/6 to 50/);
    });

    it('should fail if name is too long', function () {
      (function () { Validate.namespaceNameIsValid('sbm12345678901234567890123456789012345678901234567890'); })
        .should.throw(/6 to 50/);
    });

    it("should fail if name doesn't start with a letter", function () {
      (function () { Validate.namespaceNameIsValid('!notALetter'); })
        .should.throw(/start with a letter/);
    });

    it('should fail if ends with illegal ending', function () {
      (function () { Validate.namespaceNameIsValid('namespace-'); } )
        .should.throw(/may not end with/);

      (function () { Validate.namespaceNameIsValid('namespace-sb'); })
        .should.throw(/may not end with/);

      (function () { Validate.namespaceNameIsValid('namespace-mgmt'); })
        .should.throw(/may not end with/);

      (function () { Validate.namespaceNameIsValid('namespace-cache'); })
        .should.throw(/may not end with/);

      (function () { Validate.namespaceNameIsValid('namespace-appfabric'); })
        .should.throw(/may not end with/);
    });
  });
});<commit_msg>Added tests for container name validation<commit_after>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var should = require('should');

var testutil = require('./util');
var azure = testutil.libRequire('azure');
var Validate = azure.Validate;

suite('servicesettings-tests', function () {
  describe('isValidUri', function () {
    it('should work', function () {
      Validate.isValidUri('http://www.microsoft.com').should.be.ok;
      Validate.isValidUri('http://www.microsoft.com').should.equal(true);

      (function() {
        Validate.isValidUri('something');
      }).should.throw('The provided URI "something" is invalid.');
    });
  });

  describe('isBase64Encoded', function () {
    it('should work', function () {
      Validate.isBase64Encoded('AhlzsbLRkjfwObuqff3xrhB2yWJNh1EMptmcmxFJ6fvPTVX3PZXwrG2YtYWf5DPMVgNsteKStM5iBLlknYFVoA==').should.be.ok;

      var key = '__A&*INVALID-@Key';
      (function() {
        Validate.isBase64Encoded(key);
      }).should.throw('The provided account key ' + key + ' is not a valid base64 string.');
    });
  });

  describe('Blob container validation', function () {
    function check(name) {
      return function () {
        Validate.containerNameIsValid(name);
      };
    }

    it('should pass for $root', function () {
      check('$root').should.not.throw();
    });

    it('should throw for empty string', function () {
      check('').should.throw();
    });

    it('should throw for non-string', function () {
      check({a: 1}).should.throw();
    });

    it('should throw if name starts with "-"', function () {
      check('-notAName').should.throw();
    });

    it('should throw for name containing "--"', function () {
      check('this--isNotAValidName').should.throw();
    });

    it('should throw for name that\'s too short', function () {
      check('ab').should.throw();
    });

    it('should throw for name that\'s too long', function () {
      var name = 'abcdefghijklmnopqrstuvwxyz';
      name += name + name + name + name;
      check(name).should.throw();
    });

    it('should throw for invalid characters', function () {
      check('Not*(valid)').should.throw();
    });

  });

  describe('Namespace validation', function () {
    it('should pass on valid name', function() {
      (function() { Validate.namespaceNameIsValid('aValidNamespace'); })
        .should.not.throw();
    });

    it('should fail if name is too short', function () {
      (function() { Validate.namespaceNameIsValid("a"); })
        .should.throw(/6 to 50/);
    });

    it('should fail if name is too long', function () {
      (function () { Validate.namespaceNameIsValid('sbm12345678901234567890123456789012345678901234567890'); })
        .should.throw(/6 to 50/);
    });

    it("should fail if name doesn't start with a letter", function () {
      (function () { Validate.namespaceNameIsValid('!notALetter'); })
        .should.throw(/start with a letter/);
    });

    it('should fail if ends with illegal ending', function () {
      (function () { Validate.namespaceNameIsValid('namespace-'); } )
        .should.throw(/may not end with/);

      (function () { Validate.namespaceNameIsValid('namespace-sb'); })
        .should.throw(/may not end with/);

      (function () { Validate.namespaceNameIsValid('namespace-mgmt'); })
        .should.throw(/may not end with/);

      (function () { Validate.namespaceNameIsValid('namespace-cache'); })
        .should.throw(/may not end with/);

      (function () { Validate.namespaceNameIsValid('namespace-appfabric'); })
        .should.throw(/may not end with/);
    });
  });
});<|endoftext|>


<commit_before>import global from 'global';
import React, { Fragment, useEffect } from 'react';
import isChromatic from 'chromatic/isChromatic';
import {
  Global,
  ThemeProvider,
  themes,
  createReset,
  convert,
  styled,
  useTheme,
} from '@storybook/theming';
import { Symbols } from '@storybook/components';

import addHeadWarning from './head-warning';

const { document } = global;

if (process.env.NODE_ENV === 'development') {
  if (!process.env.DOTENV_DEVELOPMENT_DISPLAY_WARNING) {
    addHeadWarning('dotenv-env', 'Dotenv development file not loaded');
  }

  if (!process.env.STORYBOOK_DISPLAY_WARNING) {
    addHeadWarning('env-glob', 'Global storybook env var not loaded');
  }

  if (process.env.DISPLAY_WARNING) {
    addHeadWarning('env-extra', 'Global non-storybook env var loaded');
  }
}

addHeadWarning('preview-head-not-loaded', 'Preview head not loaded');
addHeadWarning('dotenv-file-not-loaded', 'Dotenv file not loaded');

const ThemeBlock = styled.div(
  {
    position: 'absolute',
    top: 0,
    left: 0,
    right: '50vw',
    width: '50vw',
    height: '100vh',
    bottom: 0,
    overflow: 'auto',
    padding: 10,
  },
  ({ theme }) => ({
    background: theme.background.app,
    color: theme.color.defaultText,
  }),
  ({ side }) =>
    side === 'left'
      ? {
          left: 0,
          right: '50vw',
        }
      : {
          right: 0,
          left: '50vw',
        }
);

const ThemeStack = styled.div(
  {
    position: 'relative',
    minHeight: 'calc(50vh - 15px)',
  },
  ({ theme }) => ({
    background: theme.background.app,
    color: theme.color.defaultText,
  })
);

const ThemedSetRoot = () => {
  const theme = useTheme();

  useEffect(() => {
    document.body.style.background = theme.background.app;
    document.body.style.color = theme.defaultText;
    return () => {
      //
    };
  });

  return null;
};

export const decorators = [
  (StoryFn, { globals: { theme = 'light' } }) => {
    switch (theme) {
      case 'side-by-side': {
        return (
          <Fragment>
            <Symbols icons={['folder', 'component', 'document', 'bookmarkhollow']} />
            <ThemeProvider theme={convert(themes.light)}>
              <Global styles={createReset} />
            </ThemeProvider>
            <ThemeProvider theme={convert(themes.light)}>
              <ThemeBlock side="left" data-side="left">
                <StoryFn />
              </ThemeBlock>
            </ThemeProvider>
            <ThemeProvider theme={convert(themes.dark)}>
              <ThemeBlock side="right" data-side="right">
                <StoryFn />
              </ThemeBlock>
            </ThemeProvider>
          </Fragment>
        );
      }
      case 'stacked': {
        return (
          <Fragment>
            <Symbols icons={['folder', 'component', 'document', 'bookmarkhollow']} />
            <ThemeProvider theme={convert(themes.light)}>
              <Global styles={createReset} />
            </ThemeProvider>
            <ThemeProvider theme={convert(themes.light)}>
              <ThemeStack side="left" data-side="left">
                <StoryFn />
              </ThemeStack>
            </ThemeProvider>
            <ThemeProvider theme={convert(themes.dark)}>
              <ThemeStack side="right" data-side="right">
                <StoryFn />
              </ThemeStack>
            </ThemeProvider>
          </Fragment>
        );
      }
      default: {
        return (
          <ThemeProvider theme={convert(themes[theme])}>
            <Symbols icons={['folder', 'component', 'document', 'bookmarkhollow']} />
            <Global styles={createReset} />
            <ThemedSetRoot />
            <StoryFn />
          </ThemeProvider>
        );
      }
    }
  },
];

export const parameters = {
  exportedParameter: 'exportedParameter',
  a11y: {
    config: {},
    options: {
      checks: { 'color-contrast': { options: { noScroll: true } } },
      restoreScroll: true,
    },
  },
  options: {
    storySort: (a, b) =>
      a[1].kind === b[1].kind ? 0 : a[1].id.localeCompare(b[1].id, undefined, { numeric: true }),
  },
  docs: {
    theme: themes.light,
  },
  controls: {
    presetColors: [
      { color: '#ff4785', title: 'Coral' },
      { color: '#1EA7FD', title: 'Ocean' },
      { color: 'rgb(252, 82, 31)', title: 'Orange' },
      { color: 'RGBA(255, 174, 0, 0.5)', title: 'Gold' },
      { color: 'hsl(101, 52%, 49%)', title: 'Green' },
      { color: 'HSLA(179,65%,53%,0.5)', title: 'Seafoam' },
      { color: '#6F2CAC', title: 'Purple' },
      { color: '#2A0481', title: 'Ultraviolet' },
      { color: 'black' },
      { color: '#333', title: 'Darkest' },
      { color: '#444', title: 'Darker' },
      { color: '#666', title: 'Dark' },
      { color: '#999', title: 'Mediumdark' },
      { color: '#ddd', title: 'Medium' },
      { color: '#EEE', title: 'Mediumlight' },
      { color: '#F3F3F3', title: 'Light' },
      { color: '#F8F8F8', title: 'Lighter' },
      { color: '#FFFFFF', title: 'Lightest' },
      '#fe4a49',
      '#FED766',
      'rgba(0, 159, 183, 1)',
      'HSLA(240,11%,91%,0.5)',
      'slategray',
    ],
  },
};

export const globals = {
  foo: 'fooValue',
};

export const globalTypes = {
  foo: { defaultValue: 'fooDefaultValue' },
  bar: { defaultValue: 'barDefaultValue' },
  theme: {
    name: 'Theme',
    description: 'Global theme for components',
    defaultValue: isChromatic() ? 'stacked' : 'light',
    toolbar: {
      icon: 'circlehollow',
      items: [
        { value: 'light', icon: 'circlehollow', title: 'light' },
        { value: 'dark', icon: 'circle', title: 'dark' },
        { value: 'side-by-side', icon: 'sidebar', title: 'side by side' },
        { value: 'stacked', icon: 'bottombar', title: 'stacked' },
      ],
      showName: true,
    },
  },
  locale: {
    name: 'Locale',
    description: 'Internationalization locale',
    defaultValue: 'en',
    toolbar: {
      icon: 'globe',
      shortcuts: {
        next: {
          label: 'Go to next language',
          keys: ['L'],
        },
        previous: {
          label: 'Go to previous language',
          keys: ['K'],
        },
      },
      items: [
        { value: '', title: 'Reset locale', type: 'reset' },
        { value: 'en', right: '🇺🇸', title: 'English' },
        { value: 'es', right: '🇪🇸', title: 'Español' },
        { value: 'zh', right: '🇨🇳', title: '中文' },
        { value: 'kr', right: '🇰🇷', title: '한국어' },
      ],
    },
    john: {},
  },
};

export const loaders = [async () => ({ globalValue: 1 })];
<commit_msg>fix: type isntead of condition<commit_after>import global from 'global';
import React, { Fragment, useEffect } from 'react';
import isChromatic from 'chromatic/isChromatic';
import {
  Global,
  ThemeProvider,
  themes,
  createReset,
  convert,
  styled,
  useTheme,
} from '@storybook/theming';
import { Symbols } from '@storybook/components';

import addHeadWarning from './head-warning';

const { document } = global;

if (process.env.NODE_ENV === 'development') {
  if (!process.env.DOTENV_DEVELOPMENT_DISPLAY_WARNING) {
    addHeadWarning('dotenv-env', 'Dotenv development file not loaded');
  }

  if (!process.env.STORYBOOK_DISPLAY_WARNING) {
    addHeadWarning('env-glob', 'Global storybook env var not loaded');
  }

  if (process.env.DISPLAY_WARNING) {
    addHeadWarning('env-extra', 'Global non-storybook env var loaded');
  }
}

addHeadWarning('preview-head-not-loaded', 'Preview head not loaded');
addHeadWarning('dotenv-file-not-loaded', 'Dotenv file not loaded');

const ThemeBlock = styled.div(
  {
    position: 'absolute',
    top: 0,
    left: 0,
    right: '50vw',
    width: '50vw',
    height: '100vh',
    bottom: 0,
    overflow: 'auto',
    padding: 10,
  },
  ({ theme }) => ({
    background: theme.background.app,
    color: theme.color.defaultText,
  }),
  ({ side }) =>
    side === 'left'
      ? {
          left: 0,
          right: '50vw',
        }
      : {
          right: 0,
          left: '50vw',
        }
);

const ThemeStack = styled.div(
  {
    position: 'relative',
    minHeight: 'calc(50vh - 15px)',
  },
  ({ theme }) => ({
    background: theme.background.app,
    color: theme.color.defaultText,
  })
);

const ThemedSetRoot = () => {
  const theme = useTheme();

  useEffect(() => {
    document.body.style.background = theme.background.app;
    document.body.style.color = theme.defaultText;
    return () => {
      //
    };
  });

  return null;
};

export const decorators = [
  (StoryFn, { globals: { theme = 'light' } }) => {
    switch (theme) {
      case 'side-by-side': {
        return (
          <Fragment>
            <Symbols icons={['folder', 'component', 'document', 'bookmarkhollow']} />
            <ThemeProvider theme={convert(themes.light)}>
              <Global styles={createReset} />
            </ThemeProvider>
            <ThemeProvider theme={convert(themes.light)}>
              <ThemeBlock side="left" data-side="left">
                <StoryFn />
              </ThemeBlock>
            </ThemeProvider>
            <ThemeProvider theme={convert(themes.dark)}>
              <ThemeBlock side="right" data-side="right">
                <StoryFn />
              </ThemeBlock>
            </ThemeProvider>
          </Fragment>
        );
      }
      case 'stacked': {
        return (
          <Fragment>
            <Symbols icons={['folder', 'component', 'document', 'bookmarkhollow']} />
            <ThemeProvider theme={convert(themes.light)}>
              <Global styles={createReset} />
            </ThemeProvider>
            <ThemeProvider theme={convert(themes.light)}>
              <ThemeStack side="left" data-side="left">
                <StoryFn />
              </ThemeStack>
            </ThemeProvider>
            <ThemeProvider theme={convert(themes.dark)}>
              <ThemeStack side="right" data-side="right">
                <StoryFn />
              </ThemeStack>
            </ThemeProvider>
          </Fragment>
        );
      }
      default: {
        return (
          <ThemeProvider theme={convert(themes[theme])}>
            <Symbols icons={['folder', 'component', 'document', 'bookmarkhollow']} />
            <Global styles={createReset} />
            <ThemedSetRoot />
            <StoryFn />
          </ThemeProvider>
        );
      }
    }
  },
];

export const parameters = {
  exportedParameter: 'exportedParameter',
  a11y: {
    config: {},
    options: {
      checks: { 'color-contrast': { options: { noScroll: true } } },
      restoreScroll: true,
    },
  },
  options: {
    storySort: (a, b) =>
      a[1].kind === b[1].kind ? 0 : a[1].id.localeCompare(b[1].id, undefined, { numeric: true }),
  },
  docs: {
    theme: themes.light,
  },
  controls: {
    presetColors: [
      { color: '#ff4785', title: 'Coral' },
      { color: '#1EA7FD', title: 'Ocean' },
      { color: 'rgb(252, 82, 31)', title: 'Orange' },
      { color: 'RGBA(255, 174, 0, 0.5)', title: 'Gold' },
      { color: 'hsl(101, 52%, 49%)', title: 'Green' },
      { color: 'HSLA(179,65%,53%,0.5)', title: 'Seafoam' },
      { color: '#6F2CAC', title: 'Purple' },
      { color: '#2A0481', title: 'Ultraviolet' },
      { color: 'black' },
      { color: '#333', title: 'Darkest' },
      { color: '#444', title: 'Darker' },
      { color: '#666', title: 'Dark' },
      { color: '#999', title: 'Mediumdark' },
      { color: '#ddd', title: 'Medium' },
      { color: '#EEE', title: 'Mediumlight' },
      { color: '#F3F3F3', title: 'Light' },
      { color: '#F8F8F8', title: 'Lighter' },
      { color: '#FFFFFF', title: 'Lightest' },
      '#fe4a49',
      '#FED766',
      'rgba(0, 159, 183, 1)',
      'HSLA(240,11%,91%,0.5)',
      'slategray',
    ],
  },
};

export const globals = {
  foo: 'fooValue',
};

export const globalTypes = {
  foo: { defaultValue: 'fooDefaultValue' },
  bar: { defaultValue: 'barDefaultValue' },
  theme: {
    name: 'Theme',
    description: 'Global theme for components',
    defaultValue: isChromatic() ? 'stacked' : 'light',
    toolbar: {
      icon: 'circlehollow',
      items: [
        { value: 'light', icon: 'circlehollow', title: 'light' },
        { value: 'dark', icon: 'circle', title: 'dark' },
        { value: 'side-by-side', icon: 'sidebar', title: 'side by side' },
        { value: 'stacked', icon: 'bottombar', title: 'stacked' },
      ],
      showName: true,
    },
  },
  locale: {
    name: 'Locale',
    description: 'Internationalization locale',
    defaultValue: 'en',
    toolbar: {
      icon: 'globe',
      shortcuts: {
        next: {
          label: 'Go to next language',
          keys: ['L'],
        },
        previous: {
          label: 'Go to previous language',
          keys: ['K'],
        },
      },
      items: [
        { value: '', title: 'Reset locale', type: 'reset' },
        { value: 'en', right: '🇺🇸', title: 'English' },
        { value: 'es', right: '🇪🇸', title: 'Español' },
        { value: 'zh', right: '🇨🇳', title: '中文' },
        { value: 'kr', right: '🇰🇷', title: '한국어' },
      ],
    },
  },
};

export const loaders = [async () => ({ globalValue: 1 })];
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var tasks = require('../task/03-date-tasks');
it.optional = require('../extensions/it-optional');

describe('03-date-tasks', function() {

    it.optional('parseDataFromRfc2822 should parse rfc2822 string into a date value', function () {
        assert.equal(
            new Date(1995, 11, 17, 3, 24, 0).valueOf(),
            tasks.parseDataFromRfc2822('December 17, 1995 03:24:00').valueOf()
        );

        assert.equal(
            1453816082000,
            tasks.parseDataFromRfc2822('Tue, 26 Jan 2016 13:48:02 GMT').valueOf()
        );

        assert.equal(
            895373940000,
            tasks.parseDataFromRfc2822('Sun, 17 May 1998 03:00:00 GMT+01').valueOf()
        );
    });

    it.optional('parseDataFromIso8601 should parse ISO 8601 string into a date value', function () {
        assert.equal(
            1453219657000,
            tasks.parseDataFromIso8601('2016-01-19T16:07:37+00:00').valueOf()
        );

        assert.equal(
            1453190857000,
            tasks.parseDataFromIso8601('2016-01-19T08:07:37Z').valueOf()
        );
    });

    it.optional('isLeapYear should true if specified year is leap', function () {
        [
            new Date(2000,1,1),
            new Date(2012,1,1)
        ].forEach(date => {
            assert(
                tasks.isLeapYear(date) == true,
                `${date} is a leap year`
            );
        });

        [
            new Date(1900,1,1),
            new Date(2001,1,1)
        ].forEach(date => {
            assert(
                tasks.isLeapYear(date) == false,
                `${date} is not a leap year`
            );
        });

    });

    it.optional('timeSpanToString should return the string represation of time span between two dates', function () {
        [
            {
                startDate: new Date(2000,1,1,10,0,0),
                endDate:   new Date(2000,1,1,11,0,0),
                expected:  '01:00:00.000'
            }, {
                startDate: new Date(2000,1,1,10,0,0),
                endDate:   new Date(2000,1,1,10,30,0),
                expected:  '00:30:00.000'
            }, {
                startDate: new Date(2000,1,1,10,0,0),
                endDate:   new Date(2000,1,1,10,0,20),
                expected:  '00:00:20.000'
            }, {
                startDate: new Date(2000,1,1,10,0,0),
                endDate:   new Date(2000,1,1,10,0,0,250),
                expected:  '00:00:00.250'
            }, {
                startDate: new Date(2000,1,1,10,0,0),
                endDate:   new Date(2000,1,1,15,20,10,453),
                expected:  '05:20:10.453'
            }
        ].forEach(data => {
            assert.equal(
                data.expected,
                tasks.timeSpanToString(data.startDate, data.endDate)
            );
        });

    });

    it.optional('angleBetweenClockHands should returns the angle bettween clock hands for specified Greenwich datetime', function () {
        [
            {
                date:     Date.UTC(2016,3,5, 0, 0),
                expected: 0
            }, {
                date:     Date.UTC(2016,3,5, 3, 0),
                expected: Math.PI/2
            }, {
                date:     Date.UTC(2016,3,5,15, 0),
                expected: Math.PI/2
            }, {
                date:     Date.UTC(2016,3,5, 6, 0),
                expected: Math.PI
            }, {
                date:     Date.UTC(2016,3,5,18, 0),
                expected: Math.PI
            }, {
                date:     Date.UTC(2016,3,5, 9, 0),
                expected: Math.PI/2
            }, {
                date:     Date.UTC(2016,3,5,21, 0),
                expected: Math.PI/2
            }, {
                date:     Date.UTC(2016,3,5,14,20),
                expected: 0.8726646259971648
            }, {
                date:     Date.UTC(2016,3,5,23,55),
                expected: 0.4799655442984406
            }
        ].forEach(data => {
            assert.equal(
                tasks.angleBetweenClockHands(new Date(data.date)),
                data.expected,
                `Incorrect result for angleBetweenClockHands(${new Date(data.date).toUTCString()}):`
            );
        });
    });

});
<commit_msg>Fix a wrong test assert for parseDataFromIso8601 function<commit_after>'use strict';

var assert = require('assert');
var tasks = require('../task/03-date-tasks');
it.optional = require('../extensions/it-optional');

describe('03-date-tasks', function() {

    it.optional('parseDataFromRfc2822 should parse rfc2822 string into a date value', function () {
        assert.equal(
            new Date(1995, 11, 17, 3, 24, 0).valueOf(),
            tasks.parseDataFromRfc2822('December 17, 1995 03:24:00').valueOf()
        );

        assert.equal(
            1453816082000,
            tasks.parseDataFromRfc2822('Tue, 26 Jan 2016 13:48:02 GMT').valueOf()
        );

        assert.equal(
            895370400000,
            tasks.parseDataFromRfc2822('Sun, 17 May 1998 03:00:00 GMT+01').valueOf()
        );
    });

    it.optional('parseDataFromIso8601 should parse ISO 8601 string into a date value', function () {
        assert.equal(
            1453219657000,
            tasks.parseDataFromIso8601('2016-01-19T16:07:37+00:00').valueOf()
        );

        assert.equal(
            1453190857000,
            tasks.parseDataFromIso8601('2016-01-19T08:07:37Z').valueOf()
        );
    });

    it.optional('isLeapYear should true if specified year is leap', function () {
        [
            new Date(2000,1,1),
            new Date(2012,1,1)
        ].forEach(date => {
            assert(
                tasks.isLeapYear(date) == true,
                `${date} is a leap year`
            );
        });

        [
            new Date(1900,1,1),
            new Date(2001,1,1)
        ].forEach(date => {
            assert(
                tasks.isLeapYear(date) == false,
                `${date} is not a leap year`
            );
        });

    });

    it.optional('timeSpanToString should return the string represation of time span between two dates', function () {
        [
            {
                startDate: new Date(2000,1,1,10,0,0),
                endDate:   new Date(2000,1,1,11,0,0),
                expected:  '01:00:00.000'
            }, {
                startDate: new Date(2000,1,1,10,0,0),
                endDate:   new Date(2000,1,1,10,30,0),
                expected:  '00:30:00.000'
            }, {
                startDate: new Date(2000,1,1,10,0,0),
                endDate:   new Date(2000,1,1,10,0,20),
                expected:  '00:00:20.000'
            }, {
                startDate: new Date(2000,1,1,10,0,0),
                endDate:   new Date(2000,1,1,10,0,0,250),
                expected:  '00:00:00.250'
            }, {
                startDate: new Date(2000,1,1,10,0,0),
                endDate:   new Date(2000,1,1,15,20,10,453),
                expected:  '05:20:10.453'
            }
        ].forEach(data => {
            assert.equal(
                data.expected,
                tasks.timeSpanToString(data.startDate, data.endDate)
            );
        });

    });

    it.optional('angleBetweenClockHands should returns the angle bettween clock hands for specified Greenwich datetime', function () {
        [
            {
                date:     Date.UTC(2016,3,5, 0, 0),
                expected: 0
            }, {
                date:     Date.UTC(2016,3,5, 3, 0),
                expected: Math.PI/2
            }, {
                date:     Date.UTC(2016,3,5,15, 0),
                expected: Math.PI/2
            }, {
                date:     Date.UTC(2016,3,5, 6, 0),
                expected: Math.PI
            }, {
                date:     Date.UTC(2016,3,5,18, 0),
                expected: Math.PI
            }, {
                date:     Date.UTC(2016,3,5, 9, 0),
                expected: Math.PI/2
            }, {
                date:     Date.UTC(2016,3,5,21, 0),
                expected: Math.PI/2
            }, {
                date:     Date.UTC(2016,3,5,14,20),
                expected: 0.8726646259971648
            }, {
                date:     Date.UTC(2016,3,5,23,55),
                expected: 0.4799655442984406
            }
        ].forEach(data => {
            assert.equal(
                tasks.angleBetweenClockHands(new Date(data.date)),
                data.expected,
                `Incorrect result for angleBetweenClockHands(${new Date(data.date).toUTCString()}):`
            );
        });
    });

});
<|endoftext|>