<commit_before>/*
    Angular State Handler
    2015-10-12
    Public Domain.
    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

! function(window, angular, undefined) {
  "use strict";
  var app = angular.module("stateHandler", ["ngRoute"]),
    randomTemplateUrl = "###" + (Math.random() * 10 / 10) + "###",
    routeHash = {},
    routeTemplateUrlCollection = [],
    dummyElem = document.createElement("a");

  function getRelativePath(url) {
    dummyElem.href = url;
    return {
      path: dummyElem.pathname,
      fullPath: dummyElem.pathname + dummyElem.search
    };
  }

  // function generateSearchStringFromObject(obj) {
  //   var str = undefined;
  //   for (var a in obj) {
  //     if (str === undefined) {
  //       str = "?";
  //     } else {
  //       str += "&";
  //     }
  //     str += a + "=" + obj[a];
  //   }

  //   return str || "";
  // }

  // Factories required to configure this module
  app.provider('$factoriesForStateHandle', ["$provide",
    function($provide) {
      var obj = {
        $get: function() {}
      };

      getFactoryReferenceFn("$route");
      getFactoryReferenceFn("$timeout");
      getFactoryReferenceFn("$location");

      function getFactoryReferenceFn(factoryName) {
        $provide.decorator(factoryName, ['$delegate', factoryDecoratorFn]);

        function factoryDecoratorFn($delegate) {
          return obj[factoryName] = $delegate;
        };
      }

      return obj;
    }
  ]);

  // Provider to handle view and path state based on routing
  app.provider('$stateHandle', ["$provide", "$factoriesForStateHandleProvider",
    function($provide, $factoriesForStateHandleProvider) {
      var $browser = undefined,
        identityHash = {},
        authParams = {
          path: undefined,
          route: null
        },
        _constructor = function(subscriber, pathExpr) {
          this.subscriber = subscriber;
          this.pathExpr = pathExpr;
          this.callBacks = [];
        },
        obj = {
          subscribe: subscribeFn,
          getSubscribers: getSubscribersFn,
          setAuthParams: setAuthParamsFn,
          getAuthParams: getAuthParamsFn
        };

      function subscribeFn(subscriber, pathExpr) {
        if (!(pathExpr in identityHash)) {
          identityHash[pathExpr] = {};
        } else if (subscriber in identityHash[pathExpr]) {
          identityHash[pathExpr][subscriber].callBacks.length = 0;
        }

        return identityHash[pathExpr][subscriber] || (identityHash[pathExpr][subscriber] = new _constructor(subscriber, pathExpr));
      }

      function getSubscribersFn(pathExpr) {
        return identityHash[pathExpr];
      }

      function setAuthParamsFn(path, route) {
        authParams.path = path;
        authParams.route = route;
        return this;
      }

      function getAuthParamsFn() {
        return authParams;
      }

      function subscriberResponseFn(callback) {
        var that = this;
        that.callBacks.push(callback);
        if (that.pathExpr == $factoriesForStateHandleProvider.$route.current.originalPath) {
          callback($factoriesForStateHandleProvider.$route.current.params);
        }
      };

      _constructor.prototype = {
        response: subscriberResponseFn
      }

      return {
        $get: function() {
          return obj;
        }
      };
    }
  ]);

  app.run(['$route', '$location', '$rootScope', '$timeout', '$stateHandle', '$window', '$q', function($route, $location, $rootScope, $timeout, $stateHandle, $window, $q) {
    var previousUrl = undefined,
      searchUrl = undefined,
      callbackTimeoutId = null,
      isNewLoaded = true,
      userAuthenticated = undefined,
      deferred = $q.defer();

    $stateHandle.route = {};

    // function getPropertyValueFromHistoryStateFn(prop) {
    //   var historyState = $location.$$state;
    //   if (historyState && ('path' in historyState)) {
    //     if (routeHash[historyState.path] && (prop in routeHash[historyState.path])) {
    //       return routeHash[historyState.path][prop];
    //     }
    //   }
    //   var fallBackValue = undefined;
    //   for (var _a3 in routeHash) {
    //     var regexp = new RegExp(routeHash[_a3].regexp),
    //       currentRoute = routeHash[_a3];
    //     if (prop in currentRoute) {
    //       if (historyState && 'path' in historyState && regexp.test(historyState.path)) {
    //         if (prop in routeHash[_a3]) {
    //           return routeHash[_a3][prop];
    //         }
    //       }
    //       if (fallBackValue === undefined) {
    //         fallBackValue = routeHash[_a3][prop];
    //       }
    //     }
    //   }

    //   return fallBackValue;
    // }

    function getPrevUrlIfReloadWhenViewIsSetFn() {
      var historyState = $location.$$state;
      if (historyState && ('path' in historyState)) {
        return historyState.path;
      } else {
        for (var a in routeHash) {
          if (/\/$/.test(a) === true) {
            return a;
          }
        }
      }
    }

    $rootScope.$on('$routeChangeStart', function(event, newUrl, prevUrl) {
      var newUrl = newUrl;
      $stateHandle.route.prevUrl = prevUrl;
      $stateHandle.route.newUrl = newUrl;
      if (newUrl.templateUrl == randomTemplateUrl) {
        if (prevUrl === undefined) {
          var location = $location.path(),
            pathToSet = getPrevUrlIfReloadWhenViewIsSetFn();
          $stateHandle.path(pathToSet);
          $timeout(function() {
            $stateHandle.path(location, false);
          });
        } else {
          $stateHandle.path($location.path(), false);
          if (previousUrl !== undefined) {
            $location.state({
              path: previousUrl,
              searchString: searchUrl
            });
          }
        }
      } else {
        previousUrl = $location.path();
        searchUrl = $location.search();
      }
    });

    $rootScope.$on('$locationChangeStart', function(event, newUrl, prevUrl) {
      var callSubscribers = function(route) {
        var subscribers = $stateHandle.getSubscribers(route.originalPath);
        for (var a in subscribers) {
          var subscriberCallbacks = subscribers[a].callBacks;
          for (var i = 0, len = subscriberCallbacks.length; i < len; i++) {
            subscriberCallbacks[i](route.params);
          }
        }

        if (isNewLoaded && $stateHandle.route.prevUrl !== undefined && route.originalPath !== $stateHandle.route.prevUrl.originalPath) {
          callSubscribers($stateHandle.route.prevUrl);
        }
        isNewLoaded = false;
      };

      $timeout.cancel(callbackTimeoutId);
      callbackTimeoutId = $timeout(function() {
        if ($stateHandle.route && $stateHandle.route.newUrl.title !== undefined) {
          document.title = $stateHandle.route.newUrl.title;
        }
        callSubscribers($stateHandle.route.newUrl);
      }, 100);
    });

    function resetRouteFn(callback) {
      $stateHandle.path(previousUrl || ($location.$$state && $location.$$state.path ||
        function() {
          for (var _a in routeHash) {
            if (/\/$/.test(a) === true) {
              return a;
            }
          }
        }()
      ), false);

      $location.search($location.$$state.searchString);
    }

    function editLocationRouteFunctions(prop) {
      var original = $location[prop];
      return function(value, reload) {
        var ArrayPassedToApply = [];
        if (reload === false) {
          var lastRoute = $route.current,
            un = $rootScope.$on('$locationChangeSuccess', function() {
              $route.current = lastRoute;
              un();
            });
        }
        if (value !== undefined) {
          ArrayPassedToApply.push(value);
        }
        return original.apply($location, ArrayPassedToApply);
      }
    }

    function setUserAuthFn(bool) {
      userAuthenticated = bool;
      deferred.resolve(userAuthenticated);
      return this;
    }

    function ifUserAuthenticatedFn(callback) {
      if (userAuthenticated === undefined) {
        deferred.resolve(false);
      }
      deferred.promise.then(function(userAuthenticated) {
        callback(userAuthenticated);
        callback = function() {};
      });
    }

    $stateHandle.ifUserAuthenticated = ifUserAuthenticatedFn;
    $stateHandle.setUserAuth = setUserAuthFn;
    $stateHandle.resetRoute = resetRouteFn;
    $stateHandle.path = editLocationRouteFunctions("path");
    $stateHandle.search = editLocationRouteFunctions("search");

    routeHash = $route.routes;
    // routeHash.getPropertyValue = getPropertyValueFromHistoryStateFn;
  }]);

  app.config(["$provide", "$routeProvider", "$httpProvider", "$locationProvider", "$stateHandleProvider", "$factoriesForStateHandleProvider",
    function($provide, $routeProvider, $httpProvider, $locationProvider, $stateHandleProvider, $factoriesForStateHandleProvider) {
      var $stateHandle = $stateHandleProvider.$get(),
        whenFn = cloneRouteProviderFn.call($stateHandleProvider, 'when'),
        otherwiseFn = cloneRouteProviderFn.call($stateHandleProvider, 'otherwise'),
        urlBeforeViewSet = undefined;

      function cloneRouteProviderFn(prop) {
        var that = this,
          functionRef = $routeProvider[prop];
        return function(path, route) {
          if (route !== undefined) {
            if (!('templateUrl' in route || 'template' in route)) {
              route.templateUrl = randomTemplateUrl;
            } else if ('templateUrl' in route) {
              if (routeTemplateUrlCollection.indexOf(route.templateUrl) === -1) {
                routeTemplateUrlCollection.push(route.templateUrl);
              }
            }
          }

          functionRef.apply($routeProvider, arguments);
          return (that);
        };
      }

      function removeFn(path) {
        var $routeRef = $routeProvider.$get();
        path = path.replace(/\/$/i, "");
        delete($routeRef.routes[path]);
        delete($routeRef.routes[path + "/"]);
        return (this);
      }

      function removeCurrentFn() {
        var $routeRef = $routeProvider.$get();
        return (this.remove($routeRef.current.originalPath));
      }

      function reloadRouteFn() {
        $factoriesForStateHandleProvider.$route.reload();
      }

      function noAuthFn(path, route) {
        var that = this,
          authParamsPathRef = $stateHandle.getAuthParams().path;

        if (authParamsPathRef !== undefined) {
          $stateHandleProvider.remove(authParamsPathRef);
        }

        $stateHandle.setAuthParams(path, route);

        if (route !== undefined && 'authentication' in route) {
          delete route['authentication'];
        }

        $stateHandleProvider.when(path, route || {});
        return that;
      }

      $stateHandle.remove = $stateHandleProvider.remove = removeFn;
      $stateHandle.removeCurrent = $stateHandleProvider.removeCurrent = removeCurrentFn;
      $stateHandle.when = $stateHandleProvider.when = whenFn;
      $stateHandle.otherwise = $stateHandleProvider.otherwise = otherwiseFn;
      $stateHandle.reloadRoute = $stateHandleProvider.reloadRoute = reloadRouteFn;
      $stateHandle.noAuth = $stateHandleProvider.noAuth = noAuthFn;

      $locationProvider.html5Mode(true);
    }
  ]);
}(window, window.angular);
<commit_msg>Added timeout so that code runs after route is set<commit_after>/*
    Angular State Handler
    2015-10-12
    Public Domain.
    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

! function(window, angular, undefined) {
  "use strict";
  var app = angular.module("stateHandler", ["ngRoute"]),
    randomTemplateUrl = "###" + (Math.random() * 10 / 10) + "###",
    routeHash = {},
    routeTemplateUrlCollection = [],
    dummyElem = document.createElement("a");

  function getRelativePath(url) {
    dummyElem.href = url;
    return {
      path: dummyElem.pathname,
      fullPath: dummyElem.pathname + dummyElem.search
    };
  }

  // function generateSearchStringFromObject(obj) {
  //   var str = undefined;
  //   for (var a in obj) {
  //     if (str === undefined) {
  //       str = "?";
  //     } else {
  //       str += "&";
  //     }
  //     str += a + "=" + obj[a];
  //   }

  //   return str || "";
  // }

  // Factories required to configure this module
  app.provider('$factoriesForStateHandle', ["$provide",
    function($provide) {
      var obj = {
        $get: function() {}
      };

      getFactoryReferenceFn("$route");
      getFactoryReferenceFn("$timeout");
      getFactoryReferenceFn("$location");

      function getFactoryReferenceFn(factoryName) {
        $provide.decorator(factoryName, ['$delegate', factoryDecoratorFn]);

        function factoryDecoratorFn($delegate) {
          return obj[factoryName] = $delegate;
        };
      }

      return obj;
    }
  ]);

  // Provider to handle view and path state based on routing
  app.provider('$stateHandle', ["$provide", "$factoriesForStateHandleProvider",
    function($provide, $factoriesForStateHandleProvider) {
      var $browser = undefined,
        identityHash = {},
        authParams = {
          path: undefined,
          route: null
        },
        _constructor = function(subscriber, pathExpr) {
          this.subscriber = subscriber;
          this.pathExpr = pathExpr;
          this.callBacks = [];
        },
        obj = {
          subscribe: subscribeFn,
          getSubscribers: getSubscribersFn,
          setAuthParams: setAuthParamsFn,
          getAuthParams: getAuthParamsFn
        };

      function subscribeFn(subscriber, pathExpr) {
        if (!(pathExpr in identityHash)) {
          identityHash[pathExpr] = {};
        } else if (subscriber in identityHash[pathExpr]) {
          identityHash[pathExpr][subscriber].callBacks.length = 0;
        }

        return identityHash[pathExpr][subscriber] || (identityHash[pathExpr][subscriber] = new _constructor(subscriber, pathExpr));
      }

      function getSubscribersFn(pathExpr) {
        return identityHash[pathExpr];
      }

      function setAuthParamsFn(path, route) {
        authParams.path = path;
        authParams.route = route;
        return this;
      }

      function getAuthParamsFn() {
        return authParams;
      }

      function subscriberResponseFn(callback) {
        var that = this;
        that.callBacks.push(callback);
        $factoriesForStateHandleProvider.$timeout(function() {
          if (that.pathExpr == $factoriesForStateHandleProvider.$route.current.originalPath) {
            callback($factoriesForStateHandleProvider.$route.current.params);
          }
        });
      };

      _constructor.prototype = {
        response: subscriberResponseFn
      }

      return {
        $get: function() {
          return obj;
        }
      };
    }
  ]);

  app.run(['$route', '$location', '$rootScope', '$timeout', '$stateHandle', '$window', '$q', function($route, $location, $rootScope, $timeout, $stateHandle, $window, $q) {
    var previousUrl = undefined,
      searchUrl = undefined,
      callbackTimeoutId = null,
      isNewLoaded = true,
      userAuthenticated = undefined,
      deferred = $q.defer();

    $stateHandle.route = {};

    // function getPropertyValueFromHistoryStateFn(prop) {
    //   var historyState = $location.$$state;
    //   if (historyState && ('path' in historyState)) {
    //     if (routeHash[historyState.path] && (prop in routeHash[historyState.path])) {
    //       return routeHash[historyState.path][prop];
    //     }
    //   }
    //   var fallBackValue = undefined;
    //   for (var _a3 in routeHash) {
    //     var regexp = new RegExp(routeHash[_a3].regexp),
    //       currentRoute = routeHash[_a3];
    //     if (prop in currentRoute) {
    //       if (historyState && 'path' in historyState && regexp.test(historyState.path)) {
    //         if (prop in routeHash[_a3]) {
    //           return routeHash[_a3][prop];
    //         }
    //       }
    //       if (fallBackValue === undefined) {
    //         fallBackValue = routeHash[_a3][prop];
    //       }
    //     }
    //   }

    //   return fallBackValue;
    // }

    function getPrevUrlIfReloadWhenViewIsSetFn() {
      var historyState = $location.$$state;
      if (historyState && ('path' in historyState)) {
        return historyState.path;
      } else {
        for (var a in routeHash) {
          if (/\/$/.test(a) === true) {
            return a;
          }
        }
      }
    }

    $rootScope.$on('$routeChangeStart', function(event, newUrl, prevUrl) {
      var newUrl = newUrl;
      $stateHandle.route.prevUrl = prevUrl;
      $stateHandle.route.newUrl = newUrl;
      if (newUrl.templateUrl == randomTemplateUrl) {
        if (prevUrl === undefined) {
          var location = $location.path(),
            pathToSet = getPrevUrlIfReloadWhenViewIsSetFn();
          $stateHandle.path(pathToSet);
          $timeout(function() {
            $stateHandle.path(location, false);
          });
        } else {
          $stateHandle.path($location.path(), false);
          if (previousUrl !== undefined) {
            $location.state({
              path: previousUrl,
              searchString: searchUrl
            });
          }
        }
      } else {
        previousUrl = $location.path();
        searchUrl = $location.search();
      }
    });

    $rootScope.$on('$locationChangeStart', function(event, newUrl, prevUrl) {
      var callSubscribers = function(route) {
        var subscribers = $stateHandle.getSubscribers(route.originalPath);
        for (var a in subscribers) {
          var subscriberCallbacks = subscribers[a].callBacks;
          for (var i = 0, len = subscriberCallbacks.length; i < len; i++) {
            subscriberCallbacks[i](route.params);
          }
        }

        if (isNewLoaded && $stateHandle.route.prevUrl !== undefined && route.originalPath !== $stateHandle.route.prevUrl.originalPath) {
          callSubscribers($stateHandle.route.prevUrl);
        }
        isNewLoaded = false;
      };

      $timeout.cancel(callbackTimeoutId);
      callbackTimeoutId = $timeout(function() {
        if ($stateHandle.route && $stateHandle.route.newUrl.title !== undefined) {
          document.title = $stateHandle.route.newUrl.title;
        }
        callSubscribers($stateHandle.route.newUrl);
      }, 100);
    });

    function resetRouteFn(callback) {
      $stateHandle.path(previousUrl || ($location.$$state && $location.$$state.path ||
        function() {
          for (var _a in routeHash) {
            if (/\/$/.test(a) === true) {
              return a;
            }
          }
        }()
      ), false);

      $location.search($location.$$state.searchString);
    }

    function editLocationRouteFunctions(prop) {
      var original = $location[prop];
      return function(value, reload) {
        var ArrayPassedToApply = [];
        if (reload === false) {
          var lastRoute = $route.current,
            un = $rootScope.$on('$locationChangeSuccess', function() {
              $route.current = lastRoute;
              un();
            });
        }
        if (value !== undefined) {
          ArrayPassedToApply.push(value);
        }
        return original.apply($location, ArrayPassedToApply);
      }
    }

    function setUserAuthFn(bool) {
      userAuthenticated = bool;
      deferred.resolve(userAuthenticated);
      return this;
    }

    function ifUserAuthenticatedFn(callback) {
      if (userAuthenticated === undefined) {
        deferred.resolve(false);
      }
      deferred.promise.then(function(userAuthenticated) {
        callback(userAuthenticated);
        callback = function() {};
      });
    }

    $stateHandle.ifUserAuthenticated = ifUserAuthenticatedFn;
    $stateHandle.setUserAuth = setUserAuthFn;
    $stateHandle.resetRoute = resetRouteFn;
    $stateHandle.path = editLocationRouteFunctions("path");
    $stateHandle.search = editLocationRouteFunctions("search");

    routeHash = $route.routes;
    // routeHash.getPropertyValue = getPropertyValueFromHistoryStateFn;
  }]);

  app.config(["$provide", "$routeProvider", "$httpProvider", "$locationProvider", "$stateHandleProvider", "$factoriesForStateHandleProvider",
    function($provide, $routeProvider, $httpProvider, $locationProvider, $stateHandleProvider, $factoriesForStateHandleProvider) {
      var $stateHandle = $stateHandleProvider.$get(),
        whenFn = cloneRouteProviderFn.call($stateHandleProvider, 'when'),
        otherwiseFn = cloneRouteProviderFn.call($stateHandleProvider, 'otherwise'),
        urlBeforeViewSet = undefined;

      function cloneRouteProviderFn(prop) {
        var that = this,
          functionRef = $routeProvider[prop];
        return function(path, route) {
          if (route !== undefined) {
            if (!('templateUrl' in route || 'template' in route)) {
              route.templateUrl = randomTemplateUrl;
            } else if ('templateUrl' in route) {
              if (routeTemplateUrlCollection.indexOf(route.templateUrl) === -1) {
                routeTemplateUrlCollection.push(route.templateUrl);
              }
            }
          }

          functionRef.apply($routeProvider, arguments);
          return (that);
        };
      }

      function removeFn(path) {
        var $routeRef = $routeProvider.$get();
        path = path.replace(/\/$/i, "");
        delete($routeRef.routes[path]);
        delete($routeRef.routes[path + "/"]);
        return (this);
      }

      function removeCurrentFn() {
        var $routeRef = $routeProvider.$get();
        return (this.remove($routeRef.current.originalPath));
      }

      function reloadRouteFn() {
        $factoriesForStateHandleProvider.$route.reload();
      }

      function noAuthFn(path, route) {
        var that = this,
          authParamsPathRef = $stateHandle.getAuthParams().path;

        if (authParamsPathRef !== undefined) {
          $stateHandleProvider.remove(authParamsPathRef);
        }

        $stateHandle.setAuthParams(path, route);

        if (route !== undefined && 'authentication' in route) {
          delete route['authentication'];
        }

        $stateHandleProvider.when(path, route || {});
        return that;
      }

      $stateHandle.remove = $stateHandleProvider.remove = removeFn;
      $stateHandle.removeCurrent = $stateHandleProvider.removeCurrent = removeCurrentFn;
      $stateHandle.when = $stateHandleProvider.when = whenFn;
      $stateHandle.otherwise = $stateHandleProvider.otherwise = otherwiseFn;
      $stateHandle.reloadRoute = $stateHandleProvider.reloadRoute = reloadRouteFn;
      $stateHandle.noAuth = $stateHandleProvider.noAuth = noAuthFn;

      $locationProvider.html5Mode(true);
    }
  ]);
}(window, window.angular);
<|endoftext|>


<commit_before>// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.
//
// Author Larry Kuhns 2011

import { Vex } from './vex';
import { Flow } from './tables';
import { StaveModifier } from './stavemodifier';

export class Barline extends StaveModifier {
  static get CATEGORY() { return 'barlines'; }
  static get type() {
    return {
      SINGLE: 1,
      DOUBLE: 2,
      END: 3,
      REPEAT_BEGIN: 4,
      REPEAT_END: 5,
      REPEAT_BOTH: 6,
      NONE: 7,
    };
  }

  /**
   * @constructor
   */
  constructor(type) {
    super();
    this.thickness = Flow.STAVE_LINE_THICKNESS;

    const TYPE = Barline.type;
    this.widths = {};
    this.widths[TYPE.SINGLE] = 5;
    this.widths[TYPE.DOUBLE] = 5;
    this.widths[TYPE.END] = 5;
    this.widths[TYPE.REPEAT_BEGIN] = 5;
    this.widths[TYPE.REPEAT_END] = 5;
    this.widths[TYPE.REPEAT_BOTH] = 5;
    this.widths[TYPE.NONE] = 5;

    this.paddings = {};
    this.paddings[TYPE.SINGLE] = 0;
    this.paddings[TYPE.DOUBLE] = 0;
    this.paddings[TYPE.END] = 0;
    this.paddings[TYPE.REPEAT_BEGIN] = 15;
    this.paddings[TYPE.REPEAT_END] = 15;
    this.paddings[TYPE.REPEAT_BOTH] = 15;
    this.paddings[TYPE.NONE] = 0;

    this.setPosition(StaveModifier.Position.BEGIN);
    this.setType(type);
  }
  getCategory() { return Barline.CATEGORY; }
  getType() { return this.type; }
  setType(type) {
    this.type = type;
    this.setWidth(this.widths[this.type]);
    this.setPadding(this.paddings[this.type]);
    return this;
  }

  // Draw barlines
  draw(stave) {
    switch (this.type) {
      case Barline.type.SINGLE:
        this.drawVerticalBar(stave, this.x, false);
        break;
      case Barline.type.DOUBLE:
        this.drawVerticalBar(stave, this.x, true);
        break;
      case Barline.type.END:
        this.drawVerticalEndBar(stave, this.x);
        break;
      case Barline.type.REPEAT_BEGIN:
        // If the barline is shifted over (in front of clef/time/key)
        // Draw vertical bar at the beginning.
        this.drawRepeatBar(stave, this.x, true);
        if (stave.getX() !== this.x) {
          this.drawVerticalBar(stave, stave.getX());
        }

        break;
      case Barline.type.REPEAT_END:
        this.drawRepeatBar(stave, this.x, false);
        break;
      case Barline.type.REPEAT_BOTH:
        this.drawRepeatBar(stave, this.x, false);
        this.drawRepeatBar(stave, this.x, true);
        break;
      default:
        // Default is NONE, so nothing to draw
        break;
    }
  }
  drawVerticalBar(stave, x, double_bar) {
    if (!stave.context) throw new Vex.RERR('NoCanvasContext',
        "Can't draw stave without canvas context.");
    const topY = stave.getYForLine(0);
    const botY = stave.getYForLine(stave.getNumLines() - 1) + this.thickness;
    if (double_bar)
      stave.context.fillRect(x - 3, topY, 1, botY - topY);
    stave.context.fillRect(x, topY, 1, botY - topY);
  }
  drawVerticalEndBar(stave, x) {
    if (!stave.context) throw new Vex.RERR('NoCanvasContext',
        "Can't draw stave without canvas context.");

    const topY = stave.getYForLine(0);
    const botY = stave.getYForLine(stave.getNumLines() - 1) + this.thickness;
    stave.context.fillRect(x - 5, topY, 1, botY - topY);
    stave.context.fillRect(x - 2, topY, 3, botY - topY);
  }
  drawRepeatBar(stave, x, begin) {
    if (!stave.context) throw new Vex.RERR('NoCanvasContext',
        "Can't draw stave without canvas context.");

    const topY = stave.getYForLine(0);
    const botY = stave.getYForLine(stave.getNumLines() - 1) + this.thickness;
    let x_shift = 3;

    if (!begin) {
      x_shift = -5;
    }

    stave.context.fillRect(x + x_shift, topY, 1, botY - topY);
    stave.context.fillRect(x - 2, topY, 3, botY - topY);

    const dot_radius = 2;

    // Shift dots left or right
    if (begin) {
      x_shift += 4;
    } else {
      x_shift -= 4;
    }

    const dot_x = (x + x_shift) + (dot_radius / 2);

    // calculate the y offset based on number of stave lines
    let y_offset = (stave.getNumLines() - 1) *
      stave.getSpacingBetweenLines();
    y_offset = (y_offset / 2) -
               (stave.getSpacingBetweenLines() / 2);
    let dot_y = topY + y_offset + (dot_radius / 2);

    // draw the top repeat dot
    stave.context.beginPath();
    stave.context.arc(dot_x, dot_y, dot_radius, 0, Math.PI * 2, false);
    stave.context.fill();

    // draw the bottom repeat dot
    dot_y += stave.getSpacingBetweenLines();
    stave.context.beginPath();
    stave.context.arc(dot_x, dot_y, dot_radius, 0, Math.PI * 2, false);
    stave.context.fill();
  }
}
<commit_msg>Fix remaining lint problems in stavebarline.js<commit_after>// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.
//
// Author Larry Kuhns 2011

import { Vex } from './vex';
import { Flow } from './tables';
import { StaveModifier } from './stavemodifier';

export class Barline extends StaveModifier {
  static get CATEGORY() { return 'barlines'; }
  static get type() {
    return {
      SINGLE: 1,
      DOUBLE: 2,
      END: 3,
      REPEAT_BEGIN: 4,
      REPEAT_END: 5,
      REPEAT_BOTH: 6,
      NONE: 7,
    };
  }

  /**
   * @constructor
   */
  constructor(type) {
    super();
    this.thickness = Flow.STAVE_LINE_THICKNESS;

    const TYPE = Barline.type;
    this.widths = {};
    this.widths[TYPE.SINGLE] = 5;
    this.widths[TYPE.DOUBLE] = 5;
    this.widths[TYPE.END] = 5;
    this.widths[TYPE.REPEAT_BEGIN] = 5;
    this.widths[TYPE.REPEAT_END] = 5;
    this.widths[TYPE.REPEAT_BOTH] = 5;
    this.widths[TYPE.NONE] = 5;

    this.paddings = {};
    this.paddings[TYPE.SINGLE] = 0;
    this.paddings[TYPE.DOUBLE] = 0;
    this.paddings[TYPE.END] = 0;
    this.paddings[TYPE.REPEAT_BEGIN] = 15;
    this.paddings[TYPE.REPEAT_END] = 15;
    this.paddings[TYPE.REPEAT_BOTH] = 15;
    this.paddings[TYPE.NONE] = 0;

    this.setPosition(StaveModifier.Position.BEGIN);
    this.setType(type);
  }
  getCategory() { return Barline.CATEGORY; }
  getType() { return this.type; }
  setType(type) {
    this.type = type;
    this.setWidth(this.widths[this.type]);
    this.setPadding(this.paddings[this.type]);
    return this;
  }

  // Draw barlines
  draw(stave) {
    switch (this.type) {
      case Barline.type.SINGLE:
        this.drawVerticalBar(stave, this.x, false);
        break;
      case Barline.type.DOUBLE:
        this.drawVerticalBar(stave, this.x, true);
        break;
      case Barline.type.END:
        this.drawVerticalEndBar(stave, this.x);
        break;
      case Barline.type.REPEAT_BEGIN:
        // If the barline is shifted over (in front of clef/time/key)
        // Draw vertical bar at the beginning.
        this.drawRepeatBar(stave, this.x, true);
        if (stave.getX() !== this.x) {
          this.drawVerticalBar(stave, stave.getX());
        }

        break;
      case Barline.type.REPEAT_END:
        this.drawRepeatBar(stave, this.x, false);
        break;
      case Barline.type.REPEAT_BOTH:
        this.drawRepeatBar(stave, this.x, false);
        this.drawRepeatBar(stave, this.x, true);
        break;
      default:
        // Default is NONE, so nothing to draw
        break;
    }
  }

  drawVerticalBar(stave, x, double_bar) {
    if (!stave.context) {
      throw new Vex.RERR('NoCanvasContext', "Can't draw stave without canvas context.");
    }

    const topY = stave.getYForLine(0);
    const botY = stave.getYForLine(stave.getNumLines() - 1) + this.thickness;
    if (double_bar) {
      stave.context.fillRect(x - 3, topY, 1, botY - topY);
    }
    stave.context.fillRect(x, topY, 1, botY - topY);
  }

  drawVerticalEndBar(stave, x) {
    if (!stave.context) {
      throw new Vex.RERR('NoCanvasContext', "Can't draw stave without canvas context.");
    }

    const topY = stave.getYForLine(0);
    const botY = stave.getYForLine(stave.getNumLines() - 1) + this.thickness;
    stave.context.fillRect(x - 5, topY, 1, botY - topY);
    stave.context.fillRect(x - 2, topY, 3, botY - topY);
  }

  drawRepeatBar(stave, x, begin) {
    if (!stave.context) {
      throw new Vex.RERR('NoCanvasContext', "Can't draw stave without canvas context.");
    }

    const topY = stave.getYForLine(0);
    const botY = stave.getYForLine(stave.getNumLines() - 1) + this.thickness;
    let x_shift = 3;

    if (!begin) {
      x_shift = -5;
    }

    stave.context.fillRect(x + x_shift, topY, 1, botY - topY);
    stave.context.fillRect(x - 2, topY, 3, botY - topY);

    const dot_radius = 2;

    // Shift dots left or right
    if (begin) {
      x_shift += 4;
    } else {
      x_shift -= 4;
    }

    const dot_x = (x + x_shift) + (dot_radius / 2);

    // calculate the y offset based on number of stave lines
    let y_offset = (stave.getNumLines() - 1) * stave.getSpacingBetweenLines();
    y_offset = (y_offset / 2) - (stave.getSpacingBetweenLines() / 2);
    let dot_y = topY + y_offset + (dot_radius / 2);

    // draw the top repeat dot
    stave.context.beginPath();
    stave.context.arc(dot_x, dot_y, dot_radius, 0, Math.PI * 2, false);
    stave.context.fill();

    // draw the bottom repeat dot
    dot_y += stave.getSpacingBetweenLines();
    stave.context.beginPath();
    stave.context.arc(dot_x, dot_y, dot_radius, 0, Math.PI * 2, false);
    stave.context.fill();
  }
}
<|endoftext|>


<commit_before>!function() {
    if ( !jar.prefixes.indexedDB ) {
        return;
    }

    var proto, idb,
        self = this,
        database = {},
        indexOf = [].indexOf,

        cantStore = {
            xml: true,
            html: true
        },

        // Prefixes
        indexedDB = jar.prefixes.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB,
        IDBTransaction = jar.prefixes.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction,
        IDBKeyRange = jar.prefixes.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;

    this.storages.push( "idb" );

    this.idb = function( name ) {
        return new proto.init( name, this );
    };

    idb = jar.idb = {};

    proto = this.idb.prototype = {
        constructor: this.idb,

        init: function( name, instance ) {
            var db, request, def,
                self = this;

            this.instance = instance;
            this.def = jar.Deferred();
            this.name = name;

            return this.setup().def;
        },

        setup: function() {
            var request,
                self = this,
                name = this.name;

            function reject() {
                self.def.reject();
            }

            // If db already initialized don't try to create another one
            if ( !idb.open ) {

                // Open connection for database
                idb.open = indexedDB.open( "jar", jar.version = new Date().getTime() );
            }

            // In case we create instance without reopening connection to database
            if ( idb.db ) {
                self.instance.stores.idb = idb.db;
            }

            // New way to do it
            if ( idb.open.onupgradeneeded === null ) {

                request = setVersion(function() {
                    self.instance.stores.idb = idb.db = this.result;
                    createObjectStore( name );
                }, this.instance );

                request.addEventListener( "success", function() {
                    self.def.resolve();
                });

            // Old way
            } else {

                // If db exist than just update it
                if ( idb.db ) {
                    update( this );
                }

                // This will not be executed if db already exist
                (request = idb.open).addEventListener( "success", function() {

                    // Create link in jar for new db
                    self.instance.stores.idb = idb.db = this.result;

                    update( self );
                });
            }

            request.addEventListener( "error", reject );
            request.addEventListener( "blocked", reject );

            return this;
        },
    };

    proto.init.prototype = proto;

    this.idb.set = function( name, data, type, id ) {

        // Reject request if store is not exist
        if ( !contains( this.name ) ) {
            jar.reject( id );
            return this;
        }

        var request,
            self = this,
            store = idb.db.transaction([ this.name ], IDBTransaction.READ_WRITE ).objectStore( this.name );

        // We can't store DOM nodes
        if ( cantStore[ type ] ) {
            data = jar.text[ type ]( data );
        }

        data = {
            name: name,
            data: data
        };

        // Use "put", so we can rewrite data
        request = store.put( data );

        request.onsuccess = function() {
            jar.resolve( id, type, "idb" );
        };

        request.onerror = function() {
            jar.reject( id );
        };

        return this;
    };

    this.idb.get = function( name, type, id ) {

        // Reject request if store is not exist
        if ( !contains( this.name ) ) {
            jar.reject( id );
            return this;
        }

        var self = this,
            store = idb.db.transaction([ this.name ], IDBTransaction.READ_ONLY ).objectStore( this.name ),
            index = store.index( "name" ),
            request = index.get( name );

        request.onsuccess = function() {
            var data = this.result && this.result.data;

            // When data isn't there its still succesfull operation for this api, but not for jar
            if ( !data ) {
                return jar.reject( id );
            }

            // IndexedDB can't store some types of data in it original type
            // we need to serialize it to right type
            if ( cantStore[ type ] ) {
                data = jar.filters[ type ]( data );
            }

            // Some types of data can't be serialize to right type
            // like javascript code, so instead we return it like text
            // and execute it
            if ( jar.executable[ type ] ) {
                jar.filters[ type ]( data );
            }

            jar.resolve( id, data, type, "idb" );
        };

        request.onerror = function() {
            jar.reject( id );
        };

        return this;
    };

    this.idb.remove = function( name, id ) {

        // Reject request if store is not exist
        if ( !contains( this.name ) ) {
            jar.reject( id );
            return this;
        }

        var self = this,
            store = idb.db.transaction([ this.name ], IDBTransaction.READ_WRITE ).objectStore( this.name ),
            request = store.delete( name );

        request.onsuccess = function() {
            jar.resolve( id );
        };

        request.onerror = function() {
            jar.reject( id );
        };

        return this;
    };

    this.idb.clear = function( id, destroy /* internal */ ) {
        var request, store,
            stores = this.stores,
            name = this.name;

        function resolve() {
            jar.resolve( id );
        }

        function reject() {
            jar.reject( id );
        }

        // Either clear or destroy
        if ( destroy ) {
            request = setVersion(function() {
                idb.db.deleteObjectStore( name );
            }, this );

        } else {
            store = idb.db.transaction([ name ], IDBTransaction.READ_WRITE ).objectStore( name );
            request = store.clear();
        }

        request.onsuccess = resolve;
        request.onerror = reject;

        return this;
    };

    var test = [];

    function setVersion( fn, instance ) {

        // Old way to set database version
        if ( idb.db && idb.db.setVersion ) {

            // If we have active request attach to it, if not create new one
            if ( !idb.setVersion || idb.setVersion.readyState == 2 /* done */ ) {
                idb.setVersion = idb.db.setVersion( new Date().getTime() );
            }

            idb.setVersion.addEventListener( "success", fn );

        } else {
            if ( idb.open.readyState == "pending" ) {
                idb.setVersion = idb.open;

            } else {
                idb.db.close();
                idb.setVersion = indexedDB.open( "jar", jar.version = new Date().getTime() );
            }

            idb.setVersion.addEventListener( "upgradeneeded", function() {
                instance.stores.idb = idb.db = this.result;
                fn.apply( this, arguments );
            });
        }

        idb.setVersion.addEventListener( "success", function() {
            this.result.onversionchange = function() {
                this.close();
            };
        });

        return idb.setVersion;
    }

    function update( instance ) {
        var request = setVersion(function() {
            createObjectStore( instance.name );
        });

        request.addEventListener( "success", function() {
            instance.def.resolve();
        });

        request.addEventListener( "error", function() {
            instance.def.reject();
        });
    }

    function contains( name ) {
        return idb.db.objectStoreNames.contains( name );
    }

    function createObjectStore( name ) {
        if ( !idb.db.objectStoreNames.contains( name ) ) {
            idb.db.createObjectStore( name, {
                keyPath: "name"
            }).createIndex( "name", "name", {
                unique: true
            });
        }
    }

}.call( jar.fn );<commit_msg>Remove useless line<commit_after>!function() {
    if ( !jar.prefixes.indexedDB ) {
        return;
    }

    var proto, idb,
        self = this,
        database = {},
        indexOf = [].indexOf,

        cantStore = {
            xml: true,
            html: true
        },

        // Prefixes
        indexedDB = jar.prefixes.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB,
        IDBTransaction = jar.prefixes.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction,
        IDBKeyRange = jar.prefixes.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;

    this.storages.push( "idb" );

    this.idb = function( name ) {
        return new proto.init( name, this );
    };

    idb = jar.idb = {};

    proto = this.idb.prototype = {
        constructor: this.idb,

        init: function( name, instance ) {
            var db, request, def,
                self = this;

            this.instance = instance;
            this.def = jar.Deferred();
            this.name = name;

            return this.setup().def;
        },

        setup: function() {
            var request,
                self = this,
                name = this.name;

            function reject() {
                self.def.reject();
            }

            // If db already initialized don't try to create another one
            if ( !idb.open ) {

                // Open connection for database
                idb.open = indexedDB.open( "jar", jar.version = new Date().getTime() );
            }

            // In case we create instance without reopening connection to database
            if ( idb.db ) {
                self.instance.stores.idb = idb.db;
            }

            // New way to do it
            if ( idb.open.onupgradeneeded === null ) {

                request = setVersion(function() {
                    self.instance.stores.idb = idb.db = this.result;
                    createObjectStore( name );
                }, this.instance );

                request.addEventListener( "success", function() {
                    self.def.resolve();
                });

            // Old way
            } else {

                // If db exist than just update it
                if ( idb.db ) {
                    update( this );
                }

                // This will not be executed if db already exist
                (request = idb.open).addEventListener( "success", function() {

                    // Create link in jar for new db
                    self.instance.stores.idb = idb.db = this.result;

                    update( self );
                });
            }

            request.addEventListener( "error", reject );
            request.addEventListener( "blocked", reject );

            return this;
        },
    };

    proto.init.prototype = proto;

    this.idb.set = function( name, data, type, id ) {

        // Reject request if store is not exist
        if ( !contains( this.name ) ) {
            jar.reject( id );
            return this;
        }

        var request,
            self = this,
            store = idb.db.transaction([ this.name ], IDBTransaction.READ_WRITE ).objectStore( this.name );

        // We can't store DOM nodes
        if ( cantStore[ type ] ) {
            data = jar.text[ type ]( data );
        }

        data = {
            name: name,
            data: data
        };

        // Use "put", so we can rewrite data
        request = store.put( data );

        request.onsuccess = function() {
            jar.resolve( id, type, "idb" );
        };

        request.onerror = function() {
            jar.reject( id );
        };

        return this;
    };

    this.idb.get = function( name, type, id ) {

        // Reject request if store is not exist
        if ( !contains( this.name ) ) {
            jar.reject( id );
            return this;
        }

        var self = this,
            store = idb.db.transaction([ this.name ], IDBTransaction.READ_ONLY ).objectStore( this.name ),
            index = store.index( "name" ),
            request = index.get( name );

        request.onsuccess = function() {
            var data = this.result && this.result.data;

            // When data isn't there its still succesfull operation for this api, but not for jar
            if ( !data ) {
                return jar.reject( id );
            }

            // IndexedDB can't store some types of data in it original type
            // we need to serialize it to right type
            if ( cantStore[ type ] ) {
                data = jar.filters[ type ]( data );
            }

            // Some types of data can't be serialize to right type
            // like javascript code, so instead we return it like text
            // and execute it
            if ( jar.executable[ type ] ) {
                jar.filters[ type ]( data );
            }

            jar.resolve( id, data, type, "idb" );
        };

        request.onerror = function() {
            jar.reject( id );
        };

        return this;
    };

    this.idb.remove = function( name, id ) {

        // Reject request if store is not exist
        if ( !contains( this.name ) ) {
            jar.reject( id );
            return this;
        }

        var self = this,
            store = idb.db.transaction([ this.name ], IDBTransaction.READ_WRITE ).objectStore( this.name ),
            request = store.delete( name );

        request.onsuccess = function() {
            jar.resolve( id );
        };

        request.onerror = function() {
            jar.reject( id );
        };

        return this;
    };

    this.idb.clear = function( id, destroy /* internal */ ) {
        var request, store,
            stores = this.stores,
            name = this.name;

        function resolve() {
            jar.resolve( id );
        }

        function reject() {
            jar.reject( id );
        }

        // Either clear or destroy
        if ( destroy ) {
            request = setVersion(function() {
                idb.db.deleteObjectStore( name );
            }, this );

        } else {
            store = idb.db.transaction([ name ], IDBTransaction.READ_WRITE ).objectStore( name );
            request = store.clear();
        }

        request.onsuccess = resolve;
        request.onerror = reject;

        return this;
    };

    var test = [];

    function setVersion( fn, instance ) {

        // Old way to set database version
        if ( idb.db && idb.db.setVersion ) {

            // If we have active request attach to it, if not create new one
            if ( !idb.setVersion || idb.setVersion.readyState == 2 /* done */ ) {
                idb.setVersion = idb.db.setVersion( new Date().getTime() );
            }

            idb.setVersion.addEventListener( "success", fn );

        } else {
            if ( idb.open.readyState == "pending" ) {
                idb.setVersion = idb.open;

            } else {
                idb.setVersion = indexedDB.open( "jar", jar.version = new Date().getTime() );
            }

            idb.setVersion.addEventListener( "upgradeneeded", function() {
                instance.stores.idb = idb.db = this.result;
                fn.apply( this, arguments );
            });
        }

        idb.setVersion.addEventListener( "success", function() {
            this.result.onversionchange = function() {
                this.close();
            };
        });

        return idb.setVersion;
    }

    function update( instance ) {
        var request = setVersion(function() {
            createObjectStore( instance.name );
        });

        request.addEventListener( "success", function() {
            instance.def.resolve();
        });

        request.addEventListener( "error", function() {
            instance.def.reject();
        });
    }

    function contains( name ) {
        return idb.db.objectStoreNames.contains( name );
    }

    function createObjectStore( name ) {
        if ( !idb.db.objectStoreNames.contains( name ) ) {
            idb.db.createObjectStore( name, {
                keyPath: "name"
            }).createIndex( "name", "name", {
                unique: true
            });
        }
    }

}.call( jar.fn );<|endoftext|>


<commit_before>import { combineReducers, createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';

import api from '../api';
import safeStorage from '../utils/safe_storage';

import user from './user_reducer';
import settings from './settings_reducer';
import tasks from './tasks_reducer';
import items from './items_reducer';
import activity from './activity_reducer';
import stats from './stats_reducer';
import modals from './modals_reducer';
import loading from './loading_reducer';

// Root reducer
const rootReducer = combineReducers({
  user,
  settings,
  tasks,
  items,
  activity,
  stats,
  modals,
  loading,
});

// Middlewares
const middlewares = [thunk];

if (process.env.NODE_ENV !== 'production') {
  const logger = createLogger();
  middlewares.push(logger);
}

// Persisted state
const persistedState = {
  user: {
    isAuthenticated: api.osm.isAuthenticated(),
  },
  settings: {
    sidebar: safeStorage.get('sidebar') || true,
    editor: safeStorage.get('editor') || 'id',
  },
};

// Store
const store = createStore(
  rootReducer,
  persistedState,
  applyMiddleware(...middlewares)
);

// Persist change in settings to local storage
store.subscribe(() => {
  const state = store.getState();
  const { sidebar, editor } = state.settings;

  if (sidebar !== safeStorage.get('sidebar')) {
    safeStorage.set('sidebar', sidebar);
  }

  if (editor !== safeStorage.get('editor')) {
    safeStorage.set('editor', editor);
  }
});

export default store;
<commit_msg>read tokens from local storage; persist on change<commit_after>import { combineReducers, createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';

import safeStorage from '../utils/safe_storage';

import user from './user_reducer';
import settings from './settings_reducer';
import tasks from './tasks_reducer';
import items from './items_reducer';
import activity from './activity_reducer';
import stats from './stats_reducer';
import modals from './modals_reducer';
import loading from './loading_reducer';

// Root reducer
const rootReducer = combineReducers({
  user,
  settings,
  tasks,
  items,
  activity,
  stats,
  modals,
  loading,
});

// Middlewares
const middlewares = [thunk];

if (process.env.NODE_ENV !== 'production') {
  const logger = createLogger();
  middlewares.push(logger);
}

// Persisted state
const persistedState = {
  user: {
    isAuthenticated: false,
    token: safeStorage.get('token') || null,
  },
  settings: {
    sidebar: safeStorage.get('sidebar') || true,
    editor: safeStorage.get('editor') || 'id',
  },
};

// Store
const store = createStore(
  rootReducer,
  persistedState,
  applyMiddleware(...middlewares)
);

// Persist change to local storage
store.subscribe(() => {
  const state = store.getState();
  const { sidebar, editor } = state.settings;
  const { token } = state.user;

  if (sidebar !== safeStorage.get('sidebar')) {
    safeStorage.set('sidebar', sidebar);
  }

  if (editor !== safeStorage.get('editor')) {
    safeStorage.set('editor', editor);
  }

  if (token !== safeStorage.get('token')) {
    safeStorage.set('token', token);
  }
});

export default store;
<|endoftext|>


<commit_before>'use strict';

import { StyleSheet } from 'react-native';
import assign from 'object-assign';

const styles = StyleSheet.create(assign({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F9',
  },
  title: {
    height: 50,
    backgroundColor: '#3F454F',
    textAlign: 'center',
    paddingTop: 25,
    color: '#fff'
  },
  content: {
    backgroundColor: '#F5F5F9',
    flex: 1,
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
}, {
  scrollContainer: {
    backgroundColor: '#F5F5F9',
    paddingBottom: 0,
  },
}, {
  topBar: {
    height: 55,
    flexDirection: 'row',
    backgroundColor: '#3F454F',
    paddingTop: 30
  },
  topBarBack: {
    width: 60,
    textAlign: 'center',
    fontSize: 12,
    color: '#fff'
  },
  topBarTitle: {
    flex: 1,
    textAlign: 'center',
    fontSize: 14,
    fontWeight: 'bold',
    color: '#fff'
  },
  topBarOptions: {
    width: 60,
    textAlign: 'center',
    fontSize: 12,
    color: '#fff'
  },
}, {
  quickEntry: {
    flexDirection: 'row',
    backgroundColor: '#3F454F',
    height: 100,
    paddingTop: 10
  },
  quickEntryItem: {
    padding: 10,
    flex: 1,
    alignItems: 'center'
  },
  quickEntryItemIcon: {
    width: 40,
    height: 40
  },
  quickEntryItemText: {
    marginTop: 8,
    color: '#fff',
    fontSize: 13
  },
  quickEntryItemTextYellow: {
    marginTop: 8,
    color: '#FFC700',
    fontSize: 13
  },
}, {
  app: {

  },
  appRow: {
    height: 75,
    flexDirection: 'row',
    backgroundColor: '#3F454F',
  },
  appRowTopBorder: {
    height: 75,
    flexDirection: 'row',
    backgroundColor: '#3F454F',
    borderTopWidth: 1,
    borderColor: '#E6E6E6',
  },
  appCol: {
    flex: 1,
    borderRightWidth: 1,
    borderBottomWidth: 1,
    borderColor: '#E6E6E6',
    backgroundColor: '#fff',
    alignItems: 'center',
    paddingTop: 15,
  },
  appItemIcon: {
    width: 24,
    height: 24,
  },
  appItemIcon2: {
    width: 24,
    height: 24,
    paddingTop: 2,
  },
  appItemText: {
    marginTop: 8,
    fontSize: 12
  },
}, {
  banner: {
    marginTop: 15,
    marginBottom: 15,
    borderTopWidth: 1,
    borderBottomWidth: 1,
    borderColor: '#E6E6E6',
    backgroundColor: '#fff',
    alignItems: 'center',
  },
  bannerImage: {
    maxWidth: 320,
    height: 70
  },
}));

export default styles;<commit_msg>优化九宫格列表 pull 效果<commit_after>'use strict';

import { StyleSheet } from 'react-native';
import assign from 'object-assign';

const styles = StyleSheet.create(assign({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F9',
  },
  title: {
    height: 50,
    backgroundColor: '#3F454F',
    textAlign: 'center',
    paddingTop: 25,
    color: '#fff'
  },
  content: {
    backgroundColor: '#F5F5F9',
    flex: 1,
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
}, {
  scrollContainer: {
    backgroundColor: '#F5F5F9',
    paddingBottom: 15,
    marginTop: -20,
  },
}, {
  topBar: {
    height: 55,
    flexDirection: 'row',
    backgroundColor: '#3F454F',
    paddingTop: 30
  },
  topBarBack: {
    width: 60,
    textAlign: 'center',
    fontSize: 12,
    color: '#fff'
  },
  topBarTitle: {
    flex: 1,
    textAlign: 'center',
    fontSize: 14,
    fontWeight: 'bold',
    color: '#fff'
  },
  topBarOptions: {
    width: 60,
    textAlign: 'center',
    fontSize: 12,
    color: '#fff'
  },
}, {
  quickEntry: {
    flexDirection: 'row',
    backgroundColor: '#3F454F',
    height: 100,
    paddingTop: 10
  },
  quickEntryItem: {
    padding: 10,
    flex: 1,
    alignItems: 'center'
  },
  quickEntryItemIcon: {
    width: 40,
    height: 40
  },
  quickEntryItemText: {
    marginTop: 8,
    color: '#fff',
    fontSize: 13
  },
  quickEntryItemTextYellow: {
    marginTop: 8,
    color: '#FFC700',
    fontSize: 13
  },
}, {
  app: {

  },
  appRow: {
    height: 75,
    flexDirection: 'row',
    backgroundColor: '#3F454F',
  },
  appRowTopBorder: {
    height: 75,
    flexDirection: 'row',
    backgroundColor: '#3F454F',
    borderTopWidth: 1,
    borderColor: '#E6E6E6',
  },
  appCol: {
    flex: 1,
    borderRightWidth: 1,
    borderBottomWidth: 1,
    borderColor: '#E6E6E6',
    backgroundColor: '#fff',
    alignItems: 'center',
    paddingTop: 15,
  },
  appItemIcon: {
    width: 24,
    height: 24,
  },
  appItemIcon2: {
    width: 24,
    height: 24,
    paddingTop: 2,
  },
  appItemText: {
    marginTop: 8,
    fontSize: 12
  },
}, {
  banner: {
    marginTop: 15,
    marginBottom: 15,
    borderTopWidth: 1,
    borderBottomWidth: 1,
    borderColor: '#E6E6E6',
    backgroundColor: '#fff',
    alignItems: 'center',
  },
  bannerImage: {
    maxWidth: 320,
    height: 70
  },
}));

export default styles;<|endoftext|>


<commit_before>/*!
 * SVG.js Pan Zoom Plugin
 * ======================
 *
 * A JavaScript library for pan and zoom SVG things.
 * Created with <3 and JavaScript by the jillix developers.
 *
 * svg.pan-zoom.js 1.0.1
 * Licensed under the MIT license.
 * */
;(function() {

    var container = null;
    var markers = null;

    var mousewheel = "onwheel" in document.createElement("div")
                     ? "wheel" : document.onmousewheel !== undefined
                     ? "mousewheel"
                     : "DOMMouseScroll";
    /**
     * panZoom
     * The pan-zoom contructor.
     *
     * @name panZoom
     * @function
     * @param {Object|undefined} opt_options An optional object containing the following fields:
     *
     *  - `zoom` (Array): An array of two float values: the minimum and maximum zoom values (default: `undefined`).
     *
     * @return {PanZoom} The PanZoom object containing the following fields:
     *
     *  - `elm` (SVG): The selected element.
     *  - `pan` (Object): An object containing pan values.
     *  - `transform` (Object): An object containing the transform data (`scaleX`, `scaleY`, `x` and `y`).
     *
     */
    function panZoom(opt_options) {

        // Selected element
        var self = this;

        // Pan zoom object
        var pz = {
            pan: {},
            elm: self
        };

        // Set options
        opt_options = Object(opt_options);
        opt_options.zoom = opt_options.zoom || [];

        // Get the svg document
        var svg = self;
        while ((svg = self.parent).node.tagName.toUpperCase() !== "SVG") {}

        // Create the rectangle
        var rect = new SVG(document.createDocumentFragment()).rect().attr({
            width: svg.width(),
            height: svg.height(),
            fill: "none"
        }).style("pointer-events", "all");

        // Insert the rectangle
        self.parent.node.insertBefore(rect.node, self.node)

        /*!
         * updateMatrix
         * An internal function called to update the svg matrix.
         *
         * @name updateMatrix
         * @function
         * @return {undefined}
         */
        function updateMatrix() {
            self.attr("transform", "matrix(" + [
                pz.transform.scaleX,
                0, 0,
                pz.transform.scaleY,
                pz.transform.x,
                pz.transform.y
            ].join(",")+ ")");
        }

        /*!
         * pan
         * The internal function called for panning.
         *
         * @name pan
         * @function
         * @param {Event} e The internal listener event.
         * @return {undefined}
         */
        function pan(e) {
            if (!pz.pan.mousedown) {
                return;
            }
            var tr = pz.transform = self.transform();
            var diffX = pz.pan.fPos.x - pz.pan.iPos.x;
            var diffY = pz.pan.fPos.y - pz.pan.iPos.y;
            tr.x += diffX;
            tr.y += diffY;
            pz.pan.iPos = pz.pan.fPos;
            self.node.dispatchEvent(new CustomEvent("pan", e, tr));
            updateMatrix();
        }

        /*!
         * zoom
         * The internal function called for zooming.
         *
         * @name zoom
         * @function
         * @param {Event} e The internal listener event.
         * @return {undefined}
         */
        function zoom (e) {

            // Get the relative mouse point
            var rP = mousePos(e, true);
            var oX = rP.x;
            var oY = rP.y;

            e.deltaY = e.deltaY || e.wheelDeltaY;

            // Compute the new scale
            var d = e.deltaY / 1000;
            var tr = pz.transform = self.transform();
            var scale = tr.scaleX + (tr.scaleX * d);

            var scaleD = scale / tr.scaleX;

            // Get the current x, y
            var currentX = tr.x;
            var currentY = tr.y;

            // Compute the final x, y
            var x = scaleD * (currentX - oX) + oX;
            var y = scaleD * (currentY - oY) + oY;

            // Handle zoom restrictions
            if (scale > opt_options.zoom[1]) {
                scale = opt_options.zoom[1];
                return;
            }

            if (scale < opt_options.zoom[0]) {
                scale = opt_options.zoom[0];
                return;
            }

            // Zoom
            tr.scaleY = tr.scaleX = scale;
            tr.x = x;
            tr.y = y;

            self.node.dispatchEvent(new CustomEvent("zoom", e, tr));
            updateMatrix();

            // Prevent the default browser behavior
            e.preventDefault();
        }

        /*!
         * mousePos
         * Returns the mouse point coordinates.
         *
         * @name mousePos
         * @function
         * @param {Event} e The mouse event.
         * @param {Boolean} rel If `true`, the relative coordinates will be returned instead.
         * @return {Object} An object containing the relative coordinates.
         */
        function mousePos(e, rel) {
            var bbox = self.bbox();
            var abs = {
                x: e.clientX || e.touches[0].pageX,
                y: e.clientY || e.touches[0].pageY
            };
            if (!rel) { return abs; }
            return {
                x: abs.x - bbox.x,
                y: abs.y - bbox.y
            };
        }

        // The event listeners
        var EventListeners = {
            mouse_down: function (e) {
                pz.pan.mousedown = true;
                pz.pan.iPos = mousePos(e);
            },
            mouse_up: function (e) {
                pz.pan.mousedown = false;
                pz.pan.fPos = mousePos(e);
                pan();
            },
            mouse_move: function (e) {
                if (!pz.pan.mousedown) { return; }
                pz.pan.fPos = mousePos(e);
                pan();
            },
            mouse_leave: function (e) {
                pz.pan.mousedown = false;
            }
        };

        // Add event listeners
        rect
          .on(mousewheel, zoom)
          .on("mousedown", EventListeners.mouse_down)
          .on("touchstart", EventListeners.mouse_down)
          .on("mousemove", EventListeners.mouse_move)
          .on("touchmove", EventListeners.mouse_move)
          .on("mouseup", EventListeners.mouse_up)
          .on("touchup", EventListeners.mouse_up)
          .on("mouseleave", EventListeners.mouse_leave)
          ;

        self.on(mousewheel, zoom);
        return pz;
    }

    // Extend the SVG.Element with the new function
    SVG.extend(SVG.Element, {
        panZoom: panZoom
    });
}).call(this);
<commit_msg>Added zoom and setPosition methods<commit_after>/*!
 * SVG.js Pan Zoom Plugin
 * ======================
 *
 * A JavaScript library for pan and zoom SVG things.
 * Created with <3 and JavaScript by the jillix developers.
 *
 * svg.pan-zoom.js 1.0.0
 * Licensed under the MIT license.
 * */
;(function() {

    var container = null;
    var markers = null;

    var mousewheel = "onwheel" in document.createElement("div")
                     ? "wheel" : document.onmousewheel !== undefined
                     ? "mousewheel"
                     : "DOMMouseScroll";
    /**
     * panZoom
     * The pan-zoom contructor.
     *
     * @name panZoom
     * @function
     * @param {Object|undefined} opt_options An optional object containing the following fields:
     *
     *  - `zoom` (Array): An array of two float values: the minimum and maximum zoom values (default: `undefined`).
     *
     * @return {PanZoom} The PanZoom object containing the following fields:
     *
     *  - `elm` (SVG): The selected element.
     *  - `pan` (Object): An object containing pan values.
     *  - `transform` (Object): An object containing the transform data (`scaleX`, `scaleY`, `x` and `y`).
     *
     */
    function panZoom(opt_options) {

        // Selected element
        var self = this;

        // Pan zoom object
        var pz = {
            pan: {},
            elm: self,
            setPosition: function (x, y, z) {
                pz.pan.iPos = pz.pan.fPos;
                pz.transform = self.transform();
                pz.transform.x = x;
                pz.transform.y = y;
                if (typeof z === "number") {
                    pz.zoom(z);
                } else {
                    updateMatrix();
                }
                return pz;
            },
            zoom: function (z) {
                pz.transform = self.transform();
                pz.transform.scaleY = pz.transform.scaleX = z;
                updateMatrix();
                return pz;
            }
        };

        // Set options
        opt_options = Object(opt_options);
        opt_options.zoom = opt_options.zoom || [];

        // Get the svg document
        var svg = self;
        while ((svg = self.parent).node.tagName.toUpperCase() !== "SVG") {}

        // Create the rectangle
        var rect = new SVG(document.createDocumentFragment()).rect().attr({
            width: svg.width(),
            height: svg.height(),
            fill: "none"
        }).style("pointer-events", "all");

        // Insert the rectangle
        self.parent.node.insertBefore(rect.node, self.node)

        /*!
         * updateMatrix
         * An internal function called to update the svg matrix.
         *
         * @name updateMatrix
         * @function
         * @return {undefined}
         */
        function updateMatrix() {
            self.attr("transform", "matrix(" + [
                pz.transform.scaleX,
                0, 0,
                pz.transform.scaleY,
                pz.transform.x,
                pz.transform.y
            ].join(",")+ ")");
        }

        /*!
         * pan
         * The internal function called for panning.
         *
         * @name pan
         * @function
         * @param {Event} e The internal listener event.
         * @return {undefined}
         */
        function pan(e) {
            if (!pz.pan.mousedown) {
                return;
            }
            var tr = pz.transform = self.transform();
            var diffX = pz.pan.fPos.x - pz.pan.iPos.x;
            var diffY = pz.pan.fPos.y - pz.pan.iPos.y;
            pz.setPosition(tr.x + diffX, tr.y + diffY);
            self.node.dispatchEvent(new CustomEvent("pan", e, tr));
        }

        /*!
         * zoom
         * The internal function called for zooming.
         *
         * @name zoom
         * @function
         * @param {Event} e The internal listener event.
         * @return {undefined}
         */
        function zoom (e) {

            // Get the relative mouse point
            var rP = mousePos(e, true);
            var oX = rP.x;
            var oY = rP.y;

            e.deltaY = e.deltaY || e.wheelDeltaY;

            // Compute the new scale
            var d = e.deltaY / 1000;
            var tr = pz.transform = self.transform();
            var scale = tr.scaleX + (tr.scaleX * d);

            var scaleD = scale / tr.scaleX;

            // Get the current x, y
            var currentX = tr.x;
            var currentY = tr.y;

            // Compute the final x, y
            var x = scaleD * (currentX - oX) + oX;
            var y = scaleD * (currentY - oY) + oY;

            // Handle zoom restrictions
            if (scale > opt_options.zoom[1]) {
                scale = opt_options.zoom[1];
                return;
            }

            if (scale < opt_options.zoom[0]) {
                scale = opt_options.zoom[0];
                return;
            }

            // Zoom
            tr.scaleY = tr.scaleX = scale;
            tr.x = x;
            tr.y = y;

            self.node.dispatchEvent(new CustomEvent("zoom", e, tr));
            updateMatrix();

            // Prevent the default browser behavior
            e.preventDefault();
        }

        /*!
         * mousePos
         * Returns the mouse point coordinates.
         *
         * @name mousePos
         * @function
         * @param {Event} e The mouse event.
         * @param {Boolean} rel If `true`, the relative coordinates will be returned instead.
         * @return {Object} An object containing the relative coordinates.
         */
        function mousePos(e, rel) {
            var bbox = self.bbox();
            var abs = {
                x: e.clientX || e.touches[0].pageX,
                y: e.clientY || e.touches[0].pageY
            };
            if (!rel) { return abs; }
            return {
                x: abs.x - bbox.x,
                y: abs.y - bbox.y
            };
        }

        // The event listeners
        var EventListeners = {
            mouse_down: function (e) {
                pz.pan.mousedown = true;
                pz.pan.iPos = mousePos(e);
            },
            mouse_up: function (e) {
                pz.pan.mousedown = false;
                pz.pan.fPos = mousePos(e);
                pan();
            },
            mouse_move: function (e) {
                if (!pz.pan.mousedown) { return; }
                pz.pan.fPos = mousePos(e);
                pan();
            },
            mouse_leave: function (e) {
                pz.pan.mousedown = false;
            }
        };

        // Add event listeners
        rect
          .on(mousewheel, zoom)
          .on("mousedown", EventListeners.mouse_down)
          .on("touchstart", EventListeners.mouse_down)
          .on("mousemove", EventListeners.mouse_move)
          .on("touchmove", EventListeners.mouse_move)
          .on("mouseup", EventListeners.mouse_up)
          .on("touchup", EventListeners.mouse_up)
          .on("mouseleave", EventListeners.mouse_leave)
          ;

        self.on(mousewheel, zoom);
        return pz;
    }

    // Extend the SVG.Element with the new function
    SVG.extend(SVG.Element, {
        panZoom: panZoom
    });
}).call(this);
<|endoftext|>


<commit_before>'use strict';
var defaults = {
	options: {
		preserveComments: 'some'
	}
};

function uglifyTask(gulp, config, stream) {
	var rename = require('gulp-rename'),
		uglify = require('gulp-uglify');

	if (!stream) {
		stream = gulp.src(config.src.globs, config.src.options);
	}

	if (!config.debug) {
		stream = stream.pipe(uglify(config.options));
	}

	// TODO: determine when to write file:
	//    1.only if config.file exist? but if user don't want to rename?
	//    2.only if config.dest exist? but config.dest usally set globally.
	if (config.file) {
		stream = stream.pipe(rename(config.file))
			.pipe(gulp.dest(config.dest.path, config.dest.options));
	}

	return stream;
}

uglifyTask.description = '';
uglifyTask.consumes = ['dest', 'file', 'options', 'src'];
uglifyTask.defaults = defaults;

module.exports = uglifyTask;
<commit_msg>add schema for uglify<commit_after>'use strict';

function uglifyTask(gulp, config, stream) {
	var rename = require('gulp-rename'),
		uglify = require('gulp-uglify');

	if (!stream) {
		stream = gulp.src(config.src.globs, config.src.options);
	}

	if (!config.debug) {
		stream = stream.pipe(uglify(config.options));
	}

	// TODO: determine when to write file:
	//    1.only if config.file exist? but if user don't want to rename?
	//    2.only if config.dest exist? but config.dest usally set globally.
	if (config.file) {
		stream = stream.pipe(rename(config.file))
			.pipe(gulp.dest(config.dest.path, config.dest.options));
	}

	return stream;
}

uglifyTask.displayName = 'uglify';
uglifyTask.description = '';
uglifyTask.schema = {
	"properties": {
		"src": {
			"description": ""
		},
		"dest": {
			"description": ""
		},
		"file": {
			"description": "",
			"type": "string"
		},
		"options": {
			"description": "",
			"properties": {
				"preserveComments": {
					"description": "",
					"type": "string",
					"default": "some"
				}
			}
		}
	},
	"required": ["src", "dest", "file"]
};

module.exports = uglifyTask;
<|endoftext|>


<commit_before>
// ================================================================
// ==  Mocks config info obtained at:                            ==
// ==  http://rest.server.location/config.js                     ==
// ================================================================

//var restHbGeoApiUrl = "http://localhost:9000/api/melfin/" ;
//var restHbGeoApiUrl = "http://localhost:9001/api/hb/geo/" ;
//DIRECT TRANFORMATION FROM 1903 <=> WGS84
//
// 1903 => WGS84
//http://geodesy.geo.admin.ch/reframe/lv03towgs84?easting=561440.184310663&northing=204769.044093776&format=json
//{"easting": "6.931704420427172", "northing": "46.992859388431334"}
//
// WGS84 => 1903
//http://geodesy.geo.admin.ch/reframe/wgs84tolv03?easting=6.931704420427172&northing=46.992859388431334&format=json
//{"easting": "561440.1848373807", "northing": "204769.04525083603"}

//var restHbGeoApiUrl = "http://geodesy.geo.admin.ch/reframe/" ;

// http://localhost:9000/coordinates/gps/561440.184310663/204769.044093776/0.0
// http://localhost:9000/coordinates/swiss/6.870381148/46.750418879/526.55
var restHbGeoApiUrl = "http://localhost:9000/" ;

var clientDebugEnabled = true;
<commit_msg>Default changed to 9001<commit_after>
// ================================================================
// ==  Mocks config info obtained at:                            ==
// ==  http://rest.server.location/config.js                     ==
// ================================================================

//var restHbGeoApiUrl = "http://localhost:9000/api/melfin/" ;
//var restHbGeoApiUrl = "http://localhost:9001/api/hb/geo/" ;
//DIRECT TRANFORMATION FROM 1903 <=> WGS84
//
// 1903 => WGS84
//http://geodesy.geo.admin.ch/reframe/lv03towgs84?easting=561440.184310663&northing=204769.044093776&format=json
//{"easting": "6.931704420427172", "northing": "46.992859388431334"}
//
// WGS84 => 1903
//http://geodesy.geo.admin.ch/reframe/wgs84tolv03?easting=6.931704420427172&northing=46.992859388431334&format=json
//{"easting": "561440.1848373807", "northing": "204769.04525083603"}

//var restHbGeoApiUrl = "http://geodesy.geo.admin.ch/reframe/" ;

// http://localhost:9000/coordinates/gps/561440.184310663/204769.044093776/0.0
// http://localhost:9000/coordinates/swiss/6.870381148/46.750418879/526.55
var restHbGeoApiUrl = "http://localhost:9001/" ;

var clientDebugEnabled = true;
<|endoftext|>


<commit_before><commit_msg>fix ScrollView.scrollWithoutAnimationTo bug<commit_after><|endoftext|>


<commit_before>var chai = require('chai');
var expect = chai.expect;

describe('Client', function() {
  //Add subsections
});<commit_msg>Add several tests for handlers.js, getRoutes()<commit_after>var chai = require('chai');
var expect = chai.expect;

describe('Client', function() {

  describe('handlers.js', function() {
    var handlers = require('../server/handlers.js');

    describe('getRoutes', function() {

      it('should be a function', function() {
        expect(handlers.getRoutes).to.be.a('function');
      });

      /**
       * Add these tests:
       * it should take two strings
       * it should return a promise that contains path data
       * it should query a string properly
       * it should provide all the required props to a ajax req
       * it should throw an error upon ajax failure
       */
    });

    describe('submit', function() {
      it('should be a function', function() {
        expect(handlers.getRoutes).to.be.a('function');
      })
    });
  });

  //Add more subsections
});<|endoftext|>


<commit_before>import Fonts from './fonts';
import Colors from './colors';

export default {
  appContainer: {
    backgroundColor: '#000',
  },
  navbar: {
    backgroundColor: Colors.brand.primary,
    borderBottomWidth: 0,
  },
  navbarTitle: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontFamily: Fonts.base.family,
    fontSize: Fonts.base.size,
  },
  navbarButton: {
    tintColor: '#ffffff',
  },
  tabbar: {
    backgroundColor: Colors.tabbar.background,
    borderTopColor: Colors.border,
    borderTopWidth: 1,
  },
};
<commit_msg>add discover component use style to styles.js.<commit_after>import { Platform } from 'react-native';
import Fonts from './fonts';
import Colors from './colors';

export default {
  appContainer: {
    backgroundColor: '#000',
  },
  navbar: {
    backgroundColor: Colors.brand.primary,
    borderBottomWidth: 0,
  },
  navbarTitle: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontFamily: Fonts.base.family,
    fontSize: Fonts.base.size,
  },
  navbarButton: {
    tintColor: '#ffffff',
  },
  tabbar: {
    backgroundColor: Colors.tabbar.background,
    borderTopColor: Colors.border,
    borderTopWidth: 1,
  },
  discoverParentStyle: {
    flex: 1,
    paddingLeft: 15,
    paddingRight: 15,
  },
  discoverTitle: {
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  discoverTextColor: {
    color: '#03a9f4',
  },
  discoverFirstGrid: {
    flex: 2,
    flexDirection: 'row',
  },
  discoverOtherGrid: {
    flex: 2,
    flexDirection: 'row',
    marginTop: 15,
  },
  discoverGridFirstItem: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 15,
  },
  discoverGrideItem: {
    color: '#333',
    ...Platform.select({
      ios: {
        marginTop: 10,
      },
      android: {
        marginTop: -15,
      },
    }),
  },
  discoverGridLastItem: {
    flex: 1,
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
  },
};
<|endoftext|>


<commit_before>/* Unicode Julian calendar date string generation functions
	Character set is UTF-8
Julian date string generation functions using Unicode tools.
	This code, to be manually imported, set properties to object Intl.DateTimeFormat, in order to generate Julian calendar date strings
	using Intl.DateTimeFormat.prototype.
Versions
	M2018-11-11 Initiate from UnicodeMilesianFormat, separate and comment
Contents
	-- unicodeCalendarHandled (calendar) : from a requested calendar, gives the effectively used one.
	-- toLocalDate : return a Date object holding the date shifted by the time zone offset of a given Unicode (IANA) time zone.
	Intl.DateTimeFormat.prototype.julianFormatToParts  : return elements of string with date and time, according to DateTimeFormat.
	Intl.DateTimeFormat.prototype.julianFormat : : return a string with date and time, according to DateTimeFormat.
Required:
	JulianDateProperties (and dependent file CBCCE)
	toLocalDate (working version on UnicodeMilesianFormat, to be transferred to some other file.)
	Intl object with FormatToParts
*/
/* Copyright Miletus 2018 - Louis A. de Fouquières
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sub-license, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
	1. The above copyright notice and this permission notice shall be included
	in all copies or substantial portions of the Software.
	2. Changes with respect to any former version shall be documented.

The software is provided "as is", without warranty of any kind,
express of implied, including but not limited to the warranties of
merchantability, fitness for a particular purpose and non infringement.
In no event shall the authors of copyright holders be liable for any
claim, damages or other liability, whether in an action of contract,
tort or otherwise, arising from, out of or in connection with the software
or the use or other dealings in the software.
Inquiries: www.calendriermilesien.org
*/
/** @description FormatToParts that issues parts of a Julian calendar date.
 * @param {Date object} myDate - the date to display, like for standard FormatToParts method.
 * @returns {Object} same object structure than for FormatToParts method.
*/
Intl.DateTimeFormat.prototype.julianFormatToParts = function (myDate, eraIfNeeded = true) { // Give formatted elements of a Julian calendar date.
	// This function works only if .formatToParts is provided, else an error is thrown.
	// .formatToParts helps it to have the same order and separator as with a Gregorian date expression.
	// eraIfNeeded means: put only BC era, in "narrow" option if "era" is undefined.
	var
		locale = this.resolvedOptions().locale,	// Fetch the locale from this
		lang = locale.includes("-") ? locale.substring (0,locale.indexOf("-")) : locale;	// the pure language identifier, without country
	// Change the calendar of locale to "gregory"
	locale = (locale.includes("-u-")
		? 	(locale.substring(locale.indexOf("-u-")).includes("ca-")
				? locale.substring (0,locale.indexOf("ca-",locale.indexOf("-u-")))
				: locale )
			+ "ca-"
		: locale + "-u-ca-"
		) + "gregory" ;
	var
		constructOptions = new Intl.DateTimeFormat(locale,this.resolvedOptions()),
		referenceOptions = constructOptions.resolvedOptions();
	try	{
		let referenceComponents = constructOptions.formatToParts (myDate); // Implementations which do not accept this function will throw an error
		let TZ = referenceOptions.timeZone;	// Used time zone. In some cases, "undefined" is given, meaning system time zone.
		var julianComponents = (TZ == undefined
			? myDate.getJulianDate()	// system local date, expressed in Julian
			: julianComponents = toLocalDate(myDate, TZ).localDate.getUTCJulianDate() ); // TZ local date.
		// Here julianComponents holds the local Julian date figures, we replace the Gregorian date, month, year and era components with those.
		// The trick is this: we construct the date and month with the Gregorian date that uses the Julian figures,
		// then we insert the right year and era, computed separately.
		var
			gregDate = new Date (Date.UTC(2000, julianComponents.month, julianComponents.date)),
			BC = (julianComponents.year <= 0),
			eraOption = (BC ? (referenceOptions.era == undefined ? 'narrow' : referenceOptions.era) : referenceOptions.era);
		if (eraOption != null) referenceOptions.era = eraOption; // add eraOption if required
		constructOptions = new Intl.DateTimeFormat(locale,referenceOptions); // Re-construct formatting object
		referenceComponents = constructOptions.formatToParts (myDate);		// and re-construct array of parts
		var eraDate = new Date (0); eraDate.setUTCFullYear(julianComponents.year); // Hold the "era" part

		return referenceComponents.map ( ({type, value}) => {
			switch (type) {
				case "era" : case "year" : return {type:type,
						value: constructOptions.formatToParts(eraDate).find(item => item.type == type).value}
				case "month" : case "day" : return {type:type,
						value: constructOptions.formatToParts(gregDate).find(item => item.type == type).value}
				default : return {type: type, value: value};
				}
			});	// End of mapping function
		}	// end of try
	catch (e) {
		throw e; // Error to be handled by caller, but do not stop working.
		}
}
/** @description a .format method that issues a string representing a Julian calendar date.
 * @param {Date object} myDate - the date to display, like for standard FormatToParts method.
 * @returns {string} the date following the Unicode options
*/
Intl.DateTimeFormat.prototype.julianFormat = function (myDate) {
	// First, try using FormatToParts
	try {
		let parts = this.julianFormatToParts (myDate); // Compute components
		return parts.map(({type, value}) => {return value;}).reduce((buf, part)=> buf + part, "");
		}
	// FormatToParts does not work -> just leave an error message
	catch (e) { // just catch and continue
		alert (milesianAlertMsg ('browserError'))
	}
}<commit_msg>Suppress alert<commit_after>/* Unicode Julian calendar date string generation functions
	Character set is UTF-8
Julian date string generation functions using Unicode tools.
	This code, to be manually imported, set properties to object Intl.DateTimeFormat, in order to generate Julian calendar date strings
	using Intl.DateTimeFormat.prototype.
Versions
	M2018-11-11 Initiate from UnicodeMilesianFormat, separate and comment
	M2018-11-14 instead of alerting, return an error message as result if FormatToParts not implemented
Contents
	-- unicodeCalendarHandled (calendar) : from a requested calendar, gives the effectively used one.
	-- toLocalDate : return a Date object holding the date shifted by the time zone offset of a given Unicode (IANA) time zone.
	Intl.DateTimeFormat.prototype.julianFormatToParts  : return elements of string with date and time, according to DateTimeFormat.
	Intl.DateTimeFormat.prototype.julianFormat : : return a string with date and time, according to DateTimeFormat.
Required:
	JulianDateProperties (and dependent file CBCCE)
	toLocalDate (working version on UnicodeMilesianFormat, to be transferred to some other file.)
	Intl object with FormatToParts
*/
/* Copyright Miletus 2018 - Louis A. de Fouquières
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sub-license, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
	1. The above copyright notice and this permission notice shall be included
	in all copies or substantial portions of the Software.
	2. Changes with respect to any former version shall be documented.

The software is provided "as is", without warranty of any kind,
express of implied, including but not limited to the warranties of
merchantability, fitness for a particular purpose and non infringement.
In no event shall the authors of copyright holders be liable for any
claim, damages or other liability, whether in an action of contract,
tort or otherwise, arising from, out of or in connection with the software
or the use or other dealings in the software.
Inquiries: www.calendriermilesien.org
*/
/** @description FormatToParts that issues parts of a Julian calendar date.
 * @param {Date object} myDate - the date to display, like for standard FormatToParts method.
 * @returns {Object} same object structure than for FormatToParts method.
*/
Intl.DateTimeFormat.prototype.julianFormatToParts = function (myDate, eraIfNeeded = true) { // Give formatted elements of a Julian calendar date.
	// This function works only if .formatToParts is provided, else an error is thrown.
	// .formatToParts helps it to have the same order and separator as with a Gregorian date expression.
	// eraIfNeeded means: put only BC era, in "narrow" option if "era" is undefined.
	var
		locale = this.resolvedOptions().locale,	// Fetch the locale from this
		lang = locale.includes("-") ? locale.substring (0,locale.indexOf("-")) : locale;	// the pure language identifier, without country
	// Change the calendar of locale to "gregory"
	locale = (locale.includes("-u-")
		? 	(locale.substring(locale.indexOf("-u-")).includes("ca-")
				? locale.substring (0,locale.indexOf("ca-",locale.indexOf("-u-")))
				: locale )
			+ "ca-"
		: locale + "-u-ca-"
		) + "gregory" ;
	var
		constructOptions = new Intl.DateTimeFormat(locale,this.resolvedOptions()),
		referenceOptions = constructOptions.resolvedOptions();
	try	{
		let referenceComponents = constructOptions.formatToParts (myDate); // Implementations which do not accept this function will throw an error
		let TZ = referenceOptions.timeZone;	// Used time zone. In some cases, "undefined" is given, meaning system time zone.
		var julianComponents = (TZ == undefined
			? myDate.getJulianDate()	// system local date, expressed in Julian
			: julianComponents = toLocalDate(myDate, TZ).localDate.getUTCJulianDate() ); // TZ local date.
		// Here julianComponents holds the local Julian date figures, we replace the Gregorian date, month, year and era components with those.
		// The trick is this: we construct the date and month with the Gregorian date that uses the Julian figures,
		// then we insert the right year and era, computed separately.
		var
			gregDate = new Date (Date.UTC(2000, julianComponents.month, julianComponents.date)),
			BC = (julianComponents.year <= 0),
			eraOption = (BC ? (referenceOptions.era == undefined ? 'narrow' : referenceOptions.era) : referenceOptions.era);
		if (eraOption != null) referenceOptions.era = eraOption; // add eraOption if required
		constructOptions = new Intl.DateTimeFormat(locale,referenceOptions); // Re-construct formatting object
		referenceComponents = constructOptions.formatToParts (myDate);		// and re-construct array of parts
		var eraDate = new Date (0); eraDate.setUTCFullYear(julianComponents.year); // Hold the "era" part

		return referenceComponents.map ( ({type, value}) => {
			switch (type) {
				case "era" : case "year" : return {type:type,
						value: constructOptions.formatToParts(eraDate).find(item => item.type == type).value}
				case "month" : case "day" : return {type:type,
						value: constructOptions.formatToParts(gregDate).find(item => item.type == type).value}
				default : return {type: type, value: value};
				}
			});	// End of mapping function
		}	// end of try
	catch (e) {
		throw e; // Error to be handled by caller, but do not stop working.
		}
}
/** @description a .format method that issues a string representing a Julian calendar date.
 * @param {Date object} myDate - the date to display, like for standard FormatToParts method.
 * @returns {string} the date following the Unicode options
*/
Intl.DateTimeFormat.prototype.julianFormat = function (myDate) {
	// First, try using FormatToParts
	try {
		let parts = this.julianFormatToParts (myDate); // Compute components
		return parts.map(({type, value}) => {return value;}).reduce((buf, part)=> buf + part, "");
		}
	// FormatToParts does not work -> just leave an error message
	catch (e) { // just catch and continue
		return (milesianAlertMsg ('browserError'))
	}
}<|endoftext|>