<commit_before> ((global) => {
  var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  const DEPLOYMENT_TEMPLATE = `<div class="mr-widget-heading" id="<%- id %>">

         <%= ci_success_icon %>

           Deployed to
           <a href="<%- url %>" target="_blank" class="environment">
             <%- name %>

           <span class="js-environment-timeago" data-toggle="tooltip" data-placement="top" data-title="<%- deployed_at_formatted %>">
             <%- deployed_at %>

           <a class="js-environment-link" href="<%- external_url %>" target="_blank">

             View on <%- external_url_formatted %>

          <a href="<%- stop_url %>" class="close-evn-link" data-method="post" rel="nofollow" data-confirm="Are you sure you want to close this environment?">

            Stop environment

`;

   global.MergeRequestWidget = (function() {
    function MergeRequestWidget(opts) {
      // Initialize MergeRequestWidget behavior
      //
      //   check_enable           - Boolean, whether to check automerge status
      //   merge_check_url - String, URL to use to check automerge status
      //   ci_status_url        - String, URL to use to check CI status
      //
      this.opts = opts;
      this.$widgetBody = $('.mr-widget-body');
      $('#modal_merge_info').modal({
        show: false
      });
      this.firstCICheck = true;
      this.readyForCICheck = false;
      this.readyForCIEnvironmentCheck = false;
      this.cancel = false;
      clearInterval(this.fetchBuildStatusInterval);
      clearInterval(this.fetchBuildEnvironmentStatusInterval);
      this.clearEventListeners();
      this.addEventListeners();
      this.getCIStatus(false);
      this.getCIEnvironmentsStatus();
      this.retrieveSuccessIcon();
      this.pollCIStatus();
      this.pollCIEnvironmentsStatus();
      notifyPermissions();
    }

    MergeRequestWidget.prototype.clearEventListeners = function() {
      return $(document).off('page:change.merge_request');
    };

    MergeRequestWidget.prototype.cancelPolling = function() {
      return this.cancel = true;
    };

    MergeRequestWidget.prototype.addEventListeners = function() {
      var allowedPages;
      allowedPages = ['show', 'commits', 'builds', 'pipelines', 'changes'];
      return $(document).on('page:change.merge_request', (function(_this) {
        return function() {
          var page;
          page = $('body').data('page').split(':').last();
          if (allowedPages.indexOf(page) < 0) {
            clearInterval(_this.fetchBuildStatusInterval);
            clearInterval(_this.fetchBuildEnvironmentStatusInterval);
            _this.cancelPolling();
            return _this.clearEventListeners();
          }
        };
      })(this));
    };

    MergeRequestWidget.prototype.retrieveSuccessIcon = function() {
       const $ciSuccessIcon = $('.js-success-icon');
       this.$ciSuccessIcon = $ciSuccessIcon.html();
       $ciSuccessIcon.remove();
     }

    MergeRequestWidget.prototype.mergeInProgress = function(deleteSourceBranch) {
      if (deleteSourceBranch == null) {
        deleteSourceBranch = false;
      }
      return $.ajax({
        type: 'GET',
        url: $('.merge-request').data('url'),
        success: (function(_this) {
          return function(data) {
            var callback, urlSuffix;
            if (data.state === "merged") {
              urlSuffix = deleteSourceBranch ? '?deleted_source_branch=true' : '';
              return window.location.href = window.location.pathname + urlSuffix;
            } else if (data.merge_error) {
              return this.$widgetBody.html("
" + data.merge_error + "
");
            } else {
              callback = function() {
                return merge_request_widget.mergeInProgress(deleteSourceBranch);
              };
              return setTimeout(callback, 2000);
            }
          };
        })(this),
        dataType: 'json'
      });
    };

    MergeRequestWidget.prototype.getMergeStatus = function() {
      return $.get(this.opts.merge_check_url, function(data) {
        return $('.mr-state-widget').replaceWith(data);
      });
    };

    MergeRequestWidget.prototype.ciLabelForStatus = function(status) {
      switch (status) {
        case 'success':
          return 'passed';
        case 'success_with_warnings':
          return 'passed with warnings';
        default:
          return status;
      }
    };

    MergeRequestWidget.prototype.pollCIStatus = function() {
      return this.fetchBuildStatusInterval = setInterval(((function(_this) {
        return function() {
          if (!_this.readyForCICheck) {
            return;
          }
          _this.getCIStatus(true);
          return _this.readyForCICheck = false;
        };
      })(this)), 10000);
    };

    MergeRequestWidget.prototype.getCIStatus = function(showNotification) {
      var _this;
      _this = this;
      $('.ci-widget-fetching').show();
      return $.getJSON(this.opts.ci_status_url, (function(_this) {
        return function(data) {
          var message, status, title;
          if (_this.cancel) {
            return;
          }
          _this.readyForCICheck = true;
          if (data.status === '') {
            return;
          }
          if (data.environments && data.environments.length) _this.renderEnvironments(data.environments);
          if (_this.firstCICheck || data.status !== _this.opts.ci_status && (data.status != null)) {
            _this.opts.ci_status = data.status;
            _this.showCIStatus(data.status);
            if (data.coverage) {
              _this.showCICoverage(data.coverage);
            }
            // The first check should only update the UI, a notification
            // should only be displayed on status changes
            if (showNotification && !_this.firstCICheck) {
              status = _this.ciLabelForStatus(data.status);
              if (status === "preparing") {
                title = _this.opts.ci_title.preparing;
                status = status.charAt(0).toUpperCase() + status.slice(1);
                message = _this.opts.ci_message.preparing.replace('{{status}}', status);
              } else {
                title = _this.opts.ci_title.normal;
                message = _this.opts.ci_message.normal.replace('{{status}}', status);
              }
              title = title.replace('{{status}}', status);
              message = message.replace('{{sha}}', data.sha);
              message = message.replace('{{title}}', data.title);
              notify(title, message, _this.opts.gitlab_icon, function() {
                this.close();
                return Turbolinks.visit(_this.opts.builds_path);
              });
            }
            return _this.firstCICheck = false;
          }
        };
      })(this));
    };

    MergeRequestWidget.prototype.pollCIEnvironmentsStatus = function() {
      this.fetchBuildEnvironmentStatusInterval = setInterval(() => {
        if (!this.readyForCIEnvironmentCheck) return;
        this.getCIEnvironmentsStatus();
        this.readyForCIEnvironmentCheck = false;
      }, 300000);
    };

    MergeRequestWidget.prototype.getCIEnvironmentsStatus = function() {
      $.getJSON(this.opts.ci_environments_status_url, (environments) => {
        if (this.cancel) return;
        this.readyForCIEnvironmentCheck = true;
        if (environments && environments.length) this.renderEnvironments(environments);
      });
    };

    MergeRequestWidget.prototype.renderEnvironments = function(environments) {
      for (let i = 0; i < environments.length; i++) {
        const environment = environments[i];
        if ($(`.mr-state-widget #${ environment.id }`).length) return;
        const $template = $(DEPLOYMENT_TEMPLATE);
        if (!environment.external_url || !environment.external_url_formatted) $('.js-environment-link', $template).remove();

        if (!environment.stop_url) {
          $('.js-close-env-link', $template).remove();
        }

        if (environment.deployed_at && environment.deployed_at_formatted) {
          environment.deployed_at = $.timeago(environment.deployed_at) + '.';
        } else {
          $('.js-environment-timeago', $template).remove();
          environment.name += '.';
        }
        environment.ci_success_icon = this.$ciSuccessIcon;
        const templateString = _.unescape($template[0].outerHTML);
        const template = _.template(templateString)(environment)
        this.$widgetBody.before(template);
      }
     };

    MergeRequestWidget.prototype.showCIStatus = function(state) {
      var allowed_states;
      if (state == null) {
        return;
      }
      $('.ci_widget').hide();
      allowed_states = ["failed", "canceled", "running", "pending", "success", "success_with_warnings", "skipped", "not_found"];
      if (indexOf.call(allowed_states, state) >= 0) {
        $('.ci_widget.ci-' + state).show();
        switch (state) {
          case "failed":
          case "canceled":
          case "not_found":
            return this.setMergeButtonClass('btn-danger');
          case "running":
            return this.setMergeButtonClass('btn-warning');
          case "success":
          case "success_with_warnings":
            return this.setMergeButtonClass('btn-create');
        }
      } else {
        $('.ci_widget.ci-error').show();
        return this.setMergeButtonClass('btn-danger');
      }
    };

    MergeRequestWidget.prototype.showCICoverage = function(coverage) {
      var text;
      text = 'Coverage ' + coverage + '%';
      return $('.ci_widget:visible .ci-coverage').text(text);
    };

    MergeRequestWidget.prototype.setMergeButtonClass = function(css_class) {
      return $('.js-merge-button,.accept-action .dropdown-toggle').removeClass('btn-danger btn-warning btn-create').addClass(css_class);
    };

    return MergeRequestWidget;

  })();

 })(window.gl || (window.gl = {}));
<commit_msg>Updates close to say stop in confirm message<commit_after> ((global) => {
  var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  const DEPLOYMENT_TEMPLATE = `<div class="mr-widget-heading" id="<%- id %>">

         <%= ci_success_icon %>

           Deployed to
           <a href="<%- url %>" target="_blank" class="environment">
             <%- name %>

           <span class="js-environment-timeago" data-toggle="tooltip" data-placement="top" data-title="<%- deployed_at_formatted %>">
             <%- deployed_at %>

           <a class="js-environment-link" href="<%- external_url %>" target="_blank">

             View on <%- external_url_formatted %>

          <a href="<%- stop_url %>" class="close-evn-link" data-method="post" rel="nofollow" data-confirm="Are you sure you want to stop this environment?">

            Stop environment

`;

   global.MergeRequestWidget = (function() {
    function MergeRequestWidget(opts) {
      // Initialize MergeRequestWidget behavior
      //
      //   check_enable           - Boolean, whether to check automerge status
      //   merge_check_url - String, URL to use to check automerge status
      //   ci_status_url        - String, URL to use to check CI status
      //
      this.opts = opts;
      this.$widgetBody = $('.mr-widget-body');
      $('#modal_merge_info').modal({
        show: false
      });
      this.firstCICheck = true;
      this.readyForCICheck = false;
      this.readyForCIEnvironmentCheck = false;
      this.cancel = false;
      clearInterval(this.fetchBuildStatusInterval);
      clearInterval(this.fetchBuildEnvironmentStatusInterval);
      this.clearEventListeners();
      this.addEventListeners();
      this.getCIStatus(false);
      this.getCIEnvironmentsStatus();
      this.retrieveSuccessIcon();
      this.pollCIStatus();
      this.pollCIEnvironmentsStatus();
      notifyPermissions();
    }

    MergeRequestWidget.prototype.clearEventListeners = function() {
      return $(document).off('page:change.merge_request');
    };

    MergeRequestWidget.prototype.cancelPolling = function() {
      return this.cancel = true;
    };

    MergeRequestWidget.prototype.addEventListeners = function() {
      var allowedPages;
      allowedPages = ['show', 'commits', 'builds', 'pipelines', 'changes'];
      return $(document).on('page:change.merge_request', (function(_this) {
        return function() {
          var page;
          page = $('body').data('page').split(':').last();
          if (allowedPages.indexOf(page) < 0) {
            clearInterval(_this.fetchBuildStatusInterval);
            clearInterval(_this.fetchBuildEnvironmentStatusInterval);
            _this.cancelPolling();
            return _this.clearEventListeners();
          }
        };
      })(this));
    };

    MergeRequestWidget.prototype.retrieveSuccessIcon = function() {
       const $ciSuccessIcon = $('.js-success-icon');
       this.$ciSuccessIcon = $ciSuccessIcon.html();
       $ciSuccessIcon.remove();
     }

    MergeRequestWidget.prototype.mergeInProgress = function(deleteSourceBranch) {
      if (deleteSourceBranch == null) {
        deleteSourceBranch = false;
      }
      return $.ajax({
        type: 'GET',
        url: $('.merge-request').data('url'),
        success: (function(_this) {
          return function(data) {
            var callback, urlSuffix;
            if (data.state === "merged") {
              urlSuffix = deleteSourceBranch ? '?deleted_source_branch=true' : '';
              return window.location.href = window.location.pathname + urlSuffix;
            } else if (data.merge_error) {
              return this.$widgetBody.html("
" + data.merge_error + "
");
            } else {
              callback = function() {
                return merge_request_widget.mergeInProgress(deleteSourceBranch);
              };
              return setTimeout(callback, 2000);
            }
          };
        })(this),
        dataType: 'json'
      });
    };

    MergeRequestWidget.prototype.getMergeStatus = function() {
      return $.get(this.opts.merge_check_url, function(data) {
        return $('.mr-state-widget').replaceWith(data);
      });
    };

    MergeRequestWidget.prototype.ciLabelForStatus = function(status) {
      switch (status) {
        case 'success':
          return 'passed';
        case 'success_with_warnings':
          return 'passed with warnings';
        default:
          return status;
      }
    };

    MergeRequestWidget.prototype.pollCIStatus = function() {
      return this.fetchBuildStatusInterval = setInterval(((function(_this) {
        return function() {
          if (!_this.readyForCICheck) {
            return;
          }
          _this.getCIStatus(true);
          return _this.readyForCICheck = false;
        };
      })(this)), 10000);
    };

    MergeRequestWidget.prototype.getCIStatus = function(showNotification) {
      var _this;
      _this = this;
      $('.ci-widget-fetching').show();
      return $.getJSON(this.opts.ci_status_url, (function(_this) {
        return function(data) {
          var message, status, title;
          if (_this.cancel) {
            return;
          }
          _this.readyForCICheck = true;
          if (data.status === '') {
            return;
          }
          if (data.environments && data.environments.length) _this.renderEnvironments(data.environments);
          if (_this.firstCICheck || data.status !== _this.opts.ci_status && (data.status != null)) {
            _this.opts.ci_status = data.status;
            _this.showCIStatus(data.status);
            if (data.coverage) {
              _this.showCICoverage(data.coverage);
            }
            // The first check should only update the UI, a notification
            // should only be displayed on status changes
            if (showNotification && !_this.firstCICheck) {
              status = _this.ciLabelForStatus(data.status);
              if (status === "preparing") {
                title = _this.opts.ci_title.preparing;
                status = status.charAt(0).toUpperCase() + status.slice(1);
                message = _this.opts.ci_message.preparing.replace('{{status}}', status);
              } else {
                title = _this.opts.ci_title.normal;
                message = _this.opts.ci_message.normal.replace('{{status}}', status);
              }
              title = title.replace('{{status}}', status);
              message = message.replace('{{sha}}', data.sha);
              message = message.replace('{{title}}', data.title);
              notify(title, message, _this.opts.gitlab_icon, function() {
                this.close();
                return Turbolinks.visit(_this.opts.builds_path);
              });
            }
            return _this.firstCICheck = false;
          }
        };
      })(this));
    };

    MergeRequestWidget.prototype.pollCIEnvironmentsStatus = function() {
      this.fetchBuildEnvironmentStatusInterval = setInterval(() => {
        if (!this.readyForCIEnvironmentCheck) return;
        this.getCIEnvironmentsStatus();
        this.readyForCIEnvironmentCheck = false;
      }, 300000);
    };

    MergeRequestWidget.prototype.getCIEnvironmentsStatus = function() {
      $.getJSON(this.opts.ci_environments_status_url, (environments) => {
        if (this.cancel) return;
        this.readyForCIEnvironmentCheck = true;
        if (environments && environments.length) this.renderEnvironments(environments);
      });
    };

    MergeRequestWidget.prototype.renderEnvironments = function(environments) {
      for (let i = 0; i < environments.length; i++) {
        const environment = environments[i];
        if ($(`.mr-state-widget #${ environment.id }`).length) return;
        const $template = $(DEPLOYMENT_TEMPLATE);
        if (!environment.external_url || !environment.external_url_formatted) $('.js-environment-link', $template).remove();

        if (!environment.stop_url) {
          $('.js-close-env-link', $template).remove();
        }

        if (environment.deployed_at && environment.deployed_at_formatted) {
          environment.deployed_at = $.timeago(environment.deployed_at) + '.';
        } else {
          $('.js-environment-timeago', $template).remove();
          environment.name += '.';
        }
        environment.ci_success_icon = this.$ciSuccessIcon;
        const templateString = _.unescape($template[0].outerHTML);
        const template = _.template(templateString)(environment)
        this.$widgetBody.before(template);
      }
     };

    MergeRequestWidget.prototype.showCIStatus = function(state) {
      var allowed_states;
      if (state == null) {
        return;
      }
      $('.ci_widget').hide();
      allowed_states = ["failed", "canceled", "running", "pending", "success", "success_with_warnings", "skipped", "not_found"];
      if (indexOf.call(allowed_states, state) >= 0) {
        $('.ci_widget.ci-' + state).show();
        switch (state) {
          case "failed":
          case "canceled":
          case "not_found":
            return this.setMergeButtonClass('btn-danger');
          case "running":
            return this.setMergeButtonClass('btn-warning');
          case "success":
          case "success_with_warnings":
            return this.setMergeButtonClass('btn-create');
        }
      } else {
        $('.ci_widget.ci-error').show();
        return this.setMergeButtonClass('btn-danger');
      }
    };

    MergeRequestWidget.prototype.showCICoverage = function(coverage) {
      var text;
      text = 'Coverage ' + coverage + '%';
      return $('.ci_widget:visible .ci-coverage').text(text);
    };

    MergeRequestWidget.prototype.setMergeButtonClass = function(css_class) {
      return $('.js-merge-button,.accept-action .dropdown-toggle').removeClass('btn-danger btn-warning btn-create').addClass(css_class);
    };

    return MergeRequestWidget;

  })();

 })(window.gl || (window.gl = {}));
<|endoftext|>


<commit_before>angular.module('kmApp').compileProvider // lazy
.directive('searchFilterSchemas', function ($http) {
    return {
        restrict: 'EAC',
        templateUrl: '/app/chm/directives/search/search-filter-schemas.partial.html?'+(new Date().getTime()),
        replace: true,
        scope: {
              title: '@title',
              items: '=ngModel',
              field: '@field',
              query: '=query',
        },
        link: function ($scope, element, attrs, ngModelController)
        {
        },
        controller : ['$scope', '$element', '$location', function ($scope, $element, $location)
        {
            $scope.expanded = false;
            $scope.selectedItems = [];
            $scope.facet = $scope.field.replace('_s', ''); // TODO: replace @field by @facet

            $scope.isSelected = function(item) {
                return $.inArray(item.symbol, $scope.selectedItems) >= 0;
            };

            $scope.closeDialog = function() {
                $element.find("#dialogSelect").modal("hide");
            };

            $scope.actionSelect = function(item) {

                if($scope.isSelected(item)) {
                    $scope.selectedItems.splice($.inArray(item.symbol, $scope.selectedItems), 1);
                } else {
                    $scope.selectedItems.push(item.symbol);
                }

                $scope.updateQuery();
            };

            $scope.actionExpand = function() {

                var count1 = Math.ceil($scope.items.length/3);
                var count2 = Math.ceil(($scope.items.length-count1)/2);
                var count3 = Math.ceil(($scope.items.length-count2-count1));

                $scope.items1 = $scope.items.slice(0, count1);
                $scope.items2 = $scope.items.slice(count1, count2+count2);
                $scope.items3 = $scope.items.slice(count1+count2, count1+count2+count3);

                $element.find("#dialogSelect").modal("show");
            };

            $scope.$on('onExpand', function(scope) {
                if(scope!=$scope && $scope.expanded)
                    $scope.expanded = false;
            });

            $scope.filterx = function(item) {
                return $scope.isSelected(item) || $scope.expanded;
            };

            $scope.ccc = function(item) {
                return $scope.isSelected(item) ? 'facet selected' : 'facet unselected';
            };

            $scope.updateQuery = function() {

                console.log($scope.query);

                $scope.query = '';

                $scope.selectedItems.forEach(function(item) {
                    $scope.query += ($scope.query=='' ? '' : ' OR ') + $scope.field+':' + item;
                });

                if($scope.query!='')
                    $scope.query = '(' + $scope.query + ')';
                else
                    $scope.query = '*:*';

                console.log($scope.query);
            };

            $scope.onclick = function (scope, evt) {
                scope.item.selected = !scope.item.selected;
                buildQuery();
            }

            function buildQuery () {
                var conditions = [];
                buildConditions(conditions, $scope.terms);

                if(conditions.length==0) $scope.query = '*:*';
                else {
                    var query = '';
                    conditions.forEach(function (condition) { query = query + (query=='' ? '( ' : ' OR ') + condition; });
                    query += ' )';
                    console.log(query);
                    $scope.query = query;
                }
            }

            function buildConditions (conditions, items) {
                items.forEach(function (item) {
                    if(item.selected)
                        conditions.push($scope.field+':'+item.identifier);
                });
            }

            function dictionarize(items) {
                var dictionary = [];
                items.forEach(function (item) {
                    item.selected = false;
                    dictionary[item.identifier] = item;
                });
                return dictionary;
            }

            $scope.outreachRecords = [
                { identifier: 'notification', title: 'Notifications'  },
                { identifier: 'pressRelease', title: 'Press Releases' },
                { identifier: 'statement'   , title: 'Statements'     },
                { identifier: 'announcement', title: 'Announcements'  }
            ];

            $scope.referenceRecords = [
                // { identifier: 'treaty'                , title: 'Treaties'                   , count: 0 },
                // { identifier: 'article'               , title: 'Treaty Articles'            },
                { identifier: 'event'                 , title: 'Related Events'             , count: 0 },
                { identifier: 'organization'          , title: 'Related Organizations'      },
                { identifier: 'resource'              , title: 'Virtual Library Resources'  }
            ];

             $scope.copRecords = [
                { identifier: 'aichiTarget'           , title: 'Aichi Biodiversity Targets' },
                { identifier: 'strategicPlanIndicator', title: 'Strategic Plan Indicators'  },
                { identifier: 'marineEbsa'            , title: 'Marine EBSAs'               },
                { identifier: 'caseStudy'             , title: 'Case Studies'               , count: 0 }
            ];

            $scope.meetingRecords = [
                { identifier: 'meeting'        , title: 'Meetings'          },
                { identifier: 'meetingDocument', title: 'Meeting Documents' },
                { identifier: 'decision'       , title: 'Decisions'         },
                { identifier: 'recommendation' , title: 'Recommendations'   }
            ];

            $scope.nationalRecords = [
                { identifier: 'focalPoint'              , title: 'National Focal Points'      },
                { identifier: 'nationalReport'          , title: 'National Reports'           },
                { identifier: 'nationalTarget'          , title: 'National Targets'           },
                { identifier: 'nationalIndicator'       , title: 'National Indicators'        },
                { identifier: 'progressAssessment'      , title: 'Progress Assessments'       },
                { identifier: 'implementationActivity'  , title: 'Implementation Activities'  },
                { identifier: 'nationalSupportTool'     , title: 'Guidance and Support Tools' , count: 0 },
                {},
                { identifier: 'resourceMobilizationTool', title: 'Resource Mobilization Tools' , count: 0 }
            ];

            $scope.terms = _.union($scope.outreachRecords, $scope.referenceRecords, $scope.copRecords, $scope.meetingRecords, $scope.nationalRecords );
            $scope.termsx = dictionarize($scope.terms);

            // Set intitial selection from QueryString parameters

            var initialSelection = $location.search()[$scope.facet];

            if(initialSelection && $scope.termsx[initialSelection]) {
                $scope.termsx[initialSelection].selected = true;
            }

            function onWatch_items(values) { if(!values) return;
                values.forEach(function (item) {
                    if(_.has($scope.termsx, item.symbol))
                        $scope.termsx[item.symbol].count = item.count;
                });
            }

            $scope.$watch('items', onWatch_items);

            $scope.refresh = buildQuery;

            buildQuery();
        }]
    }
});
<commit_msg>Added NBSAPs to the title of the NR filter<commit_after>angular.module('kmApp').compileProvider // lazy
.directive('searchFilterSchemas', function ($http) {
    return {
        restrict: 'EAC',
        templateUrl: '/app/chm/directives/search/search-filter-schemas.partial.html?'+(new Date().getTime()),
        replace: true,
        scope: {
              title: '@title',
              items: '=ngModel',
              field: '@field',
              query: '=query',
        },
        link: function ($scope, element, attrs, ngModelController)
        {
        },
        controller : ['$scope', '$element', '$location', function ($scope, $element, $location)
        {
            $scope.expanded = false;
            $scope.selectedItems = [];
            $scope.facet = $scope.field.replace('_s', ''); // TODO: replace @field by @facet

            $scope.isSelected = function(item) {
                return $.inArray(item.symbol, $scope.selectedItems) >= 0;
            };

            $scope.closeDialog = function() {
                $element.find("#dialogSelect").modal("hide");
            };

            $scope.actionSelect = function(item) {

                if($scope.isSelected(item)) {
                    $scope.selectedItems.splice($.inArray(item.symbol, $scope.selectedItems), 1);
                } else {
                    $scope.selectedItems.push(item.symbol);
                }

                $scope.updateQuery();
            };

            $scope.actionExpand = function() {

                var count1 = Math.ceil($scope.items.length/3);
                var count2 = Math.ceil(($scope.items.length-count1)/2);
                var count3 = Math.ceil(($scope.items.length-count2-count1));

                $scope.items1 = $scope.items.slice(0, count1);
                $scope.items2 = $scope.items.slice(count1, count2+count2);
                $scope.items3 = $scope.items.slice(count1+count2, count1+count2+count3);

                $element.find("#dialogSelect").modal("show");
            };

            $scope.$on('onExpand', function(scope) {
                if(scope!=$scope && $scope.expanded)
                    $scope.expanded = false;
            });

            $scope.filterx = function(item) {
                return $scope.isSelected(item) || $scope.expanded;
            };

            $scope.ccc = function(item) {
                return $scope.isSelected(item) ? 'facet selected' : 'facet unselected';
            };

            $scope.updateQuery = function() {

                console.log($scope.query);

                $scope.query = '';

                $scope.selectedItems.forEach(function(item) {
                    $scope.query += ($scope.query=='' ? '' : ' OR ') + $scope.field+':' + item;
                });

                if($scope.query!='')
                    $scope.query = '(' + $scope.query + ')';
                else
                    $scope.query = '*:*';

                console.log($scope.query);
            };

            $scope.onclick = function (scope, evt) {
                scope.item.selected = !scope.item.selected;
                buildQuery();
            }

            function buildQuery () {
                var conditions = [];
                buildConditions(conditions, $scope.terms);

                if(conditions.length==0) $scope.query = '*:*';
                else {
                    var query = '';
                    conditions.forEach(function (condition) { query = query + (query=='' ? '( ' : ' OR ') + condition; });
                    query += ' )';
                    console.log(query);
                    $scope.query = query;
                }
            }

            function buildConditions (conditions, items) {
                items.forEach(function (item) {
                    if(item.selected)
                        conditions.push($scope.field+':'+item.identifier);
                });
            }

            function dictionarize(items) {
                var dictionary = [];
                items.forEach(function (item) {
                    item.selected = false;
                    dictionary[item.identifier] = item;
                });
                return dictionary;
            }

            $scope.outreachRecords = [
                { identifier: 'notification', title: 'Notifications'  },
                { identifier: 'pressRelease', title: 'Press Releases' },
                { identifier: 'statement'   , title: 'Statements'     },
                { identifier: 'announcement', title: 'Announcements'  }
            ];

            $scope.referenceRecords = [
                // { identifier: 'treaty'                , title: 'Treaties'                   , count: 0 },
                // { identifier: 'article'               , title: 'Treaty Articles'            },
                { identifier: 'event'                 , title: 'Related Events'             , count: 0 },
                { identifier: 'organization'          , title: 'Related Organizations'      },
                { identifier: 'resource'              , title: 'Virtual Library Resources'  }
            ];

             $scope.copRecords = [
                { identifier: 'aichiTarget'           , title: 'Aichi Biodiversity Targets' },
                { identifier: 'strategicPlanIndicator', title: 'Strategic Plan Indicators'  },
                { identifier: 'marineEbsa'            , title: 'Marine EBSAs'               },
                { identifier: 'caseStudy'             , title: 'Case Studies'               , count: 0 }
            ];

            $scope.meetingRecords = [
                { identifier: 'meeting'        , title: 'Meetings'          },
                { identifier: 'meetingDocument', title: 'Meeting Documents' },
                { identifier: 'decision'       , title: 'Decisions'         },
                { identifier: 'recommendation' , title: 'Recommendations'   }
            ];

            $scope.nationalRecords = [
                { identifier: 'focalPoint'              , title: 'National Focal Points'      },
                { identifier: 'nationalReport'          , title: 'National Reports and NBSAPs'},
                { identifier: 'nationalTarget'          , title: 'National Targets'           },
                { identifier: 'nationalIndicator'       , title: 'National Indicators'        },
                { identifier: 'progressAssessment'      , title: 'Progress Assessments'       },
                { identifier: 'implementationActivity'  , title: 'Implementation Activities'  },
                { identifier: 'nationalSupportTool'     , title: 'Guidance and Support Tools' , count: 0 },
                {},
                { identifier: 'resourceMobilizationTool', title: 'Resource Mobilization Tools' , count: 0 }
            ];

            $scope.terms = _.union($scope.outreachRecords, $scope.referenceRecords, $scope.copRecords, $scope.meetingRecords, $scope.nationalRecords );
            $scope.termsx = dictionarize($scope.terms);

            // Set intitial selection from QueryString parameters

            var initialSelection = $location.search()[$scope.facet];

            if(initialSelection && $scope.termsx[initialSelection]) {
                $scope.termsx[initialSelection].selected = true;
            }

            function onWatch_items(values) { if(!values) return;
                values.forEach(function (item) {
                    if(_.has($scope.termsx, item.symbol))
                        $scope.termsx[item.symbol].count = item.count;
                });
            }

            $scope.$watch('items', onWatch_items);

            $scope.refresh = buildQuery;

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


<commit_before>import styled from 'styled-components';
import {ToolViewport} from '../Tools';

const GRAYED = 'rgba(89,89,89,1)';
const BLACKED = 'rgba(0,0,0,0.5)'
export default styled(ToolViewport)`
  background-color: ${p=>p.grayout&&!p.forceShow ? GRAYED : BLACKED };
  width: 100%;
  height: 100%;
  position: relative;
  transition: background-color 0.3s ease;
`;
<commit_msg>The black over the images on the tiles should be 65% opacity. It was darkened from the previous site. Not sure what it is now but I want to double check that it is -- https://3.basecamp.com/3161453/buckets/3412210/todos/610206408<commit_after>import styled from 'styled-components';
import {ToolViewport} from '../Tools';

const GRAYED = 'rgba(89,89,89,1)';
const BLACKED = 'rgba(0,0,0,0.65)';
export default styled(ToolViewport)`
  background-color: ${p=>p.grayout&&!p.forceShow ? GRAYED : BLACKED };
  width: 100%;
  height: 100%;
  position: relative;
  transition: background-color 0.3s ease;
`;
<|endoftext|>


<commit_before>import { FormattedMessage as T } from "react-intl";
import { StandalonePage, StandaloneHeader } from "layout";
import AccountRow from "./AccountRow";
import { DecredLoading } from "indicators";
import { InfoModalButton, PassphraseModalButton } from "buttons";
import { BalanceOverviewModalContent, AddAccountModal } from "modals";

const AccountsListHeader = ({ onGetNextAccountAttempt }) =>
  <StandaloneHeader
    title={<T id="accounts.title" m="Accounts" />}
    description={<T id="accounts.description" m={"Accounts allow you to keep separate records of your DCR funds.\nTransferring DCR across accounts will create a transaction on the blockchain."}/>}
    iconClass="accounts"
    actionButton={
      <PassphraseModalButton
        modalTitle={<T id="accounts.newAccountConfirmations" m="Create new account" />}
        modalComponent={AddAccountModal}
        onSubmit={onGetNextAccountAttempt}
        buttonLabel={<T id="accounts.addNewButton" m="Add New" />}
      />}
  />;

const AccountsList = ({
  accounts,
  isLoading,
  onGetNextAccountAttempt,
  onShowAccount,
  onHideAccount,
  onRenameAccount,
  onShowAccountDetails,
  onHideAccountDetails,
  accountNumDetailsShown,
}) => (
  <StandalonePage header={<AccountsListHeader {...{ onGetNextAccountAttempt }} />}>
    { isLoading ? <DecredLoading/> :
      <Aux>

          <InfoModalButton
            modalTitle={
<T id="accounts.balanceInfo" m="Balance Information" />
}
            modalContent={<BalanceOverviewModalContent />}
          />

          {accounts.map(account => (
            <AccountRow
              key={account.accountName}
              account={account}
              accountNumDetailsShown={accountNumDetailsShown}
              renameAccount={onRenameAccount}
              hideAccount={onHideAccount}
              showAccount={onShowAccount}
              showAccountDetails={onShowAccountDetails}
              hideAccountDetails={onHideAccountDetails}
            />
          ))}

      </Aux> }
  </StandalonePage>
);

AccountsList.propTypes = {
  accounts: PropTypes.array.isRequired,
  isLoading: PropTypes.bool.isRequired,
  onGetNextAccountAttempt: PropTypes.func.isRequired,
  onShowAccount: PropTypes.func.isRequired,
  onHideAccount: PropTypes.func.isRequired,
  onRenameAccount: PropTypes.func.isRequired,
  onShowAccountDetails: PropTypes.func.isRequired,
  onHideAccountDetails: PropTypes.func.isRequired,
  accountNumDetailsShown: PropTypes.number,
};

export default AccountsList;
<commit_msg>Fix accounts header icon (#1281)<commit_after>import { FormattedMessage as T } from "react-intl";
import { StandalonePage, StandaloneHeader } from "layout";
import AccountRow from "./AccountRow";
import { DecredLoading } from "indicators";
import { InfoModalButton, PassphraseModalButton } from "buttons";
import { BalanceOverviewModalContent, AddAccountModal } from "modals";

const AccountsListHeader = ({ onGetNextAccountAttempt }) =>
  <StandaloneHeader
    title={<T id="accounts.title" m="Accounts" />}
    description={<T id="accounts.description" m={"Accounts allow you to keep separate records of your DCR funds.\nTransferring DCR across accounts will create a transaction on the blockchain."}/>}
    iconClassName="accounts"
    actionButton={
      <PassphraseModalButton
        modalTitle={<T id="accounts.newAccountConfirmations" m="Create new account" />}
        modalComponent={AddAccountModal}
        onSubmit={onGetNextAccountAttempt}
        buttonLabel={<T id="accounts.addNewButton" m="Add New" />}
      />}
  />;

const AccountsList = ({
  accounts,
  isLoading,
  onGetNextAccountAttempt,
  onShowAccount,
  onHideAccount,
  onRenameAccount,
  onShowAccountDetails,
  onHideAccountDetails,
  accountNumDetailsShown,
}) => (
  <StandalonePage header={<AccountsListHeader {...{ onGetNextAccountAttempt }} />}>
    { isLoading ? <DecredLoading/> :
      <Aux>

          <InfoModalButton
            modalTitle={
<T id="accounts.balanceInfo" m="Balance Information" />
}
            modalContent={<BalanceOverviewModalContent />}
          />

          {accounts.map(account => (
            <AccountRow
              key={account.accountName}
              account={account}
              accountNumDetailsShown={accountNumDetailsShown}
              renameAccount={onRenameAccount}
              hideAccount={onHideAccount}
              showAccount={onShowAccount}
              showAccountDetails={onShowAccountDetails}
              hideAccountDetails={onHideAccountDetails}
            />
          ))}

      </Aux> }
  </StandalonePage>
);

AccountsList.propTypes = {
  accounts: PropTypes.array.isRequired,
  isLoading: PropTypes.bool.isRequired,
  onGetNextAccountAttempt: PropTypes.func.isRequired,
  onShowAccount: PropTypes.func.isRequired,
  onHideAccount: PropTypes.func.isRequired,
  onRenameAccount: PropTypes.func.isRequired,
  onShowAccountDetails: PropTypes.func.isRequired,
  onHideAccountDetails: PropTypes.func.isRequired,
  accountNumDetailsShown: PropTypes.number,
};

export default AccountsList;
<|endoftext|>


<commit_before>"use strict";

angular.module('arethusa.search').directive('pluginSearch', function(injectables) {
  return {
    restrict: 'AE',
    scope: true,
    replace: true,
    link: function(scope, element, attrs) {
      scope.plugin = scope.$eval(attrs.pluginSearch);
      scope.template = 'templates/arethusa.' + scope.plugin.name + '/search.html';
    },
    template: '

'
  };
});
<commit_msg>Fix plugin in pluginSeach directive<commit_after>"use strict";

angular.module('arethusa.search').directive('pluginSearch', function() {
  return {
    restrict: 'AE',
    scope: true,
    replace: true,
    link: function(scope, element, attrs) {
      scope.plugin = scope.$eval(attrs.pluginSearch);
      scope.template = 'templates/arethusa.' + scope.plugin.name + '/search.html';
    },
    template: '

'
  };
});
<|endoftext|>


<commit_before>'use strict';
angular.module('arethusa.table').directive('morphSelector',[
    'state',
    'morph',
    function (state, morph) {
        return {
            restrict: 'A',
            scope: {
                token: "=morphToken"
            },
            link: function(scope, element, attrs) {
                scope.analyses = morph.analyses[scope.token.id].forms;
                scope.form = scope.token.morphology;

                scope.longForm = function(form) {
                    var longPostag = Object.keys(form.attributes).filter(function(k) {
                        return /[A-Za-z0-9]/.test(form.attributes[k]);
                    }).map(function(k) {
                        return morph.longAttributeValue(k,form.attributes[k]);
                    }).join('-');
                    var lemma = form.lemma;
                    return lemma + ':' + longPostag;
                }

                function undoFn(tkn, frm) {
                    var token = tkn;
                    var form = frm;
                    return function() {
                        scope.form = form;
                        state.change(token.id,'morphology',form);
                    };
                }

                function preExecFn(frm) {
                    var form = frm;
                    return function() {
                        scope.form = form;
                    };
                }

                scope.onChange = function() {
                    state.change(scope.token.id, 'morphology', scope.form, undoFn(scope.token,scope.token.morphology), preExecFn(scope.form));
                };

            },
            template: '<select class="no-margin compact" ng-model="form" ng-options="analysis as longForm(analysis) for analysis in analyses" ng-change="onChange()"></select>'
        };
}]);
<commit_msg>Using morph service to create attribute string in morph selector<commit_after>'use strict';
angular.module('arethusa.table').directive('morphSelector',[
    'state',
    'morph',
    function (state, morph) {
        return {
            restrict: 'A',
            scope: {
                token: "=morphToken"
            },
            link: function(scope, element, attrs) {
                scope.analyses = morph.analyses[scope.token.id].forms;
                scope.form = scope.token.morphology;

                scope.longForm = function(form) {
                    var longPostag = morph.concatenatedAttributes(form);/*Object.keys(form.attributes).filter(function(k) {
                        return /[A-Za-z0-9]/.test(form.attributes[k]);
                    }).map(function(k) {
                        return morph.longAttributeValue(k,form.attributes[k]);
                    }).join('-');*/
                    var lemma = form.lemma;
                    return lemma + ':' + longPostag;
                }

                function undoFn(tkn, frm) {
                    var token = tkn;
                    var form = frm;
                    return function() {
                        scope.form = form;
                        state.change(token.id,'morphology',form);
                    };
                }

                function preExecFn(frm) {
                    var form = frm;
                    return function() {
                        scope.form = form;
                    };
                }

                scope.onChange = function() {
                    state.change(scope.token.id, 'morphology', scope.form, undoFn(scope.token,scope.token.morphology), preExecFn(scope.form));
                };

            },
            template: '<select class="no-margin compact" ng-model="form" ng-options="analysis as longForm(analysis) for analysis in analyses" ng-change="onChange()"></select>'
        };
}]);
<|endoftext|>


<commit_before>angular.module('pcApp.events.controllers.event', [
    'pcApp.events.services.event',
    'pcApp.references.services.reference'
])

    .controller('EventsController', ['$scope', 'Event', '$log', '$routeParams', function ($scope, Event, $log, $routeParams) {
        $scope.events = Event.query(
            {page: $routeParams.page},
            function(metricList) {
            },
            function(error) {
                throw { message: JSON.stringify(err.data)};
            }
        );

    }])

    .controller('EventDetailController', [
        '$scope',
        '$routeParams',
        '$location',
        'Event',
        '$log',
        function ($scope, $routeParams, $location, Event, $log) {

            $scope.event = Event.get({id: $routeParams.eventId},
                function (event) {
                },
                function (error) {
                    alert(error.data.message);
                }
            );

            $scope.deleteEvent = function (event) {
                event.$delete(
                    {},
                    function () {
                        $location.path('/events');
                    }
                );
            };

        }])

    .controller('EventEditController', [
        '$scope',
        '$routeParams',
        'Event',
        '$location',
        '$log',
        function ($scope, $routeParams, Event, $location, $log) {

            $scope.mode = "edit";

            $scope.event = Event.get({id: $routeParams.eventId},
                function(event) {
                },
                function(err) {
                    throw { message: JSON.stringify(err.data)};
                }
            );

            $scope.createEvent = function () {
                $scope.event.userID = 1;
                $scope.event.viewsCount = 1;

                Event.update($scope.event, function (value, responseHeaders) {
                        $location.path('/events/' + value.id);
                    },
                    function (err) {
                        throw { message: err.data};
                    }
                );
            };
        }])

    .controller('EventCreateController', [
        '$scope',
        'Event',
        '$location',
        '$log',
        function ($scope, Event, $location, $log) {

            $scope.mode = "create";

            $scope.createEvent = function () {
                $scope.event.userID = 1;
                $scope.event.viewsCount = 1;

                Event.save($scope.event, function (value, responseHeaders) {
                        $location.path('/events/' + value.id);
                    },
                    function (err) {
                        throw { message: err.data};
                    }
                );
            };
        }]);
<commit_msg>small correction<commit_after>angular.module('pcApp.events.controllers.event', [
    'pcApp.events.services.event',
    'pcApp.references.services.reference'
])

    .controller('EventsController', ['$scope', 'Event', '$log', '$routeParams', function ($scope, Event, $log, $routeParams) {
        $scope.events = Event.query(
            {page: $routeParams.page},
            function(eventList) {
            },
            function(error) {
                throw { message: JSON.stringify(err.data)};
            }
        );

    }])

    .controller('EventDetailController', [
        '$scope',
        '$routeParams',
        '$location',
        'Event',
        '$log',
        function ($scope, $routeParams, $location, Event, $log) {

            $scope.event = Event.get({id: $routeParams.eventId},
                function (event) {
                },
                function (error) {
                    alert(error.data.message);
                }
            );

            $scope.deleteEvent = function (event) {
                event.$delete(
                    {},
                    function () {
                        $location.path('/events');
                    }
                );
            };

        }])

    .controller('EventEditController', [
        '$scope',
        '$routeParams',
        'Event',
        '$location',
        '$log',
        function ($scope, $routeParams, Event, $location, $log) {

            $scope.mode = "edit";

            $scope.event = Event.get({id: $routeParams.eventId},
                function(event) {
                },
                function(err) {
                    throw { message: JSON.stringify(err.data)};
                }
            );

            $scope.createEvent = function () {
                $scope.event.userID = 1;
                $scope.event.viewsCount = 1;

                Event.update($scope.event, function (value, responseHeaders) {
                        $location.path('/events/' + value.id);
                    },
                    function (err) {
                        throw { message: err.data};
                    }
                );
            };
        }])

    .controller('EventCreateController', [
        '$scope',
        'Event',
        '$location',
        '$log',
        function ($scope, Event, $location, $log) {

            $scope.mode = "create";

            $scope.createEvent = function () {
                $scope.event.userID = 1;
                $scope.event.viewsCount = 1;

                Event.save($scope.event, function (value, responseHeaders) {
                        $location.path('/events/' + value.id);
                    },
                    function (err) {
                        throw { message: err.data};
                    }
                );
            };
        }]);
<|endoftext|>


<commit_before>import {Slice} from "../model"

import {Transform} from "./transform"
import {Step, StepResult} from "./step"
import {PosMap, ReplacedRange} from "./map"

// !! **`join`**
//   : Join two block elements together. `from` and `to` must point at
//     the end of the first and start of the second element (so that
//     the intention is preserved even when the positions are mapped).

Step.define("join", {
  apply(doc, step) {
    let $from = doc.resolve(step.from), $to = doc.resolve(step.to)
    if ($from.parentOffset < $from.parent.content.size || $to.parentOffset > 0 || $to.pos - $from.pos != 2)
      return StepResult.fail("Join positions not around a split")
    return StepResult.fromReplace(doc, $from.pos, $to.pos, Slice.empty)
  },
  posMap(step) {
    return new PosMap([new ReplacedRange(step.from, 2, 0)])
  },
  invert(step) {
    return new Step("split", step.from, step.from) // FIXME restore types
  }
})

// :: (Node, number) → bool
// Test whether the blocks before and after a given position can be
// joined.
export function joinableBlocks(doc, pos) {
  let $pos = doc.resolve(pos), before = $pos.nodeBefore, after = $pos.nodeAfter
  return before && after && !before.isText && before.type.contains &&
    before.type.canContainContent(after.type)
}

// :: (Node, number, ?number) → ?number
// Find an ancestor of the given position that can be joined to the
// block before (or after if `dir` is positive). Returns the joinable
// point, if any.
export function joinPoint(doc, pos, dir = -1) {
  let $pos = doc.resolve(pos)
  for (let d = $pos.depth; d >= 0; d--) {
    if (joinableBlocks(doc, pos)) return pos
    if (pos.depth == 0) return null
    pos = dir < 0 ? $pos.before(d) : $pos.after(d)
  }
}

// :: (number) → Transform #path=Transform.prototype.join
// Join the blocks around the given position.
Transform.define("join", function(pos, depth = 1) {
  for (let i = 0; i < depth; i++) {
    let $pos = this.doc.resolve(pos)
    // FIXME should a bogus join fail the transform?
    if ($pos.parentOffset == 0 || $pos.parentOffset == $pos.parent.content.size) break
    this.step("join", pos - 1, pos + 1)
    pos--
  }
})
<commit_msg>Make applying a failed transform raise an error<commit_after>import {Slice} from "../model"

import {Transform} from "./transform"
import {Step, StepResult} from "./step"
import {PosMap, ReplacedRange} from "./map"

// !! **`join`**
//   : Join two block elements together. `from` and `to` must point at
//     the end of the first and start of the second element (so that
//     the intention is preserved even when the positions are mapped).

Step.define("join", {
  apply(doc, step) {
    let $from = doc.resolve(step.from), $to = doc.resolve(step.to)
    if ($from.parentOffset < $from.parent.content.size || $to.parentOffset > 0 || $to.pos - $from.pos != 2)
      return StepResult.fail("Join positions not around a split")
    return StepResult.fromReplace(doc, $from.pos, $to.pos, Slice.empty)
  },
  posMap(step) {
    return new PosMap([new ReplacedRange(step.from, 2, 0)])
  },
  invert(step) {
    return new Step("split", step.from, step.from) // FIXME restore types
  }
})

// :: (Node, number) → bool
// Test whether the blocks before and after a given position can be
// joined.
export function joinableBlocks(doc, pos) {
  let $pos = doc.resolve(pos), before = $pos.nodeBefore, after = $pos.nodeAfter
  return before && after && !before.isText && before.type.contains &&
    before.type.canContainContent(after.type)
}

// :: (Node, number, ?number) → ?number
// Find an ancestor of the given position that can be joined to the
// block before (or after if `dir` is positive). Returns the joinable
// point, if any.
export function joinPoint(doc, pos, dir = -1) {
  let $pos = doc.resolve(pos)
  for (let d = $pos.depth; d >= 0; d--) {
    if (joinableBlocks(doc, pos)) return pos
    if (pos.depth == 0) return null
    pos = dir < 0 ? $pos.before(d) : $pos.after(d)
  }
}

// :: (number) → Transform #path=Transform.prototype.join
// Join the blocks around the given position.
Transform.define("join", function(pos, depth = 1) {
  for (let i = 0; i < depth; i++) {
    let $pos = this.doc.resolve(pos)
    if ($pos.parentOffset == 0 || $pos.parentOffset == $pos.parent.content.size)
      return this.fail(new Error("Nothing to join at " + pos))
    this.step("join", pos - 1, pos + 1)
    pos--
  }
})
<|endoftext|>


<commit_before>
function createImageContentFromHtmlSourceCode(source,content){
    var imagelinks = _pickImageUrlsFromSource(source);
    var imageContent = _createImageContent(content,imagelinks);
    return imageContent;
}

function _createImageContent(content,links){

  var regex = /\[img=\d+:C\].*?\[\/img\]/g;
  var originImageTag = content.match(regex);
  if (originImageTag === null){
    originImageTag = [];
  }
  var resultContent = content;

  if (links && originImageTag.length == links.length ) {
    originImageTag.forEach(function (tag, index, array) {
      var imageLink = links[index];
      if (imageLink) {
        var newTag = tag.replace(/\].*?\[\/img\]/, function(replacement) {
          return '\
\
\<img src=\"' + imageLink +
            '\"\
\
' +
            replacement.substr(1, replacement.length - 7) + '\<\/div\>\<\/div\>\<\/div\>\
';
        });
        var resultLink = newTag.replace(/\[img=\d+:C/, '');
        resultContent = resultContent.replace(tag, resultLink);
      }
    });
  }else {
    //pick error, replace all ImageTags
    originImageTag.forEach(function (tag, index, array) {
      resultContent = resultContent.replace(tag, '');
    });
  }
  return resultContent;
}

function _pickImageUrlsFromSource(source){
  var regex = /<img src=\"https:\/\/img(.)(.doubanio.com\/view\/thing_review)(.*?\")/g;
  var matchWords = source.match(regex);
  if (matchWords === null){
    matchWords = [];
  }
  var links = matchWords.map(function(word){
    return word.substr(10, word.length - 11);
  });
  return links;
}

module.exports = createImageContentFromHtmlSourceCode;
<commit_msg>handle empty input<commit_after>
function createImageContentFromHtmlSourceCode(source,content){
    if(source===undefined){
        return _createImageContent(content,undefined);
    }
    var imagelinks = _pickImageUrlsFromSource(source);
    var imageContent = _createImageContent(content,imagelinks);
    return imageContent;
}

function _createImageContent(content,links){

  var regex = /\[img=\d+:C\].*?\[\/img\]/g;
  var originImageTag = content.match(regex);
  if (originImageTag === null){
    originImageTag = [];
  }
  var resultContent = content;

  if (links && originImageTag.length == links.length ) {
    originImageTag.forEach(function (tag, index, array) {
      var imageLink = links[index];
      if (imageLink) {
        var newTag = tag.replace(/\].*?\[\/img\]/, function(replacement) {
          return '\
\
\<img src=\"' + imageLink +
            '\"\
\
' +
            replacement.substr(1, replacement.length - 7) + '\<\/div\>\<\/div\>\<\/div\>\
';
        });
        var resultLink = newTag.replace(/\[img=\d+:C/, '');
        resultContent = resultContent.replace(tag, resultLink);
      }
    });
  }else {
    //pick error, replace all ImageTags
    originImageTag.forEach(function (tag, index, array) {
      resultContent = resultContent.replace(tag, '');
    });
  }
  return resultContent;
}

function _pickImageUrlsFromSource(source){
  var regex = /<img src=\"https:\/\/img(.)(.doubanio.com\/view\/thing_review)(.*?\")/g;
  var matchWords = source.match(regex);
  if (matchWords === null){
    matchWords = [];
  }
  var links = matchWords.map(function(word){
    return word.substr(10, word.length - 11);
  });
  return links;
}

module.exports = createImageContentFromHtmlSourceCode;
<|endoftext|>


<commit_before>/**
 * Created by love on 09/02/15.
 */

function addDialog(event, data, caller) {
    var $dialog = $('#element-selector'),
    //$dialog_content = $("#element-selector-content")
        x = event.pageX,
        y = event.pageY;

    // Clear of previous HTML
    $dialog.empty();

    //console.log([x, y]);

    data.forEach(function(el) {
        $dialog.append('' + el + '
');
    });

    $(".callback-element").click(function(e) {
        $(caller).text($(this).text());
    })

    // Show modal
    if(!$($dialog).is(':visible'))
    {
        $($dialog).show(100);
    }

    // Positioning
    $dialog.css("left", x).css("top", y);
}

function addArgument(event, context, caller) {

}

$("#element-selector").click( function () {
    // Close the modal
    if($("#element-selector").is(':visible'))
    {
        $("#element-selector").delay(200).hide(100);
    }
});

$(document).mouseup(function (e)
{
    var container = $("#element-selector");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.delay(200).hide();
    }
});

function setupggDOM (data) {
    // Set up data
    var interactive_elements = $(".interactive");

    /* DATASET */
    // Loop through all elements and assign them with reasonable properties and onClick behaviour
    $(".data").data("allowed_datasets", Object.getOwnPropertyNames(data.datasets));
    console.log($(".data").data("allowed_datasets"));

    // Cycle through datasets
    // TODO: Maybe replace with selection menu later?
    $(".data").click(function(event) {
        console.log("Clicked a data set name.");
        var allowed_datasets = $(this).data("allowed_datasets");

        addDialog(event, allowed_datasets, this);

        // TODO:
        // - cycleAllAesUsingThisData();
        // - or: invalidatePlotButtonAndUnderlineFaultyElements();
    });

    /* PARAMETERS */
    function setParameterClicks() {
        $(".parameter").unbind("click");

        $(".parameter").click(function (event) {
            // Get scope
            var $scope = $(this).parents(".scope"),
                envir = $(this).parent().attr("class"),
                scope_id = $scope.attr('id');

            switch (envir) {
                case "aes":
                    if (scope_id == "canvas") {
                        var geom_name = $(".geom").text();
                        console.log("active geoms: " + geom_name);

                        var allowed_params = data.geom[geom_name].aesthetics;
                    } else {
                        //    TODO:
                        //    - getLocallyScopedElement();
                        //    - getAllowedAes();
                        var geom_name = $(this).siblings(".geom").text(),
                            allowed_params = data.geom[geom_name].args;

                        console.log("parent geom: " + geom_name);
                    }

                    console.log("Clicked an aes parameter.\n\tGeom name(s): " + geom_name + "\n\tAllowed aesthetics: " + allowed_params);

                    break;
                case "element":
                    var element_name = $(this).siblings(".element-name").text()
                        allowed_params = data.geom[element_name].args;

                    console.log(allowed_params);
                    break;
            }

            //$(this).text(next_name);
            addDialog(event, allowed_params, this);

            // modifyAesArgument();
            //var valid_arguments = getValidAesArguments(current_aesthetic);
            //updateAesArgument(valid_arguments);
        });
    }

    setParameterClicks();

    /* ARGUMENTS */
    function setArgumentClicks() {
        $(".argument").unbind("click");

        $(".argument").click(function (event) {
            // Get scope
            var parent = $(this).parents(".scope");
            if (parent.attr('class') != "scope") {
                return;
            }

            var scope = parent.attr('id'),
                parent_class = $(this).parent().attr('class');

            console.log("Parent class: " + parent_class);

            // If parent is aes, make aes modifications.
            if (parent_class == 'aes') {
                // Scope is global ('canvas')
                if (scope == "canvas") {
                    if ($(this).attr('data-type') == "varname") {
                        var active_dataset = $(this).parents(".scope").find(".data").text(),
                            data_names = data.datasets[active_dataset];

                        console.log("Clicked an aes argument that is a variable name.\n\tCurrent dataset: " + active_dataset + "\n\tAvailable names: " + data_names);
                        addDialog(event, data_names, this);
                    }
                }
                // Scope is local (geom or stat)
                else {
                    console.log("Clicked an aes argument with local scope.");
                }
            }

            // Parent is not aes, but element
            else {
                // Global scope
                if (scope == "canvas") {
                    console.log("Clicked an element argument with global scope.");
                }
                // Local scope
                else {
                    console.log("Clicked an element argument with local scope.");
                }
            }
        });
    }

    setArgumentClicks();

    /* ELEMENT */
    function setElementClicks() {
        $(".geom").unbind("click");

        $(".geom").click(function (event) {
            var allowed_geoms = Object.getOwnPropertyNames(data.geom);
            console.log(allowed_geoms);

            addDialog(event, allowed_geoms, this);
        });
    }

    setElementClicks();

    /* ADDERS */
    $(".add").click(function(event) {
        var scope = $(this).parents(".scope").attr("id"),
            $context = $(this).parent(),
            context_name = $context.attr("class");

        switch (context_name) {
            case "aes":
                var number_of_siblings = $(this).siblings().length,
                    before_insert = number_of_siblings > 1 ? ", " : "",
                    new_par = "x",
                    new_arg = "table";
                break;
            case "element":
                var number_of_siblings = $(this).siblings().length,
                    before_insert = number_of_siblings > 1 ? ", " : "",
                    new_par = "test",
                    new_arg = "test";
                break;
        }

        $(this).before(before_insert +
            '' + new_par + '\n' +
            '=\n' +
            '' + new_arg + '\n'
        )

        setParameterClicks();
        setArgumentClicks();

        console.log("Clicked add element.\n\tscope: " + scope + "\n\tcontext: " + context_name);
    });
}

/* Init */
$(function() {
    $.ajax({
        type: "GET",
        url: "./data/ggplot_docs.json",
        dataType: "json",
        success: function (response) {
            window.ggplot_docs = response;
            //console.log("Loaded data; firing up Tangle");
            setupggDOM(window.ggplot_docs);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("Error!" + textStatus);
        }
    });

    $("#plotbutton").on("click", function(e) {
        // Build ggplot command
        var plotcode = $("#ggplotCode").text()
            .replace(/[\n\t ]+/g, "")
            .replace(/[\u2026]/g, "");
        console.log(plotcode);

        e.preventDefault();
        $("#plotdiv").html("Loading...");

        var code = "parse(text = \"library(ggplot2);" + plotcode + "\");";
        console.log("Executing code: '" + code + "'");
        window.code = code;

        var response = $.ajax({
            type: "POST",
            url: "https://public.opencpu.org/ocpu/library/base/R/eval",
            data: {
                "expr": code
            },
            success: function(data, status, xhr) {
                var graphloc = xhr.getResponseHeader('Location') + "graphics/1/png";
                var tblloc = xhr.getResponseHeader('Location') + "stdout/text";
                console.log(tblloc);
                var img = $("").attr('src', graphloc)
                    //var tbl = $("<")
                    .load(function() {
                        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                            alert('broken image!');
                        } else {
                            $("#plotdiv").html(img);
                        }
                    });
            },
            fail: function() {
                $("#plotdiv").html("Error: Could not load image.
 TODO: fetch headers from request for debugging.");
            }
        });
    });

    // Activate plot on page load
    $("#plotbutton").trigger("click");
});
<commit_msg>Extend addDialog to accomodate for element params<commit_after>/**
 * Created by love on 09/02/15.
 */

function addDialog(event, data, type, caller) {
    var $dialog = $('#element-selector'),
    //$dialog_content = $("#element-selector-content")
        x = event.pageX,
        y = event.pageY;

    // Clear of previous HTML
    $dialog.empty();

    //console.log([x, y]);

    data.forEach(function(el) {
        $dialog.append('' + el + '
');
    });

    var inner_html = "";
    $(".callback-element").click(function(e) {
        switch (type) {
            case "function":
                inner_html = $(this).text() +
                '(' +
                '…' +
                ')'
                break;
            case "aes":
                inner_html = $(this).text() +
                '' +
                $(this).text() +
                '(' +
                'x' +
                '=' +
                'table' +
                '…' +
                ')' +
                '';
                break;
            default:
                inner_html = $(this).text();
                break;
        }

        console.log("Content to add: " + inner_html);
        $(caller).html(inner_html);

    });

    // Show modal
    if(!$($dialog).is(':visible'))
    {
        $($dialog).show(100);
    }

    // Positioning
    $dialog.css("left", x).css("top", y);
}

function addArgument(event, context, caller) {

}

$("#element-selector").click( function () {
    // Close the modal
    if($("#element-selector").is(':visible'))
    {
        $("#element-selector").delay(200).hide(100);
    }
});

$(document).mouseup(function (e)
{
    var container = $("#element-selector");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.delay(200).hide();
    }
});

function setupggDOM (data) {
    // Set up data
    var interactive_elements = $(".interactive");

    /* DATASET */
    // Loop through all elements and assign them with reasonable properties and onClick behaviour
    $(".data").data("allowed_datasets", Object.getOwnPropertyNames(data.datasets));
    console.log($(".data").data("allowed_datasets"));

    // Cycle through datasets
    // TODO: Maybe replace with selection menu later?
    $(".data").click(function(event) {
        console.log("Clicked a data set name.");
        var allowed_datasets = $(this).data("allowed_datasets");

        addDialog(event, allowed_datasets, "dataset", this);

        // TODO:
        // - cycleAllAesUsingThisData();
        // - or: invalidatePlotButtonAndUnderlineFaultyElements();
    });

    /* PARAMETERS */
    function setParameterClicks() {
        $(".parameter").unbind("click");

        $(".parameter").click(function (event) {
            // Get scope
            var $scope = $(this).parents(".scope"),
                envir = $(this).parent().attr("class"),
                scope_id = $scope.attr('id');

            switch (envir) {
                case "aes":
                    if (scope_id == "canvas") {
                        var geom_name = $(".geom").text();
                        console.log("active geoms: " + geom_name);

                        var allowed_params = data.elements.geom[geom_name].aesthetics;
                    } else {
                        //    TODO:
                        //    - getLocallyScopedElement();
                        //    - getAllowedAes();
                        var geom_name = $(this).siblings(".geom").text(),
                            allowed_params = data.elements.geom[geom_name].args;

                        console.log("parent geom: " + geom_name);
                    }

                    console.log("Clicked an aes parameter.\n\tGeom name(s): " + geom_name + "\n\tAllowed aesthetics: " + allowed_params);

                    break;
                case "element":
                    var element_name = $(this).siblings(".element-name").text(),
                        all_params = data.elements.geom[element_name].args,
                        allowed_params = [];

                    console.log("all_params: " + all_params);

                    for (var i = 0; i < all_params.length; i++) {
                        //console.log("parameter: " + all_params[i]);
                        var p = data.parameters[all_params[i]];
                        //console.log("p.display: " + p.display);
                        allowed_params.push(all_params[i]);
                    }

                    console.log(allowed_params);
                    break;
            }

            //$(this).text(next_name);
            addDialog(event, allowed_params, "string", this);

            // modifyAesArgument();
            //var valid_arguments = getValidAesArguments(current_aesthetic);
            //updateAesArgument(valid_arguments);
        });
    }

    setParameterClicks();

    /* ARGUMENTS */
    function setArgumentClicks() {
        $(".argument").unbind("click");

        $(".argument").click(function (event) {
            // Get scope
            var $scope = $(this).parents(".scope"),
                scope_id = $scope.attr('id'),
                $parent = $(this).parent(),
                parent_class = $parent.attr("class");

            console.log("Parent class: " + parent_class);

            // If parent is aes, make aes modifications.
            switch(parent_class) {
                case "aes": // Parameter is an aesthetic
                    // Scope is global ('canvas')
                    if (scope_id == "canvas") {
                        if ($(this).attr('data-type') == "varname") {
                            var active_dataset = $scope.find(".data").text(),
                                data_names = data.datasets[active_dataset];

                            console.log("Clicked an aes argument that is a variable name.\n\tCurrent dataset: " + active_dataset + "\n\tAvailable names: " + data_names);
                            addDialog(event, data_names, this);
                        }
                    }
                    // Scope is local (geom or stat)
                    else {
                        console.log("Clicked an aes argument with local scope.");
                    }
                    break;
                case "element": // Parameter is an element parameter
                    // Global scope
                    if (scope_id == "canvas") {
                        // TODO:
                        // Implement global parameters?
                        console.log("Clicked an element argument with global scope.");
                    }
                    // Local scope
                    else {
                        console.log("Clicked an element argument with local scope.");
                        console.log(data.parameters["mapping"]);

                        var $param = $(this).prevUntil(".parameter").prev(".parameter"),
                            param_name = $param.text(),
                            param_data = data.parameters[param_name];
                        //console.log("param_name: " + param_name + "\nparam_data.type: " + data.parameters["mapping"].type);
                        addDialog(event, param_data.value, param_data.type, this);
                    }
                    break;
            }
        });
    }

    setArgumentClicks();

    /* ELEMENT */
    function setElementClicks() {
        $(".geom").unbind("click");

        $(".geom").click(function (event) {
            var allowed_geoms = Object.getOwnPropertyNames(data.elements.geom);
            console.log(allowed_geoms);

            addDialog(event, allowed_geoms, this);
        });
    }

    setElementClicks();

    /* ADDERS */
    $(".add").click(function(event) {
        var scope = $(this).parents(".scope").attr("id"),
            $context = $(this).parent(),
            context_name = $context.attr("class");

        switch (context_name) {
            case "aes":
                var number_of_siblings = $(this).siblings().length,
                    before_insert = number_of_siblings > 1 ? ", " : "",
                    new_par = "x",
                    new_arg = "table";
                break;
            case "element":
                var number_of_siblings = $(this).siblings().length,
                    before_insert = number_of_siblings > 1 ? ", " : "",
                    new_par = "test",
                    new_arg = "test";
                break;
        }

        $(this).before(before_insert +
            '' + new_par + '\n' +
            '=\n' +
            '' + new_arg + '\n'
        )

        setParameterClicks();
        setArgumentClicks();

        console.log("Clicked add element.\n\tscope: " + scope + "\n\tcontext: " + context_name);
    });
}

/* Init */
$(function() {
    $.ajax({
        type: "GET",
        url: "./data/ggplot_docs_scraped.json",
        dataType: "json",
        success: function (response) {
            window.ggplot_docs = response;
            //console.log("Loaded data; firing up Tangle");
            setupggDOM(window.ggplot_docs);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("Error!" + textStatus);
        }
    });

    $("#plotbutton").on("click", function(e) {
        // Build ggplot command
        var plotcode = $("#ggplotCode").text()
            .replace(/[\n\t ]+/g, "")
            .replace(/[\u2026]/g, "");
        console.log(plotcode);

        e.preventDefault();
        $("#plotdiv").html("Loading...");

        var code = "parse(text = \"library(ggplot2);" + plotcode + "\");";
        console.log("Executing code: '" + code + "'");
        window.code = code;

        var response = $.ajax({
            type: "POST",
            url: "https://public.opencpu.org/ocpu/library/base/R/eval",
            data: {
                "expr": code
            },
            success: function(data, status, xhr) {
                var graphloc = xhr.getResponseHeader('Location') + "graphics/1/png";
                var tblloc = xhr.getResponseHeader('Location') + "stdout/text";
                console.log(tblloc);
                var img = $("").attr('src', graphloc)
                    //var tbl = $("<")
                    .load(function() {
                        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                            alert('broken image!');
                        } else {
                            $("#plotdiv").html(img);
                        }
                    });
            },
            fail: function() {
                $("#plotdiv").html("Error: Could not load image.
 TODO: fetch headers from request for debugging.");
            }
        });
    });

    // Activate plot on page load
    $("#plotbutton").trigger("click");
});
<|endoftext|>


<commit_before>import React from 'react';
import Renderer from 'react-test-renderer';
import Coroutine from '../modules/Coroutine';

describe('Coroutine', async () => {
  it('should render empty body until coroutine is resolved', async () => {
    async function render() {
      return
test
;
    }

    const TestComponent = Coroutine.create(render);
    const tree = Renderer.create(<TestComponent />);

    const initial = Renderer.create();
    expect(tree.toJSON()).toEqual(initial.toJSON());

    const success = await Renderer.create(
test
);
    expect(tree.toJSON()).toEqual(success.toJSON());
  });

  it('should pass initial information', async () => {
    function getVariables() {
      return { number: 13 };
    }

    async function render({ number }) {
      return
{ number }
;
    }

    const TestComponent = Coroutine.create(render, getVariables);
    const tree = Renderer.create(<TestComponent />);

    const success = await Renderer.create(
{13}
);
    expect(tree.toJSON()).toEqual(success.toJSON());
  });

  it('should re-render the component if variables are updated', async () => {
    function getVariables() {
      return { number: 0 };
    }

    async function render({ number, forceUpdate }) {
      try {
        return
{ number }
;
      } finally {
        await true;
        if (number === 0) forceUpdate({ number: 1 });
      }
    }

    const TestComponent = Coroutine.create(render, getVariables);
    const tree = await Renderer.create(<TestComponent />);

    const success = await Renderer.create(
{0}
);
    expect(tree.toJSON()).toEqual(success.toJSON());

    const updated = await Renderer.create(
{1}
);
    expect(tree.toJSON()).toEqual(updated.toJSON());
  });

  it('should render each step of async iterator', async () => {
    async function* render() {
      yield
Loading...
;
      await Promise.resolve();
      return
Done!
;
    }

    const TestComponent = Coroutine.create(render);
    const tree = await Renderer.create(<TestComponent />);

    const first = await Renderer.create(
Loading...
);
    expect(tree.toJSON()).toEqual(first.toJSON());

    const second = await Renderer.create(
Done!
);
    expect(tree.toJSON()).toEqual(second.toJSON());
  });
});
<commit_msg>get rid of test of old-way API<commit_after>import React from 'react';
import Renderer from 'react-test-renderer';
import Coroutine from '../modules/Coroutine';

describe('Coroutine', async () => {
  it('should render empty body until coroutine is resolved', async () => {
    async function render() {
      return
test
;
    }

    const TestComponent = Coroutine.create(render);
    const tree = Renderer.create(<TestComponent />);

    const initial = Renderer.create();
    expect(tree.toJSON()).toEqual(initial.toJSON());

    const success = await Renderer.create(
test
);
    expect(tree.toJSON()).toEqual(success.toJSON());
  });

  it('should pass initial information', async () => {
    function getVariables() {
      return { number: 13 };
    }

    async function render({ number }) {
      return
{ number }
;
    }

    const TestComponent = Coroutine.create(render, getVariables);
    const tree = Renderer.create(<TestComponent />);

    const success = await Renderer.create(
{13}
);
    expect(tree.toJSON()).toEqual(success.toJSON());
  });

  it('should render each step of async iterator', async () => {
    async function* render() {
      yield
Loading...
;
      await Promise.resolve();
      return
Done!
;
    }

    const TestComponent = Coroutine.create(render);
    const tree = await Renderer.create(<TestComponent />);

    const first = await Renderer.create(
Loading...
);
    expect(tree.toJSON()).toEqual(first.toJSON());

    const second = await Renderer.create(
Done!
);
    expect(tree.toJSON()).toEqual(second.toJSON());
  });
});
<|endoftext|>


<commit_before>import React  from 'react'
import $  from 'jquery'
import showMessage  from './Dialog'

const Component = React.Component;
const EventManage = $("

");
let moveElement;

class GameBoard extends Component {

	constructor(props) {
		super(props);
        this.state = {
            cards: [<Card key="0"/>],
        };
    }

	render() {
		let cards = this.state.cards;
		return (

					{cards}

);
	}

	componentDidMount() {
		this.getCards();
	}

	getCards() {
		let my_side = 0;
		let self = this;
		$.getJSON(
			'/table/table',
			{},
			function(ret){
				if(ret.code != 0){
					showMessage(ret.msg);
				}
				let my_hand = ret.data.side[my_side]['hands'];
				let my_hand_cards = [];
				for(let i in my_hand){
					let x = 20 + 110 * i;
					let y = 580;
					my_hand_cards.push(<Card x={x} y={y} key={i} name={my_hand[i]} />);
				}
				self.setState({cards: my_hand_cards});
			}
		)
	}

	handleDrop(event) {
		if (moveElement.props.fatherName == this.props.name) {
			moveElement.setState({x: event.pageX - moveElement._x, y: event.pageY - moveElement._y});
			return;
		}

		let a = <Card  key={new Date() - 0} {...moveElement.props} fatherName={this.props.name} x={event.pageX - this.refs.t.offsetLeft - moveElement._x} y={event.pageY - this.refs.t.offsetTop - moveElement._y}/>;

		this.setState(function(oldState){
			oldState.cards.push(a);
			return oldState;
		});

	}

	handDragover(event) {
		event.preventDefault()
	}

}

class Card extends Component{

	constructor(props) {
		super(props);
        this.state = {
            opacity: 1
        }
    }

	render() {
		let x = this.state.x || this.props.x || 0;
		let y = this.state.y || this.props.y || 0;
		let name = this.state.name || this.props.name || "";
		if (x || y) {
			return (

						{name}

)
		}
		return (

)
	}

	handleClick() {
		console.log(5)
	}

	handleDragLeave() {
		console.log(2)
	}

	handleDragStart(event) {
	    this.setState({opacity:0.2});
	    this._x = event.pageX - this.refs.s.offsetLeft;
	    this._y = event.pageY - this.refs.s.offsetTop;
	    moveElement = this;
	}

	handleDragEnd() {
	    this.setState({opacity:1})
	}

	handleDrag() {

	}

}

class Board extends Component {
	render() {
		return
<GameBoard/>
;
	}
}

class Hands extends Component {
	constructor(props) {
		super(props);
        this.state = {
            cards: []
        };
    }

    render() {
    	let cards = this.state.cards;
		return (

					{cards}

);
    }

    handleDrop(event) {
		if (moveElement.props.fatherName == this.props.name) {
			moveElement.setState({x: event.pageX - moveElement._x, y: event.pageY - moveElement._y});
			return;
		}

		let a = <Card  key={new Date() - 0} {...moveElement.props} fatherName={this.props.name} x={event.pageX - this.refs.t.offsetLeft - moveElement._x} y={event.pageY - this.refs.t.offsetTop - moveElement._y}/>;

		this.setState(function(oldState){
			oldState.cards.push(a);
			return oldState;
		});

	}

	handDragover(event) {
		event.preventDefault()
	}
}

export default Board
<commit_msg>feat : 前端卡牌移动，添加监听、触发<commit_after>import React  from 'react'
import $  from 'jquery'
import showMessage  from './Dialog'

const Component = React.Component;
const EventManage = $("

");
let moveElement;

class GameBoard extends Component {

	constructor(props) {
		super(props);
        this.state = {
            cards: [<Card key="0"/>],
        };
    }

	render() {
		let cards = this.state.cards;
		return (

					{cards}

);
	}

	componentDidMount() {
		this.bindEvent();
		this.getCards();
	}

	bindEvent(){
		EventManage.on('card_move', function(event, params){
			console.log(event, params);
		})
	}

	getCards() {
		let my_side = 0;
		let self = this;
		$.getJSON(
			'/table/table',
			{},
			function(ret){
				if(ret.code != 0){
					showMessage(ret.msg);
				}
				let my_hand = ret.data.side[my_side]['hands'];
				let my_hand_cards = [];
				for(let i in my_hand){
					let x = 20 + 110 * i;
					let y = 580;
					my_hand_cards.push(<Card x={x} y={y} key={i} id={my_hand[i]} name={my_hand[i]} />);
				}
				self.setState({cards: my_hand_cards});
			}
		)
	}

	handleDrop(event) {

		if (moveElement.props.fatherName == this.props.name) {
			EventManage.trigger("card_move", {id : moveElement._id, from : {x : moveElement._x, y : moveElement._y}, to : {x : event.pageX - moveElement._x, y : event.pageY - moveElement._y}});
			moveElement.setState({x: event.pageX - moveElement._x, y: event.pageY - moveElement._y});
			return;
		}

		let a = <Card key={new Date() - 0} {...moveElement.props} fatherName={this.props.name} x={event.pageX - this.refs.t.offsetLeft - moveElement._x} y={event.pageY - this.refs.t.offsetTop - moveElement._y}/>;

		this.setState(function(oldState){
			oldState.cards.push(a);
			return oldState;
		});

	}

	handDragover(event) {
		event.preventDefault()
	}

}

class Card extends Component{

	constructor(props) {
		super(props);
        this.state = {
            opacity: 1
        }
    }

	render() {
		let x = this.state.x || this.props.x || 0;
		let y = this.state.y || this.props.y || 0;
		let name = this.state.name || this.props.name || "";
		if (x || y) {
			return (

						{name}

)
		}
		return (

)
	}

	handleClick() {
		console.log(5)
	}

	handleDragLeave() {
		console.log(2)
	}

	handleDragStart(event) {
	    this.setState({opacity:0.2});
	    this._x = event.pageX - this.refs.s.offsetLeft;
	    this._y = event.pageY - this.refs.s.offsetTop;
	    this._id = this.state.id || this.props.id || "";
	    moveElement = this;
	}

	handleDragEnd() {
	    this.setState({opacity:1})
	}

	handleDrag() {

	}

}

class Board extends Component {
	render() {
		return
<GameBoard/>
;
	}
}

class Hands extends Component {
	constructor(props) {
		super(props);
        this.state = {
            cards: []
        };
    }

    render() {
    	let cards = this.state.cards;
		return (

					{cards}

);
    }

    handleDrop(event) {
		if (moveElement.props.fatherName == this.props.name) {
			moveElement.setState({x: event.pageX - moveElement._x, y: event.pageY - moveElement._y});
			return;
		}

		let a = <Card  key={new Date() - 0} {...moveElement.props} fatherName={this.props.name} x={event.pageX - this.refs.t.offsetLeft - moveElement._x} y={event.pageY - this.refs.t.offsetTop - moveElement._y}/>;

		this.setState(function(oldState){
			oldState.cards.push(a);
			return oldState;
		});

	}

	handDragover(event) {
		event.preventDefault()
	}
}

export default Board
<|endoftext|>