<commit_before>(function () {
  'use strict';

  angular.module('ng-giphy', [])

    .directive('giphyFind',  findGiphy)
    .directive('giphyId',    findGiphyById)
    .directive('giphyRand',  findRandGiphy)

    .factory('giphy',        giphyService)
    .provider('giphyConfig', giphyConfig)

    .config(ngGiphyConfig)
    .run(templateCache);

  // configure the provider to use the beta key
  ngGiphyConfig.$inject = ['giphyConfigProvider'];
  /* @ngInject */
  function ngGiphyConfig(giphyConfigProvider) {
    giphyConfigProvider.setKey('dc6zaTOxFJmzC');
  }

  /**
   * Directive: find gif by tag
   */
  function findGiphy() {
    return {
      scope: {
        q     : '=giphyTag',
        rating: '='
      },
      controller: findGiphyController,
      controllerAs: 'vm',
      bindToController: true,
      templateUrl: 'imgTemplate.html'
    };
  }

  findGiphyController.$inject = ['giphy'];
  /* @ngInject */
  function findGiphyController(giphy) {
    /* jshint validthis: true */
    var vm = this;

    giphy.find(vm.q, true).then(function (res) {
      vm.giphysrc = res;
    });
  }

  /**
   * Directive: find gif by id
   */
  function findGiphyById() {
    return {
      scope: {
        id    : '=giphyId',
        rating: '='
      },
      controller: findGiphyByIdController,
      controllerAs: 'vm',
      bindToController: true,
      templateUrl: 'imgTemplate.html'
    };
  }

  findGiphyByIdController.$inject = ['giphy'];
  /* @ngInject */
  function findGiphyByIdController(giphy) {
    /* jshint validthis: true */
    var vm = this;

    giphy.findById(vm.id, true).then(function (res) {
      vm.giphysrc = res;
    });
  }

  /**
   * Directive: find random gif by tag
   */
  function findRandGiphy() {
    return {
      scope: {
        q     : '=giphyTag',
        rating: '='
      },
      controller: findRandGiphyController,
      controllerAs: 'vm',
      bindToController: true,
      templateUrl: 'imgTemplate.html'
    };
  }

  findRandGiphyController.$inject = ['giphy'];
  /* @ngInject */
  function findRandGiphyController(giphy) {
    /* jshint validthis: true */
    var vm = this;

    giphy.random(vm.q, true).then(function (res) {
      vm.giphysrc = res;
    });
  }

  // services to interact with Giphy API endpoints
  giphyService.$inject = ['$http', 'giphyConfig'];
  /* @ngInject */
  function giphyService($http, giphyConfig) {

    var baseUrl = 'http://api.giphy.com/v1/gifs';

    var url = {
      random   : baseUrl + '/random?api_key=' + giphyConfig.key,
      find     : baseUrl + '/search?api_key=' + giphyConfig.key,
      findById : baseUrl + '/%s?api_key='     + giphyConfig.key
    };

    // expose the service API
    return {
      find        : find,
      findById    : findById,
      random      : random,
    };

    /**
     * Gets a gif url searching by tag
     *
     * @param {string} query
     * @param {Boolean} returnUrl
     * @return {string} gif url
     */
    function find(q, returnUrl){
      var query = q.constructor === Array ? q.join('+') : q;
      return $http.get(url.find + '&q=' + query).then(function (res) {
        return returnUrl ? res.data.data[0].images.original.url : res.data.data[0];
      });
    }

   /**
    * Gets a gif url searching by id
    *
    * @param {string} gif id
    * @param {Boolean} returnUrl
    * @return {string} gif url
    */
    function findById(id, returnUrl){
      return $http.get(url.findById.replace('%s', id)).then(function (res) {
        return returnUrl ? res.data.data.images.original.url : res.data.data;
      });
    }

    /**
     * Gets a random gif url searching by tag
     *
     * @param {string} query
     * @param {Boolean} returnUrl
     * @return {string} gif url
     */
    function random(q, returnUrl){
      var query = q.constructor === Array ? q.join('+') : q;
      return $http.get(url.random + '&tag=' + query).then(function (res) {
        return returnUrl ? res.data.data.image_url : res.data.data;
      });
    }
  }

  templateCache.$inject = ['$templateCache'];
  /* @ngInject */
  function templateCache($templateCache) {
    $templateCache.put('imgTemplate.html', '');
  }

  // giphy API key provider
  function giphyConfig() {
    /* jshint validthis: true */
    this.setKey = function(value) {
      this.key = value;
    };

    this.$get = function() {
      return this;
    };
  }

})();
<commit_msg>Added trending method to giphy api<commit_after>(function () {
  'use strict';

  angular.module('ng-giphy', [])

    .directive('giphyFind',  findGiphy)
    .directive('giphyId',    findGiphyById)
    .directive('giphyRand',  findRandGiphy)

    .factory('giphy',        giphyService)
    .provider('giphyConfig', giphyConfig)

    .config(ngGiphyConfig)
    .run(templateCache);

  // configure the provider to use the beta key
  ngGiphyConfig.$inject = ['giphyConfigProvider'];
  /* @ngInject */
  function ngGiphyConfig(giphyConfigProvider) {
    giphyConfigProvider.setKey('dc6zaTOxFJmzC');
  }

  /**
   * Directive: find gif by tag
   */
  function findGiphy() {
    return {
      scope: {
        q     : '=giphyTag',
        rating: '='
      },
      controller: findGiphyController,
      controllerAs: 'vm',
      bindToController: true,
      templateUrl: 'imgTemplate.html'
    };
  }

  findGiphyController.$inject = ['giphy'];
  /* @ngInject */
  function findGiphyController(giphy) {
    /* jshint validthis: true */
    var vm = this;

    giphy.find(vm.q, true).then(function (res) {
      vm.giphysrc = res;
    });
  }

  /**
   * Directive: find gif by id
   */
  function findGiphyById() {
    return {
      scope: {
        id    : '=giphyId',
        rating: '='
      },
      controller: findGiphyByIdController,
      controllerAs: 'vm',
      bindToController: true,
      templateUrl: 'imgTemplate.html'
    };
  }

  findGiphyByIdController.$inject = ['giphy'];
  /* @ngInject */
  function findGiphyByIdController(giphy) {
    /* jshint validthis: true */
    var vm = this;

    giphy.findById(vm.id, true).then(function (res) {
      vm.giphysrc = res;
    });
  }

  /**
   * Directive: find random gif by tag
   */
  function findRandGiphy() {
    return {
      scope: {
        q     : '=giphyTag',
        rating: '='
      },
      controller: findRandGiphyController,
      controllerAs: 'vm',
      bindToController: true,
      templateUrl: 'imgTemplate.html'
    };
  }

  findRandGiphyController.$inject = ['giphy'];
  /* @ngInject */
  function findRandGiphyController(giphy) {
    /* jshint validthis: true */
    var vm = this;

    giphy.random(vm.q, true).then(function (res) {
      vm.giphysrc = res;
    });
  }

  // services to interact with Giphy API endpoints
  giphyService.$inject = ['$http', 'giphyConfig'];
  /* @ngInject */
  function giphyService($http, giphyConfig) {

    var baseUrl = 'http://api.giphy.com/v1/gifs';

    var url = {
      random   : baseUrl + '/random?api_key='   + giphyConfig.key,
      find     : baseUrl + '/search?api_key='   + giphyConfig.key,
      findById : baseUrl + '/%s?api_key='       + giphyConfig.key,
      trending : baseUrl + '/trending?api_key=' + giphyConfig.key,
    };

    // expose the service API
    return {
      find        : find,
      findById    : findById,
      random      : random,
      trending    : trending
    };

    /**
     * Gets a gif url searching by tag
     *
     * @param {string} query
     * @param {Boolean} returnUrl
     * @return {string} gif url
     */
    function find(q, returnUrl){
      var query = q.constructor === Array ? q.join('+') : q;
      return $http.get(url.find + '&q=' + query).then(function (res) {
        return returnUrl ? res.data.data[0].images.original.url : res.data.data[0];
      });
    }

   /**
    * Gets a gif url searching by id
    *
    * @param {string} gif id
    * @param {Boolean} returnUrl
    * @return {string} gif url
    */
    function findById(id, returnUrl){
      return $http.get(url.findById.replace('%s', id)).then(function (res) {
        return returnUrl ? res.data.data.images.original.url : res.data.data;
      });
    }

    /**
     * Gets a random gif url searching by tag
     *
     * @param {string} query
     * @param {Boolean} returnUrl
     * @return {string} gif url
     */
    function random(q, returnUrl){
      var query = q.constructor === Array ? q.join('+') : q;
      return $http.get(url.random + '&tag=' + query).then(function (res) {
        return returnUrl ? res.data.data.image_url : res.data.data;
      });
    }

    /**
     * Fetch GIFs currently trending online. Hand curated by the Giphy editorial team.
     * The data returned mirrors the GIFs showcased on the Giphy homepage. Returns 25 results by default.
     *
     * @param {Number} limit
     * @param {Boolean} rating
     * @return {string} gif url
     */
    function trending(limit, rating) {
      return $http.get(url.trending + '&limit=' + limit).then(function (res) {
        return res.data.data;
      });
    }
  }

  templateCache.$inject = ['$templateCache'];
  /* @ngInject */
  function templateCache($templateCache) {
    $templateCache.put('imgTemplate.html', '');
  }

  // giphy API key provider
  function giphyConfig() {
    /* jshint validthis: true */
    this.setKey = function(value) {
      this.key = value;
    };

    this.$get = function() {
      return this;
    };
  }

})();
<|endoftext|>


<commit_before>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['quill'], factory)
  } else if (typeof exports === 'object') {
    module.exports = factory(require('quill'))
  } else {
    root.Requester = factory(root.Quill)
  }
}(this, function (Quill) {
  'use strict'

  var app
  // declare ngQuill module
  app = angular.module('ngQuill', [])

  app.provider('ngQuillConfig', function () {
    var config = {
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
          ['blockquote', 'code-block'],

          [{ 'header': 1 }, { 'header': 2 }],               // custom button values
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
          [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
          [{ 'direction': 'rtl' }],                         // text direction

          [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

          [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
          [{ 'font': [] }],
          [{ 'align': [] }],

          ['clean'],                                         // remove formatting button

          ['link', 'image', 'video']                         // link and image, video
        ]
      },
      theme: 'snow',
      placeholder: 'Insert text here ...',
      readOnly: false,
      bounds: document.body
    }

    this.set = function (customConf) {
      customConf = customConf || {}

      if (customConf.modules) {
        config.modules = customConf.modules
      }
      if (customConf.theme) {
        config.theme = customConf.theme
      }
      if (customConf.placeholder !== null && customConf.placeholder !== undefined) {
        config.placeholder = customConf.placeholder.trim()
      }
      if (customConf.bounds) {
        config.bounds = customConf.bounds
      }
      if (customConf.readOnly) {
        config.readOnly = customConf.readOnly
      }
      if (customConf.formats) {
        config.formats = customConf.formats
      }
    }

    this.$get = function () {
      return config
    }
  })

  app.component('ngQuillEditor', {
    bindings: {
      'modules': '<modules',
      'theme': '@?',
      'readOnly': '<?',
      'formats': '<?',
      'placeholder': '@?',
      'bounds': '<?',
      'onEditorCreated': '&?',
      'onContentChanged': '&?',
      'onSelectionChanged': '&?',
      'ngModel': '<',
      'maxLength': '<',
      'minLength': '<'
    },
    require: {
      ngModelCtrl: 'ngModel'
    },
    transclude: {
      'toolbar': '?ngQuillToolbar'
    },
    template: '
<ng-transclude ng-transclude-slot="toolbar"></ng-transclude>
',
    controller: ['$scope', '$element', '$timeout', '$transclude', 'ngQuillConfig', function ($scope, $element, $timeout, $transclude, ngQuillConfig) {
      var config = {}
      var content
      var editorElem
      var modelChanged = false
      var editorChanged = false
      var editor
      var placeholder = ngQuillConfig.placeholder

      this.validate = function (text) {
        if (this.maxLength) {
          if (text.length > this.maxLength + 1) {
            this.ngModelCtrl.$setValidity('maxlength', false)
          } else {
            this.ngModelCtrl.$setValidity('maxlength', true)
          }
        }

        if (this.minLength > 1) {
          // validate only if text.length > 1
          if (text.length <= this.minLength && text.length > 1) {
            this.ngModelCtrl.$setValidity('minlength', false)
          } else {
            this.ngModelCtrl.$setValidity('minlength', true)
          }
        }
      }

      this.$onChanges = function (changes) {
        if (changes.ngModel && changes.ngModel.currentValue !== changes.ngModel.previousValue) {
          content = changes.ngModel.currentValue

          if (editor && !editorChanged) {
            modelChanged = true
            if (content) {
              editor.pasteHTML(content)
            } else {
              editor.setText('')
            }
          }
          editorChanged = false
        }

        if (editor && changes.readOnly) {
          editor.enable(!changes.readOnly.currentValue)
        }
      }

      this.$onInit = function () {
        if (this.placeholder !== null && this.placeholder !== undefined) {
          placeholder = this.placeholder.trim()
        }

        config = {
          theme: this.theme || ngQuillConfig.theme,
          readOnly: this.readOnly || ngQuillConfig.readOnly,
          modules: this.modules || ngQuillConfig.modules,
          formats: this.formats || ngQuillConfig.formats,
          placeholder: placeholder,
          bounds: this.bounds || ngQuillConfig.bounds
        }
      }

      this.$postLink = function () {
        // create quill instance after dom is rendered
        $timeout(function () {
          this._initEditor(editorElem)
        }.bind(this), 0)
      }

      this._initEditor = function (editorElem) {
        var $editorElem = angular.element('

')
        var container = $element.children()

        editorElem = $editorElem[0]

        // set toolbar to custom one
        if ($transclude.isSlotFilled('toolbar')) {
          config.modules.toolbar = container.find('ng-quill-toolbar').children()[0]
        }

        container.append($editorElem)

        editor = new Quill(editorElem, config)

        this.ready = true

        // mark model as touched if editor lost focus
        editor.on('selection-change', function (range, oldRange, source) {
          if (this.onSelectionChanged) {
            this.onSelectionChanged({
              editor: editor,
              oldRange: oldRange,
              range: range,
              source: source
            })
          }

          if (range) {
            return
          }
          $scope.$applyAsync(function () {
            this.ngModelCtrl.$setTouched()
          }.bind(this))
        }.bind(this))

        // update model if text changes
        editor.on('text-change', function (delta, oldDelta, source) {
          var html = editorElem.children[0].innerHTML
          var text = editor.getText()

          if (html === '

') {
            html = null
          }
          this.validate(text)

          if (!modelChanged) {
            $scope.$applyAsync(function () {
              editorChanged = true

              this.ngModelCtrl.$setViewValue(html)

              if (this.onContentChanged) {
                this.onContentChanged({
                  editor: editor,
                  html: html,
                  text: text,
                  delta: delta,
                  oldDelta: oldDelta,
                  source: source
                })
              }
            }.bind(this))
          }
          modelChanged = false
        }.bind(this))

        // set initial content
        if (content) {
          modelChanged = true

          var contents = editor.clipboard.convert(content)
          editor.setContents(contents)
          editor.history.clear()
        }

        // provide event to get informed when editor is created -> pass editor object.
        if (this.onEditorCreated) {
          this.onEditorCreated({editor: editor})
        }
      }
    }]
  })
}))
<commit_msg>Issue #120: Returns module name for easy import<commit_after>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['quill'], factory)
  } else if (typeof module !== 'undefined' && typeof exports === 'object') {
    module.exports = factory(require('quill'))
  } else {
    root.Requester = factory(root.Quill)
  }
}(this, function (Quill) {
  'use strict'

  var app
  // declare ngQuill module
  app = angular.module('ngQuill', [])

  app.provider('ngQuillConfig', function () {
    var config = {
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
          ['blockquote', 'code-block'],

          [{ 'header': 1 }, { 'header': 2 }],               // custom button values
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
          [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
          [{ 'direction': 'rtl' }],                         // text direction

          [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

          [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
          [{ 'font': [] }],
          [{ 'align': [] }],

          ['clean'],                                         // remove formatting button

          ['link', 'image', 'video']                         // link and image, video
        ]
      },
      theme: 'snow',
      placeholder: 'Insert text here ...',
      readOnly: false,
      bounds: document.body
    }

    this.set = function (customConf) {
      customConf = customConf || {}

      if (customConf.modules) {
        config.modules = customConf.modules
      }
      if (customConf.theme) {
        config.theme = customConf.theme
      }
      if (customConf.placeholder !== null && customConf.placeholder !== undefined) {
        config.placeholder = customConf.placeholder.trim()
      }
      if (customConf.bounds) {
        config.bounds = customConf.bounds
      }
      if (customConf.readOnly) {
        config.readOnly = customConf.readOnly
      }
      if (customConf.formats) {
        config.formats = customConf.formats
      }
    }

    this.$get = function () {
      return config
    }
  })

  app.component('ngQuillEditor', {
    bindings: {
      'modules': '<modules',
      'theme': '@?',
      'readOnly': '<?',
      'formats': '<?',
      'placeholder': '@?',
      'bounds': '<?',
      'onEditorCreated': '&?',
      'onContentChanged': '&?',
      'onSelectionChanged': '&?',
      'ngModel': '<',
      'maxLength': '<',
      'minLength': '<'
    },
    require: {
      ngModelCtrl: 'ngModel'
    },
    transclude: {
      'toolbar': '?ngQuillToolbar'
    },
    template: '
<ng-transclude ng-transclude-slot="toolbar"></ng-transclude>
',
    controller: ['$scope', '$element', '$timeout', '$transclude', 'ngQuillConfig', function ($scope, $element, $timeout, $transclude, ngQuillConfig) {
      var config = {}
      var content
      var editorElem
      var modelChanged = false
      var editorChanged = false
      var editor
      var placeholder = ngQuillConfig.placeholder

      this.validate = function (text) {
        if (this.maxLength) {
          if (text.length > this.maxLength + 1) {
            this.ngModelCtrl.$setValidity('maxlength', false)
          } else {
            this.ngModelCtrl.$setValidity('maxlength', true)
          }
        }

        if (this.minLength > 1) {
          // validate only if text.length > 1
          if (text.length <= this.minLength && text.length > 1) {
            this.ngModelCtrl.$setValidity('minlength', false)
          } else {
            this.ngModelCtrl.$setValidity('minlength', true)
          }
        }
      }

      this.$onChanges = function (changes) {
        if (changes.ngModel && changes.ngModel.currentValue !== changes.ngModel.previousValue) {
          content = changes.ngModel.currentValue

          if (editor && !editorChanged) {
            modelChanged = true
            if (content) {
              editor.pasteHTML(content)
            } else {
              editor.setText('')
            }
          }
          editorChanged = false
        }

        if (editor && changes.readOnly) {
          editor.enable(!changes.readOnly.currentValue)
        }
      }

      this.$onInit = function () {
        if (this.placeholder !== null && this.placeholder !== undefined) {
          placeholder = this.placeholder.trim()
        }

        config = {
          theme: this.theme || ngQuillConfig.theme,
          readOnly: this.readOnly || ngQuillConfig.readOnly,
          modules: this.modules || ngQuillConfig.modules,
          formats: this.formats || ngQuillConfig.formats,
          placeholder: placeholder,
          bounds: this.bounds || ngQuillConfig.bounds
        }
      }

      this.$postLink = function () {
        // create quill instance after dom is rendered
        $timeout(function () {
          this._initEditor(editorElem)
        }.bind(this), 0)
      }

      this._initEditor = function (editorElem) {
        var $editorElem = angular.element('

')
        var container = $element.children()

        editorElem = $editorElem[0]

        // set toolbar to custom one
        if ($transclude.isSlotFilled('toolbar')) {
          config.modules.toolbar = container.find('ng-quill-toolbar').children()[0]
        }

        container.append($editorElem)

        editor = new Quill(editorElem, config)

        this.ready = true

        // mark model as touched if editor lost focus
        editor.on('selection-change', function (range, oldRange, source) {
          if (this.onSelectionChanged) {
            this.onSelectionChanged({
              editor: editor,
              oldRange: oldRange,
              range: range,
              source: source
            })
          }

          if (range) {
            return
          }
          $scope.$applyAsync(function () {
            this.ngModelCtrl.$setTouched()
          }.bind(this))
        }.bind(this))

        // update model if text changes
        editor.on('text-change', function (delta, oldDelta, source) {
          var html = editorElem.children[0].innerHTML
          var text = editor.getText()

          if (html === '

') {
            html = null
          }
          this.validate(text)

          if (!modelChanged) {
            $scope.$applyAsync(function () {
              editorChanged = true

              this.ngModelCtrl.$setViewValue(html)

              if (this.onContentChanged) {
                this.onContentChanged({
                  editor: editor,
                  html: html,
                  text: text,
                  delta: delta,
                  oldDelta: oldDelta,
                  source: source
                })
              }
            }.bind(this))
          }
          modelChanged = false
        }.bind(this))

        // set initial content
        if (content) {
          modelChanged = true

          var contents = editor.clipboard.convert(content)
          editor.setContents(contents)
          editor.history.clear()
        }

        // provide event to get informed when editor is created -> pass editor object.
        if (this.onEditorCreated) {
          this.onEditorCreated({editor: editor})
        }
      }
    }]
  })

  return app.name;
}))
<|endoftext|>


<commit_before>import Grid from './components/grid/grid';
import GridService from './services/grid';

import TemplatePath from 'core/template/template.path';
import Head from './components/head/head';
import Foot from './components/foot/foot';
import ColumnList from './components/column/column.list';
import Column from './components/column/column';
import Node from './components/node/node';
import Toolbar from './components/toolbar/toolbar';
import Selection from './components/selection/selection';
import Drag from './components/dnd/drag';
import Drop from './components/dnd/drop';

import BoxCore from './components/grid/box.core';
import ViewCore from './components/view/view.core';
import TdCore from './components/body/td.core';
import ThCore from './components/head/th.core';
import TfCore from './components/foot/tf.core';
import HeadCore from './components/head/head.core';
import BodyCore from './components/body/body.core';
import FootCore from './components/foot/foot.core';
import ToolbarCore from './components/toolbar/toolbar.core';
import SelectionCore from './components/selection/selection.core';

import Indeterminate from './directives/indeterminate';
import Focus from './directives/focus';
import Resize from './directives/resize';
import Markup from './directives/markup';

import ThemeProvider from './services/theme';
import Range from './filters/range';

import * as def from './definition';

// For now should be the last in import list cause use TemplatePath.require
// that should be filled before importing this
// TODO: get rid of static require
import Template from './components/template/tempate';

const coreModule = angular.module(def.MODULE_CORE_NAME, [])
	.component(def.TEMPLATE_NAME, Template)
	.directive(def.DRAG_NAME, () => Drag)
	.directive(def.DROP_NAME, () => Drop)
	.directive(def.INDETERMINATE_NAME, () => Indeterminate)
	.directive(def.FOCUS_NAME, () => Focus)
	.directive(def.RESIZE_NAME, () => Resize)
	.provider(def.THEME_NAME, () => new ThemeProvider())
	.service(def.TEMPLATE_PATH_NAME, () => () => TemplatePath)
	.filter(def.RANGE_NAME, () => Range)
	.name;

const layoutModel = angular.module(def.MODULE_LAYOUT_NAME, [coreModule])
	.component(def.GRID_NAME, Grid)
	.component(def.BOX_CORE_NAME, BoxCore)
	.component(def.VIEW_CORE_NAME, ViewCore)
	.component(def.HEAD_NAME, Head)
	.component(def.FOOT_NAME, Foot)
	.component(def.COLUMN_LIST_NAME, ColumnList)
	.component(def.COLUMN_NAME, Column)
	.component(def.NODE_NAME, Node)
	.component(def.TOOLBAR_NAME, Toolbar)
	.component(def.TOOLBAR_CORE_NAME, ToolbarCore)
	.component(def.SELECTION_NAME, Selection)
	.directive(def.MARKUP_NAME, () => Markup)
	.directive(def.SELECTION_CORE_NAME, () => SelectionCore)
	.directive(def.TD_CORE_NAME, () => TdCore)
	.directive(def.TH_CORE_NAME, () => ThCore)
	.directive(def.TF_CORE_NAME, () => TfCore)
	.directive(def.HEAD_CORE_NAME, () => HeadCore)
	.directive(def.BODY_CORE_NAME, () => BodyCore)
	.directive(def.FOOT_CORE_NAME, () => FootCore)
	.service(def.SERVICE_NAME, GridService)
	.config(Setup)
	.name;

import pluginModule from './plugins';

export default angular
	.module(def.MODULE_NAME, [coreModule, layoutModel, pluginModule])
	.name;

Setup.$inject = ['qgridThemeProvider'];
function Setup(qgridThemeProvider) {
	const EMPTY = '';

	qgridThemeProvider.register('default', theme => {
		theme.put('qgrid.grid.tpl.html', require('./components/grid/grid.html'));
		theme.put('qgrid.view.tpl.html', require('./components/view/view.html'));
		theme.put('qgrid.head.tpl.html', require('./components/head/head.html'));
		theme.put('qgrid.body.tpl.html', require('./components/body/body.html'));
		theme.put('qgrid.foot.tpl.html', require('./components/foot/foot.html'));
		theme.put('qgrid.toolbar.top.tpl.html', require('./components/toolbar/toolbar.top.html'));
		theme.put('qgrid.toolbar.bottom.tpl.html', require('./components/toolbar/toolbar.bottom.html'));
		theme.put('qgrid.toolbar.right.tpl.html', require('./components/toolbar/toolbar.right.html'));
		theme.put('qgrid.toolbar.left.tpl.html', require('./components/toolbar/toolbar.left.html'));

		theme.put('qgrid.head.cell.pad.tpl.html', EMPTY);
		theme.put('qgrid.body.cell.pad.tpl.html', EMPTY);
		theme.put('qgrid.foot.cell.pad.tpl.html', EMPTY);

		theme.put('qgrid.head.cell.pivot.tpl.html', require('./components/cell/pivot/head.cell.pivot.html'));
		theme.put('qgrid.body.cell.pivot.tpl.html', require('./components/cell/pivot/body.cell.pivot.html'));
		theme.put('qgrid.foot.cell.pivot.tpl.html', EMPTY);

		theme.put('qgrid.head.cell.group.tpl.html', require('./components/cell/group/head.cell.group.html'));
		theme.put('qgrid.body.cell.group.tpl.html', require('./components/cell/group/body.cell.group.html'));
		theme.put('qgrid.cell.foot.group.tpl.html', EMPTY);

		theme.put('qgrid.head.cell.text.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.text.tpl.html', require('./components/cell/text/body.cell.text.html'));
		theme.put('qgrid.foot.cell.text.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.text.edit.tpl.html', require('./components/cell/text/body.cell.text.edit.html'));
		theme.put('qgrid.body.cell.text-area.edit.tpl.html', require('./components/cell/text/body.cell.text.edit.html'));

		theme.put('qgrid.head.cell.row-number.tpl.html', require('./components/cell/row-number/head.cell.row.number.html'));
		theme.put('qgrid.body.cell.row-number.tpl.html', require('./components/cell/row-number/body.cell.row.number.html'));
		theme.put('qgrid.foot.cell.row-number.tpl.html', EMPTY);

		theme.put('qgrid.head.cell.row-indicator.tpl.html', EMPTY);
		theme.put('qgrid.body.cell.row-indicator.tpl.html', require('./components/cell/row-indicator/body.cell.row.indicator.html'));
		theme.put('qgrid.foot.cell.row-indicator.tpl.html', EMPTY);

		theme.put('qgrid.head.cell.date.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.date.tpl.html', require('./components/cell/date/body.cell.date.html'));
		theme.put('qgrid.foot.cell.date.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.date.edit.tpl.html', require('./components/cell/date/body.cell.date.edit.html'));

		theme.put('qgrid.head.cell.password.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.password.tpl.html', require('./components/cell/password/body.cell.password.html'));
		theme.put('qgrid.foot.cell.password.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.password.edit.tpl.html', require('./components/cell/password/body.cell.password.edit.html'));

		theme.put('qgrid.head.cell.bool.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.bool.tpl.html', require('./components/cell/bool/body.cell.bool.html'));
		theme.put('qgrid.foot.cell.bool.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.bool.edit.tpl.html', require('./components/cell/bool/body.cell.bool.edit.html'));

		theme.put('qgrid.head.cell.number.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.number.tpl.html', require('./components/cell/text/body.cell.text.html'));
		theme.put('qgrid.foot.cell.number.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.number.edit.tpl.html', require('./components/cell/number/body.cell.number.edit.html'));

		theme.put('qgrid.head.cell.array.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.array.tpl.html', require('./components/cell/array/body.cell.array.html'));
		theme.put('qgrid.foot.cell.array.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.array.edit.tpl.html', require('./components/cell/array/body.cell.array.edit.html'));

		theme.put('qgrid.head.cell.email.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.email.tpl.html', require('./components/cell/email/body.cell.email.html'));
		theme.put('qgrid.foot.cell.email.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.email.edit.tpl.html', require('./components/cell/text/body.cell.text.edit.html'));

		theme.put('qgrid.head.cell.select.tpl.html', require('./components/cell/select/head.cell.select.html'));
		theme.put('qgrid.body.cell.select.tpl.html', require('./components/cell/select/body.cell.select.html'));
		theme.put('qgrid.foot.cell.select.tpl.html', EMPTY);
	});
}<commit_msg>Fix template pos<commit_after>import Grid from './components/grid/grid';
import GridService from './services/grid';

import TemplatePath from 'core/template/template.path';
import Head from './components/head/head';
import Foot from './components/foot/foot';
import ColumnList from './components/column/column.list';
import Column from './components/column/column';
import Node from './components/node/node';
import Toolbar from './components/toolbar/toolbar';
import Selection from './components/selection/selection';
import Drag from './components/dnd/drag';
import Drop from './components/dnd/drop';

import BoxCore from './components/grid/box.core';
import ViewCore from './components/view/view.core';
import TdCore from './components/body/td.core';
import ThCore from './components/head/th.core';
import TfCore from './components/foot/tf.core';
import HeadCore from './components/head/head.core';
import BodyCore from './components/body/body.core';
import FootCore from './components/foot/foot.core';
import ToolbarCore from './components/toolbar/toolbar.core';
import SelectionCore from './components/selection/selection.core';

import Indeterminate from './directives/indeterminate';
import Focus from './directives/focus';
import Resize from './directives/resize';
import Markup from './directives/markup';

import ThemeProvider from './services/theme';
import Range from './filters/range';

import * as def from './definition';

const coreModule = angular.module(def.MODULE_CORE_NAME, [])
	.directive(def.DRAG_NAME, () => Drag)
	.directive(def.DROP_NAME, () => Drop)
	.directive(def.INDETERMINATE_NAME, () => Indeterminate)
	.directive(def.FOCUS_NAME, () => Focus)
	.directive(def.RESIZE_NAME, () => Resize)
	.provider(def.THEME_NAME, () => new ThemeProvider())
	.service(def.TEMPLATE_PATH_NAME, () => () => TemplatePath)
	.filter(def.RANGE_NAME, () => Range)
	.name;

import pluginModule from './plugins';

// For now should be the last in import list cause use TemplatePath.require
// that should be filled before importing this
// TODO: get rid of static require
import Template from './components/template/tempate';

const layoutModel = angular.module(def.MODULE_LAYOUT_NAME, [coreModule])
	.component(def.TEMPLATE_NAME, Template)
	.component(def.GRID_NAME, Grid)
	.component(def.BOX_CORE_NAME, BoxCore)
	.component(def.VIEW_CORE_NAME, ViewCore)
	.component(def.HEAD_NAME, Head)
	.component(def.FOOT_NAME, Foot)
	.component(def.COLUMN_LIST_NAME, ColumnList)
	.component(def.COLUMN_NAME, Column)
	.component(def.NODE_NAME, Node)
	.component(def.TOOLBAR_NAME, Toolbar)
	.component(def.TOOLBAR_CORE_NAME, ToolbarCore)
	.component(def.SELECTION_NAME, Selection)
	.directive(def.MARKUP_NAME, () => Markup)
	.directive(def.SELECTION_CORE_NAME, () => SelectionCore)
	.directive(def.TD_CORE_NAME, () => TdCore)
	.directive(def.TH_CORE_NAME, () => ThCore)
	.directive(def.TF_CORE_NAME, () => TfCore)
	.directive(def.HEAD_CORE_NAME, () => HeadCore)
	.directive(def.BODY_CORE_NAME, () => BodyCore)
	.directive(def.FOOT_CORE_NAME, () => FootCore)
	.service(def.SERVICE_NAME, GridService)
	.config(Setup)
	.name;

export default angular
	.module(def.MODULE_NAME, [coreModule, layoutModel, pluginModule])
	.name;

Setup.$inject = ['qgridThemeProvider'];
function Setup(qgridThemeProvider) {
	const EMPTY = '';

	qgridThemeProvider.register('default', theme => {
		theme.put('qgrid.grid.tpl.html', require('./components/grid/grid.html'));
		theme.put('qgrid.view.tpl.html', require('./components/view/view.html'));
		theme.put('qgrid.head.tpl.html', require('./components/head/head.html'));
		theme.put('qgrid.body.tpl.html', require('./components/body/body.html'));
		theme.put('qgrid.foot.tpl.html', require('./components/foot/foot.html'));
		theme.put('qgrid.toolbar.top.tpl.html', require('./components/toolbar/toolbar.top.html'));
		theme.put('qgrid.toolbar.bottom.tpl.html', require('./components/toolbar/toolbar.bottom.html'));
		theme.put('qgrid.toolbar.right.tpl.html', require('./components/toolbar/toolbar.right.html'));
		theme.put('qgrid.toolbar.left.tpl.html', require('./components/toolbar/toolbar.left.html'));

		theme.put('qgrid.head.cell.pad.tpl.html', EMPTY);
		theme.put('qgrid.body.cell.pad.tpl.html', EMPTY);
		theme.put('qgrid.foot.cell.pad.tpl.html', EMPTY);

		theme.put('qgrid.head.cell.pivot.tpl.html', require('./components/cell/pivot/head.cell.pivot.html'));
		theme.put('qgrid.body.cell.pivot.tpl.html', require('./components/cell/pivot/body.cell.pivot.html'));
		theme.put('qgrid.foot.cell.pivot.tpl.html', EMPTY);

		theme.put('qgrid.head.cell.group.tpl.html', require('./components/cell/group/head.cell.group.html'));
		theme.put('qgrid.body.cell.group.tpl.html', require('./components/cell/group/body.cell.group.html'));
		theme.put('qgrid.cell.foot.group.tpl.html', EMPTY);

		theme.put('qgrid.head.cell.text.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.text.tpl.html', require('./components/cell/text/body.cell.text.html'));
		theme.put('qgrid.foot.cell.text.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.text.edit.tpl.html', require('./components/cell/text/body.cell.text.edit.html'));
		theme.put('qgrid.body.cell.text-area.edit.tpl.html', require('./components/cell/text/body.cell.text.edit.html'));

		theme.put('qgrid.head.cell.row-number.tpl.html', require('./components/cell/row-number/head.cell.row.number.html'));
		theme.put('qgrid.body.cell.row-number.tpl.html', require('./components/cell/row-number/body.cell.row.number.html'));
		theme.put('qgrid.foot.cell.row-number.tpl.html', EMPTY);

		theme.put('qgrid.head.cell.row-indicator.tpl.html', EMPTY);
		theme.put('qgrid.body.cell.row-indicator.tpl.html', require('./components/cell/row-indicator/body.cell.row.indicator.html'));
		theme.put('qgrid.foot.cell.row-indicator.tpl.html', EMPTY);

		theme.put('qgrid.head.cell.date.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.date.tpl.html', require('./components/cell/date/body.cell.date.html'));
		theme.put('qgrid.foot.cell.date.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.date.edit.tpl.html', require('./components/cell/date/body.cell.date.edit.html'));

		theme.put('qgrid.head.cell.password.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.password.tpl.html', require('./components/cell/password/body.cell.password.html'));
		theme.put('qgrid.foot.cell.password.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.password.edit.tpl.html', require('./components/cell/password/body.cell.password.edit.html'));

		theme.put('qgrid.head.cell.bool.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.bool.tpl.html', require('./components/cell/bool/body.cell.bool.html'));
		theme.put('qgrid.foot.cell.bool.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.bool.edit.tpl.html', require('./components/cell/bool/body.cell.bool.edit.html'));

		theme.put('qgrid.head.cell.number.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.number.tpl.html', require('./components/cell/text/body.cell.text.html'));
		theme.put('qgrid.foot.cell.number.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.number.edit.tpl.html', require('./components/cell/number/body.cell.number.edit.html'));

		theme.put('qgrid.head.cell.array.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.array.tpl.html', require('./components/cell/array/body.cell.array.html'));
		theme.put('qgrid.foot.cell.array.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.array.edit.tpl.html', require('./components/cell/array/body.cell.array.edit.html'));

		theme.put('qgrid.head.cell.email.tpl.html', require('./components/cell/text/head.cell.text.html'));
		theme.put('qgrid.body.cell.email.tpl.html', require('./components/cell/email/body.cell.email.html'));
		theme.put('qgrid.foot.cell.email.tpl.html', require('./components/cell/text/foot.cell.text.html'));
		theme.put('qgrid.body.cell.email.edit.tpl.html', require('./components/cell/text/body.cell.text.edit.html'));

		theme.put('qgrid.head.cell.select.tpl.html', require('./components/cell/select/head.cell.select.html'));
		theme.put('qgrid.body.cell.select.tpl.html', require('./components/cell/select/body.cell.select.html'));
		theme.put('qgrid.foot.cell.select.tpl.html', EMPTY);
	});
}<|endoftext|>


<commit_before>module.exports = {
    users: [ // ADD YOUR USERNAME AT THE TOP
        'mattclaw',
        'crankeye',
        'cgroner',
        'tejohnso',
        'sp1d3rx',
        'evsie001',
        'msied',
        'd7p',
        'kasperlewau',
        'kennethrapp',
        'briansoule',
        'qguv',
        'ianwalter',
        'williamle8300',
        'jeffawang',
        'sorpaas',
        'dylnclrk',
        'dcancel',
        'theprofessor117',
        'roryokane',
        'shedd',
        'LeandroLovisolo',
        'euank',
        'humd',
        'bwlang',
        'barretts',
        'pksjce',
        'tito0224',
        'hemanth',
        'treygriffith',
        'megamattron',
        'pents90',
        'michaelnovakjr',
        'markbao',
        'kalmi',
        'lablayers',
        'dfjones'
    ]
};<commit_msg>Added `bluetidepro` to users<commit_after>module.exports = {
    users: [ // ADD YOUR USERNAME AT THE TOP
        'mattclaw',
        'crankeye',
        'cgroner',
        'tejohnso',
        'sp1d3rx',
        'evsie001',
        'msied',
        'd7p',
        'kasperlewau',
        'kennethrapp',
        'briansoule',
        'qguv',
        'ianwalter',
        'williamle8300',
        'jeffawang',
        'sorpaas',
        'dylnclrk',
        'dcancel',
        'theprofessor117',
        'roryokane',
        'shedd',
        'LeandroLovisolo',
        'euank',
        'humd',
        'bwlang',
        'barretts',
        'pksjce',
        'tito0224',
        'hemanth',
        'treygriffith',
        'megamattron',
        'pents90',
        'michaelnovakjr',
        'markbao',
        'kalmi',
        'lablayers',
        'dfjones',
        'bluetidepro'
    ]
};<|endoftext|>


<commit_before>goog.provide('ol.IView');

goog.require('ol.IView2D');
goog.require('ol.IView3D');

/**
 * Interface for views.
 * @interface
 */
ol.IView = function() {
};

/**
 * @return {ol.IView2D} View2D.
 */
ol.IView.prototype.getView2D = function() {
};

/**
 * @return {ol.IView3D} View3D.
 */
ol.IView.prototype.getView3D = function() {
};

/**
 * @return {boolean} Is defined.
 */
ol.IView.prototype.isDef = function() {
};
<commit_msg>Make ol.View2D available when exploring olx.MapOptions<commit_after>goog.provide('ol.IView');

goog.require('ol.IView2D');
goog.require('ol.IView3D');

/**
 * Interface for views. Currently {@link ol.View2D} is implemented.
 * @interface
 */
ol.IView = function() {
};

/**
 * @return {ol.IView2D} View2D.
 */
ol.IView.prototype.getView2D = function() {
};

/**
 * @return {ol.IView3D} View3D.
 */
ol.IView.prototype.getView3D = function() {
};

/**
 * @return {boolean} Is defined.
 */
ol.IView.prototype.isDef = function() {
};
<|endoftext|>


<commit_before>var PROMPT = "> ";

function runmath(s) {
    var ans;
    try {
        ans = new require("./calc-grammar.js")().feed(s);
        if (ans.results.length) {
            return ans.results[0].toString();
        } else {
            var out = new Array(PROMPT.length + s.length).join("-") + "^  Error.";
            return out;
        }
    } catch(e) {
        var out = new Array(PROMPT.length + e.offset + 1).join("-") + "^  Error.";
        return out;
    }
}

var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);

rl.setPrompt(PROMPT);
rl.prompt();

rl.on('line', function(line) {
    console.log(runmath(line));
    rl.prompt();
}).on('close', function() {
    console.log('\nBye.');
    process.exit(0);
});
<commit_msg>comments... comments everywhere\!<commit_after>// This is an example of how to use a nearley-made grammar.
var PROMPT = "> ";

// This is where the action is.
function runmath(s) {
    var ans;
    try {// We want to catch parse errors and die appropriately

        // Make a parser and feed the input
        ans = new require("./calc-grammar.js")()
            .feed(s);

        // Check if there are any results
        if (ans.results.length) {
            return ans.results[0].toString();
        } else {
            // This means the input is incomplete.
            var out = "Error: incomplete input, parse failed. :(";
            return out;
        }
    } catch(e) {
        // Panic in style, by graphically pointing out the error location.
        var out = new Array(PROMPT.length + e.offset + 1).join("-") + "^  Error.";
        //                                  --------
        //                                         ^ This comes from nearley!
        return out;
    }
}

// node readline gunk. Nothing too exciting.
var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);

rl.setPrompt(PROMPT);
rl.prompt();

rl.on('line', function(line) {
    console.log(runmath(line));
    rl.prompt();
}).on('close', function() {
    console.log('\nBye.');
    process.exit(0);
});
<|endoftext|>


<commit_before>Videbligo.directive('result', ['MetadataService', function (MetadataService) {

    return {
        restrict: 'AE',
        templateUrl: 'result_widget/result.html',
        scope: {
            elementsPerPage: '@'
        },
        link: function (scope, element, attrs) {
            scope.crossData = [];
            scope.entries = [];
            scope.length = 0;
            scope.dimOne = null;

            scope.elementsPerPage = 20;

            scope.init = function () {
                var data = MetadataService.getData();
                scope.dimOne = data.dimension(function (d) {
                    return d;
                });
                /* Set of */
                scope.visibleDetailsDivs = new StringSet();
                scope.licence_mapping = licence_mapping;
                scope.category_mapping = category_mapping;

                if(attrs.elementsPerPage) {
                    scope.elementsPerPage = parseInt(attrs.elementsPerPage);
                }

                scope.maxPage = Math.ceil(scope.length / scope.elementsPerPage);
            };
            MetadataService.registerWidget(scope.init);

            scope.$on('filterChanged', function () {
                scope.entries = scope.dimOne.top(Infinity);
                scope.length = MetadataService.length();
            });

            //default value for orderProp
            scope.orderProp = 'age';

            /**
             * Item *key* zum Set der aktuell sichtbaren Elemente hinzufuegen oder aus diesem loeschen
             *
             * @param key
             */
            scope.toggleVisible = function (key) {
                if(scope.visibleDetailsDivs.contains(key)) {
                    scope.visibleDetailsDivs.remove(key);
                } else {
                    scope.visibleDetailsDivs.add(key);
                }
            };

        }
    };
}]);<commit_msg>Update result.js<commit_after>Videbligo.directive('result', ['MetadataService', function (MetadataService) {

    return {
        restrict: 'AE',
        templateUrl: 'result_widget/result.html',
        scope: {
            elementsPerPage: '@'
        },//to separate the scope inside this directive from the one outside
        link: function (scope, element, attrs) {
            scope.crossData = [];
            scope.entries = [];
            scope.length = 0;
            scope.dimOne = null;

            scope.elementsPerPage = 20; //for pagination

            scope.init = function () {
                var data = MetadataService.getData();
                scope.dimOne = data.dimension(function (d) { //to craet a dimention for crossfilter
                    return d;
                });
                /* Set of */
                scope.visibleDetailsDivs = new StringSet();
                scope.licence_mapping = licence_mapping;
                scope.category_mapping = category_mapping;

                if(attrs.elementsPerPage) {
                    scope.elementsPerPage = parseInt(attrs.elementsPerPage);
                }
                //to set the maximum number of pages , we need to represent the result .
                scope.maxPage = Math.ceil(scope.length / scope.elementsPerPage);
            };
            MetadataService.registerWidget(scope.init);

            scope.$on('filterChanged', function () {
                //to make the data ,which are in the dimention we made as our entries
                scope.entries = scope.dimOne.top(Infinity);
                scope.length = MetadataService.length();
            });

            //default value for orderProp
            scope.orderProp = 'age';

            /**
             * the  Item *key* to set currently visible item or to delet it
             *
             * @param key
             */
            scope.toggleVisible = function (key) {
                if(scope.visibleDetailsDivs.contains(key)) {
                    //to hide the details after the click on the down-arrow
                    scope.visibleDetailsDivs.remove(key);
                } else {
                    //to show the details after the click on the down-arrow
                    scope.visibleDetailsDivs.add(key);
                }
            };

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


<commit_before>var events = require('events')
var subleveldown = require('subleveldown')
var swarm = require('webrtc-swarm')
var signalhub = require('signalhub')
var levelup = require('levelup')
var leveldown = require('leveldown')
var hyperlog = require('hyperlog')
var ghsign = require('ghsign')
var through = require('through2')

module.exports = createSwarm

function createSwarm (app) {
  var emitter = new events.EventEmitter()
  var db = levelup('../friendsdb', {db: leveldown})
  var logs = {}

  emitter.logs = logs
  emitter.db = db

  var sign
  var processor

  var startProcessor = function (log) {
    if (log.processing) return
    log.processing = true
    log.ready(function () {
      var rs = log.createReadStream({
        live: true,
        since: Math.max(log.changes - 500, 0)
      })

      rs.pipe(through.obj(function (data, enc, cb) {
        processor(data, cb)
      }))
    })
  }

  emitter.process = function (fn) {
    processor = fn
  }

  emitter.addChannel = function (name) {
    if (logs[name]) return

    var log = logs[name] = hyperlog(subleveldown(db, 'logs#' + name))
    var id = 'friends-' + name
    var hub = signalhub('http://dev.mathiasbuus.eu:8080', id)
    var sw = swarm(hub)

    sw.on('peer', function (p, id) {
      var stream = log.replicate({live: true})

      emitter.emit('peer', p, id, stream)

      stream.on('push', function () {
        emitter.emit('push')
        console.log('pushing node')
      })

      stream.on('pull', function () {
        emitter.emit('pull')
        console.log('pulling node')
      })

      p.pipe(stream).pipe(p)
    })

    startProcessor(log)
  }

  emitter.send = function (message, cb) {
    if (!sign && emitter.username) {
      sign = ghsign.signer(emitter.username)
    }

    var addMessage = function () {
      var ch = message.channel || 'friends'
      emitter.addChannel(ch)
      var log = logs[ch]
      log.heads(function (err, heads) {
        if (err) return cb(err)
        log.add(heads, JSON.stringify(message), cb)
      })
    }

    if (sign) {
      var msg = Buffer.concat([
        new Buffer(message.username),
        new Buffer(message.channel ? message.channel : ''),
        new Buffer(message.text),
        new Buffer(message.timestamp.toString())
      ])
      sign(msg, function (err, sig) {
        if (err) return cb(err)
        if (sig) {
          message.sig = sig.toString('base64')
        }
        addMessage()
      })
      return
    }

    addMessage()
  }

  emitter.addChannel('friends') // add default channel

  var loop = function (prev) { // todo: error handling :/
    var rs = db.createKeyStream({
      gt: '!logs#',
      lt: '!logs#' + (prev ? prev + '!' : '~'),
      limit: 1,
      reverse: true
    })

    var found = null

    rs.once('data', function (key) {
      found = key
    })

    rs.on('end', function () {
      if (!found) return
      var name = found.split('!logs#')[1].split('!')[0]
      emitter.addChannel(name)
      loop(name)
    })
  }

  loop()

  return emitter
}
<commit_msg>hehehe<commit_after>var events = require('events')
var subleveldown = require('subleveldown')
var swarm = require('webrtc-swarm')
var signalhub = require('signalhub')
var levelup = require('levelup')
var leveldown = require('leveldown')
var hyperlog = require('hyperlog')
var ghsign = require('ghsign')
var through = require('through2')

module.exports = createSwarm

function createSwarm (app) {
  var emitter = new events.EventEmitter()
  var db = levelup('./friendsdb', {db: leveldown})
  var logs = {}

  emitter.logs = logs
  emitter.db = db

  var sign
  var processor

  var startProcessor = function (log) {
    if (log.processing) return
    log.processing = true
    log.ready(function () {
      var rs = log.createReadStream({
        live: true,
        since: Math.max(log.changes - 500, 0)
      })

      rs.pipe(through.obj(function (data, enc, cb) {
        processor(data, cb)
      }))
    })
  }

  emitter.process = function (fn) {
    processor = fn
  }

  emitter.addChannel = function (name) {
    if (logs[name]) return

    var log = logs[name] = hyperlog(subleveldown(db, 'logs#' + name))
    var id = 'friends-' + name
    var hub = signalhub('http://dev.mathiasbuus.eu:8080', id)
    var sw = swarm(hub)

    sw.on('peer', function (p, id) {
      var stream = log.replicate({live: true})

      emitter.emit('peer', p, id, stream)

      stream.on('push', function () {
        emitter.emit('push')
        console.log('pushing node')
      })

      stream.on('pull', function () {
        emitter.emit('pull')
        console.log('pulling node')
      })

      p.pipe(stream).pipe(p)
    })

    startProcessor(log)
  }

  emitter.send = function (message, cb) {
    if (!sign && emitter.username) {
      sign = ghsign.signer(emitter.username)
    }

    var addMessage = function () {
      var ch = message.channel || 'friends'
      emitter.addChannel(ch)
      var log = logs[ch]
      log.heads(function (err, heads) {
        if (err) return cb(err)
        log.add(heads, JSON.stringify(message), cb)
      })
    }

    if (sign) {
      var msg = Buffer.concat([
        new Buffer(message.username),
        new Buffer(message.channel ? message.channel : ''),
        new Buffer(message.text),
        new Buffer(message.timestamp.toString())
      ])
      sign(msg, function (err, sig) {
        if (err) return cb(err)
        if (sig) {
          message.sig = sig.toString('base64')
        }
        addMessage()
      })
      return
    }

    addMessage()
  }

  emitter.addChannel('friends') // add default channel

  var loop = function (prev) { // todo: error handling :/
    var rs = db.createKeyStream({
      gt: '!logs#',
      lt: '!logs#' + (prev ? prev + '!' : '~'),
      limit: 1,
      reverse: true
    })

    var found = null

    rs.once('data', function (key) {
      found = key
    })

    rs.on('end', function () {
      if (!found) return
      var name = found.split('!logs#')[1].split('!')[0]
      emitter.addChannel(name)
      loop(name)
    })
  }

  loop()

  return emitter
}
<|endoftext|>


<commit_before>const _ = require('lodash');
const path = require('path');
const fs = require('fs-extra');
// const shell = require('shelljs');
const traverse = require('@babel/traverse').default;

const { ast, paths, vio, config, files } = rekit.core;

let elementById = {};
const filePropsCache = {};

function getFileProps(file) {
  if (filePropsCache[file] && filePropsCache[file].content === vio.getContent(file)) {
    return filePropsCache[file].props;
  }

  const name = path.basename(file);
  let isComponent = false;
  let isAction = false;

  // If it's pascal case and has same style file, it's a component
  if (
    /^[A-Z][a-zA-Z0-9]*\.jsx?$/.test(name) &&
    vio.fileExists(file.replace(/\.jsx?$/, `.${config.getRekitConfig().css}`))
  ) {
    isComponent = true;
  }

  // Files under redux folder are all actions excepts actions.js|constants.js|reducer.js|initialState.js
  if (
    /^src\/features\/[\w\d-]+\/redux\/[\w.]+$/.test(file) &&
    !['actions.js', 'constants.js', 'reducer.js', 'initialState.js'].includes(name)
  ) {
    isAction = true;
  }

  const fileAst = ast.getAst(file);
  const ff = {}; // File features

  traverse(fileAst, {
    ImportDeclaration(path) {
      switch (path.node.source.value) {
        case 'react':
          ff.importReact = true;
          break;
        case 'redux':
          ff.importRedux = true;
          break;
        case 'react-redux':
          ff.importReactRedux = true;
          break;
        case './constants':
          ff.importConstant = true;
          ff.importMultipleConstants = path.node.specifiers.length > 3;
          break;
        default:
          break;
      }
    },
    ClassDeclaration(path) {
      if (
        path.node.superClass &&
        path.node.body.body.some(n => n.type === 'ClassMethod' && n.key.name === 'render')
      ) {
        ff.hasClassAndRenderMethod = true;
      }
    },
    CallExpression(path) {
      if (path.node.callee.name === 'connect') {
        ff.connectCall = true;
      }
    },
    ExportNamedDeclaration(path) {
      if (_.get(path, 'node.declaration.id.name') === 'reducer') {
        ff.exportReducer = true;
      }
    },
  });
  const props = {
    component: isComponent && {
      connectToStore: ff.importReactRedux && ff.connectCall,
    },
    action: isAction && {
      isAsync: ff.importMultipleConstants,
    },
    syntaxError: !fileAst,
  };

  if (props.component) props.type = 'component';
  else if (props.action) props.type = 'action';

  filePropsCache[file] = {
    content: vio.getContent(file),
    props,
  };
  return props;
}

function getComponents(feature) {
  const components = [];
  const eleFolder = elementById[`src/features/${feature}`];
  eleFolder.children
    .map(eid => elementById[eid])
    .forEach(ele => {
      if (ele.type === 'file' && /\.jsx?$/.test(ele.name) && getFileProps(ele.id).component) {
        const styleFile = ele.id.replace(/\.jsx?$/, `.${rekit.core.config.getRekitConfig().css}`);
        const testFile = ele.id.replace(/^src\//, 'tests/').replace(/\.jsx?$/, '.test.js');
        const views = [
          { key: 'diagram', name: 'Diagram' },
          { key: 'code', name: 'Code', target: ele.id, isDefault: true },
          { key: 'style', name: 'Style', target: styleFile },
          { key: 'test', name: 'Test', target: testFile },
        ];
        const id = `v:${ele.id}`;
        const parts = [ele.id, styleFile, testFile];
        const name = ele.name.replace(/\.[^.]*$/, '');
        components.push({
          type: 'component',
          id,
          name,
          props: getFileProps(ele.id).component,
          views,
          parts,
        });
      }
    });

  components.forEach(c => {
    elementById[c.id] = c;
  });
  return components.map(c => c.id);
}

function getActions(feature) {
  const actions = [];
  const eleFolder = elementById[`src/features/${feature}/redux`];
  if (!eleFolder) return [];
  eleFolder.children
    .map(eid => elementById[eid])
    .forEach(ele => {
      if (ele.type === 'file' && /\.js$/.test(ele.name) && getFileProps(ele.id).action) {
        const testFile = ele.id.replace(/^src\//, 'tests/').replace(/\.js$/, '.test.js');
        const views = [
          { key: 'diagram', name: 'Diagram' },
          { key: 'code', name: 'Code', target: ele.id, isDefault: true },
          { key: 'test', name: 'Test', target: testFile },
        ];
        const id = `v:${ele.id}`;
        const parts = [ele.id, testFile];
        actions.push({
          type: 'action',
          id,
          name: ele.name.replace(/\.[^.]*$/, ''),
          props: getFileProps(ele.id).action,
          views,
          parts,
        });
      }
    });

  actions.forEach(c => {
    elementById[c.id] = c;
  });
  return actions.map(c => c.id);
}

function getRootRoutePath() {
  const targetPath = 'src/common/routeConfig.js';
  const theAst = ast.getAst(targetPath);
  let rootPath = '';
  traverse(theAst, {
    ObjectExpression(path) {
      const node = path.node;
      const props = node.properties;
      if (!props.length) return;
      const obj = {};
      props.forEach(p => {
        if (_.has(p, 'key.name') && !p.computed) {
          obj[p.key.name] = p;
        }
      });
      if (obj.path && obj.childRoutes && !rootPath) {
        rootPath = _.get(obj.path, 'value.value');
      }
    },
  });
  return rootPath;
}

/**
 * Get route rules defined in a feature.
 * @param {string} feature - The feature name.
 */
function getRoutes(feature) {
  const targetPath = `src/features/${feature}/route.js`; //utils.mapFeatureFile(feature, 'route.js');
  if (vio.fileNotExists(targetPath)) return [];
  const theAst = ast.getAst(targetPath);
  const arr = [];
  let rootPath = '';
  let indexRoute = null;

  traverse(theAst, {
    ObjectExpression(path) {
      const node = path.node;
      const props = node.properties;
      if (!props.length) return;
      const obj = {};
      props.forEach(p => {
        if (_.has(p, 'key.name') && !p.computed) {
          obj[p.key.name] = p;
        }
      });
      if (obj.path && obj.component) {
        // in a route config, if an object expression has both 'path' and 'component' property, then it's a route config
        arr.push({
          path: _.get(obj.path, 'value.value'), // only string literal supported
          component: _.get(obj.component, 'value.name'), // only identifier supported
          isIndex: !!obj.isIndex && _.get(obj.isIndex, 'value.value'), // suppose to be boolean
          node: {
            start: node.start,
            end: node.end,
          },
        });
      }
      if (obj.isIndex && obj.component && !indexRoute) {
        // only find the first index route
        indexRoute = {
          component: _.get(obj.component, 'value.name'),
        };
      }
      if (obj.path && obj.childRoutes && !rootPath) {
        rootPath = _.get(obj.path, 'value.value');
        if (!rootPath) rootPath = '$none'; // only find the first rootPath
      }
    },
  });
  const prjRootPath = getRootRoutePath();
  if (rootPath === '$none') rootPath = prjRootPath;
  else if (!/^\//.test(rootPath)) rootPath = prjRootPath + '/' + rootPath;
  rootPath = rootPath.replace(/\/+/, '/');
  arr.forEach(item => {
    if (!/^\//.test(item.path)) {
      item.path = (rootPath + '/' + item.path).replace(/\/+/, '/');
    }
  });
  if (indexRoute) {
    indexRoute.path = rootPath;
    arr.unshift(indexRoute);
  }
  return arr;
}

// function getFiles(feature) {
//   const res = app.readDir(paths.map(`src/features/${feature}`));
//   Object.assign(elementById, res.elementById);
//   return res.elements;
// }

function getInitialState(feature) {
  const id = `v:${feature}-initial-state`;
  const codeFile = `src/features/${feature}/redux/initialState.js`;
  const ele = {
    id,
    type: 'initial-state',
    target: codeFile,
    parts: [codeFile],
    name: 'initialState',
  };
  elementById[id] = ele;
  return ele;
}

function getFeatures() {
  // return _.toArray(shell.ls(rekit.core.paths.map('src/features')));
  const elements = [];
  if (!elementById['src/features']) return [];
  const eles = elementById['src/features'].children.map(eid => elementById[eid]);
  eles.forEach(ele => {
    if (ele.type !== 'folder') {
      elements.push(ele.id);
      return;
    }
    // feature name
    const f = ele.id.split('/').pop();
    const routes = getRoutes(f);
    const actions = getActions(f);
    const components = getComponents(f);

    actions.unshift(getInitialState(f).id);

    const routeFilePath = `src/features/${f}/route.js`;
    const children = [
      {
        id: `v:${f}-routes`,
        type: 'routes',
        name: 'Routes',
        feature: f,
        parts: [routeFilePath],
        views: [
          { key: 'diagram', name: 'Diagram' },
          { key: 'rules', name: 'Rules' },
          { key: 'code', name: 'Code', target: routeFilePath, isDefault: true },
        ],
        routes,
      },
      {
        id: `v:${f}-actions`,
        type: 'actions',
        name: 'Actions',
        children: actions,
      },
      {
        id: `v:${f}-components`,
        type: 'components',
        name: 'Components',
        children: components,
      },
    ];

    const toRemoveFromMisc = {};
    const generateToRemoveFromMisc = children =>
      children
        .map(eid => (typeof eid === 'string' ? elementById[eid] : eid))
        .forEach(ele => {
          if (ele.parts) {
            ele.parts.forEach(p => {
              toRemoveFromMisc[p] = true;
            });
          }
          if (ele.children) generateToRemoveFromMisc(ele.children);
        });
    generateToRemoveFromMisc(children);

    const filterNonMisc = children => {
      const filtered = children.filter(cid => !toRemoveFromMisc[cid]);
      filtered
        .map(cid => elementById[cid])
        .forEach(c => {
          if (c.children) c.children = filterNonMisc(c.children);
        });
      return filtered;
    };
    const misc = filterNonMisc(elementById[`src/features/${f}`].children);
    children.push({
      id: `v:${f}-misc`,
      target: `src/features/${f}`,
      type: 'folder-alias',
      name: 'Others',
      children: misc,
    });

    const id = `v:feature-${f}`;
    elements.push(id);
    elementById[id] = {
      type: 'feature',
      id,
      name: f,
      children: children.map(c => c.id),
    };
    children.forEach(c => {
      elementById[c.id] = c;
    });
  });
  return elements;
}

function getProjectData(args) {
  const srcFiles = files.readDir(paths.map('src'), args);
  const testFiles = files.readDir(paths.map('tests'), args);
  elementById = { ...srcFiles.elementById, ...testFiles.elementById };

  const eleFeatures = {
    type: 'features',
    id: 'v:features',
    name: 'Features',
    children: getFeatures(),
  };

  const eleMisc = {
    type: 'folder-alias',
    id: 'v:_src-misc',
    name: 'src',
    target: 'src',
    icon: 'src-folder',
    children: srcFiles.elements.filter(eid => eid !== 'src/features'),
  };

  const elements = [];

  [eleFeatures, eleMisc].forEach(ele => {
    elements.push(ele.id);
    elementById[ele.id] = ele;
  });
  const folders = config.getRekitConfig().folders || [];
  folders.forEach(f => {
    if (!fs.existsSync(paths.map(f))) return;
    const res = files.readDir(paths.map(f));
    Object.assign(elementById, res.elementById);

    const folderEle = {
      type: 'folder-alias',
      id: 'v:folder-' + f,
      name: f,
      target: f,
      children: res.elements,
    };
    if (!elementById[folderEle.id]) {
      elementById[folderEle.id] = folderEle;
      elements.push(folderEle.id);
    }
  });

  const extraFiles = config.getRekitConfig().files || [];
  extraFiles.forEach(f => {
    if (!fs.existsSync(paths.map(f))) return;
    const fileEle = files.getFileElement(paths.map(f));
    if (!elementById[fileEle.id]) {
      elementById[fileEle.id] = fileEle;
      elements.push(fileEle.id);
    }
  });

  return { elements, elementById };
}

module.exports = {
  getProjectData,
  getFileProps,
};
<commit_msg>Show all files by default in rekit react app.<commit_after>const _ = require('lodash');
const path = require('path');
const fs = require('fs-extra');
// const shell = require('shelljs');
const traverse = require('@babel/traverse').default;

const { ast, paths, vio, config, files } = rekit.core;

let elementById = {};
const filePropsCache = {};

function getFileProps(file) {
  if (filePropsCache[file] && filePropsCache[file].content === vio.getContent(file)) {
    return filePropsCache[file].props;
  }

  const name = path.basename(file);
  let isComponent = false;
  let isAction = false;

  // If it's pascal case and has same style file, it's a component
  if (
    /^[A-Z][a-zA-Z0-9]*\.jsx?$/.test(name) &&
    vio.fileExists(file.replace(/\.jsx?$/, `.${config.getRekitConfig().css}`))
  ) {
    isComponent = true;
  }

  // Files under redux folder are all actions excepts actions.js|constants.js|reducer.js|initialState.js
  if (
    /^src\/features\/[\w\d-]+\/redux\/[\w.]+$/.test(file) &&
    !['actions.js', 'constants.js', 'reducer.js', 'initialState.js'].includes(name)
  ) {
    isAction = true;
  }

  const fileAst = ast.getAst(file);
  const ff = {}; // File features

  traverse(fileAst, {
    ImportDeclaration(path) {
      switch (path.node.source.value) {
        case 'react':
          ff.importReact = true;
          break;
        case 'redux':
          ff.importRedux = true;
          break;
        case 'react-redux':
          ff.importReactRedux = true;
          break;
        case './constants':
          ff.importConstant = true;
          ff.importMultipleConstants = path.node.specifiers.length > 3;
          break;
        default:
          break;
      }
    },
    ClassDeclaration(path) {
      if (
        path.node.superClass &&
        path.node.body.body.some(n => n.type === 'ClassMethod' && n.key.name === 'render')
      ) {
        ff.hasClassAndRenderMethod = true;
      }
    },
    CallExpression(path) {
      if (path.node.callee.name === 'connect') {
        ff.connectCall = true;
      }
    },
    ExportNamedDeclaration(path) {
      if (_.get(path, 'node.declaration.id.name') === 'reducer') {
        ff.exportReducer = true;
      }
    },
  });
  const props = {
    component: isComponent && {
      connectToStore: ff.importReactRedux && ff.connectCall,
    },
    action: isAction && {
      isAsync: ff.importMultipleConstants,
    },
    syntaxError: !fileAst,
  };

  if (props.component) props.type = 'component';
  else if (props.action) props.type = 'action';

  filePropsCache[file] = {
    content: vio.getContent(file),
    props,
  };
  return props;
}

function getComponents(feature) {
  const components = [];
  const eleFolder = elementById[`src/features/${feature}`];
  eleFolder.children
    .map(eid => elementById[eid])
    .forEach(ele => {
      if (ele.type === 'file' && /\.jsx?$/.test(ele.name) && getFileProps(ele.id).component) {
        const styleFile = ele.id.replace(/\.jsx?$/, `.${rekit.core.config.getRekitConfig().css}`);
        const testFile = ele.id.replace(/^src\//, 'tests/').replace(/\.jsx?$/, '.test.js');
        const views = [
          { key: 'diagram', name: 'Diagram' },
          { key: 'code', name: 'Code', target: ele.id, isDefault: true },
          { key: 'style', name: 'Style', target: styleFile },
          { key: 'test', name: 'Test', target: testFile },
        ];
        const id = `v:${ele.id}`;
        const parts = [ele.id, styleFile, testFile];
        const name = ele.name.replace(/\.[^.]*$/, '');
        components.push({
          type: 'component',
          id,
          name,
          props: getFileProps(ele.id).component,
          views,
          parts,
        });
      }
    });

  components.forEach(c => {
    elementById[c.id] = c;
  });
  return components.map(c => c.id);
}

function getActions(feature) {
  const actions = [];
  const eleFolder = elementById[`src/features/${feature}/redux`];
  if (!eleFolder) return [];
  eleFolder.children
    .map(eid => elementById[eid])
    .forEach(ele => {
      if (ele.type === 'file' && /\.js$/.test(ele.name) && getFileProps(ele.id).action) {
        const testFile = ele.id.replace(/^src\//, 'tests/').replace(/\.js$/, '.test.js');
        const views = [
          { key: 'diagram', name: 'Diagram' },
          { key: 'code', name: 'Code', target: ele.id, isDefault: true },
          { key: 'test', name: 'Test', target: testFile },
        ];
        const id = `v:${ele.id}`;
        const parts = [ele.id, testFile];
        actions.push({
          type: 'action',
          id,
          name: ele.name.replace(/\.[^.]*$/, ''),
          props: getFileProps(ele.id).action,
          views,
          parts,
        });
      }
    });

  actions.forEach(c => {
    elementById[c.id] = c;
  });
  return actions.map(c => c.id);
}

function getRootRoutePath() {
  const targetPath = 'src/common/routeConfig.js';
  const theAst = ast.getAst(targetPath);
  let rootPath = '';
  traverse(theAst, {
    ObjectExpression(path) {
      const node = path.node;
      const props = node.properties;
      if (!props.length) return;
      const obj = {};
      props.forEach(p => {
        if (_.has(p, 'key.name') && !p.computed) {
          obj[p.key.name] = p;
        }
      });
      if (obj.path && obj.childRoutes && !rootPath) {
        rootPath = _.get(obj.path, 'value.value');
      }
    },
  });
  return rootPath;
}

/**
 * Get route rules defined in a feature.
 * @param {string} feature - The feature name.
 */
function getRoutes(feature) {
  const targetPath = `src/features/${feature}/route.js`; //utils.mapFeatureFile(feature, 'route.js');
  if (vio.fileNotExists(targetPath)) return [];
  const theAst = ast.getAst(targetPath);
  const arr = [];
  let rootPath = '';
  let indexRoute = null;

  traverse(theAst, {
    ObjectExpression(path) {
      const node = path.node;
      const props = node.properties;
      if (!props.length) return;
      const obj = {};
      props.forEach(p => {
        if (_.has(p, 'key.name') && !p.computed) {
          obj[p.key.name] = p;
        }
      });
      if (obj.path && obj.component) {
        // in a route config, if an object expression has both 'path' and 'component' property, then it's a route config
        arr.push({
          path: _.get(obj.path, 'value.value'), // only string literal supported
          component: _.get(obj.component, 'value.name'), // only identifier supported
          isIndex: !!obj.isIndex && _.get(obj.isIndex, 'value.value'), // suppose to be boolean
          node: {
            start: node.start,
            end: node.end,
          },
        });
      }
      if (obj.isIndex && obj.component && !indexRoute) {
        // only find the first index route
        indexRoute = {
          component: _.get(obj.component, 'value.name'),
        };
      }
      if (obj.path && obj.childRoutes && !rootPath) {
        rootPath = _.get(obj.path, 'value.value');
        if (!rootPath) rootPath = '$none'; // only find the first rootPath
      }
    },
  });
  const prjRootPath = getRootRoutePath();
  if (rootPath === '$none') rootPath = prjRootPath;
  else if (!/^\//.test(rootPath)) rootPath = prjRootPath + '/' + rootPath;
  rootPath = rootPath.replace(/\/+/, '/');
  arr.forEach(item => {
    if (!/^\//.test(item.path)) {
      item.path = (rootPath + '/' + item.path).replace(/\/+/, '/');
    }
  });
  if (indexRoute) {
    indexRoute.path = rootPath;
    arr.unshift(indexRoute);
  }
  return arr;
}

// function getFiles(feature) {
//   const res = app.readDir(paths.map(`src/features/${feature}`));
//   Object.assign(elementById, res.elementById);
//   return res.elements;
// }

function getInitialState(feature) {
  const id = `v:${feature}-initial-state`;
  const codeFile = `src/features/${feature}/redux/initialState.js`;
  const ele = {
    id,
    type: 'initial-state',
    target: codeFile,
    parts: [codeFile],
    name: 'initialState',
  };
  elementById[id] = ele;
  return ele;
}

function getFeatures() {
  // return _.toArray(shell.ls(rekit.core.paths.map('src/features')));
  const elements = [];
  if (!elementById['src/features']) return [];
  const eles = elementById['src/features'].children.map(eid => elementById[eid]);
  eles.forEach(ele => {
    if (ele.type !== 'folder') {
      elements.push(ele.id);
      return;
    }
    // feature name
    const f = ele.id.split('/').pop();
    const routes = getRoutes(f);
    const actions = getActions(f);
    const components = getComponents(f);

    actions.unshift(getInitialState(f).id);

    const routeFilePath = `src/features/${f}/route.js`;
    const children = [
      {
        id: `v:${f}-routes`,
        type: 'routes',
        name: 'Routes',
        feature: f,
        parts: [routeFilePath],
        views: [
          { key: 'diagram', name: 'Diagram' },
          { key: 'rules', name: 'Rules' },
          { key: 'code', name: 'Code', target: routeFilePath, isDefault: true },
        ],
        routes,
      },
      {
        id: `v:${f}-actions`,
        type: 'actions',
        name: 'Actions',
        children: actions,
      },
      {
        id: `v:${f}-components`,
        type: 'components',
        name: 'Components',
        children: components,
      },
    ];

    const toRemoveFromMisc = {};
    const generateToRemoveFromMisc = children =>
      children
        .map(eid => (typeof eid === 'string' ? elementById[eid] : eid))
        .forEach(ele => {
          if (ele.parts) {
            ele.parts.forEach(p => {
              toRemoveFromMisc[p] = true;
            });
          }
          if (ele.children) generateToRemoveFromMisc(ele.children);
        });
    generateToRemoveFromMisc(children);

    const filterNonMisc = children => {
      const filtered = children.filter(cid => !toRemoveFromMisc[cid]);
      filtered
        .map(cid => elementById[cid])
        .forEach(c => {
          if (c.children) c.children = filterNonMisc(c.children);
        });
      return filtered;
    };
    const misc = filterNonMisc(elementById[`src/features/${f}`].children);
    children.push({
      id: `v:${f}-misc`,
      target: `src/features/${f}`,
      type: 'folder-alias',
      name: 'Others',
      children: misc,
    });

    const id = `v:feature-${f}`;
    elements.push(id);
    elementById[id] = {
      type: 'feature',
      id,
      name: f,
      children: children.map(c => c.id),
    };
    children.forEach(c => {
      elementById[c.id] = c;
    });
  });
  return elements;
}

function getProjectData(args) {
  const allFiles = files.readDir(paths.getProjectRoot(), args);
  elementById = allFiles.elementById;
  // const srcFiles = files.readDir(paths.map('src'), args);
  // const testFiles = files.readDir(paths.map('tests'), args);
  // elementById = { ...srcFiles.elementById, ...testFiles.elementById };

  const eleFeatures = {
    type: 'features',
    id: 'v:features',
    name: 'Features',
    children: getFeatures(),
  };

  const eleSrc = {
    type: 'folder-alias',
    id: 'v:_src-misc',
    name: 'src',
    target: 'src',
    icon: 'src-folder',
    children: elementById['src'].children.filter(eid => eid !== 'src/features'),
  };

  const elements = allFiles.elements;
  _.pull(elements, 'tests');

  [eleSrc, eleFeatures].forEach(ele => {
    elements.unshift(ele.id);
    elementById[ele.id] = ele;
  });
  // const folders = config.getRekitConfig().folders || [];
  // folders.forEach(f => {
  //   if (!fs.existsSync(paths.map(f))) return;
  //   const res = files.readDir(paths.map(f));
  //   Object.assign(elementById, res.elementById);

  //   const folderEle = {
  //     type: 'folder-alias',
  //     id: 'v:folder-' + f,
  //     name: f,
  //     target: f,
  //     children: res.elements,
  //   };
  //   if (!elementById[folderEle.id]) {
  //     elementById[folderEle.id] = folderEle;
  //     elements.unshift(folderEle.id);
  //   }
  // });

  // const extraFiles = config.getRekitConfig().files || [];
  // extraFiles.forEach(f => {
  //   if (!fs.existsSync(paths.map(f))) return;
  //   const fileEle = files.getFileElement(paths.map(f));
  //   if (!elementById[fileEle.id]) {
  //     elementById[fileEle.id] = fileEle;
  //     elements.unshift(fileEle.id);
  //   }
  // });

  return { elements, elementById };
}

module.exports = {
  getProjectData,
  getFileProps,
};
<|endoftext|>