<commit_before>import { Component } from 'react'
import h from 'react-hyperscript'
import {Link} from 'react-router-dom'
import styled from 'styled-components'
import { StageDisplayNames, Stage } from '../../../constants.js'

const ItemFrame = styled('div')`
  border:2px solid ${props => props.userActionRequired ? props.theme.yellow : props.theme.dark};
  padding: 0.5em 1em;
  margin: 0.2em 0;
  background-color:${props => props.theme.light};
  text-align:left;
`

const Box = styled('div')`
  display:inline-block;
  margin-right:3em;
`

const ConceptName = styled('div')`
  color:${props => props.theme.dark};
  font-size:1.8em;
`

const AssesseeAddress = styled('a')`
  color:${props => props.theme.dark};
  font-size:0.8em;
`

// Meeting Point

const MeetingBox = styled('div')`
  background-color:${props => props.theme.veryLight};
  padding: 0.5em 1em;
  display:inline-block;
`
const MeetingCaption = styled('div')`
  color:${props => props.theme.dark};
`
const MeetingAddress = styled('a')`
  color:${props => props.theme.blue};
  font-size:0.8em;
`

// assessee/assessor badges

const AssesseeBadge = styled('div')`
  background-color:${props => props.theme.lightblue};
  border-radius:0.3em;
  padding:0.1em 0.3em;
`
const AssessorBadge = styled('div')`
  background-color:orange;
  border-radius:0.3em;
  padding:0.1em 0.3em;
`

// link to action/assessmentView

const LinkBox = styled('div')`
  float: right;
  margin-right:1.2em;
`

const LinkUnstyled = styled(Link)`
  text-decoration:none;
`

const LinkButton = styled('div')`
  display:block;
  background-color:green;
  color:${props => props.theme.lightgrey};
  text-decoration:none;
  padding: ${(props) => props.stage === Stage.Done ? '0.5em' : '1em'} 1.5em;
  width:4em;
  text-align:center;
  border: ${(props) => props.userActionRequired ? '1px solid ' + props.theme.yellow : 'none'}
`

const LinkSubtitle = styled('div')`
  color:${props => props.theme.lightgrey};
  font-size:0.6em;
  text-align:center;
`

export class AssessmentItem extends Component {
  render () {
    const assessment = this.props.assessment
    console.log(assessment)
    let userStage = assessment.userStage
    let stage = assessment.stage

    // set assessee/assessor view
    let RoleBadge = h(AssessorBadge, 'Assessor')
    let isAssessee = ''
    if (this.props.userAddress === assessment.assessee) {
      RoleBadge = h(AssesseeBadge, 'Assessee')
      isAssessee = ' (you)'
    }

    // set meeting point component
    let MeetingPoint = ' NoMeetingPointSet '
    if (assessment.data) {
      MeetingPoint = h(MeetingAddress, {
        href: assessment.data,
        target: '_blank'
      }, assessment.data)
    }

    // look if user is required to make an action
    let userActionRequired = true
    let actionText = StageDisplayNames[userStage]
    if (stage < userStage ||
      userStage === 0 ||
      userStage === 4 ||
      userStage === 5) {
      userActionRequired = false
    }
    if (stage < userStage) {
      actionText = 'Waiting...'
    }
    // if assessment stage is finished, set good message (an assessee would have userStage===0)
    if (stage === Stage.Done) {
      // display score for assessee and payout for assessor
      if (!isAssessee) {
        actionText = h('div', [
          h('div', 'Payout :'),
          h('div', '+5 AHA')
        ])
      } else {
        actionText = h('div', [
          h('div', 'Score :'),
          h('div', assessment.finalScore + ' %')
        ])
      }
    }
    if (stage === Stage.Burned) {
      actionText = 'Canceled'
    }
    return (
      h(ItemFrame, {userActionRequired}, [
        h(Box, [
          h(ConceptName, assessment.conceptData),
          h(AssesseeAddress, {
            href: 'https://' + (this.props.networkID === 4 ? 'rinkeby.' : '') + 'etherscan.io/address/' + assessment.assessee,
            target: '_blank',
            title: 'est'
          }, 'assessee: ' + assessment.assessee.substring(0, 8) + '...' + assessment.assessee.substring(30, 42) + isAssessee)
        ]),
        h(Box, [
          RoleBadge
        ]),
        h(MeetingBox, [
          h(MeetingCaption, 'Meet at:'),
          MeetingPoint
        ]
        ),
        h(LinkBox, [
          h(LinkSubtitle, 'click here for details'),
          h(LinkUnstyled, { to: 'assessment/' + assessment.address },
            h(LinkButton, { userActionRequired, stage },
              actionText
            )
          )
        ])
      ])
    )
  }
}

export default AssessmentItem
<commit_msg>used else in assessmentItem<commit_after>import { Component } from 'react'
import h from 'react-hyperscript'
import {Link} from 'react-router-dom'
import styled from 'styled-components'
import { StageDisplayNames, Stage } from '../../../constants.js'

const ItemFrame = styled('div')`
  border:2px solid ${props => props.userActionRequired ? props.theme.yellow : props.theme.dark};
  padding: 0.5em 1em;
  margin: 0.2em 0;
  background-color:${props => props.theme.light};
  text-align:left;
`

const Box = styled('div')`
  display:inline-block;
  margin-right:3em;
`

const ConceptName = styled('div')`
  color:${props => props.theme.dark};
  font-size:1.8em;
`

const AssesseeAddress = styled('a')`
  color:${props => props.theme.dark};
  font-size:0.8em;
`

// Meeting Point

const MeetingBox = styled('div')`
  background-color:${props => props.theme.veryLight};
  padding: 0.5em 1em;
  display:inline-block;
`
const MeetingCaption = styled('div')`
  color:${props => props.theme.dark};
`
const MeetingAddress = styled('a')`
  color:${props => props.theme.blue};
  font-size:0.8em;
`

// assessee/assessor badges

const AssesseeBadge = styled('div')`
  background-color:${props => props.theme.lightblue};
  border-radius:0.3em;
  padding:0.1em 0.3em;
`
const AssessorBadge = styled('div')`
  background-color:orange;
  border-radius:0.3em;
  padding:0.1em 0.3em;
`

// link to action/assessmentView

const LinkBox = styled('div')`
  float: right;
  margin-right:1.2em;
`

const LinkUnstyled = styled(Link)`
  text-decoration:none;
`

const LinkButton = styled('div')`
  display:block;
  background-color:green;
  color:${props => props.theme.lightgrey};
  text-decoration:none;
  padding: ${(props) => props.stage === Stage.Done ? '0.5em' : '1em'} 1.5em;
  width:4em;
  text-align:center;
  border: ${(props) => props.userActionRequired ? '1px solid ' + props.theme.yellow : 'none'}
`

const LinkSubtitle = styled('div')`
  color:${props => props.theme.lightgrey};
  font-size:0.6em;
  text-align:center;
`

export class AssessmentItem extends Component {
  render () {
    const assessment = this.props.assessment
    console.log(assessment)
    let userStage = assessment.userStage
    let stage = assessment.stage

    // set assessee/assessor view
    let RoleBadge = h(AssessorBadge, 'Assessor')
    let isAssessee = ''
    if (this.props.userAddress === assessment.assessee) {
      RoleBadge = h(AssesseeBadge, 'Assessee')
      isAssessee = ' (you)'
    }

    // set meeting point component
    let MeetingPoint = ' NoMeetingPointSet '
    if (assessment.data) {
      MeetingPoint = h(MeetingAddress, {
        href: assessment.data,
        target: '_blank'
      }, assessment.data)
    }

    // look if user is required to make an action
    let userActionRequired = true
    let actionText = StageDisplayNames[userStage]
    if (stage < userStage ||
      userStage === 0 ||
      userStage === 4 ||
      userStage === 5) {
      userActionRequired = false
    }
    if (stage < userStage) {
      actionText = 'Waiting...'
    }
    // if assessment stage is finished, set good message (an assessee would have userStage===0)
    else if (stage === Stage.Done) {
      // display score for assessee and payout for assessor
      if (!isAssessee) {
        actionText = h('div', [
          h('div', 'Payout :'),
          h('div', '+5 AHA')
        ])
      } else {
        actionText = h('div', [
          h('div', 'Score :'),
          h('div', assessment.finalScore + ' %')
        ])
      }
    }
    else if (stage === Stage.Burned) {
      actionText = 'Canceled'
    }
    return (
      h(ItemFrame, {userActionRequired}, [
        h(Box, [
          h(ConceptName, assessment.conceptData),
          h(AssesseeAddress, {
            href: 'https://' + (this.props.networkID === 4 ? 'rinkeby.' : '') + 'etherscan.io/address/' + assessment.assessee,
            target: '_blank',
            title: 'est'
          }, 'assessee: ' + assessment.assessee.substring(0, 8) + '...' + assessment.assessee.substring(30, 42) + isAssessee)
        ]),
        h(Box, [
          RoleBadge
        ]),
        h(MeetingBox, [
          h(MeetingCaption, 'Meet at:'),
          MeetingPoint
        ]
        ),
        h(LinkBox, [
          h(LinkSubtitle, 'click here for details'),
          h(LinkUnstyled, { to: 'assessment/' + assessment.address },
            h(LinkButton, { userActionRequired, stage },
              actionText
            )
          )
        ])
      ])
    )
  }
}

export default AssessmentItem
<|endoftext|>


<commit_before>define(['angular', 'ol', 'map', 'd3'],

    function(angular, ol, map) {
        angular.module('hs.widgets.chart_panel', ['hs.map'])
            .service('chart_panel_service', ['OlMap', function(OlMap) {
                var me = {};

                return me;
            }])
            .directive('chartpanel', function() {
                return {
                    templateUrl: hsl_path + 'examples/webgl_viz/chart_panel/partials/template.html',
                    link: function(scope, element) {
                        var link = document.createElement("link");
                        link.type = "text/css";
                        link.rel = "stylesheet";
                        link.href = hsl_path + 'examples/webgl_viz/chart_panel/partials/style.css';
                        document.getElementsByTagName("head")[0].appendChild(link);
                    }
                };
            })

        .controller('ChartPanel', ['$scope', 'OlMap', 'chart_panel_service',
            function($scope, OlMap, chart_panel_service) {

            }
        ]);

    });
<commit_msg>module name hs.map.service in chartpanel module<commit_after>define(['angular', 'ol', 'map', 'd3'],

    function(angular, ol, map) {
        angular.module('hs.widgets.chart_panel', ['hs.map'])
            .service('chart_panel_service', ['hs.map.service', function(OlMap) {
                var me = {};

                return me;
            }])
            .directive('chartpanel', function() {
                return {
                    templateUrl: hsl_path + 'examples/webgl_viz/chart_panel/partials/template.html',
                    link: function(scope, element) {
                        var link = document.createElement("link");
                        link.type = "text/css";
                        link.rel = "stylesheet";
                        link.href = hsl_path + 'examples/webgl_viz/chart_panel/partials/style.css';
                        document.getElementsByTagName("head")[0].appendChild(link);
                    }
                };
            })

        .controller('ChartPanel', ['$scope', 'hs.map.service', 'chart_panel_service',
            function($scope, OlMap, chart_panel_service) {

            }
        ]);

    });
<|endoftext|>


<commit_before>/*-
 * ========================LICENSE_START=================================
 * AEM Permission Management
 * %%
 * Copyright (C) 2013 - 2016 Cognifide Limited
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =========================LICENSE_END==================================
 */
(function (window, $) {
  $(document).on('cui-contentloaded', function () {

    const SHOW_REFERENCES_URL = '/apm/references.html';

    function Console($el) {
      this.uiHelper = $(window).adaptTo('foundation-ui');
      this.$el = $el;
      this.$textArea = this.$el.find('#cqsm').eq(0);
      this.$validationAlertContainer = $('
');
      this.$textArea.parent().append(this.$validationAlertContainer);
      this.$fileName = this.$el.find('#fname').eq(0);
      this.$showReference = this.$el.find('#showReference').eq(0);
      this.$validateButton = this.$el.find('#validateButton').eq(0);
      this.$saveButton = this.$el.find('#saveButton').eq(0);
      this.$saveAndCloseButton = this.$el.find('#saveAndCloseButton').eq(0);
      this.$cancelButton = this.$el.find('#cancelButton').eq(0);
      this.$lastSavedOn = this.$el.find('.lastSavedOn').eq(0);
      this.initialValue = this.$textArea.val();
      this.savePath = this.$el.find('#script-form').attr('action');
      this.editor = this.initEditor();
      this.delegateEvents();
    }

    Console.prototype = {
      isFileNameLocked: function () {
        return this.$fileName.is('[readonly="readonly"]');
      },
      changeFileName: function (name) {
        this.$fileName.val(name);
        this.$fileName.attr('readonly','readonly');
      },
      hasChanged: function () {
        return this.initialValue !== this.$textArea.val();
      },
      getFileName: function () {
        return this.$fileName.val() + '.cqsm';
      },
      getOverwrite: function () {
        return this.isFileNameLocked() ? 'true' : 'false';
      },
      fileUpload: function () {
        let self = this,
            boundary = '-----------------------------' +
                Math.floor(Math.random() * Math.pow(10, 8)),
            value = this.$textArea.val(),
            params = {
              file: {
                type: 'text/plain',
                filename: this.getFileName(),
                content: value
              }
            },
            content = [],
            file,
            mimeHeader;

        for (file in params) {
          if (params.hasOwnProperty(file)) {
            mimeHeader = 'Content-Disposition: form-data; name="' + file + '"; ';
            content.push('--' + boundary);

            if (params[file].filename) {
              if (this.savePath.endsWith('/' + params[file].filename)) {
                mimeHeader += 'filename="' + this.savePath + '";';
              } else {
                mimeHeader += 'filename="' + this.savePath + '/' + params[file].filename + '";';
              }
            }
            content.push(mimeHeader);

            if (params[file].type) {
              content.push('Content-Type: ' + params[file].type);
            }

            content.push('');
            content.push(params[file].content);
            content.push('--' + boundary);
          }
        }

        $.ajax({
          type: 'POST',
          async: false,
          url: '/bin/cqsm/fileUpload?overwrite=' + this.getOverwrite(),
          dataType: 'json',
          processData: false,
          contentType: 'multipart/form-data; boundary=' + boundary,
          data: content.join('\r\n'),
          success: function (data) {
            const scripts = data.uploadedScripts;
            if (scripts.length > 0) {
              if (!self.isFileNameLocked()) {
                  self.changeFileName(scripts[0].name);
              }
              self.initialValue = value;
              self.createMode = false;
              self.$lastSavedOn.text('Last saved on: ' + new Date().toLocaleString());
              self.displayResponseFeedback(data);
            } else {
              self.displayResponseFeedback({
                type:'error',
                message: 'Error while saving: ' + self.getFileName()
              });
            }
          },
          error: function(response) {
            self.displayResponseFeedback(response.responseJSON);
          }
        });
      },
      initEditor: function () {
        let editor = null;

        ace.config.set('basePath', '/apps/apm/clientlibs/externals/ace/js');
        this.$textArea.hide();
        editor = ace.edit('ace');

        editor.setTheme('ace/theme/chrome');
        editor.getSession().setMode('ace/mode/cqsm');
        editor.getSession().setValue(this.initialValue);
        ace.require(['ace/token_tooltip'], function (o) {
          editor.tokenTooltip = new o.TokenTooltip(editor);
        });

        ace.require(['ace/ext/language_tools'], function () {
          editor.setOptions({
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true
          });
        });

        return editor;
      },
      delegateEvents: function () {
        const self = this;

        this.editor.getSession().on('change', function () {
          self.$textArea.val(self.editor.getSession().getValue());
        });

        this.$showReference.click(function () {
          window.open(SHOW_REFERENCES_URL, '_blank');
        });

        this.$cancelButton.click(function () {
          window.location.href = document.referrer;
        });

        this.displayResponseFeedback = function (response) {
          this.$validateButton.blur()
          const isErrorMessage = response.type === 'error';
          const variant = isErrorMessage ? 'error' : 'success';

          let text = '';

          if (isErrorMessage) {
            text = 'error';
            if (response.errors) {
              response.message += '
';
              response.errors.forEach(function(error) {
                response.message += '
' + error;
              });
              response.message += '
';
            }
            self.uiHelper.notify(text, response.message, variant);
          } else {
            text = 'info';
            self.uiHelper.notify(text, response.message, variant);
          }
        };

        this.$validateButton.click(function () {
          $.ajax({
            type: 'POST',
            async: false,
            url: '/bin/cqsm/validate',
            data: {
              content: self.$textArea.val()
            },
            success: function (response) {
              self.displayResponseFeedback(response);
            },
            error: function (response) {
              self.displayResponseFeedback(response.responseJSON);
            }
          });
        });

        this.$saveButton.click(function () {
          self.fileUpload();
        });

        this.$saveAndCloseButton.click(function () {
          self.fileUpload();
          window.location.href = document.referrer;
        });

        $(document).ready(function () {
          $(document).keydown(function (e) {
            const S_CHARACTER_CODE = 83;
            if (e.ctrlKey && e.keyCode === S_CHARACTER_CODE) {
              e.stopPropagation();
              e.preventDefault();
              self.fileUpload();
            }
          });

          $(window).on('beforeunload', function () {
            if (self.hasChanged()) {
              return 'You have unsaved changes';
            }
          });
        });
      }
    };
    new Console($('body'));
  });
})(window, jQuery);
<commit_msg>Fixed bug when save button was creating new script instead of changing current one.<commit_after>/*-
 * ========================LICENSE_START=================================
 * AEM Permission Management
 * %%
 * Copyright (C) 2013 - 2016 Cognifide Limited
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =========================LICENSE_END==================================
 */
(function (window, $) {
  $(document).on('cui-contentloaded', function () {

    const SHOW_REFERENCES_URL = '/apm/references.html';

    function Console($el) {
      this.uiHelper = $(window).adaptTo('foundation-ui');
      this.$el = $el;
      this.$textArea = this.$el.find('#cqsm').eq(0);
      this.$validationAlertContainer = $('
');
      this.$textArea.parent().append(this.$validationAlertContainer);
      this.$fileName = this.$el.find('#fname').eq(0);
      this.$showReference = this.$el.find('#showReference').eq(0);
      this.$validateButton = this.$el.find('#validateButton').eq(0);
      this.$saveButton = this.$el.find('#saveButton').eq(0);
      this.$saveAndCloseButton = this.$el.find('#saveAndCloseButton').eq(0);
      this.$cancelButton = this.$el.find('#cancelButton').eq(0);
      this.$lastSavedOn = this.$el.find('.lastSavedOn').eq(0);
      this.initialValue = this.$textArea.val();
      this.savePath = this.$el.find('#script-form').attr('action');
      this.editor = this.initEditor();
      this.delegateEvents();
    }

    Console.prototype = {
      isFileNameLocked: function () {
        return this.$fileName.is(':disabled');
      },
      changeFileName: function (name) {
        this.$fileName.val(name);
        this.$fileName.attr('disabled', 'disabled');
      },
      hasChanged: function () {
        return this.initialValue !== this.$textArea.val();
      },
      getFileName: function () {
        return this.$fileName.val() + '.cqsm';
      },
      getOverwrite: function () {
        return this.isFileNameLocked() ? 'true' : 'false';
      },
      fileUpload: function () {
        let self = this,
            boundary = '-----------------------------' +
                Math.floor(Math.random() * Math.pow(10, 8)),
            value = this.$textArea.val(),
            params = {
              file: {
                type: 'text/plain',
                filename: this.getFileName(),
                content: value
              }
            },
            content = [],
            file,
            mimeHeader;

        for (file in params) {
          if (params.hasOwnProperty(file)) {
            mimeHeader = 'Content-Disposition: form-data; name="' + file + '"; ';
            content.push('--' + boundary);

            if (params[file].filename) {
              if (this.savePath.endsWith('/' + params[file].filename)) {
                mimeHeader += 'filename="' + this.savePath + '";';
              } else {
                mimeHeader += 'filename="' + this.savePath + '/' + params[file].filename + '";';
              }
            }
            content.push(mimeHeader);

            if (params[file].type) {
              content.push('Content-Type: ' + params[file].type);
            }

            content.push('');
            content.push(params[file].content);
            content.push('--' + boundary);
          }
        }

        $.ajax({
          type: 'POST',
          async: false,
          url: '/bin/cqsm/fileUpload?overwrite=' + this.getOverwrite(),
          dataType: 'json',
          processData: false,
          contentType: 'multipart/form-data; boundary=' + boundary,
          data: content.join('\r\n'),
          success: function (data) {
            const scripts = data.uploadedScripts;
            if (scripts.length > 0) {
              if (!self.isFileNameLocked()) {
                  self.changeFileName(scripts[0].name);
              }
              self.initialValue = value;
              self.createMode = false;
              self.$lastSavedOn.text('Last saved on: ' + new Date().toLocaleString());
              self.displayResponseFeedback(data);
            } else {
              self.displayResponseFeedback({
                type:'error',
                message: 'Error while saving: ' + self.getFileName()
              });
            }
          },
          error: function(response) {
            self.displayResponseFeedback(response.responseJSON);
          }
        });
      },
      initEditor: function () {
        let editor = null;

        ace.config.set('basePath', '/apps/apm/clientlibs/externals/ace/js');
        this.$textArea.hide();
        editor = ace.edit('ace');

        editor.setTheme('ace/theme/chrome');
        editor.getSession().setMode('ace/mode/cqsm');
        editor.getSession().setValue(this.initialValue);
        ace.require(['ace/token_tooltip'], function (o) {
          editor.tokenTooltip = new o.TokenTooltip(editor);
        });

        ace.require(['ace/ext/language_tools'], function () {
          editor.setOptions({
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true
          });
        });

        return editor;
      },
      delegateEvents: function () {
        const self = this;

        this.editor.getSession().on('change', function () {
          self.$textArea.val(self.editor.getSession().getValue());
        });

        this.$showReference.click(function () {
          window.open(SHOW_REFERENCES_URL, '_blank');
        });

        this.$cancelButton.click(function () {
          window.location.href = document.referrer;
        });

        this.displayResponseFeedback = function (response) {
          this.$validateButton.blur()
          const isErrorMessage = response.type === 'error';
          const variant = isErrorMessage ? 'error' : 'success';

          let text = '';

          if (isErrorMessage) {
            text = 'error';
            if (response.errors) {
              response.message += '
';
              response.errors.forEach(function(error) {
                response.message += '
' + error;
              });
              response.message += '
';
            }
            self.uiHelper.notify(text, response.message, variant);
          } else {
            text = 'info';
            self.uiHelper.notify(text, response.message, variant);
          }
        };

        this.$validateButton.click(function () {
          $.ajax({
            type: 'POST',
            async: false,
            url: '/bin/cqsm/validate',
            data: {
              content: self.$textArea.val()
            },
            success: function (response) {
              self.displayResponseFeedback(response);
            },
            error: function (response) {
              self.displayResponseFeedback(response.responseJSON);
            }
          });
        });

        this.$saveButton.click(function () {
          self.fileUpload();
        });

        this.$saveAndCloseButton.click(function () {
          self.fileUpload();
          window.location.href = document.referrer;
        });

        $(document).ready(function () {
          $(document).keydown(function (e) {
            const S_CHARACTER_CODE = 83;
            if (e.ctrlKey && e.keyCode === S_CHARACTER_CODE) {
              e.stopPropagation();
              e.preventDefault();
              self.fileUpload();
            }
          });

          $(window).on('beforeunload', function () {
            if (self.hasChanged()) {
              return 'You have unsaved changes';
            }
          });
        });
      }
    };
    new Console($('body'));
  });
})(window, jQuery);
<|endoftext|>


<commit_before>import './TweetList.styl';
import Component from 'react-pure-render/component';
import React, {PropTypes} from 'react';
import Tweet from 'react-tweet'
import {Input,ButtonGroup, DropdownButton, Button, MenuItem} from 'react-bootstrap';

export default class TweetList extends Component {

  static propTypes = {
    tweets: PropTypes.array
  };

  constructor(props) {
    super(props);
  }

  render() {
    let tweets = this.props.tweets.map(currentTweet =>
      <Tweet data={currentTweet} key={currentTweet.id}/>
    );

    return (

        <ButtonGroup>
          <DropdownButton disabled title="Sort by date" bsStyle="info" bsSize="xsmall" id="dropdown1">
            <MenuItem eventKey="1">Ascending</MenuItem>
            <MenuItem eventKey="2">Descending</MenuItem>
          </DropdownButton>
          <DropdownButton disabled title="Sort by likes" bsStyle="info" bsSize="xsmall" id="dropdown2">
            <MenuItem eventKey="1">Ascending</MenuItem>
            <MenuItem eventKey="2">Descending</MenuItem>
          </DropdownButton>
          <Button
            disabled
            bsStyle="success"
            bsSize="xsmall">
            Show modal info
          </Button>
        </ButtonGroup>
        <Input
          bsSize="small"
          disabled
          placeholder="Search in tweets"
          type="text"

          //TODO: search in tweets
          //onChange={this.handleChange}
        />
        {tweets}

    );
  }
}

<commit_msg>Implemented sorting by date and tweets<commit_after>import './TweetList.styl';
import Component from 'react-pure-render/component';
import React, {PropTypes} from 'react';
import Tweet from 'react-tweet'
import {Input,ButtonGroup, DropdownButton, Button, MenuItem} from 'react-bootstrap';

export default class TweetList extends Component {

  static propTypes = {
    tweets: PropTypes.array
  };

  constructor(props) {
    super(props);
    this.state = {
      currentSorting : "date",
      currentSortingType : "desc",
      sortedTweets : props.tweets
    };
    this._sortByDate = this._sortByDate.bind(this);
    this._sortByLikes = this._sortByLikes.bind(this);
  }

  _sortByDate(e, sortingType) {
    if(this.state.currentSorting !== "date" || this.state.currentSortingType !== sortingType) {
      let reSortedTweets;

      if(sortingType == "desc") {
        reSortedTweets= this.state.sortedTweets.sort((a,b)=>(
          new Date(b.created_at) - new Date(a.created_at)
        ));
      }else{
        reSortedTweets = this.state.sortedTweets.sort((a,b)=>(
          new Date(a.created_at) - new Date(b.created_at)
        ));
      }
      this.setState(
        {
          currentSorting : "date",
          currentSortingType : sortingType,
          sortedTweets : reSortedTweets
        }
      );
    }
  }

  _sortByLikes(e, sortingType) {
    if(this.state.currentSorting !== "likes" || this.state.currentSortingType !== sortingType) {
      let reSortedTweets;

      if(sortingType == "desc") {
        reSortedTweets= this.state.sortedTweets.sort((a,b)=>{
          let aFavorite_count = a.hasOwnProperty("retweeted_status") ? a.retweeted_status.favorite_count :
            a.favorite_count;
          let bFavorite_count = b.hasOwnProperty("retweeted_status") ? b.retweeted_status.favorite_count :
            b.favorite_count;

          return bFavorite_count - aFavorite_count;
        });
      }else{
        reSortedTweets = this.state.sortedTweets.sort((a,b)=> {
          let aFavorite_count = a.hasOwnProperty("retweeted_status") ? a.retweeted_status.favorite_count :
            a.favorite_count;
          let bFavorite_count = b.hasOwnProperty("retweeted_status") ? b.retweeted_status.favorite_count :
            b.favorite_count;

          return aFavorite_count - bFavorite_count;
        });
      }
      this.setState(
        {
          currentSorting : "likes",
          currentSortingType : sortingType,
          sortedTweets : reSortedTweets
        }
      );
    }
  }

  render() {
    let tweets = this.state.sortedTweets.map(currentTweet =>
      <Tweet data={currentTweet} key={currentTweet.id}/>
    );

    return (

        <ButtonGroup>
          <DropdownButton title="Sort by date" bsStyle="info" bsSize="xsmall" id="dropdown1" onSelect={this._sortByDate}>
            <MenuItem eventKey="asc">Ascending</MenuItem>
            <MenuItem eventKey="desc">Descending</MenuItem>
          </DropdownButton>
          <DropdownButton title="Sort by likes" bsStyle="info" bsSize="xsmall" id="dropdown2" onSelect={this._sortByLikes}>
            <MenuItem eventKey="asc">Ascending</MenuItem>
            <MenuItem eventKey="desc">Descending</MenuItem>
          </DropdownButton>
          <Button
            disabled
            bsStyle="success"
            bsSize="xsmall">
            Show modal info
          </Button>
        </ButtonGroup>
        <Input
          bsSize="small"
          disabled
          placeholder="Search in tweets"
          type="text"

          //TODO: search in tweets
          //onChange={this.handleChange}
        />
        {tweets}

    );
  }
}

<|endoftext|>


<commit_before>var win = Ti.UI.currentWindow;

var connectingSocket = null;

function pumpCallback(e) {
	if (e.bytesProcessed == -1) { // EOF
		statusArea.value = "<EOF> - Can't perform any more operations on connected socket";
	}
	else if (e.errorDescription == null || e.errorDescription == "") {
		statusArea.value = "DATA: "+e.buffer.toString();
	}
	else {
		statusArea.value = "READ ERROR: "+e.errorDescription;
	}
}

var hostField = Ti.UI.createTextField({
	value:'HOSTNAME',
	top:20,
	left:20,
	width:140,
	height:40,
	borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	autocorrect:false,
	autocapitalization:Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
	clearOnEdit:true
});
win.add(hostField);

var portField = Ti.UI.createTextField({
	value:'PORT',
	top:20,
	right:20,
	width:100,
	height:40,
	borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	autocorrect:false,
	autocapitalization:Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
	clearOnEdit:true
});
win.add(portField);

var writeArea = Ti.UI.createTextArea({
	editable:true,
	value:'Data to write',
	height:100,
	width:300,
	top:80,
	textAlign:'left',
	borderWidth:2,
	borderColor:'#bbb',
	borderRadius:5,
	suppressReturn:false
});
win.add(writeArea);

var statusArea = Ti.UI.createTextArea({
	editable:false,
	value:'Socket status',
	height:100,
	width:300,
	bottom:80,
	textAlign:'left',
	borderWidth:2,
	borderColor:'#bbb',
	borderRadius:5,
	suppressReturn:false
});
win.add(statusArea);

var connectButton = Ti.UI.createButton({
	title:'Connect',
	width:80,
	height:40,
	left:20,
	bottom:20
});
connectButton.addEventListener('click', function() {
	if (connectingSocket == null) {
		try {
			connectingSocket = Ti.Network.Socket.createTCP({
				host:hostField.value,
				port:portField.value,
				connected:function(e) {
					e.socket.write(Ti.createBuffer({data:"Well, hello there!"}));
					Ti.Stream.pump(e.socket,pumpCallback,1024, true);
				},
				error:function(e) {
					statusArea.value = "ERROR ("+e.errorCode+"): "+e.error;
				},
				closed:function(e) {
					statusArea.value = "CLOSED CONNECTION TO: "+e.socket.host+":"+e.socket.port;
				}
			});
			connectingSocket.connect();
		}
		catch (e) {
			statusArea.value = "EXCEPTION (connect): "+e.toString();
		}
	}
	else {
		statusArea.value = 'Already created: '+connectingSocket.host +':'+connectingSocket.port;
	}
});
win.add(connectButton);

var disconnectButton = Ti.UI.createButton({
	title:'Disconnect',
	width:100,
	height:40,
	right:20,
	bottom:20
});
disconnectButton.addEventListener('click', function() {
	if (connectingSocket != null) {
		try {
			connectingSocket.close();
			connectingSocket = null;
		}
		catch (e) {
			statusArea.value = "EXCEPTION (close): "+e.toString();
		}
	}
	else {
		statusArea.value = 'Not connected';
	}
});
win.add(disconnectButton);

var writeButton = Ti.UI.createButton({
	title:'Write',
	width:80,
	height:40,
	bottom:20,
	left:110
});
writeButton.addEventListener('click', function() {
	if (connectingSocket != null && connectingSocket.isWritable()) {
		connectingSocket.write(Ti.createBuffer({data:writeArea.value}));
	}
});
win.add(writeButton);
<commit_msg>TIMOB-3677  update test to use correct values for buffer creation<commit_after>var win = Ti.UI.currentWindow;

var connectingSocket = null;

function pumpCallback(e) {
	if (e.bytesProcessed == -1) { // EOF
		statusArea.value = "<EOF> - Can't perform any more operations on connected socket";
	}
	else if (e.errorDescription == null || e.errorDescription == "") {
		statusArea.value = "DATA: "+e.buffer.toString();
	}
	else {
		statusArea.value = "READ ERROR: "+e.errorDescription;
	}
}

var hostField = Ti.UI.createTextField({
	value:'HOSTNAME',
	top:20,
	left:20,
	width:140,
	height:40,
	borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	autocorrect:false,
	autocapitalization:Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
	clearOnEdit:true
});
win.add(hostField);

var portField = Ti.UI.createTextField({
	value:'PORT',
	top:20,
	right:20,
	width:100,
	height:40,
	borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	autocorrect:false,
	autocapitalization:Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
	clearOnEdit:true
});
win.add(portField);

var writeArea = Ti.UI.createTextArea({
	editable:true,
	value:'Data to write',
	height:100,
	width:300,
	top:80,
	textAlign:'left',
	borderWidth:2,
	borderColor:'#bbb',
	borderRadius:5,
	suppressReturn:false
});
win.add(writeArea);

var statusArea = Ti.UI.createTextArea({
	editable:false,
	value:'Socket status',
	height:100,
	width:300,
	bottom:80,
	textAlign:'left',
	borderWidth:2,
	borderColor:'#bbb',
	borderRadius:5,
	suppressReturn:false
});
win.add(statusArea);

var connectButton = Ti.UI.createButton({
	title:'Connect',
	width:80,
	height:40,
	left:20,
	bottom:20
});
connectButton.addEventListener('click', function() {
	if (connectingSocket == null) {
		try {
			connectingSocket = Ti.Network.Socket.createTCP({
				host:hostField.value,
				port:portField.value,
				connected:function(e) {
					e.socket.write(Ti.createBuffer({value:"Well, hello there!"}));
					Ti.Stream.pump(e.socket,pumpCallback,1024, true);
				},
				error:function(e) {
					statusArea.value = "ERROR ("+e.errorCode+"): "+e.error;
				},
				closed:function(e) {
					statusArea.value = "CLOSED CONNECTION TO: "+e.socket.host+":"+e.socket.port;
				}
			});
			connectingSocket.connect();
		}
		catch (e) {
			statusArea.value = "EXCEPTION (connect): "+e.toString();
		}
	}
	else {
		statusArea.value = 'Already created: '+connectingSocket.host +':'+connectingSocket.port;
	}
});
win.add(connectButton);

var disconnectButton = Ti.UI.createButton({
	title:'Disconnect',
	width:100,
	height:40,
	right:20,
	bottom:20
});
disconnectButton.addEventListener('click', function() {
	if (connectingSocket != null) {
		try {
			connectingSocket.close();
			connectingSocket = null;
			statusArea.value = 'Disconnected';
		}
		catch (e) {
			statusArea.value = "EXCEPTION (close): "+e.toString();
		}
	}
	else {
		statusArea.value = 'Not connected';
	}
});
win.add(disconnectButton);

var writeButton = Ti.UI.createButton({
	title:'Write',
	width:80,
	height:40,
	bottom:20,
	left:110
});
writeButton.addEventListener('click', function() {
	if (connectingSocket != null && connectingSocket.isWritable()) {
		connectingSocket.write(Ti.createBuffer({value:writeArea.value}));
	}
});
win.add(writeButton);
<|endoftext|>


<commit_before>frappe.provide("frappe.ui");
frappe.provide("frappe.views");

window.web_form_list = null;

frappe.views.WebFormList = class WebFormList {
	constructor(opts) {
		Object.assign(this, opts);
		window.web_form_list = this;
		this.wrapper = document.getElementById("datatable");
		this.refresh();
		this.make_actions();
		this.make_filters();
		$('.link-btn').remove()
	}

	refresh() {
		this.table && Array.from(this.table.tBodies).forEach(tbody => tbody.remove());
		this.rows = [];
		this.page_length = 20;
		this.web_list_start = 0;

		frappe.run_serially([
			() => this.get_list_view_fields(),
			() => this.get_data(),
			() => this.make_table(),
		]);
	}

	make_filters() {
		this.filters = {}
		this.filter_input = []
		const filter_area = document.getElementById('list-filters');

		frappe.call('frappe.website.doctype.web_form.web_form.get_web_form_filters', {
			web_form_name: this.web_form_name
		}).then(response => {
			let fields = response.message;
			fields.forEach(field => {
				let col = document.createElement('div.col-sm-4')
				col.classList.add('col', 'col-sm-3')
				filter_area.appendChild(col)

				let input = frappe.ui.form.make_control({
					df: {
						fieldtype: field.fieldtype,
						fieldname: field.fieldname,
						options: field.options,
						only_select: true,
						label: __(field.label),
						onchange: (event) => {
							this.add_filter(field.fieldname, input.value, field.fieldtype)
						}
					},
					parent: col,
					render_input: 1,
				})
				this.filter_input.push(input)
			})
		})
	}

	add_filter(field, value, fieldtype) {
		if (!value && field in this.filters) {
			delete this.filters[field]
		}
		else {
			if (fieldtype === 'Data') value = ['like', value + '%']
			Object.assign(this.filters, Object.fromEntries([[field, value]]))
		}
		this.refresh();
	}

	get_list_view_fields() {
		return frappe
			.call({
				method:
					"frappe.website.doctype.web_form.web_form.get_in_list_view_fields",
				args: { doctype: this.doctype }
			})
			.then(response => (this.fields_list = response.message));
	}

	fetch_data() {
		return frappe.call({
			method: "frappe.www.list.get_list_data",
			args: {
				doctype: this.doctype,
				fields: this.fields_list.map(df => df.fieldname),
				limit_start: this.web_list_start,
				...this.filters
			}
		});
	}

	async get_data() {
		let response = await this.fetch_data();
		this.data = await response.message;
	}

	more() {
		this.web_list_start += this.page_length
		this.fetch_data().then((res) => {
			if (res.message.length === 0) {
				frappe.msgprint("No more items to display")
			}
			this.append_rows(res.message)
		})

	}

	make_table() {
		this.columns = this.fields_list.map(df => {
			return {
				label: df.label,
				fieldname: df.fieldname,
				fieldtype: df.fieldtype
			};
		});

		if (! this.table) {
			this.table = document.createElement("table");
			this.table.classList.add("table");
			this.make_table_head();
		}

		this.append_rows(this.data);

		this.wrapper.appendChild(this.table);
	}

	make_table_head() {
		// Create Heading
		let thead = this.table.createTHead();
		thead.style.backgroundColor = "#f7fafc";
		thead.style.color = "#8d99a6";
		let row = thead.insertRow();

		let th = document.createElement("th");

		let checkbox = document.createElement("input");
		checkbox.type = "checkbox";
		checkbox.onclick = event =>
			this.toggle_select_all(event.target.checked);

		th.appendChild(checkbox);
		row.appendChild(th);

		add_heading(row, "Sr.");
		this.columns.forEach(col => {
			let th = document.createElement("th");
			let text = document.createTextNode(col.label);
			th.appendChild(text);
			row.appendChild(th);
		});

		function add_heading(row, label) {
			let th = document.createElement("th");
			th.innerText = label;
			row.appendChild(th);
		}
	}

	append_rows(row_data) {
		const tbody = this.table.childNodes[1] || this.table.createTBody();
		row_data.forEach((data_item) => {
			let row_element = tbody.insertRow();
			row_element.setAttribute("id", data_item.name);

			let row = new frappe.ui.WebFromListRow({
				row: row_element,
				doc: data_item,
				columns: this.columns,
				serial_number: web_form_list.rows.length + 1,
				events: {
					onEdit: () => this.open_form(data_item.name),
					onSelect: () => this.toggle_delete()
				}
			});

			this.rows.push(row);
		});
	}

	make_actions() {
		const actions = document.querySelector(".list-view-actions");
		const footer = document.querySelector(".list-view-footer");

		addButton(actions, "delete-rows", "danger", true, "Delete", () =>
			this.delete_rows()
		);

		addButton(
			actions,
			"new",
			"primary",
			false,
			"New",
			() => (window.location.href = window.location.pathname + "?new=1")
		);

		if (!(this.rows.length < this.page_length)) {
			addButton(footer, "more", "secondary", false, "More", () =>  this.more());
		}

		function addButton(wrapper, id, type, hidden, name, action) {
			const button = document.createElement("button");
			button.classList.add("btn", "btn-primary", "btn-sm", "ml-2");
			if (type == "secondary")
				button.classList.add(
					"btn",
					"btn-secondary",
					"btn-sm",
					"ml-2",
					"text-white"
				);
			if (type == "danger")
				button.classList.add(
					"btn",
					"btn-danger",
					"button-delete",
					"btn-sm",
					"ml-2"
				);

			button.id = id;
			button.innerText = name;
			button.hidden = hidden;

			button.onclick = action;
			wrapper.appendChild(button);
		}
	}

	toggle_select_all(checked) {
		this.rows.forEach(row => row.toggle_select(checked));
	}

	open_form(name) {
		window.location.href = window.location.pathname + "?name=" + name;
	}

	get_selected() {
		return this.rows.filter(row => row.is_selected());
	}

	toggle_delete() {
		let btn = document.getElementById("delete-rows");
		btn.hidden = !this.get_selected().length;
	}

	delete_rows() {
		frappe
			.call({
				type: "POST",
				method:
					"frappe.website.doctype.web_form.web_form.delete_multiple",
				args: {
					web_form_name: this.web_form_name,
					docnames: this.get_selected().map(row => row.doc.name)
				}
			})
			.then(() => {
				this.refresh()
				this.toggle_delete()
			});
	}
};

frappe.ui.WebFromListRow = class WebFromListRow {
	constructor({ row, doc, columns, serial_number, events, options }) {
		Object.assign(this, { row, doc, columns, serial_number, events });
		this.make_row();
	}

	make_row() {
		// Add Checkboxes
		let cell = this.row.insertCell();

		this.checkbox = document.createElement("input");
		this.checkbox.type = "checkbox";
		this.checkbox.onclick = event => {
			this.toggle_select(event.target.checked);
			event.stopImmediatePropagation();
		}

		cell.appendChild(this.checkbox);

		// Add Serial Number
		let serialNo = this.row.insertCell();
		serialNo.innerText = this.serial_number;

		this.columns.forEach(field => {
			let cell = this.row.insertCell();
			let formatter = frappe.form.get_formatter(field.fieldtype)
			cell.innerHTML = formatter(this.doc[field.fieldname]) || "";
		});

		this.row.onclick = () => this.events.onEdit();
		this.row.style.cursor = "pointer";
	}

	toggle_select(checked) {
		this.checkbox.checked = checked;
		this.events.onSelect(checked);
	}

	is_selected() {
		return this.checkbox.checked;
	}
};<commit_msg>style: fix minor typo<commit_after>frappe.provide("frappe.ui");
frappe.provide("frappe.views");

window.web_form_list = null;

frappe.views.WebFormList = class WebFormList {
	constructor(opts) {
		Object.assign(this, opts);
		window.web_form_list = this;
		this.wrapper = document.getElementById("datatable");
		this.refresh();
		this.make_actions();
		this.make_filters();
		$('.link-btn').remove()
	}

	refresh() {
		this.table && Array.from(this.table.tBodies).forEach(tbody => tbody.remove());
		this.rows = [];
		this.page_length = 20;
		this.web_list_start = 0;

		frappe.run_serially([
			() => this.get_list_view_fields(),
			() => this.get_data(),
			() => this.make_table(),
		]);
	}

	make_filters() {
		this.filters = {}
		this.filter_input = []
		const filter_area = document.getElementById('list-filters');

		frappe.call('frappe.website.doctype.web_form.web_form.get_web_form_filters', {
			web_form_name: this.web_form_name
		}).then(response => {
			let fields = response.message;
			fields.forEach(field => {
				let col = document.createElement('div.col-sm-4')
				col.classList.add('col', 'col-sm-3')
				filter_area.appendChild(col)

				let input = frappe.ui.form.make_control({
					df: {
						fieldtype: field.fieldtype,
						fieldname: field.fieldname,
						options: field.options,
						only_select: true,
						label: __(field.label),
						onchange: (event) => {
							this.add_filter(field.fieldname, input.value, field.fieldtype)
						}
					},
					parent: col,
					render_input: 1,
				})
				this.filter_input.push(input)
			})
		})
	}

	add_filter(field, value, fieldtype) {
		if (!value && field in this.filters) {
			delete this.filters[field]
		}
		else {
			if (fieldtype === 'Data') value = ['like', value + '%']
			Object.assign(this.filters, Object.fromEntries([[field, value]]))
		}
		this.refresh();
	}

	get_list_view_fields() {
		return frappe
			.call({
				method:
					"frappe.website.doctype.web_form.web_form.get_in_list_view_fields",
				args: { doctype: this.doctype }
			})
			.then(response => (this.fields_list = response.message));
	}

	fetch_data() {
		return frappe.call({
			method: "frappe.www.list.get_list_data",
			args: {
				doctype: this.doctype,
				fields: this.fields_list.map(df => df.fieldname),
				limit_start: this.web_list_start,
				...this.filters
			}
		});
	}

	async get_data() {
		let response = await this.fetch_data();
		this.data = await response.message;
	}

	more() {
		this.web_list_start += this.page_length
		this.fetch_data().then((res) => {
			if (res.message.length === 0) {
				frappe.msgprint("No more items to display")
			}
			this.append_rows(res.message)
		})

	}

	make_table() {
		this.columns = this.fields_list.map(df => {
			return {
				label: df.label,
				fieldname: df.fieldname,
				fieldtype: df.fieldtype
			};
		});

		if (! this.table) {
			this.table = document.createElement("table");
			this.table.classList.add("table");
			this.make_table_head();
		}

		this.append_rows(this.data);

		this.wrapper.appendChild(this.table);
	}

	make_table_head() {
		// Create Heading
		let thead = this.table.createTHead();
		thead.style.backgroundColor = "#f7fafc";
		thead.style.color = "#8d99a6";
		let row = thead.insertRow();

		let th = document.createElement("th");

		let checkbox = document.createElement("input");
		checkbox.type = "checkbox";
		checkbox.onclick = event =>
			this.toggle_select_all(event.target.checked);

		th.appendChild(checkbox);
		row.appendChild(th);

		add_heading(row, "Sr.");
		this.columns.forEach(col => {
			let th = document.createElement("th");
			let text = document.createTextNode(col.label);
			th.appendChild(text);
			row.appendChild(th);
		});

		function add_heading(row, label) {
			let th = document.createElement("th");
			th.innerText = label;
			row.appendChild(th);
		}
	}

	append_rows(row_data) {
		const tbody = this.table.childNodes[1] || this.table.createTBody();
		row_data.forEach((data_item) => {
			let row_element = tbody.insertRow();
			row_element.setAttribute("id", data_item.name);

			let row = new frappe.ui.WebFormListRow({
				row: row_element,
				doc: data_item,
				columns: this.columns,
				serial_number: web_form_list.rows.length + 1,
				events: {
					onEdit: () => this.open_form(data_item.name),
					onSelect: () => this.toggle_delete()
				}
			});

			this.rows.push(row);
		});
	}

	make_actions() {
		const actions = document.querySelector(".list-view-actions");
		const footer = document.querySelector(".list-view-footer");

		addButton(actions, "delete-rows", "danger", true, "Delete", () =>
			this.delete_rows()
		);

		addButton(
			actions,
			"new",
			"primary",
			false,
			"New",
			() => (window.location.href = window.location.pathname + "?new=1")
		);

		if (!(this.rows.length < this.page_length)) {
			addButton(footer, "more", "secondary", false, "More", () =>  this.more());
		}

		function addButton(wrapper, id, type, hidden, name, action) {
			const button = document.createElement("button");
			button.classList.add("btn", "btn-primary", "btn-sm", "ml-2");
			if (type == "secondary")
				button.classList.add(
					"btn",
					"btn-secondary",
					"btn-sm",
					"ml-2",
					"text-white"
				);
			if (type == "danger")
				button.classList.add(
					"btn",
					"btn-danger",
					"button-delete",
					"btn-sm",
					"ml-2"
				);

			button.id = id;
			button.innerText = name;
			button.hidden = hidden;

			button.onclick = action;
			wrapper.appendChild(button);
		}
	}

	toggle_select_all(checked) {
		this.rows.forEach(row => row.toggle_select(checked));
	}

	open_form(name) {
		window.location.href = window.location.pathname + "?name=" + name;
	}

	get_selected() {
		return this.rows.filter(row => row.is_selected());
	}

	toggle_delete() {
		let btn = document.getElementById("delete-rows");
		btn.hidden = !this.get_selected().length;
	}

	delete_rows() {
		frappe
			.call({
				type: "POST",
				method:
					"frappe.website.doctype.web_form.web_form.delete_multiple",
				args: {
					web_form_name: this.web_form_name,
					docnames: this.get_selected().map(row => row.doc.name)
				}
			})
			.then(() => {
				this.refresh()
				this.toggle_delete()
			});
	}
};

frappe.ui.WebFormListRow = class WebFormListRow {
	constructor({ row, doc, columns, serial_number, events, options }) {
		Object.assign(this, { row, doc, columns, serial_number, events });
		this.make_row();
	}

	make_row() {
		// Add Checkboxes
		let cell = this.row.insertCell();

		this.checkbox = document.createElement("input");
		this.checkbox.type = "checkbox";
		this.checkbox.onclick = event => {
			this.toggle_select(event.target.checked);
			event.stopImmediatePropagation();
		}

		cell.appendChild(this.checkbox);

		// Add Serial Number
		let serialNo = this.row.insertCell();
		serialNo.innerText = this.serial_number;

		this.columns.forEach(field => {
			let cell = this.row.insertCell();
			let formatter = frappe.form.get_formatter(field.fieldtype)
			cell.innerHTML = formatter(this.doc[field.fieldname]) || "";
		});

		this.row.onclick = () => this.events.onEdit();
		this.row.style.cursor = "pointer";
	}

	toggle_select(checked) {
		this.checkbox.checked = checked;
		this.events.onSelect(checked);
	}

	is_selected() {
		return this.checkbox.checked;
	}
};<|endoftext|>


<commit_before>/**
 * @file TableLayout vendor
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import sum from 'lodash/sum';

import TableFragment from '../_statics/TableFragment';
import HorizontalAlign from '../_statics/HorizontalAlign';
import Direction from '../_statics/Direction';

import ScrollBar from './ScrollBar';

/**
 * calculate each head, body and foot column width
 * @returns {null|{[p: string]: *|*}}
 */
function getColumnsWidth(tableEl) {

    if (!tableEl) {
        return null;
    }

    return {
        [TableFragment.HEAD]: [].map.call(tableEl.querySelector('thead tr').querySelectorAll('th'),
            el => el.offsetWidth),
        [TableFragment.BODY]: [].map.call(tableEl.querySelector('tbody tr').querySelectorAll('td'),
            el => el.offsetWidth),
        [TableFragment.FOOT]: [].map.call(tableEl.querySelector('tfoot tr').querySelectorAll('td'),
            el => el.offsetWidth)
    };

}

/**
 * calculate each head, body and foot row height
 * @returns {null|{[p: string]: *|*}}
 */
function getRowsHeight(tableEl) {

    if (!tableEl) {
        return null;
    }

    return {
        [TableFragment.HEAD]: [].map.call(tableEl.querySelectorAll('thead tr'),
            el => el.offsetHeight),
        [TableFragment.BODY]: [].map.call(tableEl.querySelectorAll('tbody tr'),
            el => el.offsetHeight),
        [TableFragment.FOOT]: [].map.call(tableEl.querySelectorAll('tfoot tr'),
            el => el.offsetHeight)
    };

}

/**
 * calculate table body scroller height
 * @param headHeight
 * @param footHeight
 * @returns {{height: string}}
 */
function getbodyScollerHeight(headHeight, footHeight) {
    return `calc(100%${headHeight ? ` - ${sum(headHeight)}px` : ''}${footHeight ? ` - ${sum(footHeight)}px` : ''})`;
}

function maskCenterBody(wrapperEl, tableEl, fixedHeadHeight, fixedFootHeight) {
    const el = wrapperEl.querySelector('.table-content-center .scrollable-table-body-mask');
    if (el) {
        el.style.height = `${tableEl.offsetHeight - fixedHeadHeight - fixedFootHeight - 2}px`;
        const table = el.querySelector('table');
        if (table) {
            table.style.marginTop = `${-fixedHeadHeight - 1}px`;
        }
    }
}

function fixFragmentWidth(wrapperEl, columnsWidth, fixed, fragment, selector) {

    const el = wrapperEl.querySelector(`${selector} .scrollable-table-${fragment}-scroller`);

    if (el) {
        const cols = el.querySelectorAll('col');
        if (cols) {
            if (fixed === HorizontalAlign.RIGHT) {
                cols.forEach((el, index) => {
                    if (el) {
                        el.style.width = `${columnsWidth[fragment]
                            [columnsWidth[fragment].length - (cols.length - index)]}px`;
                    }
                });
            } else {
                cols.forEach((el, index) => {
                    if (el) {
                        el.style.width = `${columnsWidth[fragment][index]}px`;
                    }
                });
            }
        }
    }

}

function fixTableWidth(wrapperEl, columnsWidth, fixed, props) {

    if (!wrapperEl) {
        return;
    }

    const selector = `.table-content-${fixed || 'center'}`;

    /**
     * head
     */
    if (props && props.isHeadFixed) {
        fixFragmentWidth(wrapperEl, columnsWidth, fixed, TableFragment.HEAD, selector);
    }

    /**
     * body
     */
    if (fixed) {
        fixFragmentWidth(wrapperEl, columnsWidth, fixed, TableFragment.BODY, selector);
    }

    /**
     * foot
     */
    if (props && props.isHeadFixed) {
        fixFragmentWidth(wrapperEl, columnsWidth, fixed, TableFragment.FOOT, selector);
    }

}

function fixFragmentHeight(wrapperEl, rowsHeight, fixed, fragment, selector) {

    const el = wrapperEl.querySelector(`${selector} .scrollable-table-${fragment} t${fragment}`);

    if (el) {
        const trs = el.querySelectorAll('tr');
        if (trs) {
            trs.forEach((el, index) => {
                if (el) {
                    el.style.height = `${rowsHeight[fragment][index]}px`;
                }
            });
        }
    }

}

function fixTableHeight(wrapperEl, rowsHeight, fixed, props) {

    if (!wrapperEl) {
        return;
    }

    const selector = `.table-content-${fixed || 'center'}`;

    /**
     * head
     */
    if (props && props.isHeadFixed) {
        fixFragmentHeight(wrapperEl, rowsHeight, fixed, TableFragment.HEAD, selector);
    }

    /**
     * body
     */
    if (fixed) {
        fixFragmentHeight(wrapperEl, rowsHeight, fixed, TableFragment.BODY, selector);
    }

    /**
     * foot
     */
    if (props && props.isHeadFixed) {
        fixFragmentHeight(wrapperEl, rowsHeight, fixed, TableFragment.FOOT, selector);
    }

}

function handleHorizontalScrollStyle(el, shouldScroll, size = ScrollBar.getSize(Direction.HORIZONTAL)) {

    if (!el) {
        return;
    }

    if (!shouldScroll) {
        el.style.marginBottom = 0;
        el.style.paddingBottom = 0;
    } else if (size && size > 0) {
        el.style.marginBottom = `${-size}px`;
        el.style.paddingBottom = 0;
    } else {
        el.style.marginBottom = '-20px';
        el.style.paddingBottom = '20px';
    }

}

function fixTableHorizontalScroll(wrapperEl, props) {

    if (!wrapperEl) {
        return;
    }

    // no need to fix the scroll problem in mac
    const horizontalScrollBarSize = ScrollBar.getSize(Direction.HORIZONTAL);
    if (!horizontalScrollBarSize || horizontalScrollBarSize <= 0) {
        return;
    }

    const centerBody = wrapperEl.querySelector('.table-content-center .scrollable-table-body-scroller'),
        shouldScroll = centerBody.offsetWidth < centerBody.scrollWidth;

    /**
     * center head scroller
     */
    if (props && props.isHeadFixed) {
        const centerHead = wrapperEl.querySelector('.table-content-center .scrollable-table-head-scroller');
        if (centerHead) {
            handleHorizontalScrollStyle(centerHead, shouldScroll, horizontalScrollBarSize);
        }
    }

    /**
     * center foot scroller
     */
    if (props && props.isFootFixed) {
        const centerFoot = wrapperEl.querySelector('.table-content-center .scrollable-table-foot-scroller');
        if (centerFoot) {
            handleHorizontalScrollStyle(centerFoot, shouldScroll, horizontalScrollBarSize);
        }
    }

    /**
     * left body scroller
     */
    const leftBody = wrapperEl.querySelector('.table-content-left .scrollable-table-body-scroller');
    if (leftBody) {
        handleHorizontalScrollStyle(leftBody, shouldScroll, horizontalScrollBarSize);
    }

    /**
     * left body mask
     */
    const leftBodyMask = wrapperEl.querySelector('.table-content-left .scrollable-table-body-mask');
    if (leftBodyMask) {
        leftBodyMask.style.paddingBottom = shouldScroll ? `${horizontalScrollBarSize}px` : 0;
    }

    /**
     * left foot
     */
    const leftFoot = wrapperEl.querySelector('.table-content-left .scrollable-table-foot');
    if (leftFoot) {
        leftFoot.style.marginTop = shouldScroll ? `${horizontalScrollBarSize}px` : 0;
    }

    /**
     * right body scroller
     */
    const rightBody = wrapperEl.querySelector('.table-content-right .scrollable-table-body-scroller');
    if (rightBody) {
        handleHorizontalScrollStyle(rightBody, shouldScroll, horizontalScrollBarSize);
    }

    /**
     * right body mask
     */
    const rightBodyMask = wrapperEl.querySelector('.table-content-right .scrollable-table-body-mask');
    if (rightBodyMask) {
        rightBodyMask.style.paddingBottom = shouldScroll ? `${horizontalScrollBarSize}px` : 0;
    }

    /**
     * right foot
     */
    const rightFoot = wrapperEl.querySelector('.table-content-right .scrollable-table-foot');
    if (rightFoot) {
        rightFoot.style.marginTop = shouldScroll ? `${horizontalScrollBarSize}px` : 0;
    }

}

function fixTableVerticalScroll(wrapperEl, props) {

    if (!wrapperEl) {
        return;
    }

    const verticalScrollBarSize = ScrollBar.getSize(Direction.VERTICAL);

    /**
     * fix center head width
     */
    if (props && props.isHeadFixed && verticalScrollBarSize && verticalScrollBarSize > 0) {
        const centerHead = wrapperEl.querySelector('.table-content-center .scrollable-table-head-scroller');
        if (centerHead) {
            centerHead.style.width = `calc(100% - ${verticalScrollBarSize}px)`;
        }
    }

    /**
     * fix center foot width
     */
    if (props && props.isFootFixed && verticalScrollBarSize && verticalScrollBarSize > 0) {
        const centerFoot = wrapperEl.querySelector('.table-content-center .scrollable-table-foot-scroller');
        if (centerFoot) {
            centerFoot.style.width = `calc(100% - ${verticalScrollBarSize}px)`;
        }
    }

    /**
     * fix left body horizontal scroll bar
     */
    const leftBody = wrapperEl.querySelector('.table-content-left .scrollable-table-body-scroller');
    if (leftBody) {
        if (verticalScrollBarSize && verticalScrollBarSize > 0) {
            leftBody.style.marginRight = `-${verticalScrollBarSize}px`;
            leftBody.style.paddingRight = 0;
        } else {
            const leftBodyTable = leftBody.querySelector('table');
            if (leftBodyTable) {
                const restWidth = wrapperEl.offsetWidth - leftBodyTable.offsetWidth;
                leftBody.style.marginRight = `-${restWidth}px`;
                leftBody.style.paddingRight = `${restWidth}px`;
            }
        }
    }

}

function fixLayout(wrapperEl, props) {

    if (!wrapperEl) {
        return;
    }

    const tableEl = wrapperEl.querySelector('.table-content-center .scrollable-table-body table');

    if (!tableEl) {
        return;
    }

    /**
     * fix scroll style
     */
    fixTableHorizontalScroll(wrapperEl, props);
    fixTableVerticalScroll(wrapperEl, props);

    const columnsWidth = getColumnsWidth(tableEl),
        rowsHeight = getRowsHeight(tableEl),

        fixedHeadHeight = sum(rowsHeight[TableFragment.HEAD]) || 0,
        fixedFootHeight = sum(rowsHeight[TableFragment.FOOT]) || 0;

    /**
     * center
     */
    maskCenterBody(wrapperEl, tableEl, fixedHeadHeight, fixedFootHeight);
    fixTableWidth(wrapperEl, columnsWidth, null, props);
    fixTableHeight(wrapperEl, rowsHeight, null, props);

    /**
     * left
     */
    fixTableWidth(wrapperEl, columnsWidth, HorizontalAlign.LEFT, props);
    fixTableHeight(wrapperEl, rowsHeight, HorizontalAlign.LEFT, props);

    /**
     * right
     */
    fixTableWidth(wrapperEl, columnsWidth, HorizontalAlign.RIGHT, props);
    fixTableHeight(wrapperEl, rowsHeight, HorizontalAlign.RIGHT, props);

}

export default {
    getColumnsWidth,
    getRowsHeight,
    getbodyScollerHeight,
    fixLayout
};
<commit_msg>update TableLayout<commit_after>/**
 * @file TableLayout vendor
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import sum from 'lodash/sum';

import TableFragment from '../_statics/TableFragment';
import HorizontalAlign from '../_statics/HorizontalAlign';
import Direction from '../_statics/Direction';

import ScrollBar from './ScrollBar';

/**
 * calculate each head, body and foot column width
 * @returns {null|{[p: string]: *|*}}
 */
function getColumnsWidth(tableEl) {

    if (!tableEl) {
        return null;
    }

    return {
        [TableFragment.HEAD]: [].map.call(tableEl.querySelector('thead tr').querySelectorAll('th'),
            el => el.offsetWidth),
        [TableFragment.BODY]: [].map.call(tableEl.querySelector('tbody tr').querySelectorAll('td'),
            el => el.offsetWidth),
        [TableFragment.FOOT]: [].map.call(tableEl.querySelector('tfoot tr').querySelectorAll('td'),
            el => el.offsetWidth)
    };

}

/**
 * calculate each head, body and foot row height
 * @returns {null|{[p: string]: *|*}}
 */
function getRowsHeight(tableEl) {

    if (!tableEl) {
        return null;
    }

    return {
        [TableFragment.HEAD]: [].map.call(tableEl.querySelectorAll('thead tr'),
            el => el.offsetHeight),
        [TableFragment.BODY]: [].map.call(tableEl.querySelectorAll('tbody tr'),
            el => el.offsetHeight),
        [TableFragment.FOOT]: [].map.call(tableEl.querySelectorAll('tfoot tr'),
            el => el.offsetHeight)
    };

}

/**
 * calculate table body scroller height
 * @param headHeight
 * @param footHeight
 * @returns {{height: string}}
 */
function getbodyScollerHeight(headHeight, footHeight) {
    return `calc(100%${headHeight ? ` - ${sum(headHeight)}px` : ''}${footHeight ? ` - ${sum(footHeight)}px` : ''})`;
}

function maskCenterBody(wrapperEl, tableEl, fixedHeadHeight, fixedFootHeight) {
    const el = wrapperEl.querySelector('.table-content-center .scrollable-table-body-mask');
    if (el) {
        el.style.height = `${tableEl.offsetHeight - fixedHeadHeight - fixedFootHeight - 2}px`;
        const table = el.querySelector('table');
        if (table) {
            table.style.marginTop = `${-fixedHeadHeight - 1}px`;
        }
    }
}

function fixFragmentWidth(wrapperEl, columnsWidth, fixed, fragment, selector) {

    const el = wrapperEl.querySelector(`${selector} .scrollable-table-${fragment}-scroller`);

    if (el) {
        const cols = el.querySelectorAll('col');
        if (cols) {
            if (fixed === HorizontalAlign.RIGHT) {
                cols.forEach((el, index) => {
                    if (el) {
                        el.style.width = `${columnsWidth[fragment]
                            [columnsWidth[fragment].length - (cols.length - index)]}px`;
                    }
                });
            } else {
                cols.forEach((el, index) => {
                    if (el) {
                        el.style.width = `${columnsWidth[fragment][index]}px`;
                    }
                });
            }
        }
    }

}

function fixTableWidth(wrapperEl, columnsWidth, fixed, props) {

    if (!wrapperEl) {
        return;
    }

    const selector = `.table-content-${fixed || 'center'}`;

    /**
     * head
     */
    if (props && props.isHeadFixed) {
        fixFragmentWidth(wrapperEl, columnsWidth, fixed, TableFragment.HEAD, selector);
    }

    /**
     * body
     */
    if (fixed) {
        fixFragmentWidth(wrapperEl, columnsWidth, fixed, TableFragment.BODY, selector);
    }

    /**
     * foot
     */
    if (props && props.isHeadFixed) {
        fixFragmentWidth(wrapperEl, columnsWidth, fixed, TableFragment.FOOT, selector);
    }

}

function fixFragmentHeight(wrapperEl, rowsHeight, fixed, fragment, selector) {

    const el = wrapperEl.querySelector(`${selector} .scrollable-table-${fragment} t${fragment}`);

    if (el) {
        const trs = el.querySelectorAll('tr');
        if (trs) {
            trs.forEach((el, index) => {
                if (el) {
                    el.style.height = `${rowsHeight[fragment][index]}px`;
                }
            });
        }
    }

}

function fixTableHeight(wrapperEl, rowsHeight, fixed, props) {

    if (!wrapperEl) {
        return;
    }

    const selector = `.table-content-${fixed || 'center'}`;

    /**
     * head
     */
    if (props && props.isHeadFixed) {
        fixFragmentHeight(wrapperEl, rowsHeight, fixed, TableFragment.HEAD, selector);
    }

    /**
     * body
     */
    if (fixed) {
        fixFragmentHeight(wrapperEl, rowsHeight, fixed, TableFragment.BODY, selector);
    }

    /**
     * foot
     */
    if (props && props.isHeadFixed) {
        fixFragmentHeight(wrapperEl, rowsHeight, fixed, TableFragment.FOOT, selector);
    }

}

function handleHorizontalScrollStyle(el, shouldScroll, size = ScrollBar.getSize(Direction.HORIZONTAL)) {

    if (!el) {
        return;
    }

    if (!shouldScroll) {
        el.style.marginBottom = 0;
        el.style.paddingBottom = 0;
    } else if (size && size > 0) {
        el.style.marginBottom = `${-size}px`;
        el.style.paddingBottom = 0;
    } else {
        el.style.marginBottom = '-20px';
        el.style.paddingBottom = '20px';
    }

}

function fixTableHorizontalScroll(wrapperEl, props) {

    if (!wrapperEl) {
        return;
    }

    // no need to fix the scroll problem in mac
    const horizontalScrollBarSize = ScrollBar.getSize(Direction.HORIZONTAL);
    if (!horizontalScrollBarSize || horizontalScrollBarSize <= 0) {
        return;
    }

    const centerBody = wrapperEl.querySelector('.table-content-center .scrollable-table-body-scroller'),
        shouldScroll = centerBody.offsetWidth - horizontalScrollBarSize < centerBody.scrollWidth;

    /**
     * center head scroller
     */
    if (props && props.isHeadFixed) {
        const centerHead = wrapperEl.querySelector('.table-content-center .scrollable-table-head-scroller');
        if (centerHead) {
            handleHorizontalScrollStyle(centerHead, shouldScroll, horizontalScrollBarSize);
        }
    }

    /**
     * center foot scroller
     */
    if (props && props.isFootFixed) {
        const centerFoot = wrapperEl.querySelector('.table-content-center .scrollable-table-foot-scroller');
        if (centerFoot) {
            handleHorizontalScrollStyle(centerFoot, shouldScroll, horizontalScrollBarSize);
        }
    }

    /**
     * left body scroller
     */
    const leftBody = wrapperEl.querySelector('.table-content-left .scrollable-table-body-scroller');
    if (leftBody) {
        handleHorizontalScrollStyle(leftBody, shouldScroll, horizontalScrollBarSize);
    }

    /**
     * left body mask
     */
    const leftBodyMask = wrapperEl.querySelector('.table-content-left .scrollable-table-body-mask');
    if (leftBodyMask) {
        leftBodyMask.style.paddingBottom = shouldScroll ? `${horizontalScrollBarSize}px` : 0;
    }

    /**
     * left foot
     */
    const leftFoot = wrapperEl.querySelector('.table-content-left .scrollable-table-foot');
    if (leftFoot) {
        leftFoot.style.marginTop = shouldScroll ? `${horizontalScrollBarSize}px` : 0;
    }

    /**
     * right body scroller
     */
    const rightBody = wrapperEl.querySelector('.table-content-right .scrollable-table-body-scroller');
    if (rightBody) {
        handleHorizontalScrollStyle(rightBody, shouldScroll, horizontalScrollBarSize);
    }

    /**
     * right body mask
     */
    const rightBodyMask = wrapperEl.querySelector('.table-content-right .scrollable-table-body-mask');
    if (rightBodyMask) {
        rightBodyMask.style.paddingBottom = shouldScroll ? `${horizontalScrollBarSize}px` : 0;
    }

    /**
     * right foot
     */
    const rightFoot = wrapperEl.querySelector('.table-content-right .scrollable-table-foot');
    if (rightFoot) {
        rightFoot.style.marginTop = shouldScroll ? `${horizontalScrollBarSize}px` : 0;
    }

}

function fixTableVerticalScroll(wrapperEl, props) {

    if (!wrapperEl) {
        return;
    }

    const verticalScrollBarSize = ScrollBar.getSize(Direction.VERTICAL);

    /**
     * fix center head width
     */
    if (props && props.isHeadFixed && verticalScrollBarSize && verticalScrollBarSize > 0) {
        const centerHead = wrapperEl.querySelector('.table-content-center .scrollable-table-head-scroller');
        if (centerHead) {
            centerHead.style.width = `calc(100% - ${verticalScrollBarSize}px)`;
        }
    }

    /**
     * fix center foot width
     */
    if (props && props.isFootFixed && verticalScrollBarSize && verticalScrollBarSize > 0) {
        const centerFoot = wrapperEl.querySelector('.table-content-center .scrollable-table-foot-scroller');
        if (centerFoot) {
            centerFoot.style.width = `calc(100% - ${verticalScrollBarSize}px)`;
        }
    }

    /**
     * fix left body horizontal scroll bar
     */
    const leftBody = wrapperEl.querySelector('.table-content-left .scrollable-table-body-scroller');
    if (leftBody) {
        if (verticalScrollBarSize && verticalScrollBarSize > 0) {
            leftBody.style.marginRight = `-${verticalScrollBarSize}px`;
            leftBody.style.paddingRight = 0;
        } else {
            const leftBodyTable = leftBody.querySelector('table');
            if (leftBodyTable) {
                const restWidth = wrapperEl.offsetWidth - leftBodyTable.offsetWidth;
                leftBody.style.marginRight = `-${restWidth}px`;
                leftBody.style.paddingRight = `${restWidth}px`;
            }
        }
    }

}

function fixLayout(wrapperEl, props) {

    if (!wrapperEl) {
        return;
    }

    const tableEl = wrapperEl.querySelector('.table-content-center .scrollable-table-body table');

    if (!tableEl) {
        return;
    }

    /**
     * fix scroll style
     */
    fixTableHorizontalScroll(wrapperEl, props);
    fixTableVerticalScroll(wrapperEl, props);

    const columnsWidth = getColumnsWidth(tableEl),
        rowsHeight = getRowsHeight(tableEl),

        fixedHeadHeight = sum(rowsHeight[TableFragment.HEAD]) || 0,
        fixedFootHeight = sum(rowsHeight[TableFragment.FOOT]) || 0;

    /**
     * center
     */
    maskCenterBody(wrapperEl, tableEl, fixedHeadHeight, fixedFootHeight);
    fixTableWidth(wrapperEl, columnsWidth, null, props);
    fixTableHeight(wrapperEl, rowsHeight, null, props);

    /**
     * left
     */
    fixTableWidth(wrapperEl, columnsWidth, HorizontalAlign.LEFT, props);
    fixTableHeight(wrapperEl, rowsHeight, HorizontalAlign.LEFT, props);

    /**
     * right
     */
    fixTableWidth(wrapperEl, columnsWidth, HorizontalAlign.RIGHT, props);
    fixTableHeight(wrapperEl, rowsHeight, HorizontalAlign.RIGHT, props);

}

export default {
    getColumnsWidth,
    getRowsHeight,
    getbodyScollerHeight,
    fixLayout
};
<|endoftext|>


<commit_before>import './LinkedWebentities.styl'

import { FormattedMessage as T, useIntl } from 'react-intl'

import React, {useEffect, useState, useMemo} from 'react'
import cx from 'classnames'

import HelpPin from '../HelpPin'
import EntityCard from '../EntityCard'
import CardsList from '../CardsList'
import DownloadListBtn from '../DownloadListBtn'
import MergeActionsModal from './MergeActionsModal'
import { filter } from 'lodash'

const LinkedWebentities = ({
  webentity,
  tlds,
  linkedEntities,
  linkedEntitiesList,
  viewedSuggestionIds,
  loadingBatchActions,
  resetActions,
  submitActions,
  pendingActions,
  statusActions,
  setStatusActions,
  updateList,
  onOpenTab,
  onDownloadList
}) => {
  const { formatMessage } = useIntl()

  const [stateList, setStateList] = useState(linkedEntitiesList)
  const [mergeActions, setMergeActions] = useState([])

  useEffect(() => {
    setStateList(linkedEntitiesList)
  }, [linkedEntitiesList])

  const degreeCount = webentity[(linkedEntities === 'referrers' ? 'in' : 'out') + 'degree']

  const handleCloseMergeModal = () => {
    setMergeActions([])
  }

  const handleValidateMerge = (mergeActions) => {
    submitActions(mergeActions)
    const newList = [...stateList]
    mergeActions.forEach((action) => {
      newList.forEach((entity) => {
        if(entity.id === action.id) {
          entity.previousStatus = entity.status
          entity.status = action.type
        }
      })
    })
    setStateList(newList)
    setMergeActions([])
  }

  const handleSubmitActions = () => {
    const nonMergeActions = pendingActions.filter((action) => action.type !== 'MERGE')
    setMergeActions(pendingActions.filter((action) => action.type === 'MERGE'))
    const newList = [...stateList]
    nonMergeActions.forEach((action) => {
      newList.forEach((entity) => {
        if(entity.id === action.id) {
          entity.previousStatus = entity.status
          entity.status = action.type
        }
      })
    })
    setStateList(newList)
    submitActions(nonMergeActions)
  }

  const handleUpdateList = () => updateList(linkedEntities)

  const handleDownloadList = () => {
    onDownloadList(linkedEntities)
  }

  return (

        {
          // only show actualize button when webentity is set to IN
          degreeCount !== stateList.length && webentity.status === 'IN' &&

            <button className="btn actualize" onClick={ handleUpdateList }>
              {formatMessage({ id: 'actualize-entities-list' })}
              {` (${degreeCount > stateList.length ? `+${degreeCount - stateList.length}` : `-${ stateList.length  - degreeCount }`})`}
            </button>

        }
        <CardsList>
          { stateList.length ? stateList.map((link, index) => {
            const toggleAction = (obj, key, status) => {
              return {
                ...obj,
                [key]: obj[key] === status ? null : status
              }
            }

            const handleClickLink = () => onOpenTab(link.homepage)
            const handleClickMerge = (e) => {
              e.stopPropagation()
              setStatusActions(toggleAction(statusActions, link.id, 'MERGE'))
            }
            const handleClickOut = (e) => {
              e.stopPropagation()
              setStatusActions(toggleAction(statusActions, link.id, 'OUT'))
            }
            const handleClickUndecided = (e) => {
              e.stopPropagation()
              setStatusActions(toggleAction(statusActions, link.id, 'UNDECIDED'))
            }

            const isViewed = link.status === 'DISCOVERED' && viewedSuggestionIds && viewedSuggestionIds.has(link.id)

            return (
              <EntityCard
                key={ index }
                allowMerge
                link={ link }
                isViewed={ isViewed }
                onClickLink={ handleClickLink }
                onClickMerge={ handleClickMerge }
                onClickOut={ handleClickOut }
                onClickUndecided={ handleClickUndecided }
                isMergeActive={ statusActions[link.id] === 'MERGE' }
                isUndecidedActive={ statusActions[link.id] === 'UNDECIDED' }
                isOutActive={ statusActions[link.id] === 'OUT' }
              />
            )
          })
            :

              { formatMessage({ id: 'none' }) }

          }
        </CardsList>

        {
          pendingActions && pendingActions.length > 0
          &&

              <button className="btn cancel-btn">
                <T id="discard-decisions" />
              </button>

<button className="btn confirm-btn">
              <T id="apply-decisions" values={ { count: pendingActions.length } } />
            </button>

        }

        { stateList.length > 0 && (!pendingActions || pendingActions.length === 0) &&

            <DownloadListBtn onClickDownload={ handleDownloadList } />

        }

      {
        mergeActions.length > 0 &&
        <MergeActionsModal
          isOpen
          mergeActions={ mergeActions }
          linkedList={ webentity[linkedEntities] }
          tlds={ tlds }
          webentityName={ webentity.name }
          onClose={ handleCloseMergeModal }
          onValidateMerge={ handleValidateMerge }
        />
      }

  )
}

export default React.memo(LinkedWebentities)
<commit_msg>show actualize button with condition #197<commit_after>import './LinkedWebentities.styl'

import { FormattedMessage as T, useIntl } from 'react-intl'

import React, {useEffect, useState, useMemo} from 'react'
import cx from 'classnames'

import HelpPin from '../HelpPin'
import EntityCard from '../EntityCard'
import CardsList from '../CardsList'
import DownloadListBtn from '../DownloadListBtn'
import MergeActionsModal from './MergeActionsModal'
import { filter } from 'lodash'

const LinkedWebentities = ({
  webentity,
  tlds,
  linkedEntities,
  linkedEntitiesList,
  viewedSuggestionIds,
  loadingBatchActions,
  resetActions,
  submitActions,
  pendingActions,
  statusActions,
  setStatusActions,
  updateList,
  onOpenTab,
  onDownloadList
}) => {
  const { formatMessage } = useIntl()

  const [stateList, setStateList] = useState(linkedEntitiesList)
  const [mergeActions, setMergeActions] = useState([])

  useEffect(() => {
    setStateList(linkedEntitiesList)
  }, [linkedEntitiesList])

  const degreeCount = webentity[(linkedEntities === 'referrers' ? 'in' : 'out') + 'degree']

  const handleCloseMergeModal = () => {
    setMergeActions([])
  }

  const handleValidateMerge = (mergeActions) => {
    submitActions(mergeActions)
    const newList = [...stateList]
    mergeActions.forEach((action) => {
      newList.forEach((entity) => {
        if(entity.id === action.id) {
          entity.previousStatus = entity.status
          entity.status = action.type
        }
      })
    })
    setStateList(newList)
    setMergeActions([])
  }

  const handleSubmitActions = () => {
    const nonMergeActions = pendingActions.filter((action) => action.type !== 'MERGE')
    setMergeActions(pendingActions.filter((action) => action.type === 'MERGE'))
    const newList = [...stateList]
    nonMergeActions.forEach((action) => {
      newList.forEach((entity) => {
        if(entity.id === action.id) {
          entity.previousStatus = entity.status
          entity.status = action.type
        }
      })
    })
    setStateList(newList)
    submitActions(nonMergeActions)
  }

  const handleUpdateList = () => updateList(linkedEntities)

  const handleDownloadList = () => {
    onDownloadList(linkedEntities)
  }

  const filteredList = linkedEntities === 'referrers' && stateList.filter((entity) => entity.status === 'IN' || entity.status === 'UNDICIDED')

  return (

        {
          // show actualize button of referrals and during webentity is crawling
          degreeCount !== stateList.length && webentity.status === 'IN' && linkedEntities === 'referrals' && webentity.crawling_status === 'RUNNING' &&

            <button className="btn actualize" onClick={ handleUpdateList }>
              {formatMessage({ id: 'actualize-entities-list' })}
              {` (${degreeCount > stateList.length ? `+${degreeCount - stateList.length}` : `-${ stateList.length  - degreeCount }`})`}
            </button>

        }
        {
          // show actualize button of referrers compared with filteredList
          linkedEntities === 'referrers' &&  filteredList && degreeCount !== filteredList.length &&

            <button className="btn actualize" onClick={ handleUpdateList }>
              {formatMessage({ id: 'actualize-entities-list' })}
              {` (${degreeCount > filteredList.length ? `+${degreeCount - filteredList.length}` : `-${ filteredList.length  - degreeCount }`})`}
            </button>

        }
        <CardsList>
          { stateList.length ? stateList.map((link, index) => {
            const toggleAction = (obj, key, status) => {
              return {
                ...obj,
                [key]: obj[key] === status ? null : status
              }
            }

            const handleClickLink = () => onOpenTab(link.homepage)
            const handleClickMerge = (e) => {
              e.stopPropagation()
              setStatusActions(toggleAction(statusActions, link.id, 'MERGE'))
            }
            const handleClickOut = (e) => {
              e.stopPropagation()
              setStatusActions(toggleAction(statusActions, link.id, 'OUT'))
            }
            const handleClickUndecided = (e) => {
              e.stopPropagation()
              setStatusActions(toggleAction(statusActions, link.id, 'UNDECIDED'))
            }

            const isViewed = link.status === 'DISCOVERED' && viewedSuggestionIds && viewedSuggestionIds.has(link.id)

            return (
              <EntityCard
                key={ index }
                allowMerge
                link={ link }
                isViewed={ isViewed }
                onClickLink={ handleClickLink }
                onClickMerge={ handleClickMerge }
                onClickOut={ handleClickOut }
                onClickUndecided={ handleClickUndecided }
                isMergeActive={ statusActions[link.id] === 'MERGE' }
                isUndecidedActive={ statusActions[link.id] === 'UNDECIDED' }
                isOutActive={ statusActions[link.id] === 'OUT' }
              />
            )
          })
            :

              { formatMessage({ id: 'none' }) }

          }
        </CardsList>

        {
          pendingActions && pendingActions.length > 0
          &&

              <button className="btn cancel-btn">
                <T id="discard-decisions" />
              </button>

<button className="btn confirm-btn">
              <T id="apply-decisions" values={ { count: pendingActions.length } } />
            </button>

        }

        { stateList.length > 0 && (!pendingActions || pendingActions.length === 0) &&

            <DownloadListBtn onClickDownload={ handleDownloadList } />

        }

      {
        mergeActions.length > 0 &&
        <MergeActionsModal
          isOpen
          mergeActions={ mergeActions }
          linkedList={ webentity[linkedEntities] }
          tlds={ tlds }
          webentityName={ webentity.name }
          onClose={ handleCloseMergeModal }
          onValidateMerge={ handleValidateMerge }
        />
      }

  )
}

export default React.memo(LinkedWebentities)
<|endoftext|>


<commit_before>console.log("Initializing the runway handlers.");
var runway = document.querySelector('.widget-runway-tray-wrapper');

var initialMousePosition = null;
var initialScrollLeft = null;

runway.addEventListener('touchstart', function(e){
  console.log('touchstart');

	// this should be enabled only in chrome
	// in chromium I need to support the multiple touch events when using one finger,
	// so I just take the first one currently
  // if (e.touches.length > 1) { console.log('No multiple touch allowed'); return; }

  initialMousePosition = e.touches[0].pageX;
  initialScrollLeft = runway.scrollLeft;
},
true);

runway.addEventListener('touchend', function(e){
  console.log('touchend');
  initialMousePosition = null;
},
true);

runway.addEventListener('touchmove', function(e){
  console.log('touchmove');
  if (initialMousePosition === null) return;

	// this should be enabled only in chrome
	// in chromium I need to support the multiple touch events when using one finger,
	// so I just take the first one currently
  //if (e.touches.length > 1) { console.log('No multiple touch allowed'); return; }
  var dx = e.touches[0].pageX - initialMousePosition;
  runway.scrollLeft = initialScrollLeft + dx;
},
true);
<commit_msg>Tab fixes<commit_after>console.log("Initializing the runway handlers.");
var runway = document.querySelector('.widget-runway-tray-wrapper');

var initialMousePosition = null;
var initialScrollLeft = null;

runway.addEventListener('touchstart', function(e){
  console.log('touchstart');

  // this should be enabled only in chrome
  // in chromium I need to support the multiple touch events when using one finger,
  // so I just take the first one currently
  // if (e.touches.length > 1) { console.log('No multiple touch allowed'); return; }

  initialMousePosition = e.touches[0].pageX;
  initialScrollLeft = runway.scrollLeft;
},
true);

runway.addEventListener('touchend', function(e){
  console.log('touchend');
  initialMousePosition = null;
},
true);

runway.addEventListener('touchmove', function(e){
  console.log('touchmove');
  if (initialMousePosition === null) return;

  // this should be enabled only in chrome
  // in chromium I need to support the multiple touch events when using one finger,
  // so I just take the first one currently
  //if (e.touches.length > 1) { console.log('No multiple touch allowed'); return; }
  var dx = e.touches[0].pageX - initialMousePosition;
  runway.scrollLeft = initialScrollLeft + dx;
},
true);
<|endoftext|>