<commit_before>window.onload = function () {

  //Check if AngularJs and Showdown is defined and only load ng-Showdown if both are present
  if (typeof angular !== 'undefined' && typeof showdown !== 'undefined') {
    (function (module, showdown) {
      'use strict';

      module
        .provider('$showdown', ngShowdown)
        .directive('sdModelToHtml', ['$showdown', '$sanitize', '$sce', sdModelToHtmlDirective]) //<-- DEPRECATED: will be removed in the next major version release
        .directive('markdownToHtml', ['$showdown', '$sanitize', '$sce', markdownToHtmlDirective])
        .filter('sdStripHtml', ['$showdown', stripHtmlFilter]) //<-- DEPRECATED: will be removed in the next major version release
        .filter('stripHtml', ['$showdown', stripHtmlFilter]);

      /**
       * Angular Provider
       * Enables configuration of showdown via angular.config and Dependency Injection into controllers, views
       * directives, etc... This assures the directives and filters provided by the library itself stay consistent
       * with the user configurations.
       * If the user wants to use a different configuration in a determined context, he can use the "classic" Showdown
       * object instead.
       */
      function ngShowdown() {

        // Configuration parameters for Showdown
        var config = {
          extensions: [],
          sanitize: false
        };

        /**
         * Sets a configuration option
         *
         * @param {string} key Config parameter key
         * @param {string} value Config parameter value
         */
        /* jshint validthis: true */
        this.setOption = function (key, value) {
          config[key] = value;
          return this;
        };

        /**
         * Gets the value of the configuration parameter specified by key
         *
         * @param {string} key The config parameter key
         * @returns {string|null} Returns the value of the config parameter. (or null if the config parameter is not set)
         */
        this.getOption = function (key) {
          if (config.hasOwnProperty(key)) {
            return config[key];
          } else {
            return undefined;
          }
        };

        /**
         * Loads a Showdown Extension
         *
         * @param {string} extensionName The name of the extension to load
         */
        this.loadExtension = function (extensionName) {
          config.extensions.push(extensionName);

          return this;
        };

        function SDObject() {
          var converter = new showdown.Converter(config);

          /**
           * Converts a markdown text into HTML
           *
           * @param {string} markdown The markdown string to be converted to HTML
           * @returns {string} The converted HTML
           */
          this.makeHtml = function (markdown) {
            return converter.makeHtml(markdown);
          };

          /**
           * Strips a text of it's HTML tags. See http://stackoverflow.com/questions/17289448/angularjs-to-output-plain-text-instead-of-html
           *
           * @param {string} text
           * @returns {string}
           */
          this.stripHtml = function (text) {
            return String(text).replace(/<[^>]+>/gm, '');
          };

          /**
           * Gets the value of the configuration parameter of CONVERTER specified by key
           * @param {string} key The config parameter key
           * @returns {*}
           */
          this.getOption = function (key) {
            return converter.getOption(key);
          };

          /**
           * Gets the converter configuration params
           * @returns {*}
           */
          this.getOptions = function () {
            return converter.getOptions();
          };

          /**
           * Sets a configuration option
           *
           * @param {string} key Config parameter key
           * @param {string} value Config parameter value
           * @returns {SDObject}
           */
          this.setOption = function (key, value) {
            converter.setOption(key, value);
            return this;
          };
        }

        // The object returned by service provider
        this.$get = function () {
          return new SDObject();
        };
      }

      /**
       * @deprecated
       * Legacy AngularJS Directive to Md to HTML transformation
       *
       * Usage example:
       *

       *
       * @param {showdown.Converter} $showdown
       * @param {$sanitize} $sanitize
       * @param {$sce} $sce
       * @returns {*}
       */
      function sdModelToHtmlDirective($showdown, $sanitize, $sce) {
        return {
          restrict: 'A',
          link: getLinkFn($showdown, $sanitize, $sce),
          scope: {
            model: '=sdModelToHtml'
          },
          template: '

'
        };
      }

      /**
       * AngularJS Directive to Md to HTML transformation
       *
       * Usage example:
       *

       *
       * @param {showdown.Converter} $showdown
       * @param {$sanitize} $sanitize
       * @param {$sce} $sce
       * @returns {*}
       */
      function markdownToHtmlDirective($showdown, $sanitize, $sce) {
        return {
          restrict: 'A',
          link: getLinkFn($showdown, $sanitize, $sce),
          scope: {
            model: '=markdownToHtml'
          },
          template: '

'
        };
      }

      function getLinkFn($showdown, $sanitize, $sce) {
        return function (scope, element, attrs) {
          scope.$watch('model', function (newValue) {
            var showdownHTML;
            if (typeof newValue === 'string') {
              showdownHTML = $showdown.makeHtml(newValue);
              scope.trustedHtml = ($showdown.getOption('sanitize')) ? $sanitize(showdownHTML) : $sce.trustAsHtml(showdownHTML);
            } else {
              scope.trustedHtml = typeof newValue;
            }
          });
        };
      }

      /**
       * AngularJS Filter to Strip HTML tags from text
       *
       * @returns {Function}
       */
      function stripHtmlFilter($showdown) {
        return function (text) {
          return $showdown.stripHtml(text);
        };
      }

    })(angular.module('ng-showdown', ['ngSanitize']), showdown);

  } else {
    document.cookie = 'version=develop';
    throw new Error('ng-showdown was not loaded because one of its dependencies (AngularJS or Showdown) was not met');
  }

  var app = angular.module('showdown.editor', ['ng-showdown', 'pageslide-directive', 'ngAnimate', 'ngRoute', 'ngCookies']);

  app.directive('squeeze', ['$animate', function ($animate) {
    return {
      link: function (scope, element, attrs) {
        scope.$watch('checked', function (newValue) {
          if (!scope.firstLoad) {
            if (newValue) {
              $animate.addClass(element, 'squeezed-body');
              element.removeClass('full-body');
            } else {
              $animate.addClass(element, 'full-body');
              element.removeClass('squeezed-body');
            }
          }
        });
      }
    };
  }]);

  app.controller('editorCtrl', ['$scope', '$showdown', '$http', '$cookies', function ($scope, $showdown, $http, $cookies) {

    var hack = true;

    $scope.versions = ['develop', 'master'];
    $scope.version = $cookies.get('version') || 'develop';
    $scope.showModal = false;
    $scope.hashTxt = '';
    $scope.checked = false;
    $scope.firstLoad = true;
    $scope.text = '';

    $scope.checkOpts = $cookies.getObject('checkOpts') || [
        {name: 'omitExtraWLInCodeBlocks', value: true},
        {name: 'noHeaderId', value: false},
        {name: 'parseImgDimensions', value: true},
        {name: 'simplifiedAutoLink', value: true},
        {name: 'literalMidWordUnderscores', value: true},
        {name: 'strikethrough', value: true},
        {name: 'tables', value: true},
        {name: 'tablesHeaderId', value: false},
        {name: 'ghCodeBlocks', value: true},
        {name: 'tasklists', value: true},
        {name: 'smoothLivePreview', value: true},
        {name: 'prefixHeaderId', value: false}
      ];

    $scope.valOpts = $cookies.getObject('valOpts') || [
        {name: 'headerLevelStart', value: 3}
      ];

    $scope.toggleMenu = function () {
      $scope.firstLoad = false;
      $scope.checked = !$scope.checked;
    };

    $scope.getHash = function () {
      $scope.hashTxt = document.location.origin + document.location.pathname + '#/' + encodeURIComponent($scope.text);
      $scope.showModal = true;
    };

    $scope.closeModal = function () {
      $scope.showModal = false;
    };

    $scope.loadVersion = function () {
      $cookies.put('version', $scope.version);
      sessionStorage.setItem("text", $scope.text);
      location.reload();
    };

    $scope.updateOptions = function () {
      for (var i = 0; i < $scope.checkOpts.length; ++i) {
        $showdown.setOption($scope.checkOpts[i].name, $scope.checkOpts[i].value);
      }

      for (i = 0; i < $scope.valOpts.length; ++i) {
        if ($scope.valOpts[i].name === 'headerLevelStart') {
          if (isNaN($scope.valOpts[i].value) || $scope.valOpts[i].value < 1) {
            $scope.valOpts[i].value = 1;
          } else if ($scope.valOpts[i].value > 6) {
            $scope.valOpts[i].value = 6;
          }
        }
        $showdown.setOption($scope.valOpts[i].name, $scope.valOpts[i].value);
      }

      // trigger text repaint (hackish way)
      $scope.text = $scope.text.replace(/\u200B/, '');
      if (hack) {
        $scope.text = '\u200B' + $scope.text;
      } else {
        $scope.text = $scope.text + '\u200B';
      }

      hack = !hack;
      $cookies.putObject('checkOpts', $scope.checkOpts);
      $cookies.putObject('valOpts', $scope.valOpts);
    };

    //load available versions
    $http.get('https://api.github.com/repos/showdownjs/showdown/releases')
      .then(
      function (response) {
        for (var i = 0; i < response.data.length; ++i) {
          if (compareVersions(response.data[i].tag_name, '1.0.0') >= 0) {
            $scope.versions.push(response.data[i].tag_name);
          }
        }
      },
      function (error) {
        console.error('Error retrieving versions', error);
      }
    );

    $scope.updateOptions();

    // get text from URL or load the default text
    if (window.location.hash) {
      var hashText = window.location.hash.replace(/^#(\/)?/, '');
      hashText = decodeURIComponent(hashText);
      $scope.text = hashText;
    } else if (sessionStorage.getItem('text')) {
      $scope.text = sessionStorage.getItem('text');
    } else {
      $http.get('md/text.md')
        .success(function (data) {
					$scope.text = data;
					$http.get('//raw.githubusercontent.com/wiki/showdownjs/showdown/Showdown\'s-Markdown-syntax.md')
						.success(function (data2) {
							$scope.text = $scope.text + '\n\n' + data2;
						});
        })
        .error(function () {
          $scope.text = '';
        });
    }

  }]);

  angular.bootstrap(document, ['showdown.editor']);
};<commit_msg>add latest options to demo<commit_after>window.onload = function () {

  //Check if AngularJs and Showdown is defined and only load ng-Showdown if both are present
  if (typeof angular !== 'undefined' && typeof showdown !== 'undefined') {
    (function (module, showdown) {
      'use strict';

      module
        .provider('$showdown', ngShowdown)
        .directive('sdModelToHtml', ['$showdown', '$sanitize', '$sce', sdModelToHtmlDirective]) //<-- DEPRECATED: will be removed in the next major version release
        .directive('markdownToHtml', ['$showdown', '$sanitize', '$sce', markdownToHtmlDirective])
        .filter('sdStripHtml', ['$showdown', stripHtmlFilter]) //<-- DEPRECATED: will be removed in the next major version release
        .filter('stripHtml', ['$showdown', stripHtmlFilter]);

      /**
       * Angular Provider
       * Enables configuration of showdown via angular.config and Dependency Injection into controllers, views
       * directives, etc... This assures the directives and filters provided by the library itself stay consistent
       * with the user configurations.
       * If the user wants to use a different configuration in a determined context, he can use the "classic" Showdown
       * object instead.
       */
      function ngShowdown() {

        // Configuration parameters for Showdown
        var config = {
          extensions: [],
          sanitize: false
        };

        /**
         * Sets a configuration option
         *
         * @param {string} key Config parameter key
         * @param {string} value Config parameter value
         */
        /* jshint validthis: true */
        this.setOption = function (key, value) {
          config[key] = value;
          return this;
        };

        /**
         * Gets the value of the configuration parameter specified by key
         *
         * @param {string} key The config parameter key
         * @returns {string|null} Returns the value of the config parameter. (or null if the config parameter is not set)
         */
        this.getOption = function (key) {
          if (config.hasOwnProperty(key)) {
            return config[key];
          } else {
            return undefined;
          }
        };

        /**
         * Loads a Showdown Extension
         *
         * @param {string} extensionName The name of the extension to load
         */
        this.loadExtension = function (extensionName) {
          config.extensions.push(extensionName);

          return this;
        };

        function SDObject() {
          var converter = new showdown.Converter(config);

          /**
           * Converts a markdown text into HTML
           *
           * @param {string} markdown The markdown string to be converted to HTML
           * @returns {string} The converted HTML
           */
          this.makeHtml = function (markdown) {
            return converter.makeHtml(markdown);
          };

          /**
           * Strips a text of it's HTML tags. See http://stackoverflow.com/questions/17289448/angularjs-to-output-plain-text-instead-of-html
           *
           * @param {string} text
           * @returns {string}
           */
          this.stripHtml = function (text) {
            return String(text).replace(/<[^>]+>/gm, '');
          };

          /**
           * Gets the value of the configuration parameter of CONVERTER specified by key
           * @param {string} key The config parameter key
           * @returns {*}
           */
          this.getOption = function (key) {
            return converter.getOption(key);
          };

          /**
           * Gets the converter configuration params
           * @returns {*}
           */
          this.getOptions = function () {
            return converter.getOptions();
          };

          /**
           * Sets a configuration option
           *
           * @param {string} key Config parameter key
           * @param {string} value Config parameter value
           * @returns {SDObject}
           */
          this.setOption = function (key, value) {
            converter.setOption(key, value);
            return this;
          };
        }

        // The object returned by service provider
        this.$get = function () {
          return new SDObject();
        };
      }

      /**
       * @deprecated
       * Legacy AngularJS Directive to Md to HTML transformation
       *
       * Usage example:
       *

       *
       * @param {showdown.Converter} $showdown
       * @param {$sanitize} $sanitize
       * @param {$sce} $sce
       * @returns {*}
       */
      function sdModelToHtmlDirective($showdown, $sanitize, $sce) {
        return {
          restrict: 'A',
          link: getLinkFn($showdown, $sanitize, $sce),
          scope: {
            model: '=sdModelToHtml'
          },
          template: '

'
        };
      }

      /**
       * AngularJS Directive to Md to HTML transformation
       *
       * Usage example:
       *

       *
       * @param {showdown.Converter} $showdown
       * @param {$sanitize} $sanitize
       * @param {$sce} $sce
       * @returns {*}
       */
      function markdownToHtmlDirective($showdown, $sanitize, $sce) {
        return {
          restrict: 'A',
          link: getLinkFn($showdown, $sanitize, $sce),
          scope: {
            model: '=markdownToHtml'
          },
          template: '

'
        };
      }

      function getLinkFn($showdown, $sanitize, $sce) {
        return function (scope, element, attrs) {
          scope.$watch('model', function (newValue) {
            var showdownHTML;
            if (typeof newValue === 'string') {
              showdownHTML = $showdown.makeHtml(newValue);
              scope.trustedHtml = ($showdown.getOption('sanitize')) ? $sanitize(showdownHTML) : $sce.trustAsHtml(showdownHTML);
            } else {
              scope.trustedHtml = typeof newValue;
            }
          });
        };
      }

      /**
       * AngularJS Filter to Strip HTML tags from text
       *
       * @returns {Function}
       */
      function stripHtmlFilter($showdown) {
        return function (text) {
          return $showdown.stripHtml(text);
        };
      }

    })(angular.module('ng-showdown', ['ngSanitize']), showdown);

  } else {
    document.cookie = 'version=develop';
    throw new Error('ng-showdown was not loaded because one of its dependencies (AngularJS or Showdown) was not met');
  }

  var app = angular.module('showdown.editor', ['ng-showdown', 'pageslide-directive', 'ngAnimate', 'ngRoute', 'ngCookies']);

  app.directive('squeeze', ['$animate', function ($animate) {
    return {
      link: function (scope, element, attrs) {
        scope.$watch('checked', function (newValue) {
          if (!scope.firstLoad) {
            if (newValue) {
              $animate.addClass(element, 'squeezed-body');
              element.removeClass('full-body');
            } else {
              $animate.addClass(element, 'full-body');
              element.removeClass('squeezed-body');
            }
          }
        });
      }
    };
  }]);

  app.controller('editorCtrl', ['$scope', '$showdown', '$http', '$cookies', function ($scope, $showdown, $http, $cookies) {

    var hack = true;

    $scope.versions = ['develop', 'master'];
    $scope.version = $cookies.get('version') || 'develop';
    $scope.showModal = false;
    $scope.hashTxt = '';
    $scope.checked = false;
    $scope.firstLoad = true;
    $scope.text = '';

		var savedCheckOpts = $cookies.getObject('checkOpts') || [];
    $scope.checkOpts = [
        {name: 'omitExtraWLInCodeBlocks', value: true},
        {name: 'noHeaderId', value: false},
        {name: 'parseImgDimensions', value: true},
        {name: 'simplifiedAutoLink', value: true},
        {name: 'literalMidWordUnderscores', value: true},
        {name: 'strikethrough', value: true},
        {name: 'tables', value: true},
        {name: 'tablesHeaderId', value: false},
        {name: 'ghCodeBlocks', value: true},
        {name: 'tasklists', value: true},
        {name: 'smoothLivePreview', value: true},
        {name: 'prefixHeaderId', value: false},
        {name: 'disableForced4SpacesIndentedSublists', value: false}
      ];

		for (var i = 0; i < $scope.checkOpts.length; ++i) {
			for (var ii = 0; ii < savedCheckOpts.length; ++ii) {
				if ($scope.checkOpts[i].name === savedCheckOpts[ii].name) {
					$scope.checkOpts[i].value = savedCheckOpts[ii].value;
					break;
				}
			}
		}

    $scope.valOpts = $cookies.getObject('valOpts') || [
        {name: 'headerLevelStart', value: 3}
      ];

    $scope.toggleMenu = function () {
      $scope.firstLoad = false;
      $scope.checked = !$scope.checked;
    };

    $scope.getHash = function () {
      $scope.hashTxt = document.location.origin + document.location.pathname + '#/' + encodeURIComponent($scope.text);
      $scope.showModal = true;
    };

    $scope.closeModal = function () {
      $scope.showModal = false;
    };

    $scope.loadVersion = function () {
      $cookies.put('version', $scope.version);
      sessionStorage.setItem("text", $scope.text);
      location.reload();
    };

    $scope.updateOptions = function () {
      for (var i = 0; i < $scope.checkOpts.length; ++i) {
        $showdown.setOption($scope.checkOpts[i].name, $scope.checkOpts[i].value);
      }

      for (i = 0; i < $scope.valOpts.length; ++i) {
        if ($scope.valOpts[i].name === 'headerLevelStart') {
          if (isNaN($scope.valOpts[i].value) || $scope.valOpts[i].value < 1) {
            $scope.valOpts[i].value = 1;
          } else if ($scope.valOpts[i].value > 6) {
            $scope.valOpts[i].value = 6;
          }
        }
        $showdown.setOption($scope.valOpts[i].name, $scope.valOpts[i].value);
      }

      // trigger text repaint (hackish way)
      $scope.text = $scope.text.replace(/\u200B/, '');
      if (hack) {
        $scope.text = '\u200B' + $scope.text;
      } else {
        $scope.text = $scope.text + '\u200B';
      }

      hack = !hack;
      $cookies.putObject('checkOpts', $scope.checkOpts);
      $cookies.putObject('valOpts', $scope.valOpts);
    };

    //load available versions
    $http.get('https://api.github.com/repos/showdownjs/showdown/releases')
      .then(
      function (response) {
        for (var i = 0; i < response.data.length; ++i) {
          if (compareVersions(response.data[i].tag_name, '1.0.0') >= 0) {
            $scope.versions.push(response.data[i].tag_name);
          }
        }
      },
      function (error) {
        console.error('Error retrieving versions', error);
      }
    );

    $scope.updateOptions();

    // get text from URL or load the default text
    if (window.location.hash) {
      var hashText = window.location.hash.replace(/^#(\/)?/, '');
      hashText = decodeURIComponent(hashText);
      $scope.text = hashText;
    } else if (sessionStorage.getItem('text')) {
      $scope.text = sessionStorage.getItem('text');
    } else {
      $http.get('md/text.md')
        .success(function (data) {
					$scope.text = data;
					$http.get('//raw.githubusercontent.com/wiki/showdownjs/showdown/Showdown\'s-Markdown-syntax.md')
						.success(function (data2) {
							$scope.text = $scope.text + '\n\n' + data2;
						});
        })
        .error(function () {
          $scope.text = '';
        });
    }

  }]);

  angular.bootstrap(document, ['showdown.editor']);
};<|endoftext|>


<commit_before>angular.
  module('myApp.core', ['ngResource']).
  factory('Contact', ['$resource',
    function($resource) {
      return $resource('http://localhost/api/contacts/:id', {id: ''}, {
        query: {
          method: 'GET',
          isArray: true
        },
        get: {
          method: 'GET'
        },
        insert: {
          method: 'POST'
        },
        update: {
          method: 'PUT'
        },
        delete: {
          method: 'DELETE'
        },
        favorite: {
          url: 'http://localhost/api/contacts/:id/favorite',
          method: 'PUT'
        }
      });
    }
  ]);<commit_msg>Add service patch method<commit_after>angular.
  module('myApp.core', ['ngResource']).
  factory('Contact', ['$resource',
    function($resource) {
      return $resource('http://localhost/api/contacts/:id', {id: ''}, {
        query: {
          method: 'GET',
          isArray: true
        },
        get: {
          method: 'GET'
        },
        insert: {
          method: 'POST'
        },
        update: {
          method: 'PUT'
        },
        delete: {
          method: 'DELETE'
        },
        favorite: {
         // url: 'http://localhost/api/contacts/:id/favorite',
          method: 'PATCH'
        }
      });
    }
  ]);<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.6.2
(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  define(function(require) {
    var $, Errors, Header, Items, Keys, Properties, Signals, TimeIndicator, Timeline, Utils, d3, extend;

    $ = require('jquery');
    d3 = require('d3');
    Signals = require('Signal');
    Utils = require('cs!core/Utils');
    Header = require('cs!graph/Header');
    TimeIndicator = require('cs!graph/TimeIndicator');
    Items = require('cs!graph/Items');
    Properties = require('cs!graph/Properties');
    Keys = require('cs!graph/Keys');
    Errors = require('cs!graph/Errors');
    extend = function(object, properties) {
      var key, val;

      for (key in properties) {
        val = properties[key];
        object[key] = val;
      }
      return object;
    };
    return Timeline = (function() {
      function Timeline(tweenTime, selectionManager) {
        var height, margin, self, width,
          _this = this;

        this.tweenTime = tweenTime;
        this.selectionManager = selectionManager;
        this.render = __bind(this.render, this);
        this.isDirty = true;
        this.onSelect = new Signals.Signal();
        this.timer = this.tweenTime.timer;
        this.currentTime = this.timer.time;
        this.initialDomain = [0, this.timer.totalDuration - 220 * 1000];
        margin = {
          top: 6,
          right: 20,
          bottom: 0,
          left: 190
        };
        this.margin = margin;
        width = window.innerWidth - margin.left - margin.right;
        height = 270 - margin.top - margin.bottom - 40;
        this.lineHeight = 20;
        this.label_position_x = -170;
        this.x = d3.time.scale().range([0, width]);
        this.x.domain(this.initialDomain);
        this.xAxis = d3.svg.axis().scale(this.x).orient("top").tickSize(-height, 0).tickFormat(Utils.formatMinutes);
        this.svg = d3.select('.timeline__main').append("svg").attr("width", width + margin.left + margin.right).attr("height", 600);
        this.svgContainer = this.svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
        this.svgContainerTime = this.svg.append("g").attr("transform", "translate(" + margin.left + ",0)");
        this.linesContainer = this.svg.append("g").attr("transform", "translate(" + margin.left + "," + (margin.top + 10) + ")");
        this.header = new Header(this.timer, this.initialDomain, this.tweenTime, width);
        this.timeIndicator = new TimeIndicator(this, this.svgContainerTime);
        self = this;
        console.log(this.linesContainer);
        this.linesContainer.on("mousedown", function() {
          var p;

          p = d3.mouse(this);
          return self.linesContainer.append('rect').attr({
            rx: 6,
            ry: 6,
            "class": 'selection',
            x: p[0],
            y: p[1],
            width: 0,
            height: 0
          });
        }).on("mousemove", function() {
          var containerBounding, d, move, p, s;

          s = self.linesContainer.select('.selection');
          if (s.empty()) {
            return;
          }
          p = d3.mouse(this);
          d = {
            x: parseInt(s.attr('x'), 10),
            y: parseInt(s.attr('y'), 10),
            width: parseInt(s.attr('width'), 10),
            height: parseInt(s.attr('height'), 10)
          };
          move = {
            x: p[0] - d.x,
            y: p[1] - d.y
          };
          if (move.x < 1 || move.x * 2 < d.width) {
            d.x = p[0];
            d.width -= move.x;
          } else {
            d.width = move.x;
          }
          if (move.y < 1 || move.y * 2 < d.height) {
            d.y = p[1];
            d.height -= move.y;
          } else {
            d.height = move.y;
          }
          s.attr(d);
          console.log(".......");
          d.timeStart = self.x.invert(d.x).getTime() / 1000;
          d.timeEnd = self.x.invert(d.x + d.width).getTime() / 1000;
          console.log(d);
          containerBounding = self.linesContainer[0][0].getBoundingClientRect();
          d3.selectAll('.key__shape--selected').classed('key__shape--selected', false);
          return d3.selectAll('.key').each(function(state_data, i) {
            var itemBounding, y;

            itemBounding = d3.select(this)[0][0].getBoundingClientRect();
            y = itemBounding.top - containerBounding.top;
            if (state_data.time >= d.timeStart && state_data.time <= d.timeEnd) {
              console.log(y + " / " + d.y);
              if (y >= d.y && y <= d.y + d.height) {
                console.log("ok");
                return console.log(state_data);
              }
            }
          });
        }).on("mouseup", function() {
          return self.linesContainer.selectAll('.selection').remove();
        });
        this.items = new Items(this, this.linesContainer);
        this.items.onUpdate.add(function() {
          return _this.isDirty = true;
        });
        this.items.onSelect.add(function(d) {
          return _this.onSelect.dispatch(d);
        });
        this.properties = new Properties(this);
        this.properties.onKeyAdded.add(function() {
          return _this.isDirty = true;
        });
        this.errors = new Errors(this);
        this.keys = new Keys(this);
        this.keys.onKeyUpdated.add(function() {
          return _this.isDirty = true;
        });
        this.xAxisGrid = d3.svg.axis().scale(this.x).ticks(100).tickSize(-this.items.dy, 0).tickFormat("").orient("top");
        this.xGrid = this.svgContainer.append('g').attr('class', 'x axis grid').attr("transform", "translate(0," + margin.top + ")").call(this.xAxisGrid);
        this.xAxisElement = this.svgContainer.append("g").attr("class", "x axis").attr("transform", "translate(0," + margin.top + ")").call(this.xAxis);
        this.header.onBrush.add(function(extent) {
          _this.x.domain(extent);
          _this.xGrid.call(_this.xAxisGrid);
          _this.xAxisElement.call(_this.xAxis);
          return _this.isDirty = true;
        });
        window.requestAnimationFrame(this.render);
        window.onresize = function() {
          var INNER_WIDTH;

          INNER_WIDTH = window.innerWidth;
          width = INNER_WIDTH - margin.left - margin.right;
          _this.svg.attr("width", width + margin.left + margin.right);
          _this.svg.selectAll('.timeline__right-mask').attr('width', INNER_WIDTH);
          _this.x.range([0, width]);
          _this.xGrid.call(_this.xAxisGrid);
          _this.xAxisElement.call(_this.xAxis);
          return _this.header.resize(INNER_WIDTH);
        };
      }

      Timeline.prototype.render = function(time, time_changed) {
        var bar, height, properties;

        if (this.isDirty || time_changed) {
          this.header.render();
          this.timeIndicator.render();
        }
        if (this.isDirty) {
          bar = this.items.render();
          properties = this.properties.render(bar);
          this.errors.render(properties);
          this.keys.render(properties);
          this.isDirty = false;
          height = Math.max(this.items.dy + 30, 230);
          this.xAxis.tickSize(-height, 0);
          this.xAxisGrid.tickSize(-height, 0);
          this.xGrid.call(this.xAxisGrid);
          this.xAxisElement.call(this.xAxis);
          return this.svg.attr("height", height);
        }
      };

      return Timeline;

    })();
  });

}).call(this);
<commit_msg>remove compiled Timeline.js<commit_after><|endoftext|>


<commit_before>'use strict';

var gulp            = require('gulp'),
    autoprefixer    = require('gulp-autoprefixer'),
    babel           = require("gulp-babel"),
    browserify      = require('gulp-browserify'),
    cssnano         = require('gulp-cssnano'),
    imagemin        = require('gulp-imagemin'),
    jade            = require('gulp-jade'),
    jshint          = require('gulp-jshint'),
    sass            = require('gulp-sass'),
    stylish         = require('jshint-stylish'),
    uglify          = require('gulp-uglify'),
    browserSync     = require('browser-sync').create();

const SRC = './src';
const DIST = './dist';

gulp.task('scripts',() => {
  return gulp.src([SRC+'/js/*.js', '!./node_modules/**', '!./dist/**'])
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter(stylish))
    .pipe(babel())
    .pipe(browserify({
      insertGlobals : true
    }))
    .pipe(uglify())
    .pipe(gulp.dest(DIST+'/src/js'));
});

gulp.task('templates', function() {
  var LOCALS = {};
  gulp.src(['**/*.jade', '!./node_modules/**', '!./dist/**', '!./includes/**'])
    .pipe(jade({
      locals: LOCALS
    }))
    .pipe(gulp.dest(DIST));
});

gulp.task('images', () => {
  return gulp.src([SRC+'/img/**/*', '!./node_modules/**', '!./dist/**'])
    .pipe(imagemin({
      optimizationLevel: 2,
      progressive: true,
      svgoPlugins: [
        {removeViewBox: false},
        {cleanupIDs: false}
      ]}))
    .pipe(gulp.dest(DIST+'/src/img'));
});

gulp.task('sass', () => {
  return gulp.src([SRC+'/scss/**/*.scss', '!./node_modules/**', '!./dist/**'])
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: ['>1%'],
      cascade: false
    }))
    .pipe(cssnano())
    .pipe(gulp.dest(DIST+'/src/css'));
});

gulp.task('copy',() => {
  return gulp.src(['CNAME'])
    .pipe(gulp.dest(DIST));
});

gulp.task('browser-sync', () => {
  browserSync.init({
    server: {
      baseDir: DIST
    }
  });
});

gulp.task('watch',['browser-sync'], () => {
  gulp.watch('CNAME',['copy']);
  gulp.watch('**/*.jade', ['templates']);
  gulp.watch(SRC+'/scss/**/*.scss', ['sass']);
  gulp.watch(SRC+'/js/**/*.js', ['scripts']);
  gulp.watch(SRC+'/img/**/*', ['images']);
});

gulp.task('default', ['sass','scripts','images','templates']);
<commit_msg>change order of scripts<commit_after>'use strict';

var gulp            = require('gulp'),
    autoprefixer    = require('gulp-autoprefixer'),
    babel           = require("gulp-babel"),
    browserify      = require('gulp-browserify'),
    cssnano         = require('gulp-cssnano'),
    imagemin        = require('gulp-imagemin'),
    jade            = require('gulp-jade'),
    jshint          = require('gulp-jshint'),
    sass            = require('gulp-sass'),
    stylish         = require('jshint-stylish'),
    uglify          = require('gulp-uglify'),
    browserSync     = require('browser-sync').create();

const SRC = './src';
const DIST = './dist';

gulp.task('scripts',() => {
  return gulp.src([SRC+'/js/*.js', '!./node_modules/**', '!./dist/**'])
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter(stylish))
    .pipe(babel())
    .pipe(browserify({
      insertGlobals : true
    }))
    .pipe(uglify())
    .pipe(gulp.dest(DIST+'/src/js'));
});

gulp.task('templates', function() {
  var LOCALS = {};
  gulp.src(['**/*.jade', '!./node_modules/**', '!./dist/**', '!./includes/**'])
    .pipe(jade({
      locals: LOCALS
    }))
    .pipe(gulp.dest(DIST));
});

gulp.task('images', () => {
  return gulp.src([SRC+'/img/**/*', '!./node_modules/**', '!./dist/**'])
    .pipe(imagemin({
      optimizationLevel: 2,
      progressive: true,
      svgoPlugins: [
        {removeViewBox: false},
        {cleanupIDs: false}
      ]}))
    .pipe(gulp.dest(DIST+'/src/img'));
});

gulp.task('sass', () => {
  return gulp.src([SRC+'/scss/**/*.scss', '!./node_modules/**', '!./dist/**'])
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: ['>1%'],
      cascade: false
    }))
    .pipe(cssnano())
    .pipe(gulp.dest(DIST+'/src/css'));
});

gulp.task('copy',() => {
  return gulp.src(['CNAME'])
    .pipe(gulp.dest(DIST));
});

gulp.task('browser-sync', () => {
  browserSync.init({
    server: {
      baseDir: DIST
    }
  });
});

gulp.task('watch',['default','browser-sync'], () => {
  gulp.watch('CNAME',['copy']);
  gulp.watch('**/*.jade', ['templates']);
  gulp.watch(SRC+'/scss/**/*.scss', ['sass']);
  gulp.watch(SRC+'/js/**/*.js', ['scripts']);
  gulp.watch(SRC+'/img/**/*', ['images']);
});

gulp.task('default', ['copy','templates','sass','scripts','images']);
<|endoftext|>


<commit_before>var Luc = require('../lib/luc'),
    ie = 'internet explorer',
    ff = 'firefox',
    latestFF = 25,
    s = 'safari',
    ch = 'chrome',
    ip= 'IPHONE',
    an = 'ANDROID',
    op = 'opera',
    browsers;

    module.exports = [];

browsers = {
    XP: [{
        name: ie,
        version: 6
    }, {
        name: ie,
        version: 7
    }, {
        name: ie,
        version: 8
    },{
        name: ff,
        version: 4
    },{
        name: ff,
        version: 3.6
    },{
        name: ff,
        version: 3.5
    }],
    WIN8: [{
        name: ie,
        version: 10
    }, {
        name: ch
    }],
    'WIN8.1': [{
        name: ie,
        version: 11
    }, {
        name: ch
    }],
    'OSX 10.8': [{
        name: s,
        version: 6
    },{
        name: ip,
        version: 6
    },{
        name: ip,
        version: 5
    }],
    'OSX 10.6': [{
        name: s,
        version: 5
    },{
        name: ch
    },{
        name: ip,
        version: 4
    }],
    'linux': [{
        name: an,
        version: 4
    },{
        name: ch
    }],
    'Windows 2008': [{
        version: 12,
        name: op
    }]
};

Luc.Object.each(browsers, function(key, values) {

    Luc.Array.each(values, function(value) {
        var obj = {
            platform: key,
            version: value.version,
            browserName: value.name
        };

        if(obj.version) {
            obj.version += '';
        }
        else {
            delete obj.version;
        }

        module.exports.push(obj);
    });
});<commit_msg>add more ff remove android<commit_after>var Luc = require('../lib/luc'),
    ie = 'internet explorer',
    ff = 'firefox',
    latestFF = 25,
    s = 'safari',
    ch = 'chrome',
    ip= 'IPHONE',
    an = 'ANDROID',
    op = 'opera',
    browsers;

    module.exports = [];

browsers = {
    XP: [{
        name: ie,
        version: 6
    }, {
        name: ie,
        version: 7
    }, {
        name: ie,
        version: 8
    }, {
        name: ff,
        version: 25
    }, {
        name: ff,
        version: 24
    },{
        name: ff,
        version: 4
    },{
        name: ff,
        version: 3.6
    },{
        name: ff,
        version: 3.5
    }],
    WIN8: [{
        name: ie,
        version: 10
    }, {
        name: ch
    }],
    'WIN8.1': [{
        name: ie,
        version: 11
    }, {
        name: ch
    }],
    'OSX 10.8': [{
        name: s,
        version: 6
    },{
        name: ip,
        version: 6
    },{
        name: ip,
        version: 5
    }],
    'OSX 10.6': [{
        name: s,
        version: 5
    },{
        name: ch
    },{
        name: ip,
        version: 4
    }],
    'linux': [/*{
        name: an,
        version: 4
    },*/{
        name: ch
    }],
    'Windows 2008': [{
        version: 12,
        name: op
    }]
};

Luc.Object.each(browsers, function(key, values) {

    Luc.Array.each(values, function(value) {
        var obj = {
            platform: key,
            version: value.version,
            browserName: value.name
        };

        if(obj.version) {
            obj.version += '';
        }
        else {
            delete obj.version;
        }

        module.exports.push(obj);
    });
});<|endoftext|>


<commit_before>var eecQaPlugin = {};

eecQaPlugin.callApi = function(service, method, parameters, callback) {
  var url = eecQaPlugin.application + '/services/AMS/' + service + '/' + method;
  var data = { data: JSON.stringify(parameters) };
  if (!(service == 'Authentication' && method == 'Authenticate')) {
    data.token = eecQaPlugin.token['Token'];
  }
  $.get(url, data, function(response) {
    if (response['Status'] == 0) {
      if (typeof callback === 'function') { callback(response['Value']); }
    } else if (response['Status'] == 1) {
      alert('Error calling Cityworks API.  ' + response['Message']);
      if (typeof callback === 'function') { callback(); }
    } else if (response['Status'] == 2) {
      //TODO: Re-Authenticate?  Throw unauthorized error?  Does this happen when they just don't have permissions too?
    }
  });
};

eecQaPlugin.getStatusLabel = function(test) {
  var label;
  if (test.total > 0) {
    label = test.complete + ' / ' + test.total;
  } else {
    if (test.status == 'pass') {
      label = '\u2611';  //ballot box with check
    } else {
      label = '\u2610';  //blank ballot box
    }
  }
  return label;
};

eecQaPlugin.updateTestView = function(testName) {
  var test = eecQaPlugin.tests[testName];
  var statusView = $(eecQaPlugin.selector + ' #eec-qa-test-' + testName + ' label.eec-qa-status');
  statusView.text(eecQaPlugin.getStatusLabel(test));
  if (test.status == 'pass') {
    statusView
      .addClass('eec-qa-status-pass')
      .removeClass('eec-qa-status-fail')
    ;
  } else {
    statusView
      .addClass('eec-qa-status-fail')
      .removeClass('eec-qa-status-pass')
    ;
  }
};

eecQaPlugin.setTestResults = function(testName, status, complete, total) {
  var test = eecQaPlugin.tests[testName];
  test.status = status;
  if (complete != undefined) { test.complete = complete; }
  if (total) { test.total = total; }
  eecQaPlugin.updateTestView(testName);
};

eecQaPlugin.update = function(tests) {

  if (typeof tests === 'string') { tests = [tests]; }

  var updateTestByName = function(test) {
    eecQaPlugin.tests[test].update();
  };

  if (tests == undefined || tests == null) {
    // Nothing specified.  Update all.
    for (var test in eecQaPlugin.tests) {
      if (eecQaPlugin.tests.hasOwnProperty(test)) {
        updateTestByName(test);
      }
    }
  } else {
    // Tests specified.  Update by name.
    for (var i=0; i<tests.length; i++) {
      if (eecQaPlugin.tests.hasOwnProperty(tests[i])) {
        updateTestByName(tests[i]);
      }
    }
  }
  //TODO: Callback?
};

eecQaPlugin.init = function(params) {

  var authenticate = function(callback) {

    var authWithServer = function(callback) {
      eecQaPlugin.callApi('Authentication', 'Authenticate', eecQaPlugin['credentials'], function(data) {
        eecQaPlugin.token = data;
        localStorage.setItem('eec-qa-token', JSON.stringify(eecQaPlugin.token));  //TODO: Use sessionStorage instead?
        if (typeof callback === 'function') { callback(); }
      });
    };

    var tokenSave = localStorage.getItem('eec-qa-token');
    if (tokenSave == null) { //TODO: Need better error handling than this.  Basically, if anything goes not perfect,
                             // then re-auth with the server (i.e. don't assume the localStorage value isn't messed up)
      authWithServer(callback);
    } else {
      var token = JSON.parse(tokenSave);  //TODO: Check token with Authentication/Validate service
      if (token['Expires'] < new Date()) {  //TODO: Timezone check
        authWithServer(callback);
      } else {
        eecQaPlugin.token = token;
        if (typeof callback === 'function') { callback(); }
      }
    }
  };

  var build = function() {

    for (var testName in eecQaPlugin.tests) {
      if (eecQaPlugin.tests.hasOwnProperty(testName)) {
        var test = eecQaPlugin.tests[testName];
        $(eecQaPlugin.selector)
          .append($('
')
            .append($('')
              .text(eecQaPlugin.getStatusLabel(test))
            )
            .append($('
')
              .text(test.description)
            )
          )
        ;
      }
    }

    eecQaPlugin.update(); //TODO: Add others as they're finished.
  };

  eecQaPlugin.application = params['application'];
  eecQaPlugin.credentials = params['credentials'];
  eecQaPlugin.selector = params['selector'];

  authenticate(build);

};
<commit_msg>Logging bug<commit_after>var eecQaPlugin = {};

eecQaPlugin.callApi = function(service, method, parameters, callback) {
  var url = eecQaPlugin.application + '/services/AMS/' + service + '/' + method;
  var data = { data: JSON.stringify(parameters) };
  if (!(service == 'Authentication' && method == 'Authenticate')) {
    data.token = eecQaPlugin.token['Token'];
  }
  $.get(url, data, function(response) {
    if (response['Status'] == 0) {
      if (typeof callback === 'function') { callback(response['Value']); }
    } else if (response['Status'] == 1) {
      alert('Error calling Cityworks API.  ' + response['Message']);
      if (typeof callback === 'function') { callback(); }
    } else if (response['Status'] == 2) {
      //TODO: Re-Authenticate?  Throw unauthorized error?  Does this happen when they just don't have permissions too?
    }
  });
};

eecQaPlugin.getStatusLabel = function(test) {
  var label;
  if (test.total > 0) {
    label = test.complete + ' / ' + test.total;
  } else {
    if (test.status == 'pass') {
      label = '\u2611';  //ballot box with check
    } else {
      label = '\u2610';  //blank ballot box
    }
  }
  return label;
};

eecQaPlugin.updateTestView = function(testName) {
  var test = eecQaPlugin.tests[testName];
  var statusView = $(eecQaPlugin.selector + ' #eec-qa-test-' + testName + ' label.eec-qa-status');
  statusView.text(eecQaPlugin.getStatusLabel(test));
  if (test.status == 'pass') {
    statusView
      .addClass('eec-qa-status-pass')
      .removeClass('eec-qa-status-fail')
    ;
  } else {
    statusView
      .addClass('eec-qa-status-fail')
      .removeClass('eec-qa-status-pass')
    ;
  }
};

eecQaPlugin.setTestResults = function(testName, status, complete, total) {
  var test = eecQaPlugin.tests[testName];
  test.status = status;
  if (complete != undefined) { test.complete = complete; }
  if (total) { test.total = total; }
  eecQaPlugin.updateTestView(testName);
};

eecQaPlugin.update = function(tests) {  //TODO: Counts are not accurate for large numbers of thing?  Maybe there's an issue with loading order?

  if (typeof tests === 'string') { tests = [tests]; }

  var updateTestByName = function(test) {
    eecQaPlugin.tests[test].update();
  };

  if (tests == undefined || tests == null) {
    // Nothing specified.  Update all.
    for (var test in eecQaPlugin.tests) {
      if (eecQaPlugin.tests.hasOwnProperty(test)) {
        updateTestByName(test);
      }
    }
  } else {
    // Tests specified.  Update by name.
    for (var i=0; i<tests.length; i++) {
      if (eecQaPlugin.tests.hasOwnProperty(tests[i])) {
        updateTestByName(tests[i]);
      }
    }
  }
  //TODO: Callback?
};

eecQaPlugin.init = function(params) {

  var authenticate = function(callback) {

    var authWithServer = function(callback) {
      eecQaPlugin.callApi('Authentication', 'Authenticate', eecQaPlugin['credentials'], function(data) {
        eecQaPlugin.token = data;
        localStorage.setItem('eec-qa-token', JSON.stringify(eecQaPlugin.token));  //TODO: Use sessionStorage instead?
        if (typeof callback === 'function') { callback(); }
      });
    };

    var tokenSave = localStorage.getItem('eec-qa-token');
    if (tokenSave == null) { //TODO: Need better error handling than this.  Basically, if anything goes not perfect,
                             // then re-auth with the server (i.e. don't assume the localStorage value isn't messed up)
      authWithServer(callback);
    } else {
      var token = JSON.parse(tokenSave);  //TODO: Check token with Authentication/Validate service
      if (token['Expires'] < new Date()) {  //TODO: Timezone check
        authWithServer(callback);
      } else {
        eecQaPlugin.token = token;
        if (typeof callback === 'function') { callback(); }
      }
    }
  };

  var build = function() {

    for (var testName in eecQaPlugin.tests) {
      if (eecQaPlugin.tests.hasOwnProperty(testName)) {
        var test = eecQaPlugin.tests[testName];
        $(eecQaPlugin.selector)
          .append($('
')
            .append($('')
              .text(eecQaPlugin.getStatusLabel(test))
            )
            .append($('
')
              .text(test.description)
            )
          )
        ;
      }
    }

    eecQaPlugin.update(); //TODO: Add others as they're finished.
  };

  eecQaPlugin.application = params['application'];
  eecQaPlugin.credentials = params['credentials'];
  eecQaPlugin.selector = params['selector'];

  authenticate(build);

};
<|endoftext|>


<commit_before>//var md = require("markdown");
var fs = require('fs');
var md = require('markdown').markdown;
fs.readFile('home.md', 'utf-8', function (err, data) {
  if (err) throw err;
  var tree = md.toHTMLTree(data);
  var blocks = [];
  var str = '';
  var block = [];
  tree.splice(1).forEach(function(item, index){
  	if (item[0] == 'h1' && block.length){
		blocks.push(block);
		block = [];
	} else {
		block.push(item);
	}
  });

  console.log(blocks);
//  console.log(md.renderJsonML(['html', ['h1', 'fdsafdas']]));
});

<commit_msg>Made block parsing work<commit_after>//var md = require("markdown");
var fs = require('fs');
var md = require('markdown').markdown;
fs.readFile('home.md', 'utf-8', function (err, data) {
  if (err) throw err;
  var tree = md.toHTMLTree(data);
  var blocks = [];
  var block = [];
  tree = tree.splice(1);
  while(tree.length){
    if (block.length && tree[0][0] == 'h1'){
		blocks.push(block);
		block = [];
	} else {
		block.push(tree.shift());
	}
  };
  blocks.puhs(block);

  console.log(blocks);
//  console.log(md.renderJsonML(['html', ['h1', 'fdsafdas']]));
});

<|endoftext|>


<commit_before>// *************************************
//  Gulpfile
// *************************************

'use strict';

var gulp         = require('gulp');
var sass         = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var browserSync  = require('browser-sync');

// -------------------------------------
//  Options
// -------------------------------------

var options = {

	html: {
		files       : '*.html'
	},

	sass: {
		files	    : 'src/scss/**/*.scss',
		destination : 'dist/css'
	}
};

// -------------------------------------
//  Task: Serve
// -------------------------------------

gulp.task('serve', ['styles'], function() {
	browserSync.init({
		server: './'
	});

	gulp.watch(options.sass.files, ['styles']);
	gulp.watch(options.html.files).on('change', browserSync.reload);
});

// -------------------------------------
//  Task: Sass
// -------------------------------------

gulp.task('styles', function() {
	return gulp.src(options.sass.files)
		.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
		.pipe(autoprefixer('last 3 versions'))
		.pipe(gulp.dest(options.sass.destination))
		.pipe(browserSync.stream());
});

// -------------------------------------
//  Task: Default
// -------------------------------------

gulp.task('default', ['serve']);
<commit_msg>Update variables names<commit_after>// *************************************
//  Gulpfile
// *************************************

'use strict';

var gulp         = require('gulp');
var sass         = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var browserSync  = require('browser-sync');

// -------------------------------------
//  Options
// -------------------------------------

var paths = {

	html: {
		src  : '*.html'
	},

	styles: {
		src	 : 'src/scss/**/*.scss',
		dest : 'dist/css'
	}
};

// -------------------------------------
//  Task: Serve
// -------------------------------------

gulp.task('serve', ['styles'], function() {
	browserSync.init({
		server: './'
	});

	gulp.watch(paths.styles.src, ['styles']);
	gulp.watch(paths.html.src).on('change', browserSync.reload);
});

// -------------------------------------
//  Task: Sass
// -------------------------------------

gulp.task('styles', function() {
	return gulp.src(paths.styles.src)
		.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
		.pipe(autoprefixer('last 3 versions'))
		.pipe(gulp.dest(paths.styles.dest))
		.pipe(browserSync.stream());
});

// -------------------------------------
//  Task: Default
// -------------------------------------

gulp.task('default', ['serve']);
<|endoftext|>


<commit_before>(function () {
    var Ext = window.Ext4 || window.Ext;

    /**
     * PI Kanban Board App
     * Displays a cardboard and a type selector. Board shows States for the selected Type.
     */
    Ext.define('Rally.apps.portfoliokanban.PortfolioKanbanApp', {
        extend: 'Rally.app.App',
        requires: [
            'Rally.data.util.PortfolioItemHelper',
            'Rally.apps.portfoliokanban.PortfolioKanbanCard',
            'Rally.apps.portfoliokanban.PortfolioKanbanPolicy',
            'Rally.ui.cardboard.plugin.ColumnPolicy',
            'Rally.ui.cardboard.Column',
            'Rally.ui.cardboard.CardBoard',
            'Rally.ui.cardboard.Card',
            'Rally.data.QueryFilter',
            'Rally.ui.notify.Notifier',
            'Rally.util.Help',
            'Rally.util.Test'
        ],
        layout: 'auto',
        appName: 'Portfolio Kanban',

        cls: 'portfolio-kanban',

        config: {
            defaultSettings: {
                fields: 'PercentDoneByStoryCount'
            }
        },

        clientMetrics: [
            {
                method: '_showHelp',
                defaultUserAction: 'portfolio-kanban-show-help'
            }
        ],

        items: [
            {
                xtype: 'container',
                itemId: 'header',
                cls: 'header'
            },
            {
                xtype: 'container',
                itemId: 'bodyContainer',
                width: '100%'
            }
        ],

        afterRender: function () {
            this.callParent(arguments);

            if (Rally.environment.getContext().getSubscription().isModuleEnabled('Rally Portfolio Manager')) {

                Rally.data.util.PortfolioItemHelper.loadTypeOrDefault({
                    typeRef: this.getSetting('type'),
                    defaultToLowest: true,
                    context: this.getContext().getDataContext(),
                    success: function (record) {
                        this.currentType = record;

                        this._drawHeader();
                        this._loadCardboard();
                    },
                    scope: this
                });
            } else {
                this.down('#bodyContainer').add({
                    xtype: 'container',
                    html: '
You do not have RPM enabled for your subscription
'
                });

                this._publishContentUpdated();
            }
        },

        _drawHeader: function () {
            var header = this.down('#header');

            header.add([
                this._buildHelpComponent(),
                this._buildShowPolicies(),
                this._buildFilterInfo()
            ]);
        },

        _loadCardboard: function () {
            this._loadStates({
                success: function (states) {
                    var columns = this._createColumns(states);
                    if (this.rendered) {
                        this._drawCardboard(columns);
                    } else {
                        this.on('afterrender', Ext.bind(this._drawCardboard, this, [columns]), this, {single: true});
                    }
                },
                scope: this
            });

        },

        /**
         * @private
         * We need the States of the selected Portfolio Item Type to know what columns to show.
         * Whenever the type changes, reload the states to redraw the cardboard.
         * @param options
         * @param options.success called when states are loaded
         * @param options.scope the scope to call success with
         */
        _loadStates: function (options) {
            Ext.create('Rally.data.WsapiDataStore', {
                model: 'State',
                context: this.getContext().getDataContext(),
                autoLoad: true,
                fetch: ['Name', 'WIPLimit', 'Description'],
                filters: [
                    {
                        property: 'TypeDef',
                        value: this.currentType.get('_ref')
                    },
                    {
                        property: 'Enabled',
                        value: true
                    }
                ],
                sorters: [
                    {
                        property: 'OrderIndex',
                        direction: 'ASC'
                    }
                ],
                listeners: {
                    load: function (store, records) {
                        if (options.success) {
                            options.success.call(options.scope || this, records);
                        }
                    }
                }
            });

        },

        /**
         * Given a set of columns, build a cardboard component. Otherwise show an empty message.
         * @param columns
         */
        _drawCardboard: function (columns) {
            if (columns) {
                this._showColumns(columns);
            }
            else {
                this._showNoColumns();
            }
        },

        _showColumns: function (columns) {
            var cardboard = this.down('#cardboard'),
                filters = [
                    {
                        property: 'PortfolioItemType',
                        value: this.currentType.get('_ref')
                    }
                ];

            if (cardboard) {
                cardboard.destroy();
            }

            if (this.getSetting('query')) {
                try {
                    filters.push(Rally.data.QueryFilter.fromQueryString(this.getSetting('query')));
                } catch (e) {
                    Rally.ui.notify.Notifier.showError({
                        message: e.message
                    });
                }
            }

            var columnConfig = {
                xtype: 'rallycardboardcolumn',
                cardLimit: 50,
                drawFooter: Ext.emptyFn,
                enableWipLimit: true
            };

            var cardConfig = {
                xtype: 'rallyportfoliokanbancard',
                editable: true,
                showColorIcon: true
            };

            var fields = this.getSetting('fields');

            if (fields) {
                columnConfig.additionalFetchFields = fields.split(',');
                cardConfig.fields = fields.split(',').sort();
            } else {
                columnConfig.additionalFetchFields = [];
                cardConfig.fields = Rally.apps.portfolioitem.PortfolioKanbanCard.defaultFields;
            }

            if (Ext.Array.intersect(cardConfig.fields, ['PercentDoneByStoryPlanEstimate', 'PercentDoneByStoryCount']).length > 0) {
                columnConfig.additionalFetchFields = Ext.Array.merge(cardConfig.fields, ['PercentDoneByStoryPlanEstimate', 'PercentDoneByStoryCount']);
            }

            columnConfig.additionalFetchFields.push('Discussion');
            cardConfig.fields.push('Discussion');

            cardboard = this.cardboard = Ext.widget('rallycardboard', {
                types: [this.currentType.get('TypePath')],
                context: this.getContext(),
                itemId: 'cardboard',
                attribute: 'State',
                columns: columns,
                ddGroup: this.currentType.get('TypePath'),
                cls: 'cardboard',
                columnConfig: columnConfig,
                cardConfig: cardConfig,
                storeConfig: {
                    filters: filters,
                    context: this.context.getDataContext()
                },
                listeners: {
                    load: this._onBoardLoad,
                    cardupdated: this._publishContentUpdatedNoDashboardLayout,
                    scope: this
                },

                loadDescription: 'Portfolio Kanban',
                loadMask: false
            });

            this.down('#bodyContainer').add(cardboard);
            this.setLoading({ id: this.getMaskId() });

            this._renderPolicies();
        },

        getMaskId: function () {
            return 'btid-portfolio-kanban-board-load-mask-' + this.id;
        },

        _onBoardLoad: function (cardboard) {
            this._attachPercentDoneToolTip(cardboard);
            this._publishContentUpdated();
            this.setLoading(false);
            Rally.environment.getMessageBus().publish(Rally.Message.piKanbanBoardReady);
        },

        _showNoColumns: function () {
            this.add({
                xtype: 'container',
                cls: 'no-type-text',
                html: '
This Type has no states defined.
'
            });
            this._publishContentUpdated();
        },

        /**
         * @private
         * @return columns for the cardboard, as a map with keys being the column name.
         */
        _createColumns: function (states) {
            if (!states.length) {
                return undefined;
            }

            var columns = [
                {
                    columnHeaderConfig: {
                        headerTpl: 'No Entry'
                    },
                    value: null,
                    plugins: [{
                        ptype: 'rallycolumnpolicy',
                        policyCmpConfig: {
                            xtype: 'rallyportfoliokanbanpolicy',
                            hidden: true,
                            title: 'Exit Policy'
                        }
                    }]
                }
            ];

            Ext.Array.each(states, function (state) {
                columns.push({
                    value: state.get('_ref'),
                    wipLimit: state.get('WIPLimit'),
                    enableWipLimit: true,
                    columnHeaderConfig: {
                        record: state,
                        fieldToDisplay: 'Name',
                        editable: false
                    },
                    plugins: [{
                        ptype: 'rallycolumnpolicy',
                        policyCmpConfig: {
                            xtype: 'rallyportfoliokanbanpolicy',
                            hidden: true,
                            stateRecord: state,
                            title: 'Exit Policy'
                        }
                    }]
                });
            });

            return columns;
        },

        _attachPercentDoneToolTip: function (cardboard) {
            cardboard.getEl().select('.rui-card .progress-bar-container').each(function (flyEl) {
                var el = Ext.get(flyEl.dom);
                el.on('click', function () {
                    var cardEl = el.up('.rui-card');
                    var card = Ext.getCmp(cardEl.id);
                    var record = card.getRecord();
                    Ext4.create('Rally.ui.popover.PercentDonePopover', {
                        target: el,
                        targetSelector: '#' + cardEl.id + ' .progress-bar-container',
                        percentDoneData: record.data,
                        percentDoneName: 'PercentDoneByStoryCount',
                        piRef: record.data._ref
                    });
                });
            });
        },

        _renderPolicies: function () {
            var showPoliciesCheckbox = this.down("#showPoliciesCheckbox");

            Ext.each(this.cardboard.getColumns(), function (column) {
                if (showPoliciesCheckbox.getValue()) {
                    column.fireEvent('showpolicy');
                } else {
                    column.fireEvent('hidepolicy');
                }
            });
        },

        _buildShowPolicies: function () {
            return Ext.widget('checkbox', {
                cls: 'showPolicies',
                itemId: 'showPoliciesCheckbox',
                fieldCls: 'showPoliciesCheckbox',
                boxLabel: "Show Policies",
                listeners: {
                    change: {
                        fn: this._renderPolicies,
                        scope: this
                    }
                }
            });

        },

        _buildHelpComponent: function (config) {
            return Ext.create('Ext.Component', Ext.apply({
                cls: Rally.util.Test.toBrowserTestCssClass('portfolio-kanban-help-container'),
                renderTpl: Rally.util.Help.getIcon({
                    id: 265
                })
            }, config));
        },

        _buildFilterInfo: function () {
            return Ext.create('Rally.ui.tooltip.FilterInfo', {
                projectName: this.getSetting('project') && this.getContext().get('project').Name || 'Following Global Project Setting',
                typePath: this.currentType.get('Name'),
                scopeUp: this.getSetting('projectScopeUp'),
                scopeDown: this.getSetting('projectScopeDown'),
                query: this.getSetting('query')
            });
        },

        _publishContentUpdated: function () {
            this.fireEvent('contentupdated');
            if (Rally.BrowserTest) {
                Rally.BrowserTest.publishComponentReady(this);
            }
        },

        _publishContentUpdatedNoDashboardLayout: function () {
            this._attachPercentDoneToolTip(this.cardboard);
            this.fireEvent('contentupdated', {dashboardLayout: false});
        }

    });
})();
<commit_msg>DE17734:bad path to PortfolioKanbanCard<commit_after>(function () {
    var Ext = window.Ext4 || window.Ext;

    /**
     * PI Kanban Board App
     * Displays a cardboard and a type selector. Board shows States for the selected Type.
     */
    Ext.define('Rally.apps.portfoliokanban.PortfolioKanbanApp', {
        extend: 'Rally.app.App',
        requires: [
            'Rally.data.util.PortfolioItemHelper',
            'Rally.apps.portfoliokanban.PortfolioKanbanCard',
            'Rally.apps.portfoliokanban.PortfolioKanbanPolicy',
            'Rally.ui.cardboard.plugin.ColumnPolicy',
            'Rally.ui.cardboard.Column',
            'Rally.ui.cardboard.CardBoard',
            'Rally.ui.cardboard.Card',
            'Rally.data.QueryFilter',
            'Rally.ui.notify.Notifier',
            'Rally.util.Help',
            'Rally.util.Test'
        ],
        layout: 'auto',
        appName: 'Portfolio Kanban',

        cls: 'portfolio-kanban',

        config: {
            defaultSettings: {
                fields: 'PercentDoneByStoryCount'
            }
        },

        clientMetrics: [
            {
                method: '_showHelp',
                defaultUserAction: 'portfolio-kanban-show-help'
            }
        ],

        items: [
            {
                xtype: 'container',
                itemId: 'header',
                cls: 'header'
            },
            {
                xtype: 'container',
                itemId: 'bodyContainer',
                width: '100%'
            }
        ],

        afterRender: function () {
            this.callParent(arguments);

            if (Rally.environment.getContext().getSubscription().isModuleEnabled('Rally Portfolio Manager')) {

                Rally.data.util.PortfolioItemHelper.loadTypeOrDefault({
                    typeRef: this.getSetting('type'),
                    defaultToLowest: true,
                    context: this.getContext().getDataContext(),
                    success: function (record) {
                        this.currentType = record;

                        this._drawHeader();
                        this._loadCardboard();
                    },
                    scope: this
                });
            } else {
                this.down('#bodyContainer').add({
                    xtype: 'container',
                    html: '
You do not have RPM enabled for your subscription
'
                });

                this._publishContentUpdated();
            }
        },

        _drawHeader: function () {
            var header = this.down('#header');

            header.add([
                this._buildHelpComponent(),
                this._buildShowPolicies(),
                this._buildFilterInfo()
            ]);
        },

        _loadCardboard: function () {
            this._loadStates({
                success: function (states) {
                    var columns = this._createColumns(states);
                    if (this.rendered) {
                        this._drawCardboard(columns);
                    } else {
                        this.on('afterrender', Ext.bind(this._drawCardboard, this, [columns]), this, {single: true});
                    }
                },
                scope: this
            });

        },

        /**
         * @private
         * We need the States of the selected Portfolio Item Type to know what columns to show.
         * Whenever the type changes, reload the states to redraw the cardboard.
         * @param options
         * @param options.success called when states are loaded
         * @param options.scope the scope to call success with
         */
        _loadStates: function (options) {
            Ext.create('Rally.data.WsapiDataStore', {
                model: 'State',
                context: this.getContext().getDataContext(),
                autoLoad: true,
                fetch: ['Name', 'WIPLimit', 'Description'],
                filters: [
                    {
                        property: 'TypeDef',
                        value: this.currentType.get('_ref')
                    },
                    {
                        property: 'Enabled',
                        value: true
                    }
                ],
                sorters: [
                    {
                        property: 'OrderIndex',
                        direction: 'ASC'
                    }
                ],
                listeners: {
                    load: function (store, records) {
                        if (options.success) {
                            options.success.call(options.scope || this, records);
                        }
                    }
                }
            });

        },

        /**
         * Given a set of columns, build a cardboard component. Otherwise show an empty message.
         * @param columns
         */
        _drawCardboard: function (columns) {
            if (columns) {
                this._showColumns(columns);
            }
            else {
                this._showNoColumns();
            }
        },

        _showColumns: function (columns) {
            var cardboard = this.down('#cardboard'),
                filters = [
                    {
                        property: 'PortfolioItemType',
                        value: this.currentType.get('_ref')
                    }
                ];

            if (cardboard) {
                cardboard.destroy();
            }

            if (this.getSetting('query')) {
                try {
                    filters.push(Rally.data.QueryFilter.fromQueryString(this.getSetting('query')));
                } catch (e) {
                    Rally.ui.notify.Notifier.showError({
                        message: e.message
                    });
                }
            }

            var columnConfig = {
                xtype: 'rallycardboardcolumn',
                cardLimit: 50,
                drawFooter: Ext.emptyFn,
                enableWipLimit: true
            };

            var cardConfig = {
                xtype: 'rallyportfoliokanbancard',
                editable: true,
                showColorIcon: true
            };

            var fields = this.getSetting('fields');

            if (fields) {
                columnConfig.additionalFetchFields = fields.split(',');
                cardConfig.fields = fields.split(',').sort();
            } else {
                columnConfig.additionalFetchFields = [];
                cardConfig.fields = Rally.apps.portfoliokanban.PortfolioKanbanCard.defaultFields;
            }

            if (Ext.Array.intersect(cardConfig.fields, ['PercentDoneByStoryPlanEstimate', 'PercentDoneByStoryCount']).length > 0) {
                columnConfig.additionalFetchFields = Ext.Array.merge(cardConfig.fields, ['PercentDoneByStoryPlanEstimate', 'PercentDoneByStoryCount']);
            }

            columnConfig.additionalFetchFields.push('Discussion');
            cardConfig.fields.push('Discussion');

            cardboard = this.cardboard = Ext.widget('rallycardboard', {
                types: [this.currentType.get('TypePath')],
                context: this.getContext(),
                itemId: 'cardboard',
                attribute: 'State',
                columns: columns,
                ddGroup: this.currentType.get('TypePath'),
                cls: 'cardboard',
                columnConfig: columnConfig,
                cardConfig: cardConfig,
                storeConfig: {
                    filters: filters,
                    context: this.context.getDataContext()
                },
                listeners: {
                    load: this._onBoardLoad,
                    cardupdated: this._publishContentUpdatedNoDashboardLayout,
                    scope: this
                },

                loadDescription: 'Portfolio Kanban',
                loadMask: false
            });

            this.down('#bodyContainer').add(cardboard);
            this.setLoading({ id: this.getMaskId() });

            this._renderPolicies();
        },

        getMaskId: function () {
            return 'btid-portfolio-kanban-board-load-mask-' + this.id;
        },

        _onBoardLoad: function (cardboard) {
            this._attachPercentDoneToolTip(cardboard);
            this._publishContentUpdated();
            this.setLoading(false);
            Rally.environment.getMessageBus().publish(Rally.Message.piKanbanBoardReady);
        },

        _showNoColumns: function () {
            this.add({
                xtype: 'container',
                cls: 'no-type-text',
                html: '
This Type has no states defined.
'
            });
            this._publishContentUpdated();
        },

        /**
         * @private
         * @return columns for the cardboard, as a map with keys being the column name.
         */
        _createColumns: function (states) {
            if (!states.length) {
                return undefined;
            }

            var columns = [
                {
                    columnHeaderConfig: {
                        headerTpl: 'No Entry'
                    },
                    value: null,
                    plugins: [{
                        ptype: 'rallycolumnpolicy',
                        policyCmpConfig: {
                            xtype: 'rallyportfoliokanbanpolicy',
                            hidden: true,
                            title: 'Exit Policy'
                        }
                    }]
                }
            ];

            Ext.Array.each(states, function (state) {
                columns.push({
                    value: state.get('_ref'),
                    wipLimit: state.get('WIPLimit'),
                    enableWipLimit: true,
                    columnHeaderConfig: {
                        record: state,
                        fieldToDisplay: 'Name',
                        editable: false
                    },
                    plugins: [{
                        ptype: 'rallycolumnpolicy',
                        policyCmpConfig: {
                            xtype: 'rallyportfoliokanbanpolicy',
                            hidden: true,
                            stateRecord: state,
                            title: 'Exit Policy'
                        }
                    }]
                });
            });

            return columns;
        },

        _attachPercentDoneToolTip: function (cardboard) {
            cardboard.getEl().select('.rui-card .progress-bar-container').each(function (flyEl) {
                var el = Ext.get(flyEl.dom);
                el.on('click', function () {
                    var cardEl = el.up('.rui-card');
                    var card = Ext.getCmp(cardEl.id);
                    var record = card.getRecord();
                    Ext4.create('Rally.ui.popover.PercentDonePopover', {
                        target: el,
                        targetSelector: '#' + cardEl.id + ' .progress-bar-container',
                        percentDoneData: record.data,
                        percentDoneName: 'PercentDoneByStoryCount',
                        piRef: record.data._ref
                    });
                });
            });
        },

        _renderPolicies: function () {
            var showPoliciesCheckbox = this.down("#showPoliciesCheckbox");

            Ext.each(this.cardboard.getColumns(), function (column) {
                if (showPoliciesCheckbox.getValue()) {
                    column.fireEvent('showpolicy');
                } else {
                    column.fireEvent('hidepolicy');
                }
            });
        },

        _buildShowPolicies: function () {
            return Ext.widget('checkbox', {
                cls: 'showPolicies',
                itemId: 'showPoliciesCheckbox',
                fieldCls: 'showPoliciesCheckbox',
                boxLabel: "Show Policies",
                listeners: {
                    change: {
                        fn: this._renderPolicies,
                        scope: this
                    }
                }
            });

        },

        _buildHelpComponent: function (config) {
            return Ext.create('Ext.Component', Ext.apply({
                cls: Rally.util.Test.toBrowserTestCssClass('portfolio-kanban-help-container'),
                renderTpl: Rally.util.Help.getIcon({
                    id: 265
                })
            }, config));
        },

        _buildFilterInfo: function () {
            return Ext.create('Rally.ui.tooltip.FilterInfo', {
                projectName: this.getSetting('project') && this.getContext().get('project').Name || 'Following Global Project Setting',
                typePath: this.currentType.get('Name'),
                scopeUp: this.getSetting('projectScopeUp'),
                scopeDown: this.getSetting('projectScopeDown'),
                query: this.getSetting('query')
            });
        },

        _publishContentUpdated: function () {
            this.fireEvent('contentupdated');
            if (Rally.BrowserTest) {
                Rally.BrowserTest.publishComponentReady(this);
            }
        },

        _publishContentUpdatedNoDashboardLayout: function () {
            this._attachPercentDoneToolTip(this.cardboard);
            this.fireEvent('contentupdated', {dashboardLayout: false});
        }

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


<commit_before>var gulp = require('gulp'),
    concat = require('gulp-concat'),

    tsc = require('gulp-typescript'),
    mocha = require('gulp-mocha'),
    jsMinify = require('gulp-uglify'),

    scssLint = require('gulp-scss-lint'),
    sass = require('gulp-sass'),
    cssPrefixer = require('gulp-autoprefixer'),
    cssMinify = require('gulp-cssnano'),

    del = require('del'),
    merge = require('merge-stream'),
    SystemBuilder = require('systemjs-builder');

gulp.task('clean', () => {
    return del('dist');
});

gulp.task('shims', () => {
    return gulp.src([
            'node_modules/zone.js/dist/zone.js',
            'node_modules/reflect-metadata/Reflect.js'
        ])
        .pipe(concat('shims.js'))
        .pipe(gulp.dest('dist/js/'));
});

gulp.task('system-build', [ 'tsc' ], () => {
    var builder = new SystemBuilder();

    return builder.loadConfig('system.config.js')
        .then(() => builder.buildStatic('app', 'dist/js/bundle.js'))
        .then(() => del('build'));
});

gulp.task('tsc', () => {
    var tsProject = tsc.createProject('tsconfig.json'),
        tsResult = tsProject.src()
            .pipe(tsc(tsProject));

    return tsResult.js
        .pipe(gulp.dest('build/'));
});

gulp.task('html', () => {
    return gulp.src('src/**/**.html')
        .pipe(gulp.dest('dist/'));
});

gulp.task('lintScss', function() {
    return gulp.src('src/scss/**/*.scss')
        .pipe(scssLint({ config: 'lint.yml' }));
});

gulp.task('scss', () => {
    return gulp.src('src/scss/main.scss')
        .pipe(sass({
            precision: 10,
            includePaths: 'node_modules/node-normalize-scss'
        }))
        .pipe(concat('styles.css'))
        .pipe(cssPrefixer())
        .pipe(gulp.dest('dist/css/'));
});

gulp.task('test-tsc', () => {
    var tsProject = tsc.createProject('tsconfig.json');

    return tsProject.src()
        .pipe(tsc(tsProject))
        .pipe(gulp.dest('test/js/'));
});

gulp.task('test-run', [ 'test-tsc' ], () => {
    return gulp.src('test/**/*.spec.js')
        .pipe(mocha());
});

gulp.task('test', [ 'test-run' ], () => {
    return del('test/js');
});

gulp.task('minify', () => {
    var js = gulp.src('dist/js/bundle.js')
        .pipe(jsMinify())
        .pipe(gulp.dest('dist/js/'));

    var css = gulp.src('dist/css/styles.css')
        .pipe(cssMinify())
        .pipe(gulp.dest('dist/css/'));

    return merge(js, css);
});

gulp.task('watch', () => {
    var watchTs = gulp.watch('src/app/**/**.ts', [ 'system-build' ]),
        watchScss = gulp.watch('src/scss/**/*.scss', [ 'lintScss', 'styles' ]),
        watchHtml = gulp.watch('src/**/*.html', [ 'html' ]),
        watchImages = gulp.watch('src/images/**/*.*', [ 'images' ]),

        onChanged = function(event) {
            console.log('File ' + event.path + ' was ' + event.type + '. Running tasks...');
        };

    watchTs.on('change', onChanged);
    watchScss.on('change', onChanged);
    watchHtml.on('change', onChanged);
    watchImages.on('change', onChanged);
});

gulp.task('watchtests', () => {
    var watchTs = gulp.watch('src/app/**/**.ts', [ 'test-run' ]),
        watchTests = gulp.watch('test/**/*.spec.js', [ 'test-run' ]),

        onChanged = function(event) {
            console.log('File ' + event.path + ' was ' + event.type + '. Running tasks...');
        };

        watchTs.on('change', onChanged);
        watchTests.on('change', onChanged);
});

gulp.task('default', [ 'shims', 'system-build', 'html', 'lintScss', 'scss' ]);

<commit_msg>Add images task<commit_after>var gulp = require('gulp'),
    concat = require('gulp-concat'),

    tsc = require('gulp-typescript'),
    mocha = require('gulp-mocha'),
    jsMinify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),

    scssLint = require('gulp-scss-lint'),
    sass = require('gulp-sass'),
    cssPrefixer = require('gulp-autoprefixer'),
    cssMinify = require('gulp-cssnano'),

    del = require('del'),
    merge = require('merge-stream'),
    SystemBuilder = require('systemjs-builder');

gulp.task('clean', () => {
    return del('dist');
});

gulp.task('shims', () => {
    return gulp.src([
            'node_modules/zone.js/dist/zone.js',
            'node_modules/reflect-metadata/Reflect.js'
        ])
        .pipe(concat('shims.js'))
        .pipe(gulp.dest('dist/js/'));
});

gulp.task('system-build', [ 'tsc' ], () => {
    var builder = new SystemBuilder();

    return builder.loadConfig('system.config.js')
        .then(() => builder.buildStatic('app', 'dist/js/bundle.js'))
        .then(() => del('build'));
});

gulp.task('tsc', () => {
    var tsProject = tsc.createProject('tsconfig.json'),
        tsResult = tsProject.src()
            .pipe(tsc(tsProject));

    return tsResult.js
        .pipe(gulp.dest('build/'));
});

gulp.task('html', () => {
    return gulp.src('src/**/**.html')
        .pipe(gulp.dest('dist/'));
});

gulp.task('images', () => {
    return gulp.src('src/images/**/*.*')
        .pipe(imagemin())
        .pipe(gulp.dest('dist/images/'));
});

gulp.task('lintScss', function() {
    return gulp.src('src/scss/**/*.scss')
        .pipe(scssLint({ config: 'lint.yml' }));
});

gulp.task('scss', () => {
    return gulp.src('src/scss/main.scss')
        .pipe(sass({
            precision: 10,
            includePaths: 'node_modules/node-normalize-scss'
        }))
        .pipe(concat('styles.css'))
        .pipe(cssPrefixer())
        .pipe(gulp.dest('dist/css/'));
});

gulp.task('test-tsc', () => {
    var tsProject = tsc.createProject('tsconfig.json');

    return tsProject.src()
        .pipe(tsc(tsProject))
        .pipe(gulp.dest('test/js/'));
});

gulp.task('test-run', [ 'test-tsc' ], () => {
    return gulp.src('test/**/*.spec.js')
        .pipe(mocha());
});

gulp.task('test', [ 'test-run' ], () => {
    return del('test/js');
});

gulp.task('minify', () => {
    var js = gulp.src('dist/js/bundle.js')
        .pipe(jsMinify())
        .pipe(gulp.dest('dist/js/'));

    var css = gulp.src('dist/css/styles.css')
        .pipe(cssMinify())
        .pipe(gulp.dest('dist/css/'));

    return merge(js, css);
});

gulp.task('watch', () => {
    var watchTs = gulp.watch('src/app/**/**.ts', [ 'system-build' ]),
        watchScss = gulp.watch('src/scss/**/*.scss', [ 'lintScss', 'styles' ]),
        watchHtml = gulp.watch('src/**/*.html', [ 'html' ]),
        watchImages = gulp.watch('src/images/**/*.*', [ 'images' ]),

        onChanged = function(event) {
            console.log('File ' + event.path + ' was ' + event.type + '. Running tasks...');
        };

    watchTs.on('change', onChanged);
    watchScss.on('change', onChanged);
    watchHtml.on('change', onChanged);
    watchImages.on('change', onChanged);
});

gulp.task('watchtests', () => {
    var watchTs = gulp.watch('src/app/**/**.ts', [ 'test-run' ]),
        watchTests = gulp.watch('test/**/*.spec.js', [ 'test-run' ]),

        onChanged = function(event) {
            console.log('File ' + event.path + ' was ' + event.type + '. Running tasks...');
        };

        watchTs.on('change', onChanged);
        watchTests.on('change', onChanged);
});

gulp.task('default', [
    'shims',
    'system-build',
    'html',
    'images',
    'lintScss',
    'scss'
]);

<|endoftext|>


<commit_before>"use strict";

class gsuiPopup {
	static alert( title, msg, ok ) {
		this._init();
		this._emptyCnt();
		this.clWindow.add( "gsuiPopup-noText", "gsuiPopup-noCancel" );
		this._setOkCancelBtns( ok, false );
		return this._open( "alert", title, msg );
	}
	static confirm( title, msg, ok, cancel ) {
		this._init();
		this._emptyCnt();
		this.clWindow.remove( "gsuiPopup-noCancel" );
		this.clWindow.add( "gsuiPopup-noText" );
		this._setOkCancelBtns( ok, cancel );
		return this._open( "confirm", title, msg );
	}
	static prompt( title, msg, val, ok, cancel ) {
		this._init();
		this._emptyCnt();
		this.clWindow.remove( "gsuiPopup-noText", "gsuiPopup-noCancel" );
		this._setOkCancelBtns( ok, cancel );
		return this._open( "prompt", title, msg, val );
	}
	static custom( obj ) {
		this._init();
		this._emptyCnt();
		this._fnSubmit = obj.submit || null;
		this.clWindow.remove( "gsuiPopup-noText" );
		this._setOkCancelBtns( obj.ok, obj.cancel || false );
		obj.element
			? this.elCnt.append( obj.element )
			: Element.prototype.append.apply( this.elCnt, obj.elements );
		return this._open( "custom", obj.title );
	}
	static close() {
		if ( this.isOpen ) {
			this.elCancel.click();
		}
	}

	// private:
	static _setOkCancelBtns( ok, cancel ) {
		this.clWindow.toggle( "gsuiPopup-noCancel", cancel === false );
		this.elCancel.value = cancel || "Cancel";
		this.elOk.value = ok || "Ok";
	}
	static _emptyCnt() {
		const elCnt = this.elCnt;

		while ( elCnt.firstChild ) {
			elCnt.firstChild.remove();
		}
	}
	static _init() {
		if ( !this._ready ) {
			const qs = s => document.querySelector( `#gsuiPopup${ s }` );

			this.elRoot = qs( "" );
			this.elOk = qs( "Ok" );
			this.elCnt = qs( "Content" );
			this.elMsg = qs( "Message" );
			this.elText = qs( "InputText" );
			this.elForm = qs( "Body" );
			this.elWindow = qs( "Window" );
			this.elHeader = qs( "Head" );
			this.elCancel = qs( "Cancel" );
			this.clWindow = this.elWindow.classList;

			this.elRoot.onclick =
			this.elCancel.onclick = this._cancelClick.bind( this );
			this.elForm.onsubmit = this._submit.bind( this );
			this.elWindow.onkeyup =
			this.elWindow.onclick = e => { e.stopPropagation(); };
			this.elWindow.onkeydown = e => {
				if ( e.keyCode === 27 ) {
					this._cancelClick();
				}
				e.stopPropagation();
			};
			this._ready = true;
		}
	}
	static _open( type, title, msg, value ) {
		this.type = type;
		this.isOpen = true;
		this.elHeader.textContent = title;
		this.elMsg.innerHTML = msg || "";
		this.elText.value = arguments.length > 3 ? value : "";
		this.elWindow.dataset.type = type;
		this.elRoot.classList.add( "gsuiPopup-show" );
		setTimeout( () => {
			if ( type === "prompt" ) {
				this.elText.select();
			} else {
				const inp = type !== "custom" ? null
					: this.elCnt.querySelector( "input" );

				( inp || this.elOk ).focus();
			}
		}, 250 );
		return new Promise( res => this.resolve = res )
			.then( val => {
				this.isOpen = false;
				this.elRoot.classList.remove( "gsuiPopup-show" );
				return val;
			} );
	}
	static _cancelClick() {
		this.resolve(
			this.type === "confirm" ? false :
			this.type === "prompt" ? null : undefined );
	}
	static _submit() {
		switch ( this.type ) {
			case "alert": this.resolve( undefined ); break;
			case "prompt": this.resolve( this.elText.value ); break;
			case "confirm": this.resolve( true ); break;
			case "custom": this._submitCustom(); break;
		}
		return false;
	}
	static _submitCustom() {
		const fn = this._fnSubmit,
			inps = Array.from( this.elForm ),
			obj = inps.reduce( ( obj, inp ) => {
				if ( inp.name ) {
					obj[ inp.name ] =
						inp.type === "number" ? +inp.value :
						inp.type === "file" ? inp.files : inp.value;
				}
				return obj;
			}, {} );

		if ( !fn ) {
			this.resolve( obj );
		} else {
			const fnRes = fn( obj );

			if ( fnRes !== false ) {
				fnRes && fnRes.then
					? fnRes.then( res => {
						if ( res !== false ) {
							this.resolve( obj );
						}
					} )
					: this.resolve( obj );
			}
		}
	}
}
<commit_msg>gsuiPopup: Object.seal( this )<commit_after>"use strict";

const gsuiPopup = new class {
	constructor() {
		const qs = s => document.querySelector( `#gsuiPopup${ s }` );

		this.elRoot = qs( "" );
		this.elOk = qs( "Ok" );
		this.elCnt = qs( "Content" );
		this.elMsg = qs( "Message" );
		this.elText = qs( "InputText" );
		this.elForm = qs( "Body" );
		this.elWindow = qs( "Window" );
		this.elHeader = qs( "Head" );
		this.elCancel = qs( "Cancel" );
		this.clWindow = this.elWindow.classList;
		this.type = "";
		this.isOpen = false;
		this.resolve = null;
		Object.seal( this );

		this.elRoot.onclick =
		this.elCancel.onclick = this._cancelClick.bind( this );
		this.elForm.onsubmit = this._submit.bind( this );
		this.elWindow.onkeyup =
		this.elWindow.onclick = e => { e.stopPropagation(); };
		this.elWindow.onkeydown = e => {
			if ( e.keyCode === 27 ) {
				this._cancelClick();
			}
			e.stopPropagation();
		};
	}

	alert( title, msg, ok ) {
		this._emptyCnt();
		this.clWindow.add( "gsuiPopup-noText", "gsuiPopup-noCancel" );
		this._setOkCancelBtns( ok, false );
		return this._open( "alert", title, msg );
	}
	confirm( title, msg, ok, cancel ) {
		this._emptyCnt();
		this.clWindow.remove( "gsuiPopup-noCancel" );
		this.clWindow.add( "gsuiPopup-noText" );
		this._setOkCancelBtns( ok, cancel );
		return this._open( "confirm", title, msg );
	}
	prompt( title, msg, val, ok, cancel ) {
		this._emptyCnt();
		this.clWindow.remove( "gsuiPopup-noText", "gsuiPopup-noCancel" );
		this._setOkCancelBtns( ok, cancel );
		return this._open( "prompt", title, msg, val );
	}
	custom( obj ) {
		this._emptyCnt();
		this._fnSubmit = obj.submit || null;
		this.clWindow.remove( "gsuiPopup-noText" );
		this._setOkCancelBtns( obj.ok, obj.cancel || false );
		obj.element
			? this.elCnt.append( obj.element )
			: Element.prototype.append.apply( this.elCnt, obj.elements );
		return this._open( "custom", obj.title );
	}
	close() {
		if ( this.isOpen ) {
			this.elCancel.click();
		}
	}

	// private:,
	_setOkCancelBtns( ok, cancel ) {
		this.clWindow.toggle( "gsuiPopup-noCancel", cancel === false );
		this.elCancel.value = cancel || "Cancel";
		this.elOk.value = ok || "Ok";
	}
	_emptyCnt() {
		const elCnt = this.elCnt;

		while ( elCnt.firstChild ) {
			elCnt.firstChild.remove();
		}
	}
	_open( type, title, msg, value ) {
		this.type = type;
		this.isOpen = true;
		this.elHeader.textContent = title;
		this.elMsg.innerHTML = msg || "";
		this.elText.value = arguments.length > 3 ? value : "";
		this.elWindow.dataset.type = type;
		this.elRoot.classList.add( "gsuiPopup-show" );
		setTimeout( () => {
			if ( type === "prompt" ) {
				this.elText.select();
			} else {
				const inp = type !== "custom" ? null
					: this.elCnt.querySelector( "input" );

				( inp || this.elOk ).focus();
			}
		}, 250 );
		return new Promise( res => this.resolve = res )
			.then( val => {
				this.isOpen = false;
				this.elRoot.classList.remove( "gsuiPopup-show" );
				return val;
			} );
	}
	_cancelClick() {
		this.resolve(
			this.type === "confirm" ? false :
			this.type === "prompt" ? null : undefined );
	}
	_submit() {
		switch ( this.type ) {
			case "alert": this.resolve( undefined ); break;
			case "prompt": this.resolve( this.elText.value ); break;
			case "confirm": this.resolve( true ); break;
			case "custom": this._submitCustom(); break;
		}
		return false;
	}
	_submitCustom() {
		const fn = this._fnSubmit,
			inps = Array.from( this.elForm ),
			obj = inps.reduce( ( obj, inp ) => {
				if ( inp.name ) {
					obj[ inp.name ] =
						inp.type === "number" ? +inp.value :
						inp.type === "file" ? inp.files : inp.value;
				}
				return obj;
			}, {} );

		if ( !fn ) {
			this.resolve( obj );
		} else {
			const fnRes = fn( obj );

			if ( fnRes !== false ) {
				fnRes && fnRes.then
					? fnRes.then( res => {
						if ( res !== false ) {
							this.resolve( obj );
						}
					} )
					: this.resolve( obj );
			}
		}
	}
};
<|endoftext|>


<commit_before>/** @jsx hJSX */

import {Rx} from '@cycle/core';
import {hJSX} from '@cycle/dom'; // eslint-disable-line

const DIALOGUE_NAME = `<%= moduleName %>`;

let n = 0;

function randomNamespace() {
  return `${n++}`;
}

function <%= moduleNameCamelized %>({DOM, props$}, optNamespace = randomNamespace()) {
  const namespace = optNamespace.trim();

  return {
    DOM: props$.map(
      (props) => ( // eslint-disable-line
        <div className={`${namespace} ${DIALOGUE_NAME}`}>
          {props.text}

      )
    ),
  };
}

export default <%= moduleNameCamelized %>;
<commit_msg>feat(module.js): make complete MVI example<commit_after>/** @jsx hJSX */

import {hJSX} from '@cycle/dom'; // eslint-disable-line

const DIALOGUE_NAME = `yeoman-test`;

let idSuffix = 0;

function makeCycleId() {
  return `${DIALOGUE_NAME}-${idSuffix++}`;
}

function intent(DOM, cycleId) {
  return {
    isClicked$: DOM.select(`.${cycleId}`).events(`click`)
      .map(() => true)
      .startWith(false),
  };
}

function model(actions) {
  return actions.isClicked$.map(isClicked => {
    return {
      data: isClicked ?
        <span style={{whiteSpace: `nowrap`}}>I was clicked :
        `Click me!`,
    };
  });
}

function view({props$, state$}, cycleId) {
  return props$.combineLatest(
    state$,
    (props, state) => ( // eslint-disable-line
      <div className={`${cycleId} ${DIALOGUE_NAME}`}>
        {props.text} {state.data}

    )
  );
}

function <%= moduleNameCamelized %>({DOM, props$}, optCycleId = makeCycleId()) {
  const cycleId = optCycleId.trim();
  const actions = intent(DOM, cycleId);
  const state$ = model(actions);

  return {
    DOM: view({props$, state$}, cycleId),
  };
}

export default <%= moduleNameCamelized %>;
<|endoftext|>