<commit_before>/**
 * This file contains all necessary Angular controller definitions for 'frontend.admin.login-history' module.
 *
 * Note that this file should only contain controllers and nothing else.
 */
(function () {
  'use strict';

  angular.module('frontend.certificates')
    .controller('CertificatesController', [
      '$scope', '$rootScope', '$log', '$state', 'ApiService', '$uibModal', 'DialogService', 'UserService',
      'MessageService', 'SettingsService', '$http', 'Upload', 'Semver', '$timeout', 'CertificateModel', 'ListConfig',
      function controller($scope, $rootScope, $log, $state, ApiService, $uibModal, DialogService, UserService,
                          MessageService, SettingsService, $http, Upload, Semver, $timeout, CertificateModel, ListConfig) {

        CertificateModel.setScope($scope, false, 'items', 'itemCount');
        $scope = angular.extend($scope, angular.copy(ListConfig.getConfig('certificate', CertificateModel)));
        $scope.user = UserService.user();

        $scope.openUploadCertsModal = function (certificate) {
          var modalInstance = $uibModal.open({
            animation: true,
            ariaLabelledBy: 'modal-title',
            ariaDescribedBy: 'modal-body',
            templateUrl: 'js/app/certificates/add-certificates-modal.html',
            controller: function ($scope, $uibModal, $uibModalInstance, SnisModel, DialogService, _certificate) {
              $scope.update = _certificate
              $scope.data = _certificate || {}
              $scope.close = function () {
                return $uibModalInstance.dismiss()
              }

              $scope.deleteSNI = function (sni) {
                DialogService.prompt(
                  "Confirm", "Really want to delete the selected item?",
                  ['No don\'t', 'Yes! delete it'],
                  function accept() {
                    SnisModel.delete(sni)
                      .then(function (res) {

                        $scope.data.snis.splice($scope.data.snis.indexOf(sni), 1);
                      }, function (err) {
                        $log.error("ListConfigService : Model delete failed => ", err)
                      });
                  }, function decline() {
                  })
              }

              $scope.openAddSniModal = function () {
                var modalInstance = $uibModal.open({
                  animation: true,
                  ariaLabelledBy: 'modal-title',
                  ariaDescribedBy: 'modal-body',
                  templateUrl: 'js/app/certificates/add-sni-modal.html',
                  size: 'sm',
                  controller: function ($scope, $uibModalInstance, SnisModel, DialogService, _certId) {

                    $scope.close = function () {
                      return $uibModalInstance.dismiss();
                    };

                    $scope.submit = function () {

                      var data = {
                        name: $scope.sni,
                        ssl_certificate_id: _certId
                      }

                      if ($rootScope.isGatewayVersionEqOrGreater('0.14')) {
                        data.certificate = {
                          id: _certId
                        };
                        delete data.ssl_certificate_id;
                      }

                      SnisModel.create(data).then(function (created) {
                        $uibModalInstance.close({
                          data: created.data.name
                        });
                      }).catch(function (err) {
                        console.error("Failed to create SNI =>", err);
                        SnisModel.handleError($scope, err);
                      });
                    };

                  },
                  resolve: {
                    _certId: function () {
                      return _certificate.id;
                    }
                  }

                });

                modalInstance.result.then(function (data) {
                  if (data && data.data) $scope.data.snis.push(data.data);
                }, function (data) {
                });
              }

              $scope.submitCerts = function () {

                $scope.errorMessage = ""

                var data = angular.copy($scope.data);

                data.cert = data.cert.trim();
                data.key = data.key.trim();

                if ($rootScope.isGatewayVersionEqOrGreater('0.14')) {
                  data.snis = data.snis.split(",")
                }

                CertificateModel.create(data)
                  .then(function (resp) {
                    console.log('Success', resp.data);
                    $uibModalInstance.dismiss({
                      data: resp
                    })
                  }).catch(function (err) {
                  console.error('Error', err);
                  handleErrors(err)
                })

              }

              $scope.updateCerts = function () {

                $scope.errorMessage = ""

                var data = angular.copy($scope.data);

                data.cert = data.cert.trim();
                data.key = data.key.trim();

                CertificateModel.update(data.id, _.omit(data,['id']))
                  .then(function (resp) {
                    console.log('Success', resp.data);
                    $uibModalInstance.dismiss({
                      data: resp
                    })
                  }).catch(function (err) {
                  console.error('Error', err);
                  handleErrors(err)
                })

              }

              function handleErrors(err) {
                $scope.errors = {}

                if (err.data) {
                  if (err.data.customMessage) {

                    for (var key in err.data.customMessage) {
                      $scope.errors[key] = err.data.customMessage[key]
                    }
                  }

                  if (err.data.message) {
                    $scope.errorMessage = err.data.message
                  }
                } else {
                  $scope.errorMessage = "An unknown error has occured"
                }

                //console.log("SCOPE ERRORS",$scope.errors)
              }

            },
            controllerAs: '$ctrl',
            resolve: {
              _certificate: function () {
                return certificate
              }
            }
            //size: 'lg',
          });

          modalInstance.result.then(function () {

          }, function (data) {
            if (data && data.data) _fetchData()
          });
        }

        function _fetchData() {
          $scope.loading = true;
          CertificateModel.load({
            size: $scope.itemsFetchSize
          }).then(function (response) {
            console.log(response)
            $scope.items = response;
            $scope.loading = false;

            if (response.data && Object.keys(response.data).length) {
              $scope.certificates = Semver.cmp($rootScope.Gateway.version, "0.10.1") > 0 ? response.data.data : response.data
            } else {
              $scope.certificates = []
            }
          })
        }

        _fetchData()

        $scope.$on('user.node.updated', function (node) {
          $timeout(function () {
            _fetchData()
          })

        })

      }
    ])
  ;
}());
<commit_msg>handle empty fields<commit_after>/**
 * This file contains all necessary Angular controller definitions for 'frontend.admin.login-history' module.
 *
 * Note that this file should only contain controllers and nothing else.
 */
(function () {
  'use strict';

  angular.module('frontend.certificates')
    .controller('CertificatesController', [
      '$scope', '$rootScope', '$log', '$state', 'ApiService', '$uibModal', 'DialogService', 'UserService',
      'MessageService', 'SettingsService', '$http', 'Upload', 'Semver', '$timeout', 'CertificateModel', 'ListConfig',
      function controller($scope, $rootScope, $log, $state, ApiService, $uibModal, DialogService, UserService,
                          MessageService, SettingsService, $http, Upload, Semver, $timeout, CertificateModel, ListConfig) {

        CertificateModel.setScope($scope, false, 'items', 'itemCount');
        $scope = angular.extend($scope, angular.copy(ListConfig.getConfig('certificate', CertificateModel)));
        $scope.user = UserService.user();

        $scope.openUploadCertsModal = function (certificate) {
          var modalInstance = $uibModal.open({
            animation: true,
            ariaLabelledBy: 'modal-title',
            ariaDescribedBy: 'modal-body',
            templateUrl: 'js/app/certificates/add-certificates-modal.html',
            controller: function ($scope, $uibModal, $uibModalInstance, SnisModel, DialogService, _certificate) {
              $scope.update = _certificate
              $scope.data = _certificate || {}
              $scope.close = function () {
                return $uibModalInstance.dismiss()
              }

              $scope.deleteSNI = function (sni) {
                DialogService.prompt(
                  "Confirm", "Really want to delete the selected item?",
                  ['No don\'t', 'Yes! delete it'],
                  function accept() {
                    SnisModel.delete(sni)
                      .then(function (res) {

                        $scope.data.snis.splice($scope.data.snis.indexOf(sni), 1);
                      }, function (err) {
                        $log.error("ListConfigService : Model delete failed => ", err)
                      });
                  }, function decline() {
                  })
              }

              $scope.openAddSniModal = function () {
                var modalInstance = $uibModal.open({
                  animation: true,
                  ariaLabelledBy: 'modal-title',
                  ariaDescribedBy: 'modal-body',
                  templateUrl: 'js/app/certificates/add-sni-modal.html',
                  size: 'sm',
                  controller: function ($scope, $uibModalInstance, SnisModel, DialogService, _certId) {

                    $scope.close = function () {
                      return $uibModalInstance.dismiss();
                    };

                    $scope.submit = function () {

                      var data = {
                        name: $scope.sni,
                        ssl_certificate_id: _certId
                      }

                      if ($rootScope.isGatewayVersionEqOrGreater('0.14')) {
                        data.certificate = {
                          id: _certId
                        };
                        delete data.ssl_certificate_id;
                      }

                      SnisModel.create(data).then(function (created) {
                        $uibModalInstance.close({
                          data: created.data.name
                        });
                      }).catch(function (err) {
                        console.error("Failed to create SNI =>", err);
                        SnisModel.handleError($scope, err);
                      });
                    };

                  },
                  resolve: {
                    _certId: function () {
                      return _certificate.id;
                    }
                  }

                });

                modalInstance.result.then(function (data) {
                  if (data && data.data) $scope.data.snis.push(data.data);
                }, function (data) {
                });
              }

              $scope.submitCerts = function () {

                $scope.errorMessage = ""

                var data = angular.copy($scope.data);

                if(!data.cert || !data.key) {
                  $scope.errorMessage = "The `Certificate` and `Key` fields cannot be empty"
                  return false;
                }

                data.cert = data.cert.trim();
                data.key = data.key.trim();

                if ($rootScope.isGatewayVersionEqOrGreater('0.14')) {
                  data.snis = data.snis.split(",")
                }

                CertificateModel.create(data)
                  .then(function (resp) {
                    console.log('Success', resp.data);
                    $uibModalInstance.dismiss({
                      data: resp
                    })
                  }).catch(function (err) {
                  console.error('Error', err);
                  handleErrors(err)
                })

              }

              $scope.updateCerts = function () {

                $scope.errorMessage = ""

                var data = angular.copy($scope.data);

                data.cert = data.cert.trim();
                data.key = data.key.trim();

                CertificateModel.update(data.id, _.omit(data,['id']))
                  .then(function (resp) {
                    console.log('Success', resp.data);
                    $uibModalInstance.dismiss({
                      data: resp
                    })
                  }).catch(function (err) {
                  console.error('Error', err);
                  handleErrors(err)
                })

              }

              function handleErrors(err) {
                $scope.errors = {}

                if (err.data) {
                  if (err.data.customMessage) {

                    for (var key in err.data.customMessage) {
                      $scope.errors[key] = err.data.customMessage[key]
                    }
                  }

                  if (err.data.message) {
                    $scope.errorMessage = err.data.message
                  }
                } else {
                  $scope.errorMessage = "An unknown error has occured"
                }

                //console.log("SCOPE ERRORS",$scope.errors)
              }

            },
            controllerAs: '$ctrl',
            resolve: {
              _certificate: function () {
                return certificate
              }
            }
            //size: 'lg',
          });

          modalInstance.result.then(function () {

          }, function (data) {
            if (data && data.data) _fetchData()
          });
        }

        function _fetchData() {
          $scope.loading = true;
          CertificateModel.load({
            size: $scope.itemsFetchSize
          }).then(function (response) {
            console.log(response)
            $scope.items = response;
            $scope.loading = false;

            if (response.data && Object.keys(response.data).length) {
              $scope.certificates = Semver.cmp($rootScope.Gateway.version, "0.10.1") > 0 ? response.data.data : response.data
            } else {
              $scope.certificates = []
            }
          })
        }

        _fetchData()

        $scope.$on('user.node.updated', function (node) {
          $timeout(function () {
            _fetchData()
          })

        })

      }
    ])
  ;
}());
<|endoftext|>


<commit_before>(function($) {
	$.fn.paginate = function(options) {
		var opts = $.extend({}, $.fn.paginate.defaults, options);
		return this.each(function() {
			$this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			var selectedpage = o.start;
			$.fn.draw(o,$this,selectedpage);
		});
	};
	var outsidewidth_tmp = 0;
	var insidewidth 	 = 0;
	var bName = navigator.appName;
	var bVer = navigator.appVersion;
	if(bVer.indexOf('MSIE 7.0') > 0)
		var ver = "ie7";
	$.fn.paginate.defaults = {
		count 		: 5,
		start 		: 12,
		display  	: 5,
		border					: true,
		border_color			: '#fff',
		text_color  			: '#8cc59d',
		background_color    	: 'black',
		border_hover_color		: '#fff',
		text_hover_color  		: '#fff',
		background_hover_color	: '#fff',
		rotate      			: true,
		images					: true,
		mouse					: 'slide',
		onChange				: function(){return false;}
	};
	$.fn.draw = function(o,obj,selectedpage){
		if(o.display > o.count)
			o.display = o.count;
		$this.empty();
		if(o.images){
			var spreviousclass 	= 'jPag-sprevious-img';
			var previousclass 	= 'jPag-previous-img';
			var snextclass 		= 'jPag-snext-img';
			var nextclass 		= 'jPag-next-img';
		}
		else{
			var spreviousclass 	= 'jPag-sprevious';
			var previousclass 	= 'jPag-previous';
			var snextclass 		= 'jPag-snext';
			var nextclass 		= 'jPag-next';
		}
		var _first		= $(document.createElement('a')).addClass('jPag-first').html('First');

		if(o.rotate){
			if(o.images) var _rotleft	= $(document.createElement('span')).addClass(spreviousclass);
			else var _rotleft	= $(document.createElement('span')).addClass(spreviousclass).html('«');
		}

		var _divwrapleft	= $(document.createElement('div')).addClass('jPag-control-back');
		_divwrapleft.append(_first).append(_rotleft);

		var _ulwrapdiv	= $(document.createElement('div')).css('overflow','hidden');
		var _ul			= $(document.createElement('ul')).addClass('jPag-pages')
		var c = (o.display - 1) / 2;
		var first = selectedpage - c;
		var selobj;
		for(var i = 0; i < o.count; i++){
			var val = i+1;
			if(val == selectedpage){
				var _obj = $(document.createElement('li')).html(''+val+'');
				selobj = _obj;
				_ul.append(_obj);
			}
			else{
				var _obj = $(document.createElement('li')).html(''+ val +'');
				_ul.append(_obj);
				}
		}
		_ulwrapdiv.append(_ul);

		if(o.rotate){
			if(o.images) var _rotright	= $(document.createElement('span')).addClass(snextclass);
			else var _rotright	= $(document.createElement('span')).addClass(snextclass).html('»');
		}

		var _last		= $(document.createElement('a')).addClass('jPag-last').html('Last');
		var _divwrapright	= $(document.createElement('div')).addClass('jPag-control-front');
		_divwrapright.append(_rotright).append(_last);

		//append all:
		$this.addClass('jPaginate').append(_divwrapleft).append(_ulwrapdiv).append(_divwrapright);

		if(!o.border){
			if(o.background_color == 'none') var a_css 				= {'color':o.text_color};
			else var a_css 											= {'color':o.text_color,'background-color':o.background_color};
			if(o.background_hover_color == 'none')	var hover_css 	= {'color':o.text_hover_color};
			else var hover_css 										= {'color':o.text_hover_color,'background-color':o.background_hover_color};
		}
		else{
			if(o.background_color == 'none') var a_css 				= {'color':o.text_color,'border':'1px solid '+o.border_color};
			else var a_css 											= {'color':o.text_color,'background-color':o.background_color,'border':'1px solid '+o.border_color};
			if(o.background_hover_color == 'none')	var hover_css 	= {'color':o.text_hover_color,'border':'1px solid '+o.border_hover_color};
			else var hover_css 										= {'color':o.text_hover_color,'background-color':o.background_hover_color,'border':'1px solid '+o.border_hover_color};
		}

		$.fn.applystyle(o,$this,a_css,hover_css,_first,_ul,_ulwrapdiv,_divwrapright);
		//calculate width of the ones displayed:
		var outsidewidth = outsidewidth_tmp - _first.parent().width() -3;
		if(ver == 'ie7'){
			_ulwrapdiv.css('width',outsidewidth+72+'px');
			_divwrapright.css('left',outsidewidth_tmp+6+72+'px');
		}
		else{
			_ulwrapdiv.css('width',outsidewidth+'px');
			_divwrapright.css('left',outsidewidth_tmp+6+'px');
		}

		if(o.rotate){
			_rotright.hover(
				function() {
				  thumbs_scroll_interval = setInterval(
					function() {
					  var left = _ulwrapdiv.scrollLeft() + 1;
					  _ulwrapdiv.scrollLeft(left);
					},
					20
				  );
				},
				function() {
				  clearInterval(thumbs_scroll_interval);
				}
			);
			_rotleft.hover(
				function() {
				  thumbs_scroll_interval = setInterval(
					function() {
					  var left = _ulwrapdiv.scrollLeft() - 1;
					  _ulwrapdiv.scrollLeft(left);
					},
					20
				  );
				},
				function() {
				  clearInterval(thumbs_scroll_interval);
				}
			);
			if(o.mouse == 'press'){
				_rotright.mousedown(
					function() {
					  thumbs_mouse_interval = setInterval(
						function() {
						  var left = _ulwrapdiv.scrollLeft() + 5;
						  _ulwrapdiv.scrollLeft(left);
						},
						20
					  );
					}
				).mouseup(
					function() {
					  clearInterval(thumbs_mouse_interval);
					}
				);
				_rotleft.mousedown(
					function() {
					  thumbs_mouse_interval = setInterval(
						function() {
						  var left = _ulwrapdiv.scrollLeft() - 5;
						  _ulwrapdiv.scrollLeft(left);
						},
						20
					  );
					}
				).mouseup(
					function() {
					  clearInterval(thumbs_mouse_interval);
					}
				);
			}
			else{
				_rotleft.click(function(e){
					var width = outsidewidth - 10;
					var left = _ulwrapdiv.scrollLeft() - width;
					_ulwrapdiv.animate({scrollLeft: left +'px'});
				});

				_rotright.click(function(e){
					var width = outsidewidth - 10;
					var left = _ulwrapdiv.scrollLeft() + width;
					_ulwrapdiv.animate({scrollLeft: left +'px'});
				});
			}
		}

		//first and last:
		_first.click(function(e){
				_ulwrapdiv.animate({scrollLeft: '0px'});
				_ulwrapdiv.find('li').eq(0).click();
		});
		_last.click(function(e){
				_ulwrapdiv.animate({scrollLeft: insidewidth +'px'});
				_ulwrapdiv.find('li').eq(o.count - 1).click();
		});

		//click a page
		_ulwrapdiv.find('li').click(function(e){
			selobj.html(''+selobj.find('.jPag-current').html()+'');
			var currval = $(this).find('a').html();
			$(this).html(''+currval+'');
			selobj = $(this);
			$.fn.applystyle(o,$(this).parent().parent().parent(),a_css,hover_css,_first,_ul,_ulwrapdiv,_divwrapright);
			var left = (this.offsetLeft) / 2;
			var left2 = _ulwrapdiv.scrollLeft() + left;
			var tmp = left - (outsidewidth / 2);
			if(ver == 'ie7')
				_ulwrapdiv.animate({scrollLeft: left + tmp - _first.parent().width() + 52 + 'px'});
			else
				_ulwrapdiv.animate({scrollLeft: left + tmp - _first.parent().width() + 'px'});
			o.onChange(currval);
		});

		var last = _ulwrapdiv.find('li').eq(o.start-1);
		last.attr('id','tmp');
		var left = document.getElementById('tmp').offsetLeft / 2;
		last.removeAttr('id');
		var tmp = left - (outsidewidth / 2);
		if(ver == 'ie7') _ulwrapdiv.animate({scrollLeft: left + tmp - _first.parent().width() + 52 + 'px'});
		else _ulwrapdiv.animate({scrollLeft: left + tmp - _first.parent().width() + 'px'});
	}

	$.fn.applystyle = function(o,obj,a_css,hover_css,_first,_ul,_ulwrapdiv,_divwrapright){
					obj.find('a').css(a_css);
					obj.find('span.jPag-current').css(hover_css);
					obj.find('a').hover(
					function(){
						$(this).css(hover_css);
					},
					function(){
						$(this).css(a_css);
					}
					);
					obj.css('padding-left',_first.parent().width() + 5 +'px');
					insidewidth = 0;

					obj.find('li').each(function(i,n){
						if(i == (o.display-1)){
							outsidewidth_tmp = this.offsetLeft + this.offsetWidth ;
						}
						insidewidth += this.offsetWidth;
					})
					_ul.css('width',insidewidth+'px');
	}
})(jQuery);<commit_msg>INC-15 removing jpaginate<commit_after><|endoftext|>


<commit_before>import Webiny from 'Webiny';

class Module extends Webiny.Module {

    getCookieName() {
        return 'webiny-token';
    }

    /**
     * Triggerred when user is not authenticated
     *
     * @param routerEvent
     * @param apiResponse
     */
    onForbidden() {
        Q.all([
            Webiny.Dispatcher.dispatch('Logout')
        ]).then(() => {
            Webiny.Router.goToRoute('Login', {logout: 'expired'});
        });
    }

    onNoToken(routerEvent) {
        localStorage.loginRedirect = window.location.href;
        routerEvent.stop();

        const isLoginRoute = routerEvent.route.name === 'Login';

        if (!isLoginRoute) {
            routerEvent.goToRoute('Login', {logout: 'not'});
        }

        return routerEvent;
    }

    onVerifyUser(routerEvent, apiResponse) {
        const data = apiResponse.getData();
        if (!_.find(data.groups, {tag: 'administrators'})) {
            Webiny.Cookies.remove(this.getCookieName());
            return this.goToLogin(routerEvent);
        }
        Webiny.Model.set('User', data);

        return routerEvent;
    }

    onLogout() {
        Webiny.Model.set('User', null);
        Webiny.Cookies.remove(this.getCookieName());
        Webiny.Router.goToRoute('Login');
    }

    getUserEntity() {
        return '/core/users';
    }

    getUserFields() {
        return '*,groups.tag';
    }

    getUser(routerEvent) {
        return new Webiny.Api.Endpoint('/entities' + this.getUserEntity()).get('/me', {_fields: this.getUserFields()}).then(apiResponse => {
            return this.onVerifyUser(routerEvent, apiResponse);
        });
    }

    goToLogin(routerEvent) {
        localStorage.loginRedirect = window.location.href;
        routerEvent.stop();

        const isLoginRoute = routerEvent.route.name === 'Login';

        if (!isLoginRoute) {
            routerEvent.goToRoute('Login');
        }

        return routerEvent;
    }

    run() {
        Webiny.Dispatcher.on('Logout', this.onLogout.bind(this));

        Webiny.Router.onBeforeStart(routerEvent => {
            Webiny.Http.addRequestInterceptor(http => {
                http.addHeader('Authorization', Webiny.Cookies.get(this.getCookieName()));
            });

            // Watch if we got a forbidden request - then log out
            Webiny.Http.addResponseInterceptor(response => {
                if (response.status === 403) {
                    this.onForbidden(routerEvent, response);
                }
            });

            return this.checkUser(routerEvent);
        });

        Webiny.Router.onRouteWillChange(this.checkUser.bind(this));
    }

    checkUser(routerEvent) {
        if (Webiny.Model.get('User')) {
            return false;
        }

        const token = Webiny.Cookies.get(this.getCookieName());

        // Check if token exists on client side
        if (!token) {
            return this.onNoToken(routerEvent);
        }

        // Try fetching user data
        return this.getUser(routerEvent);
    }
}

export default Module;<commit_msg>- just checking this file<commit_after>import Webiny from 'Webiny';

class Module extends Webiny.Module {

	getCookieName() {
		return 'webiny-token';
	}

	/**
	 * Triggerred when user is not authenticated
	 *
	 * @param routerEvent
	 * @param apiResponse
	 */
	onForbidden() {
		Q.all([
			Webiny.Dispatcher.dispatch('Logout')
		]).then(() => {
			Webiny.Router.goToRoute('Login', {logout: 'expired'});
		});
	}

	onNoToken(routerEvent) {
		localStorage.loginRedirect = window.location.href;
		routerEvent.stop();

		const isLoginRoute = routerEvent.route.name === 'Login';

		if (!isLoginRoute) {
			routerEvent.goToRoute('Login', {logout: 'not'});
		}

		return routerEvent;
	}

	onVerifyUser(routerEvent, apiResponse) {
		const data = apiResponse.getData();
		if (!_.find(data.groups, {tag: 'administrators'})) {
			Webiny.Cookies.remove(this.getCookieName());
			return this.goToLogin(routerEvent);
		}
		Webiny.Model.set('User', data);

		return routerEvent;
	}

	onLogout() {
		Webiny.Model.set('User', null);
		Webiny.Cookies.remove(this.getCookieName());
		Webiny.Router.goToRoute('Login');
	}

	getUserEntity() {
		return '/core/users';
	}

	getUserFields() {
		return '*,groups.tag';
	}

	getUser(routerEvent) {
		return new Webiny.Api.Endpoint('/entities' + this.getUserEntity()).get('/me', {_fields: this.getUserFields()}).then(apiResponse => {
			return this.onVerifyUser(routerEvent, apiResponse);
		});
	}

	goToLogin(routerEvent) {
		localStorage.loginRedirect = window.location.href;
		routerEvent.stop();

		const isLoginRoute = routerEvent.route.name === 'Login';

		if (!isLoginRoute) {
			routerEvent.goToRoute('Login');
		}

		return routerEvent;
	}

	run() {
		Webiny.Dispatcher.on('Logout', this.onLogout.bind(this));

		Webiny.Router.onBeforeStart(routerEvent => {
			Webiny.Http.addRequestInterceptor(http => {
				http.addHeader('Authorization', Webiny.Cookies.get(this.getCookieName()));
			});

			// Watch if we got a forbidden request - then log out
			Webiny.Http.addResponseInterceptor(response => {
				if (response.status === 403) {
					this.onForbidden(routerEvent, response);
				}
			});

			return this.checkUser(routerEvent);
		});

		Webiny.Router.onRouteWillChange(this.checkUser.bind(this));
	}

	checkUser(routerEvent) {
		if (Webiny.Model.get('User')) {
			return false;
		}

		const token = Webiny.Cookies.get(this.getCookieName());

		// Check if token exists on client side
		if (!token) {
			return this.onNoToken(routerEvent);
		}

		// Try fetching user data
		return this.getUser(routerEvent);
	}
}

export default Module;<|endoftext|>


<commit_before>module.exports = function (writePath, file, cb) {
  var done =  function(err){
    if (err) return cb(err);
    cb(null, file);
  };

  // if no contents then do nothing
  if (file.isNull()) return done();

  // if directory then mkdirp it
  // probably redundant since we are already doing an mkdirp
  if (file.isDirectory()) {
    writeDir(writePath, file, done);
    return;
  }

  // stream it to disk yo
  if (file.isStream()) {
    writeStream(file, done);
    return;
  }

  if (file.isBuffer()) {
    // write it like normal
    writeBuffer(file, done);
    return;
  }
};<commit_msg>require deps in writecontent.js<commit_after>var writeDir = require('./writeDir');
var writeStream = require('./writeStream');
var writeBuffer = require('./writeBuffer');

module.exports = function (writePath, file, cb) {
  var done =  function(err){
    if (err) return cb(err);
    cb(null, file);
  };

  // if no contents then do nothing
  if (file.isNull()) return done();

  // if directory then mkdirp it
  // probably redundant since we are already doing an mkdirp
  if (file.isDirectory()) {
    writeDir(writePath, file, done);
    return;
  }

  // stream it to disk yo
  if (file.isStream()) {
    writeStream(file, done);
    return;
  }

  if (file.isBuffer()) {
    // write it like normal
    writeBuffer(file, done);
    return;
  }
};<|endoftext|>


<commit_before>(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery', 'store'], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory(require('jquery', 'store'));
    } else {
        root.returnExports = factory(root.jQuery, root.store);
    }
}(this, function ($, storage) {
    var options     = {};
    var data        = {};
    var intercept   = false;
    var refreshing  = false;
    var buffer      = [];
    var currentRequests = [];

    var publicApi = {
        hasAccessToken: function() {
            return data.accessToken !== null;
        },
        hasAccessTokenExpiration: function() {
            return data.accessTokenExpiration !== null;
        },
        logout: function() {
            privateApi.resetData();
            privateApi.updateStorage();
            privateApi.deactivateInterceptor();
            privateApi.removeAjaxHeader("Authorization");
            privateApi.fireEvent("logout");
        },
        login: function(accessToken, accessTokenExpiration) {
            this.setAccessToken(accessToken, accessTokenExpiration);

            privateApi.activateInterceptor();
            privateApi.fireEvent("login");
        },
        initialize: function(inputOptions) {
            privateApi.resetOptions();
            privateApi.setupInterceptor();

            $.extend(options, inputOptions);

            if (privateApi.hasStoredData()) {
                privateApi.getStoredData();

                if (this.hasAccessToken() && this.hasAccessTokenExpiration()) {
                    this.login(data.accessToken, data.accessTokenExpiration);
                }
            } else {
                privateApi.resetData();
                privateApi.updateStorage();
            }

            if (options.csrfToken !== null) {
                privateApi.setCsrfHeader();
            }
        },
        setAccessToken: function(accessToken, accessTokenExpiration) {
            if (accessTokenExpiration === undefined) {
                accessTokenExpiration = null;
            }

            data.accessToken           = accessToken;
            data.accessTokenExpiration = accessTokenExpiration;

            privateApi.setAuthorizationHeader();
            privateApi.updateStorage();
        },
        setCsrfToken: function(csrfToken) {
            options.csrfToken = csrfToken;

            privateApi.setCsrfHeader();
        }
    };

    var privateApi = {
        activateInterceptor: function() {
            intercept = true;
        },
        addToBuffer: function(settings, deferred) {
            buffer.push({
                deferred: deferred,
                settings: settings
            });
        },
        clearBuffer: function() {
            buffer = [];
        },
        deactivateInterceptor: function() {
            intercept = false;
        },
        fireBuffer: function() {
            var self = this;
            var deferred;
            var promises = [];
            for(var i in buffer) {
                deferred = buffer[i].deferred;

                buffer[i].settings.refreshRetry = true;
                buffer[i].settings.headers["Authorization"] = $.ajaxSettings.headers["Authorization"];

                promises.push($.ajax(buffer[i].settings).then(deferred.resolve, deferred.reject));
            }

            self.clearBuffer();

            $.when.apply($, promises)
                .done(function() {
                    self.setRefreshingFlag(false);
                })
                .fail(function(){
                    self.setRefreshingFlag(false);
                    publicApi.logout();
                });
        },
        fireEvent: function(eventType) {
            if (this.hasEvent(eventType)) {
                return options.events[eventType]();
            }
        },
        getStoredData: function() {
            $.extend(data, storage.get("jquery.oauth"));
        },
        hasEvent: function(eventType) {
            return options.events[eventType] !== undefined && typeof options.events[eventType] === "function";
        },
        hasStoredData: function() {
            return storage.get("jquery.oauth") !== undefined;
        },
        isAjaxHeadersInitialized: function() {
            return $.ajaxSettings.headers !== undefined;
        },
        removeAjaxHeader: function(header) {
            if (!this.isAjaxHeadersInitialized()) {
                return true;
            }
            $.ajaxSettings.headers[header] = undefined;
        },
        removeAllAjaxHeaders: function() {
            this.removeAjaxHeader("Authorization");
            this.removeAjaxHeader("X-CSRF-Token");
        },
        resetData: function() {
            data = {
                accessToken: null,
                accessTokenExpiration: null
            };
        },
        resetOptions: function() {
            options = {
                bufferInterval: 25,
                bufferWaitLimit: 500,
                csrfToken: null,
                events: {}
            };

            this.removeAllAjaxHeaders();
        },
        setAjaxHeader: function(header, value) {
            if (!this.isAjaxHeadersInitialized()) {
                $.ajaxSettings.headers = {};
            }

            $.ajaxSettings.headers[header] = value;
        },
        setAuthorizationHeader: function() {
            this.setAjaxHeader("Authorization", "Bearer " + data.accessToken);
        },
        setCsrfHeader: function() {
            this.setAjaxHeader("X-CSRF-Token", options.csrfToken);
        },
        setRefreshingFlag: function(newFlag) {
            refreshing = newFlag;
        },
        setupInterceptor: function() {
            var self = this;

            // Credits to gnarf @ http://stackoverflow.com/a/12446363/602488
            $.ajaxPrefilter(function(options, originalOptions, jqxhr) {
                if (options.refreshRetry === true) {
                    return;
                }

                var deferred = $.Deferred();

                currentRequests.push(options.url);
                jqxhr.always(function(){
                    currentRequests.splice($.inArray(options.url, currentRequests), 1);
                });
                jqxhr.done(deferred.resolve);
                jqxhr.fail(function() {
                    var args = Array.prototype.slice.call(arguments);

                    if (intercept && jqxhr.status === 401 && self.hasEvent("tokenExpiration")) {
                        self.addToBuffer(options, deferred);

                        if (!refreshing) {
                            self.setRefreshingFlag(true);
                            self.fireEvent("tokenExpiration")
                                .success(function () {
                                    // Setup buffer interval that waits for all sent requests to return
                                    var waited   = 0;
                                    var interval = setInterval(function(){
                                        waited += options.bufferInterval;

                                        // All requests have returned 401 and have been buffered
                                        if (currentRequests.length === 0 || waited >= options.bufferWaitLimit) {
                                            clearInterval(interval);
                                            self.fireBuffer();
                                        }
                                    }, options.bufferInterval);
                                })
                                .fail(function () {
                                    publicApi.logout();
                                });
                        }
                    } else {
                        deferred.rejectWith(jqxhr, args);
                    }
                });

                return deferred.promise(jqxhr);
            });
        },
        updateStorage: function() {
            storage.set("jquery.oauth", data);
        }
    };

    return publicApi;
}));<commit_msg>Removed access token expiration<commit_after>(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery', 'store'], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory(require('jquery', 'store'));
    } else {
        root.returnExports = factory(root.jQuery, root.store);
    }
}(this, function ($, storage) {
    var options     = {};
    var data        = {};
    var intercept   = false;
    var refreshing  = false;
    var buffer      = [];
    var currentRequests = [];

    var publicApi = {
        hasAccessToken: function() {
            return data.accessToken !== null;
        },
        logout: function() {
            privateApi.resetData();
            privateApi.updateStorage();
            privateApi.deactivateInterceptor();
            privateApi.removeAjaxHeader("Authorization");
            privateApi.fireEvent("logout");
        },
        login: function(accessToken) {
            this.setAccessToken(accessToken);

            privateApi.activateInterceptor();
            privateApi.fireEvent("login");
        },
        initialize: function(inputOptions) {
            privateApi.resetOptions();
            privateApi.setupInterceptor();

            $.extend(options, inputOptions);

            if (privateApi.hasStoredData()) {
                privateApi.getStoredData();

                if (this.hasAccessToken()) {
                    this.login(data.accessToken);
                }
            } else {
                privateApi.resetData();
                privateApi.updateStorage();
            }

            if (options.csrfToken !== null) {
                privateApi.setCsrfHeader();
            }
        },
        setAccessToken: function(accessToken) {
            data.accessToken = accessToken;

            privateApi.setAuthorizationHeader();
            privateApi.updateStorage();
        },
        setCsrfToken: function(csrfToken) {
            options.csrfToken = csrfToken;

            privateApi.setCsrfHeader();
        }
    };

    var privateApi = {
        activateInterceptor: function() {
            intercept = true;
        },
        addToBuffer: function(settings, deferred) {
            buffer.push({
                deferred: deferred,
                settings: settings
            });
        },
        clearBuffer: function() {
            buffer = [];
        },
        deactivateInterceptor: function() {
            intercept = false;
        },
        fireBuffer: function() {
            var self = this;
            var deferred;
            var promises = [];
            for(var i in buffer) {
                deferred = buffer[i].deferred;

                buffer[i].settings.refreshRetry = true;
                buffer[i].settings.headers["Authorization"] = $.ajaxSettings.headers["Authorization"];

                promises.push($.ajax(buffer[i].settings).then(deferred.resolve, deferred.reject));
            }

            self.clearBuffer();

            $.when.apply($, promises)
                .done(function() {
                    self.setRefreshingFlag(false);
                })
                .fail(function(){
                    self.setRefreshingFlag(false);
                    publicApi.logout();
                });
        },
        fireEvent: function(eventType) {
            if (this.hasEvent(eventType)) {
                return options.events[eventType]();
            }
        },
        getStoredData: function() {
            $.extend(data, storage.get("jquery.oauth"));
        },
        hasEvent: function(eventType) {
            return options.events[eventType] !== undefined && typeof options.events[eventType] === "function";
        },
        hasStoredData: function() {
            return storage.get("jquery.oauth") !== undefined;
        },
        isAjaxHeadersInitialized: function() {
            return $.ajaxSettings.headers !== undefined;
        },
        removeAjaxHeader: function(header) {
            if (!this.isAjaxHeadersInitialized()) {
                return true;
            }
            $.ajaxSettings.headers[header] = undefined;
        },
        removeAllAjaxHeaders: function() {
            this.removeAjaxHeader("Authorization");
            this.removeAjaxHeader("X-CSRF-Token");
        },
        resetData: function() {
            data = {
                accessToken: null
            };
        },
        resetOptions: function() {
            options = {
                bufferInterval: 25,
                bufferWaitLimit: 500,
                csrfToken: null,
                events: {}
            };

            this.removeAllAjaxHeaders();
        },
        setAjaxHeader: function(header, value) {
            if (!this.isAjaxHeadersInitialized()) {
                $.ajaxSettings.headers = {};
            }

            $.ajaxSettings.headers[header] = value;
        },
        setAuthorizationHeader: function() {
            this.setAjaxHeader("Authorization", "Bearer " + data.accessToken);
        },
        setCsrfHeader: function() {
            this.setAjaxHeader("X-CSRF-Token", options.csrfToken);
        },
        setRefreshingFlag: function(newFlag) {
            refreshing = newFlag;
        },
        setupInterceptor: function() {
            var self = this;

            // Credits to gnarf @ http://stackoverflow.com/a/12446363/602488
            $.ajaxPrefilter(function(options, originalOptions, jqxhr) {
                if (options.refreshRetry === true) {
                    return;
                }

                var deferred = $.Deferred();

                currentRequests.push(options.url);
                jqxhr.always(function(){
                    currentRequests.splice($.inArray(options.url, currentRequests), 1);
                });
                jqxhr.done(deferred.resolve);
                jqxhr.fail(function() {
                    var args = Array.prototype.slice.call(arguments);

                    if (intercept && jqxhr.status === 401 && self.hasEvent("tokenExpiration")) {
                        self.addToBuffer(options, deferred);

                        if (!refreshing) {
                            self.setRefreshingFlag(true);
                            self.fireEvent("tokenExpiration")
                                .success(function () {
                                    // Setup buffer interval that waits for all sent requests to return
                                    var waited   = 0;
                                    var interval = setInterval(function(){
                                        waited += options.bufferInterval;

                                        // All requests have returned 401 and have been buffered
                                        if (currentRequests.length === 0 || waited >= options.bufferWaitLimit) {
                                            clearInterval(interval);
                                            self.fireBuffer();
                                        }
                                    }, options.bufferInterval);
                                })
                                .fail(function () {
                                    publicApi.logout();
                                });
                        }
                    } else {
                        deferred.rejectWith(jqxhr, args);
                    }
                });

                return deferred.promise(jqxhr);
            });
        },
        updateStorage: function() {
            storage.set("jquery.oauth", data);
        }
    };

    return publicApi;
}));<|endoftext|>


<commit_before>import { suite as creation } from './micro/creation';
import { suite as reject} from './micro/reject';
import { suite as resolve } from './micro/resolve';
import { suite as resolvePromise } from './micro/resolve_promise';
import { suite as sequence } from './micro/sequence';
import { suite as all_number } from './micro/all/number';
import { suite as all_thenable } from './micro/all/thenable';
import { suite as all_object } from './micro/all/object';
import { suite as filter_true } from './micro/filter/true';
import { suite as filter_false } from './micro/filter/false';
import { suite as filter_promise_fn_true } from './micro/filter/promise_fn_true';
import { suite as thenning } from './micro/thenning';

// TODO: load all these dynamically, but cross platform
// TODO: 1 base test, that accepts N as a parameter, this should keep the duplicate tests, and maintence way down
var suites = [
  filter_promise_fn_true,
  filter_false,
  filter_true,
  all_number,
  all_thenable,
  all_object,
  creation,
  reject,
  resolve,
  resolvePromise,
  thenning,
  sequence
];

export default suites;
<commit_msg>re-order<commit_after>import { suite as creation } from './micro/creation';
import { suite as reject} from './micro/reject';
import { suite as resolve } from './micro/resolve';
import { suite as resolvePromise } from './micro/resolve_promise';
import { suite as sequence } from './micro/sequence';
import { suite as all_number } from './micro/all/number';
import { suite as all_thenable } from './micro/all/thenable';
import { suite as all_object } from './micro/all/object';
import { suite as filter_true } from './micro/filter/true';
import { suite as filter_false } from './micro/filter/false';
import { suite as filter_promise_fn_true } from './micro/filter/promise_fn_true';
import { suite as thenning } from './micro/thenning';

// TODO: load all these dynamically, but cross platform
// TODO: 1 base test, that accepts N as a parameter, this should keep the duplicate tests, and maintence way down
var suites = [
  filter_promise_fn_true,
  filter_false,
  filter_true,
  sequence,
  all_thenable,
  all_object,
  all_number,
  creation,
  reject,
  resolve,
  resolvePromise,
  thenning
];

export default suites;
<|endoftext|>


<commit_before>angular.module('orka.featurelist', [])

.directive('orkaFeatureList', ['$filter', '$timeout', 'MapService', 'LayersService', 'LayertreeService', function($filter, $timeout, MapService, LayersService, LayertreeService) {
    return {
        restrict: 'A',
        scope: {
            'featureLayerName': '@featureLayer',
            'markerLayerName': '@markerLayer'
        },
        transclude: true,
        templateUrl: 'orka/modules/featurelist/templates/featurelist.html',
        link: {
            pre: function(scope, element, attr) {
                scope.map = MapService.getMap();
                scope.featureLayer = LayersService.layersByProperty('layer', scope.featureLayerName)[0];
                scope.markerLayer = LayersService.layersByProperty('layer', scope.markerLayerName)[0];

                scope.typeMap = {};

                LayertreeService.poisLoaded.then(function(topics) {
                    angular.forEach(topics, function(topic) {
                        scope.typeMap[topic.name] = topic.title;
                        if(topic.groups !== undefined) {
                            angular.forEach(topic.groups, function(group) {
                                scope.typeMap[group.type] = group.title;
                            });
                        }
                    });
                });

                scope.toggleMarker = function(feature) {
                    if(scope.showFeatureContent) {
                        var geometry = feature.getGeometry().clone();
                        if(scope.markerFeature === undefined) {
                            scope.markerFeature = new ol.Feature();
                            scope.markerLayer.getSource().addFeatures([scope.markerFeature]);
                        }
                        scope.markerFeature.setGeometry(geometry);
                    }
                    scope.markerLayer.setVisible(scope.showFeatureContent);
                };

                scope.moveContentOutofOverflow = function() {
                    if(scope.showFeatureContent !== false) {
                        var id = 'feature_' + scope.showFeatureContent;
                        var featureElement = element.find('#' + id);
                        var featureListContainer = element.find('#orka-feature-list-container');

                        var elementBottom = featureElement.offset().top + featureElement.height();
                        var containerBottom = featureListContainer.offset().top + featureListContainer.height();

                        var delta = elementBottom - containerBottom;
                        if(delta > 0) {
                            var currentScrollTop = featureListContainer.scrollTop();
                            var scrollTo = currentScrollTop + delta;
                            featureListContainer.scrollTop(scrollTo);
                        }
                    }
                };

                scope.toggleFeatureContent = function(feature) {
                    scope.showFeatureContent = scope.showFeatureContent === feature.get('osm_id') ? false : feature.get('osm_id');
                    scope.toggleMarker(feature);
                    // timeout function is runing right after scope digest completet.
                    // before digest is not complete, browser has not updated html.
                    // so element is hidden although scope.showFeatureContent is true
                    $timeout(scope.moveContentOutofOverflow, 0, false);
                };
            },
            post: function(scope, element, attr) {
                var calculateExtent = function(map) {
                    return map.getView().calculateExtent(map.getSize());
                };
                var sortFeaturesByNumValue = function(feature) {
                    return feature.get('osm_id');
                };
                var featuresByExtent = function() {
                    var featureGroups = {};
                    if(scope.featureLayer.getVisible()) {
                        var _features = scope.featureLayer.getSource().getFeatures();
                        angular.forEach(_features, function(feature) {
                            if(ol.extent.intersects(scope.extent, feature.getGeometry().getExtent())) {
                                var featureType = feature.get('type');
                                if(featureGroups[featureType] === undefined) {
                                    featureGroups[featureType] = [];
                                }
                                featureGroups[featureType].push(feature);
                            }
                        });
                    }
                    angular.forEach(featureGroups, function(features) {
                        features = $filter('orderBy')(features, sortFeaturesByNumValue, false);
                    });

                    return featureGroups;
                };

                scope.map.on('moveend', function(evt) {
                    scope.$apply(function() {
                        scope.extent = calculateExtent(evt.target);
                    });
                });

                scope.featureLayer.getSource().on('change', function() {
                    var features = featuresByExtent();
                    scope.$applyAsync(function() {
                        scope.featureGroups = features;
                    });
                });

                scope.$watch('extent', function(newVal, oldVal) {
                    scope.featureGroups = featuresByExtent();
                });

                scope.extent = calculateExtent(scope.map);
            }
        },
        controller: function($scope, $element, $attrs) {
            this.scrollTo = function(feature) {
                $scope.$apply(function() {
                    $scope.showGroup = feature.get('type');
                    $scope.showFeatureContent = feature.get('osm_id');
                });
                $scope.toggleMarker();
                var id = 'feature_' + feature.get('osm_id');
                var featureElement = $element.find('#' + id);
                var featureListContainer = $element.find('#orka-feature-list-container');

                var currentScrollTop = featureListContainer.scrollTop();
                var containerTop = featureListContainer.offset().top;
                var elementTop = featureElement.offset().top;
                var scrollTo = (elementTop + currentScrollTop) - containerTop;

                featureListContainer.scrollTop(scrollTo);
            };
        }
    };
}]);
<commit_msg>Keep marker and select featurelist entry visible as long as feature is present<commit_after>angular.module('orka.featurelist', [])

.directive('orkaFeatureList', ['$filter', '$timeout', 'MapService', 'LayersService', 'LayertreeService', function($filter, $timeout, MapService, LayersService, LayertreeService) {
    return {
        restrict: 'A',
        scope: {
            'featureLayerName': '@featureLayer',
            'markerLayerName': '@markerLayer'
        },
        transclude: true,
        templateUrl: 'orka/modules/featurelist/templates/featurelist.html',
        link: {
            pre: function(scope, element, attr) {
                scope.map = MapService.getMap();
                scope.featureLayer = LayersService.layersByProperty('layer', scope.featureLayerName)[0];
                scope.markerLayer = LayersService.layersByProperty('layer', scope.markerLayerName)[0];

                scope.typeMap = {};

                LayertreeService.poisLoaded.then(function(topics) {
                    angular.forEach(topics, function(topic) {
                        scope.typeMap[topic.name] = topic.title;
                        if(topic.groups !== undefined) {
                            angular.forEach(topic.groups, function(group) {
                                scope.typeMap[group.type] = group.title;
                            });
                        }
                    });
                });

                scope.toggleMarker = function(feature) {
                    if(scope.showFeatureContent !== false && feature !== undefined) {
                        var geometry = feature.getGeometry().clone();
                        if(scope.markerFeature === undefined) {
                            scope.markerFeature = new ol.Feature();
                            scope.markerLayer.getSource().addFeatures([scope.markerFeature]);
                        }
                        scope.markerFeature.setGeometry(geometry);
                    }
                    scope.markerLayer.setVisible(scope.showFeatureContent !== false);
                };

                scope.moveContentOutofOverflow = function() {
                    if(scope.showFeatureContent !== false) {
                        var id = 'feature_' + scope.showFeatureContent;
                        var featureElement = element.find('#' + id);
                        var featureListContainer = element.find('#orka-feature-list-container');

                        var elementBottom = featureElement.offset().top + featureElement.height();
                        var containerBottom = featureListContainer.offset().top + featureListContainer.height();

                        var delta = elementBottom - containerBottom;
                        if(delta > 0) {
                            var currentScrollTop = featureListContainer.scrollTop();
                            var scrollTo = currentScrollTop + delta;
                            featureListContainer.scrollTop(scrollTo);
                        }
                    }
                };

                scope.toggleFeatureContent = function(feature) {
                    scope.showFeatureContent = scope.showFeatureContent === feature.get('osm_id') ? false : feature.get('osm_id');
                    scope.toggleMarker(feature);
                    // timeout function is runing right after scope digest completet.
                    // before digest is not complete, browser has not updated html.
                    // so element is hidden although scope.showFeatureContent is true
                    $timeout(scope.moveContentOutofOverflow, 0, false);
                };
            },
            post: function(scope, element, attr) {
                var calculateExtent = function(map) {
                    return map.getView().calculateExtent(map.getSize());
                };
                var sortFeaturesByNumValue = function(feature) {
                    return feature.get('osm_id');
                };
                var featuresByExtent = function() {
                    var featureGroups = {};
                    var selectedFeatureRemoved = scope.showFeatureContent !== false;
                    if(scope.featureLayer.getVisible()) {
                        var _features = scope.featureLayer.getSource().getFeatures();
                        angular.forEach(_features, function(feature) {
                            if(ol.extent.intersects(scope.extent, feature.getGeometry().getExtent())) {
                                var featureType = feature.get('type');
                                if(selectedFeatureRemoved === true) {
                                    selectedFeatureRemoved = scope.showFeatureContent === feature.get('osm_id') ? false : true;
                                }
                                if(featureGroups[featureType] === undefined) {
                                    featureGroups[featureType] = [];
                                }
                                featureGroups[featureType].push(feature);
                            }
                        });
                    }
                    angular.forEach(featureGroups, function(features) {
                        features = $filter('orderBy')(features, sortFeaturesByNumValue, false);
                    });
                    if(selectedFeatureRemoved) {
                        scope.showFeatureContent = false;
                        scope.toggleMarker();
                    }

                    return featureGroups;
                };

                scope.map.on('moveend', function(evt) {
                    scope.$apply(function() {
                        scope.extent = calculateExtent(evt.target);
                    });
                });

                scope.featureLayer.getSource().on('anolSourceUpdated', function() {
                    var features = featuresByExtent();
                    scope.$applyAsync(function() {
                        scope.featureGroups = features;
                        if(scope.showFeatureContent !== false) {
                            $timeout(scope.moveContentOutofOverflow, 0, false);
                        }
                    });
                });

                scope.$watch('extent', function(newVal, oldVal) {
                    scope.featureGroups = featuresByExtent();
                });

                scope.extent = calculateExtent(scope.map);
            }
        },
        controller: function($scope, $element, $attrs) {
            this.scrollTo = function(feature) {
                $scope.$apply(function() {
                    $scope.showGroup = feature.get('type');
                    $scope.showFeatureContent = feature.get('osm_id');
                });
                $scope.toggleMarker();
                var id = 'feature_' + feature.get('osm_id');
                var featureElement = $element.find('#' + id);
                var featureListContainer = $element.find('#orka-feature-list-container');

                var currentScrollTop = featureListContainer.scrollTop();
                var containerTop = featureListContainer.offset().top;
                var elementTop = featureElement.offset().top;
                var scrollTo = (elementTop + currentScrollTop) - containerTop;

                featureListContainer.scrollTop(scrollTo);
            };
        }
    };
}]);
<|endoftext|>


<commit_before>'use strict';
/* global EVENTS, $*/
var TICKS = 0;

var team = {
    resources: {Alice: 10, Barry: 7, Chris: 12, Dan: 9, Englebert:9},
    story_points: 0,
    morale: 100,

    addResourcePoints: function() {
        this.story_points += Object.keys(this.resources).length;
    },

    updateVals: function(item) {
        if (item.morale !== undefined) {
            var val = randomNoise(item.morale, 10);
            console.log('morale: ' + val);
            this.morale += val;
        }
        if (item.story_points !== undefined) {
            var val = randomNoise(item.story_points, 6);
            console.log('story points: ' + val);
            this.story_points += val;
        }
        if (item.resources !== undefined) {
            if (item.resources > 0) {
                // chose a silly name
                var name = random(['Phil Pack', 'Jason Test', 'Shak.', 'Zool']);
                this.resources[name] = randomNoise(10, 4);
                return 'Please welcome ' + name + ' to the team!';
            } else if (item.resources < 0) {
                var keys = Object.keys(this.resources);
                var dead_employee = keys[Math.floor(keys.length * Math.random())];
                delete this.resources[dead_employee];
                return 'Farewell, ' + dead_employee + ', we hardly knew ye.';
            } // else i probably fucked up and wrote resources : 0 oh well
        }
    },

    isACompleteAndAbjectFailure: function() {
        return Object.keys(this.resources).length === 0 || this.morale <= 0 || this.story_points <= -50;
    },

    IsAGroupOfShiningGoldenGods: function() {
        return this.story_points >= 100;
    }
};

var randomNoise = function(val, max_deviance) {
    return val + (
        (Math.random() * max_deviance * 2 - max_deviance) +
        (Math.random() * max_deviance * 2 - max_deviance) +
        (Math.random() * max_deviance * 2 - max_deviance)
        ) / 3;
};

var random = function(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
};

var teamStatus = function() {
    $('#morale').text(Math.floor(team.morale));
    $('#story_points').text(Math.floor(team.story_points));
    $('#resources').empty();
    for (var name in team.resources) {
        $('#resources').append($('<li>').text(name));
    }
};

var tick = function() {
    if (team.IsAGroupOfShiningGoldenGods()){
        return success();
    }
    if (team.isACompleteAndAbjectFailure() || TICKS > 20){
        return fail();
    }
    TICKS++;
    if (TICKS > 0) {
        $('#title').hide();
    }
    // disable the next sprint button
    //$('#tick').attr("disabled", true);
    $('#controls').hide();

    var wild_encounter = random(EVENTS);
    $('#event_name').text(wild_encounter.title);
    $('#description').text(wild_encounter.description);
    var music_src = "sound/title.mp3";
    if (wild_encounter.music) {
        music_src = "sound/" + wild_encounter.music;
        if ($('#music source').attr("src") !== music_src) {
            $('#music source').attr("src", music_src);
            $('#music').trigger('pause');
            $('#music').trigger('load');
            $('#music').trigger('play');
        }
    }
    var weather_descs = ['working','wheezing', 'working','broken']
    $('#weather_status').html(weather_descs[Math.floor(Math.random() * (weather_descs.length - 1))]);

    var story_points = Math.floor(team.story_points);
    var velocity_desc = '';
    if (story_points >= 10) {
        velocity_desc = 'bonuses++';
    }
    else if (story_points >= 5) {
        velocity_desc = 'industry leading';
    }
    else if (story_points >= 0) {
        velocity_desc = 'average';
    }
    else if (story_points >= -5) {
        velocity_desc = 'industry standard';
    }
    else if (story_points >= -10) {
        velocity_desc = 'sub-par';
    }
    else if (story_points >= -15) {
        velocity_desc = 'AWOL';
    }
    else {
        velocity_desc = 'unknown';
    }
    $('#velocity_status').html(velocity_desc);

    var morale = Math.floor(team.morale);
    var morale_desc = '';
    if (morale >= 115) {
        morale_desc = 'out of this <s>world</s> office';
    } else if (morale >= 110) {
        morale_desc = 'bouyant';
    } else if(morale >= 105) {
        morale_desc = 'above par';
    } else if (morale >= 100) {
        morale_desc = 'average';
    } else if (morale >= -5) {
        morale_desc = 'industry standard';
    } else if(morale >= -10) {
        morale_desc = 'sub-par';
    } else if(morale >= -15) {
        morale_desc = 'AWOL';
    } else {
        morale_desc = 'unknown';
    }
    $('#morale_status').html(morale_desc);

    var resource_level = Object.keys(team.resources).length;
    if (resource_level == 4 && Math.random() > 0.7) {
        $('#resource_status').html('4 DAYS TO USE BY DATE');
    } else {
        $('#resource_status').html(resource_level);
    }

    $('#team_status').show();
    $('#team').hide();
    wild_encounter.options.forEach(function(option) {
        $('#choices').append(
            $('<li>').text(option.text).click(function(){
                var txt = team.updateVals(option);
                team.addResourcePoints();
                teamStatus();
                clean_up_dom();
                if (txt) {
                    $("#description").text(txt);
                }
            })
        );
    });
};

var clean_up_dom = function() {
    // $('#tick').removeAttr('disabled');
    $('#controls').show();
    $('#title').empty();

    // the event bits:
    $('#event_name').empty();
    $('#description').empty();
    $('#choices').empty();

    $('#team_status').hide();
    $('#team').show();
};

var fail = function() {
    clean_up_dom();
    $('#title').text('GAME OVER').show();
    $('#controls').hide();
    $('#music source').attr("src", 'sound/sad.mp3');
    $('#music').trigger('pause');
    $('#music').trigger('load');
    $('#music').trigger('play');
    var txt = 'You lasted ' + TICKS + ' sprints, but had to throw in the towel. Out of money, out of time, ' +
        'and out of resources, the project is doomed to failure. Maybe you should change career and become a pioneer in ' +
        'northwest America.';
    $('#description').text(txt);
};

var success = function() {
    clean_up_dom();
    $('#title').text('YOUR WINNER!').show();
    $('#controls').hide();
    $('#music source').attr("src", 'sound/yay.mp3');
    $('#music').trigger('pause');
    $('#music').trigger('load');
    $('#music').trigger('play');
    var txt = 'Your project succeeded in only ' + TICKS + ' sprints! You have entered the pantheon of the greats, ' +
        'ready to go down in history as the greatest scrum team the world has ever known. Congratulations!';
    $('#description').text(txt);
};

window.addEventListener("keypress", checkKeys, false);

function checkKeys(e) {
    if (e.charCode === 32 || e.charCode === 13) {
        if ($('#controls').is(':visible')) {
            tick();
        }
    }
}

// This is to fix a wierd bug in firefox whereby refreshing the page does not reset the button state
window.onload = function() {
    if (TICKS === 0) {
        $('#tick').attr("disabled", false);
    }
};
<commit_msg>Fix a logic bug<commit_after>'use strict';
/* global EVENTS, $*/
var TICKS = 0;

var team = {
    resources: {Alice: 10, Barry: 7, Chris: 12, Dan: 9, Englebert:9},
    story_points: 0,
    morale: 100,

    addResourcePoints: function() {
        this.story_points += Object.keys(this.resources).length;
    },

    updateVals: function(item) {
        if (item.morale !== undefined) {
            var val = randomNoise(item.morale, 10);
            console.log('morale: ' + val);
            this.morale += val;
        }
        if (item.story_points !== undefined) {
            var val = randomNoise(item.story_points, 6);
            console.log('story points: ' + val);
            this.story_points += val;
        }
        if (item.resources !== undefined) {
            if (item.resources > 0) {
                // chose a silly name
                var name = random(['Phil Pack', 'Jason Test', 'Shak.', 'Zool']);
                this.resources[name] = randomNoise(10, 4);
                return 'Please welcome ' + name + ' to the team!';
            } else if (item.resources < 0) {
                var keys = Object.keys(this.resources);
                var dead_employee = keys[Math.floor(keys.length * Math.random())];
                delete this.resources[dead_employee];
                return 'Farewell, ' + dead_employee + ', we hardly knew ye.';
            } // else i probably fucked up and wrote resources : 0 oh well
        }
    },

    isACompleteAndAbjectFailure: function() {
        return Object.keys(this.resources).length === 0 || this.morale <= 0 || this.story_points <= -50;
    },

    IsAGroupOfShiningGoldenGods: function() {
        return this.story_points >= 100;
    }
};

var randomNoise = function(val, max_deviance) {
    return val + (
        (Math.random() * max_deviance * 2 - max_deviance) +
        (Math.random() * max_deviance * 2 - max_deviance) +
        (Math.random() * max_deviance * 2 - max_deviance)
        ) / 3;
};

var random = function(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
};

var teamStatus = function() {
    $('#morale').text(Math.floor(team.morale));
    $('#story_points').text(Math.floor(team.story_points));
    $('#resources').empty();
    for (var name in team.resources) {
        $('#resources').append($('<li>').text(name));
    }
};

var tick = function() {
    if (team.IsAGroupOfShiningGoldenGods()){
        return success();
    }
    if (team.isACompleteAndAbjectFailure() || TICKS > 20){
        return fail();
    }
    TICKS++;
    if (TICKS > 0) {
        $('#title').hide();
    }
    // disable the next sprint button
    //$('#tick').attr("disabled", true);
    $('#controls').hide();

    var wild_encounter = random(EVENTS);
    $('#event_name').text(wild_encounter.title);
    $('#description').text(wild_encounter.description);
    var music_src = "sound/title.mp3";
    if (wild_encounter.music) {
        music_src = "sound/" + wild_encounter.music;
        if ($('#music source').attr("src") !== music_src) {
            $('#music source').attr("src", music_src);
            $('#music').trigger('pause');
            $('#music').trigger('load');
            $('#music').trigger('play');
        }
    }
    var weather_descs = ['working','wheezing', 'working','broken']
    $('#weather_status').html(weather_descs[Math.round(Math.random() * (weather_descs.length))]);

    var story_points = Math.floor(team.story_points);
    var velocity_desc = '';
    if (story_points >= 10) {
        velocity_desc = 'bonuses++';
    }
    else if (story_points >= 5) {
        velocity_desc = 'industry leading';
    }
    else if (story_points >= 0) {
        velocity_desc = 'average';
    }
    else if (story_points >= -5) {
        velocity_desc = 'industry standard';
    }
    else if (story_points >= -10) {
        velocity_desc = 'sub-par';
    }
    else if (story_points >= -15) {
        velocity_desc = 'AWOL';
    }
    else {
        velocity_desc = 'unknown';
    }
    $('#velocity_status').html(velocity_desc);

    var morale = Math.floor(team.morale);
    var morale_desc = '';
    if (morale >= 115) {
        morale_desc = 'out of this <s>world</s> office';
    } else if (morale >= 110) {
        morale_desc = 'bouyant';
    } else if(morale >= 105) {
        morale_desc = 'above par';
    } else if (morale >= 100) {
        morale_desc = 'average';
    } else if (morale >= -5) {
        morale_desc = 'industry standard';
    } else if(morale >= -10) {
        morale_desc = 'sub-par';
    } else if(morale >= -15) {
        morale_desc = 'AWOL';
    } else {
        morale_desc = 'unknown';
    }
    $('#morale_status').html(morale_desc);

    var resource_level = Object.keys(team.resources).length;
    if (resource_level == 4 && Math.random() > 0.7) {
        $('#resource_status').html('4 DAYS TO USE BY DATE');
    } else {
        $('#resource_status').html(resource_level);
    }

    $('#team_status').show();
    $('#team').hide();
    wild_encounter.options.forEach(function(option) {
        $('#choices').append(
            $('<li>').text(option.text).click(function(){
                var txt = team.updateVals(option);
                team.addResourcePoints();
                teamStatus();
                clean_up_dom();
                if (txt) {
                    $("#description").text(txt);
                }
            })
        );
    });
};

var clean_up_dom = function() {
    // $('#tick').removeAttr('disabled');
    $('#controls').show();
    $('#title').empty();

    // the event bits:
    $('#event_name').empty();
    $('#description').empty();
    $('#choices').empty();

    $('#team_status').hide();
    $('#team').show();
};

var fail = function() {
    clean_up_dom();
    $('#title').text('GAME OVER').show();
    $('#controls').hide();
    $('#music source').attr("src", 'sound/sad.mp3');
    $('#music').trigger('pause');
    $('#music').trigger('load');
    $('#music').trigger('play');
    var txt = 'You lasted ' + TICKS + ' sprints, but had to throw in the towel. Out of money, out of time, ' +
        'and out of resources, the project is doomed to failure. Maybe you should change career and become a pioneer in ' +
        'northwest America.';
    $('#description').text(txt);
};

var success = function() {
    clean_up_dom();
    $('#title').text('YOUR WINNER!').show();
    $('#controls').hide();
    $('#music source').attr("src", 'sound/yay.mp3');
    $('#music').trigger('pause');
    $('#music').trigger('load');
    $('#music').trigger('play');
    var txt = 'Your project succeeded in only ' + TICKS + ' sprints! You have entered the pantheon of the greats, ' +
        'ready to go down in history as the greatest scrum team the world has ever known. Congratulations!';
    $('#description').text(txt);
};

window.addEventListener("keypress", checkKeys, false);

function checkKeys(e) {
    if (e.charCode === 32 || e.charCode === 13) {
        if ($('#controls').is(':visible')) {
            tick();
        }
    }
}

// This is to fix a wierd bug in firefox whereby refreshing the page does not reset the button state
window.onload = function() {
    if (TICKS === 0) {
        $('#tick').attr("disabled", false);
    }
};
<|endoftext|>


<commit_before>var React = require('react-native');

var {
View,
Text,
Component,
AsyncStorage,
StyleSheet,
Image,
PanResponder,
Animated,
MapView,
TouchableOpacity,
Linking
} = React;

const DELTA = 0.003021;

class RestaurantInfo extends Component {

  renderBackButton() {
    return (
      <TouchableOpacity
        onPress={this.goBack.bind(this)}
      >
        <Text style={styles.backButton}> {'< Back'} </Text>
      </TouchableOpacity>)
  }

  goBack() {
    this.props.navigator.pop();
  }

  render() {
    var restaurant = this.props.restaurant;
    console.log(restaurant)
    if(restaurant) {
      if(restaurant.website){
        var website = <TouchableOpacity onPress={ () => { Linking.openURL(restaurant.website)}}><Text style={styles.websiteButton}>Go To Webpage</Text></TouchableOpacity>;
      }
      var splitAddress=restaurant.address.split(", ");
      var streetAddress = splitAddress[0];
      var city = splitAddress[1];
      var stateAndZip = splitAddress[2];
      var content = (
        <View style={styles.container}>
           <Image
            style={styles.logo}
            source={require('../thumbnails/logohighreswhite_720.png')}
          />
          <Text style={styles.title}>{restaurant.name}</Text>
          <MapView
            style={styles.map}
            showUserLocation={true}
            region={{
              latitude: Number(restaurant.lat),
              longitude: Number(restaurant.lng),
              latitudeDelta: DELTA,
              longitudeDelta: DELTA,
            }}
            onPress={ () => { Linking.openURL("http://maps.apple.com/?daddr=" + restaurant.lat + "," + restaurant.lng)}}
            annotations={[{
              animateDrop: true,
              latitude: Number(restaurant.lat),
              longitude: Number(restaurant.lng),
              title: "Go now!",
              detailCalloutView: <View><Text style={styles.directions} onPress={()=>{Linking.openURL("http://maps.apple.com/?daddr=" + restaurant.lat + "," + restaurant.lng)}}>Directions</Text></View>,
            }]}
          />
          {website}
          {<TouchableOpacity onPress={()=>{Linking.openURL("tel:" + restaurant.phone)}}>
            <Text style={styles.phoneNumber}>{restaurant.phone}</Text>
          </TouchableOpacity>}
          <Text style={styles.content}>{streetAddress}</Text>
          <Text style={styles.content}>{city}, {stateAndZip}</Text>
          {this.renderBackButton()}
        </View>);
    } else {
      var content = 'NOTHING';
    }

    return (<View style={styles.container}>
          {content}
        </View>)
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#300030',
  },
  title: {
    color: 'white',
    fontFamily: 'Hiragino Kaku Gothic ProN',
    marginBottom: 10,
    fontWeight: 'bold',
    fontSize: 18,
    marginTop: 10
  },
  content: {
    color: 'white',
    fontFamily: 'Hiragino Kaku Gothic ProN',
  },
  map: {
    width: 350,
    height: 310,
    marginBottom: 5,
  },
  logo: {
    // marginTop: 10,
    marginBottom: 10,
    height: 100,
    width: 150
  },
  backButton: {
    color: 'white',
    marginRight: 310,
    fontWeight: 'bold',
  },
  websiteButton: {
    textAlign: 'center',
    color: 'white',
    marginBottom: 7,
    marginTop: 7,
    borderWidth: 1,
    borderColor: 'white',
    backgroundColor: '#300030',
    padding: 7,
    borderRadius: 5,
  },
  directions: {
    textDecorationLine: 'underline',
    height: 20,
    width: 100,
  },
  phoneNumber: {
    textDecorationLine: 'underline',
    color: 'white',
    paddingBottom: 4
  }
})

module.exports = RestaurantInfo;
<commit_msg>Add directions button, added address to pin bubble, and fixed margins.<commit_after>var React = require('react-native');

var {
View,
Text,
Component,
AsyncStorage,
StyleSheet,
Image,
PanResponder,
Animated,
MapView,
TouchableOpacity,
Linking
} = React;

const DELTA = 0.003021;

class RestaurantInfo extends Component {

  renderBackButton() {
    return (
      <TouchableOpacity
        onPress={this.goBack.bind(this)}
      >
        <Text style={styles.backButton}> {'< Back'} </Text>
      </TouchableOpacity>)
  }

  goBack() {
    this.props.navigator.pop();
  }

  render() {
    var restaurant = this.props.restaurant;
    console.log(restaurant)
    if(restaurant) {
      if(restaurant.website){
        var website = <TouchableOpacity onPress={ () => { Linking.openURL(restaurant.website)}}><Text style={styles.websiteButton}>Go To Webpage</Text></TouchableOpacity>;
      }
      var splitAddress=restaurant.address.split(", ");
      var streetAddress = splitAddress[0];
      var city = splitAddress[1];
      var stateAndZip = splitAddress[2];
      var content = (
        <View style={styles.container}>
           <Image
            style={styles.logo}
            source={require('../thumbnails/logohighreswhite_720.png')}
          />
          <Text style={styles.title}>{restaurant.name}</Text>
          <MapView
            style={styles.map}
            showUserLocation={true}
            region={{
              latitude: Number(restaurant.lat),
              longitude: Number(restaurant.lng),
              latitudeDelta: DELTA,
              longitudeDelta: DELTA,
            }}
            onPress={ () => { Linking.openURL("http://maps.apple.com/?daddr=" + restaurant.lat + "," + restaurant.lng)}}
            annotations={[{
              animateDrop: true,
              latitude: Number(restaurant.lat),
              longitude: Number(restaurant.lng),
              title: restaurant.address,
            }]}
          />
          {website}
          <Text style={styles.directions} onPress={()=>{Linking.openURL("http://maps.apple.com/?daddr=" + restaurant.lat + "," + restaurant.lng)}}>Directions</Text>
          {<TouchableOpacity onPress={()=>{Linking.openURL("tel:" + restaurant.phone)}}>
            <Text style={styles.phoneNumber}>{restaurant.phone}</Text>
          </TouchableOpacity>}
          <Text style={styles.content}>{city}, {stateAndZip}</Text>
          {this.renderBackButton()}
        </View>);
    } else {
      var content = 'NOTHING';
    }

    return (<View style={styles.container}>
          {content}
        </View>)
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#300030',
  },
  title: {
    color: 'white',
    fontFamily: 'Hiragino Kaku Gothic ProN',
    marginBottom: 10,
    fontWeight: 'bold',
    fontSize: 18,
    marginTop: 10
  },
  content: {
    color: 'white',
    fontFamily: 'Hiragino Kaku Gothic ProN',
  },
  map: {
    width: 350,
    height: 310,
    marginBottom: 5,
  },
  logo: {
    // marginTop: 10,
    marginBottom: 10,
    height: 100,
    width: 150
  },
  backButton: {
    color: 'white',
    marginRight: 310,
    fontWeight: 'bold',
  },
  websiteButton: {
    textAlign: 'center',
    color: 'white',
    marginBottom: 2,
    marginTop: 7,
    borderWidth: 1,
    borderColor: 'white',
    backgroundColor: '#300030',
    padding: 7,
    borderRadius: 5,
  },
  directions: {
    textAlign: 'center',
    color: 'white',
    marginBottom: 2,
    marginTop: 2,
    borderWidth: 1,
    borderColor: 'white',
    backgroundColor: '#300030',
    padding: 7,
    borderRadius: 5,
  },
  phoneNumber: {
    textDecorationLine: 'underline',
    color: 'white',
    paddingBottom: 4,
    marginTop: 4
  }
})

module.exports = RestaurantInfo;
<|endoftext|>


<commit_before>/**
 * `core/modules` data store settings
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://www.apache.org/licenses/LICENSE2.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.
 */

/**
 * External dependencies
 */
import invariant from 'invariant';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
// import { dispatch } from '@wordpress/data';
const { createRegistrySelector, createRegistryControl } = Data;
// import { STORE_NAME } from './constants';
import { STORE_NAME as CORE_MODULES } from './constants';

const SETTINGS_SUBMIT_CHANGES = 'SETTINGS_SUBMIT_CHANGES';

export const actions = {
	/**
	 * Submits all changes for a module.
	 *
	 * @since 1.20.0
	 *
	 * @param {string} slug Slug for module store.
	 * @return {Object} Module's submitChanges response object if it exists, otherwise object with `error` property if it doesn't.
	 */
	submitChanges( slug ) {
		invariant( slug, 'slug is required.' );

		return ( function* () {
			return yield {
				payload: { slug },
				type: SETTINGS_SUBMIT_CHANGES,
			};
		}() );
	},
};

export const controls = {
	[ SETTINGS_SUBMIT_CHANGES ]: createRegistryControl( ( registry ) => async ( { payload } ) => {
		const { slug } = payload;
		const storeName = registry.select( CORE_MODULES )?.getModuleStoreName( slug );

		if ( ! storeName ) {
			return { error: `The module '${ slug }' does not have a store.` };
		}

		const { submitChanges } = await registry.dispatch( storeName );
		if ( ! submitChanges ) {
			return { error: `The module ${ slug } does not have a submitChanges() action.` };
		}

		return submitChanges( slug );
	} ),
};

export const selectors = {
	/**
	 * Checks whether changes are currently being submitted for a module.
	 *
	 * @since 1.20.0
	 *
	 * @param {string} slug Slug for module store.
	 * @return {Object} Module's submitChanges response object if it exists, otherwise object with `error` property if it doesn't.
	 */
	isDoingSubmitChanges: createRegistrySelector( ( select ) => ( state, slug ) => {
		invariant( slug, 'slug is required.' );
		const storeName = select( CORE_MODULES )?.getModuleStoreName( slug );
		return !! select( storeName )?.isDoingSubmitChanges?.();
	} ),

	/**
	 * Checks whether we can submit changes for a module.
	 *
	 * @since 1.20.0
	 *
	 * @param {string} slug Slug for module store.
	 * @return {boolean} Whether the module supports submitting changes.
	 */
	canSubmitChanges: createRegistrySelector( ( select ) => ( state, slug ) => {
		invariant( slug, 'slug is required.' );
		const storeName = select( CORE_MODULES ).getModuleStoreName( slug );
		return !! select( storeName )?.canSubmitChanges?.();
	} ),
};

export default {
	actions,
	controls,
	selectors,
};
<commit_msg>Update assets/js/googlesitekit/modules/datastore/settings.js<commit_after>/**
 * `core/modules` data store settings
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://www.apache.org/licenses/LICENSE2.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.
 */

/**
 * External dependencies
 */
import invariant from 'invariant';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
// import { dispatch } from '@wordpress/data';
const { createRegistrySelector, createRegistryControl } = Data;
// import { STORE_NAME } from './constants';
import { STORE_NAME as CORE_MODULES } from './constants';

const SETTINGS_SUBMIT_CHANGES = 'SETTINGS_SUBMIT_CHANGES';

export const actions = {
	/**
	 * Submits all changes for a module.
	 *
	 * @since 1.20.0
	 *
	 * @param {string} slug Slug for module store.
	 * @return {Object} Module's submitChanges response object if it exists, otherwise object with `error` property if it doesn't.
	 */
	submitChanges( slug ) {
		invariant( slug, 'slug is required.' );

		return ( function* () {
			return yield {
				payload: { slug },
				type: SETTINGS_SUBMIT_CHANGES,
			};
		}() );
	},
};

export const controls = {
	[ SETTINGS_SUBMIT_CHANGES ]: createRegistryControl( ( registry ) => async ( { payload } ) => {
		const { slug } = payload;
		const storeName = registry.select( CORE_MODULES )?.getModuleStoreName( slug );

		if ( ! storeName ) {
			return { error: `The module '${ slug }' does not have a store.` };
		}

		const { submitChanges } = await registry.dispatch( storeName );
		if ( ! submitChanges ) {
			return { error: `The module '${ slug }' does not have a submitChanges() action.` };
		}

		return submitChanges( slug );
	} ),
};

export const selectors = {
	/**
	 * Checks whether changes are currently being submitted for a module.
	 *
	 * @since 1.20.0
	 *
	 * @param {string} slug Slug for module store.
	 * @return {Object} Module's submitChanges response object if it exists, otherwise object with `error` property if it doesn't.
	 */
	isDoingSubmitChanges: createRegistrySelector( ( select ) => ( state, slug ) => {
		invariant( slug, 'slug is required.' );
		const storeName = select( CORE_MODULES )?.getModuleStoreName( slug );
		return !! select( storeName )?.isDoingSubmitChanges?.();
	} ),

	/**
	 * Checks whether we can submit changes for a module.
	 *
	 * @since 1.20.0
	 *
	 * @param {string} slug Slug for module store.
	 * @return {boolean} Whether the module supports submitting changes.
	 */
	canSubmitChanges: createRegistrySelector( ( select ) => ( state, slug ) => {
		invariant( slug, 'slug is required.' );
		const storeName = select( CORE_MODULES ).getModuleStoreName( slug );
		return !! select( storeName )?.canSubmitChanges?.();
	} ),
};

export default {
	actions,
	controls,
	selectors,
};
<|endoftext|>