<commit_before>//= require import

/* global miqSparkleOn miqSparkleOff showSuccessMessage showErrorMessage showWarningMessage clearMessages */

var Automate = {
  getAndRenderAutomateJson: function(importFileUploadId, message) {
    $('.hidden-import-file-upload-id').val(importFileUploadId);

    $.getJSON("automate_json?import_file_upload_id=" + importFileUploadId)
      .done(function(rows_json) {
        Automate.addDomainOptions(rows_json);
        Automate.setupInitialTree(rows_json);

        $('select.importing-domains').change(function() {
          Automate.importingDomainsChangeHandler(rows_json);
        });

        $('#import_file_upload_id').val(importFileUploadId);
        $('.import-data').show();
        $('.import-or-export').hide();
        showSuccessMessage(JSON.parse(message).message);
      })
      .fail(function(failedMessage) {
        var messageData = JSON.parse(failedMessage.responseText);

        if (messageData.level == 'warning') {
          showWarningMessage(messageData.message);
        } else {
          showErrorMessage(messageData.message);
        }
      });
  },

  renderGitImport: function(branches, tags, gitRepoId, messages) {
    clearMessages();
    message = JSON.parse(messages).message;
    messageLevel = JSON.parse(messages).level;

    if (messageLevel === "error") {
      showErrorMessage(message);
    } else {
      $('.hidden-git-repo-id').val(gitRepoId);
      $('.git-import-data').show();
      $('.import-or-export').hide();
      if (messageLevel === "warning") {
        showWarningMessage(message);
      } else {
        showSuccessMessage(message);
      }

      var addToDropDown = function(identifier, child) {
        $('select.git-' + identifier).append(
          $('<option>', {
            value: child,
            text: child
          })
        );
      };

      $.each(JSON.parse(branches), function(index, child) {
        addToDropDown('branches', child);
      });
      $.each(JSON.parse(tags), function(index, child) {
        addToDropDown('tags', child);
      });

      Automate.selectDefaultBranch();

      $('select.git-branches').selectpicker('refresh');
      $('select.git-tags').selectpicker('refresh');
    }

    miqSparkleOff();
  },

  selectDefaultBranch: function() {
    if ($('select.git-branches').find('option[value="origin/master"]').length === 0) {
      $('select.git-branches').prop('selectedIndex', 0);
    } else {
      $('select.git-branches').val('origin/master');
    }

    $('.git-branch-or-tag').val($('select.git-branches').val());
    $('.git-import-submit').prop('disabled', false);
  },

  addDomainOptions: function(domains) {
    $('select.importing-domains').empty();

    $.each(domains, function(_index, child) {
      $('select.importing-domains').append(
        $('<option>', {
          value: child.key,
          text:  child.text
        })
      );
    });

    $('select.importing-domains').selectpicker('refresh');
  },

  setupInitialTree: function(domains) {
    $('.domain-tree').treeview({
      data:              domains[0].nodes,
      levels:            1,
      showCheckbox:      true,
      showImage:         true,
      hierarchicalCheck: true,
      expandIcon:        'fa fa-fw fa-chevron-right',
      collapseIcon:      'fa fa-fw fa-chevron-down'
    });
  },

  importingDomainsChangeHandler: function(domains) {
    $.each(domains, function(_index, child) {
      if ($('select.importing-domains').val() === child.key) {
        $('.domain-tree').treeview({
          data:              child.nodes,
          levels:            1,
          showCheckbox:      true,
          showImage:         true,
          hierarchicalCheck: true,
          expandIcon:        'fa fa-fw fa-chevron-right',
          collapseIcon:      'fa fa-fw fa-chevron-down'
        });
      }
    });

    $('#toggle-all').prop('checked', false);
  },

  setUpAutomateImportClickHandlers: function() {
    var tearDownGitImportOptions = function() {
      $('select.git-branches').find('option').remove().end();
      $('select.git-tags').find('option').remove().end();
      $('select.git-branches').selectpicker('refresh');
      $('select.git-tags').selectpicker('refresh');

      $('.import-or-export').show();
      $('.git-import-data').hide();
      $('#git-url-import').prop('disabled', null);
    };

    $('.import-commit').click(function(event) {
      event.preventDefault();
      miqSparkleOn();
      clearMessages();

      var postData = $('#import-form').serialize();
      postData += '&';

      var treeName = $('.domain-tree').attr('name');
      var serialized = $.param($('.domain-tree').treeview(true).getChecked().map(function (node) {
        return {name: treeName, value: node.key}
      }));
      postData = postData.concat(serialized);

      $.post('import_automate_datastore', postData, function(data) {
        var flashMessage = JSON.parse(data)[0];
        if (flashMessage.level == 'error') {
          showErrorMessage(flashMessage.message);
        } else {
          showSuccessMessage(flashMessage.message);
        }

        miqSparkleOff();
      });
    });

    Automate.setUpGitRefreshClickHandlers();

    $('.git-retreive-datastore').click(function() {
      miqSparkleOn();
    });

    $('.git-import-submit').click(function(event) {
      event.preventDefault();
      miqSparkleOn();
      clearMessages();

      $.post('import_via_git', $('#git-branch-tag-form').serialize(), function(data) {
        var flashMessage = data[0];
        if (flashMessage.level == 'error') {
          showErrorMessage(flashMessage.message);
        } else {
          showSuccessMessage(flashMessage.message);
        }

        tearDownGitImportOptions();

        miqSparkleOff();
      }, 'json');
    });

    $('.import-back').click(function(event) {
      event.preventDefault();
      miqSparkleOn();
      clearMessages();

      $('.domain-tree').empty();

      $.post('cancel_import', $('#import-form').serialize(), function(data) {
        var flashMessage = JSON.parse(data)[0];
        showSuccessMessage(flashMessage.message);

        $('.import-or-export').show();
        $('.import-data').hide();
        miqSparkleOff();
      });
    });

    $('.git-import-cancel').click(function(event) {
      event.preventDefault();
      clearMessages();
      tearDownGitImportOptions();
      showSuccessMessage('Import cancelled');
    });

    $('#toggle-all').on('change', function() {
      $('#toggle-all').prop('checked') ? $('.domain-tree').treeview(true).checkAll() : $('.domain-tree').treeview(true).uncheckAll();
    });
  },

  setUpDefaultGitBranchOrTagValue: function() {
    $('.git-branch-or-tag').val($('select.git-branches').val());
  },

  setUpGitRefreshClickHandlers: function() {
    var toggleSubmitButton = function() {
      var branchOrTagSelected = $('.git-branch-or-tag').val() === '';
      $('.git-import-submit').prop('disabled', branchOrTagSelected);
    };

    $('.git-branch-or-tag-select').on('change', function(event) {
      event.preventDefault();
      if ($(event.currentTarget).val() === "Branch") {
        $('.git-branch-group').show();
        $('.git-tag-group').hide();
        $('.git-branch-or-tag').val($('select.git-branches').val());
      } else if ($(event.currentTarget).val() === "Tag") {
        $('.git-branch-group').hide();
        $('.git-tag-group').show();
        $('.git-branch-or-tag').val($('select.git-tags').val());
      }
      toggleSubmitButton();
    });

    $('select.git-branches').on('change', function(event) {
      $('.git-branch-or-tag').val($('select.git-branches').val());
      toggleSubmitButton();
    });

    $('select.git-tags').on('change', function(event) {
      $('.git-branch-or-tag').val($('select.git-tags').val());
      toggleSubmitButton();
    });
  }
};
<commit_msg>Small fixes to up the grade on AutomateImportExport.js (transferred from ManageIQ/manageiq@5750045430c7faa58a5d79f17d37e996a232405e)<commit_after>//= require import

/* global miqSparkleOn miqSparkleOff showSuccessMessage showErrorMessage showWarningMessage clearMessages */

var Automate = {
  getAndRenderAutomateJson: function(importFileUploadId, message) {
    $('.hidden-import-file-upload-id').val(importFileUploadId);

    $.getJSON('automate_json?import_file_upload_id=' + importFileUploadId)
      .done(function(rows_json) {
        Automate.addDomainOptions(rows_json);
        Automate.setupInitialTree(rows_json);

        $('select.importing-domains').change(function() {
          Automate.importingDomainsChangeHandler(rows_json);
        });

        $('#import_file_upload_id').val(importFileUploadId);
        $('.import-data').show();
        $('.import-or-export').hide();
        showSuccessMessage(JSON.parse(message).message);
      })
      .fail(function(failedMessage) {
        var messageData = JSON.parse(failedMessage.responseText);

        if (messageData.level === 'warning') {
          showWarningMessage(messageData.message);
        } else {
          showErrorMessage(messageData.message);
        }
      });
  },

  renderGitImport: function(branches, tags, gitRepoId, messages) {
    clearMessages();
    var message = JSON.parse(messages).message;
    var messageLevel = JSON.parse(messages).level;

    if (messageLevel === 'error') {
      showErrorMessage(message);
    } else {
      $('.hidden-git-repo-id').val(gitRepoId);
      $('.git-import-data').show();
      $('.import-or-export').hide();
      if (messageLevel === 'warning') {
        showWarningMessage(message);
      } else {
        showSuccessMessage(message);
      }

      var addToDropDown = function(identifier, child) {
        $('select.git-' + identifier).append(
          $('<option>', {
            value: child,
            text: child,
          })
        );
      };

      $.each(JSON.parse(branches), function(_index, child) {
        addToDropDown('branches', child);
      });
      $.each(JSON.parse(tags), function(_index, child) {
        addToDropDown('tags', child);
      });

      Automate.selectDefaultBranch();

      $('select.git-branches').selectpicker('refresh');
      $('select.git-tags').selectpicker('refresh');
    }

    miqSparkleOff();
  },

  selectDefaultBranch: function() {
    if ($('select.git-branches').find('option[value="origin/master"]').length === 0) {
      $('select.git-branches').prop('selectedIndex', 0);
    } else {
      $('select.git-branches').val('origin/master');
    }

    $('.git-branch-or-tag').val($('select.git-branches').val());
    $('.git-import-submit').prop('disabled', false);
  },

  addDomainOptions: function(domains) {
    $('select.importing-domains').empty();

    $.each(domains, function(_index, child) {
      $('select.importing-domains').append(
        $('<option>', {
          value: child.key,
          text:  child.text,
        })
      );
    });

    $('select.importing-domains').selectpicker('refresh');
  },

  setupInitialTree: function(domains) {
    $('.domain-tree').treeview({
      data:              domains[0].nodes,
      levels:            1,
      showCheckbox:      true,
      showImage:         true,
      hierarchicalCheck: true,
      expandIcon:        'fa fa-fw fa-chevron-right',
      collapseIcon:      'fa fa-fw fa-chevron-down',
    });
  },

  importingDomainsChangeHandler: function(domains) {
    $.each(domains, function(_index, child) {
      if ($('select.importing-domains').val() === child.key) {
        $('.domain-tree').treeview({
          data:              child.nodes,
          levels:            1,
          showCheckbox:      true,
          showImage:         true,
          hierarchicalCheck: true,
          expandIcon:        'fa fa-fw fa-chevron-right',
          collapseIcon:      'fa fa-fw fa-chevron-down',
        });
      }
    });

    $('#toggle-all').prop('checked', false);
  },

  setUpAutomateImportClickHandlers: function() {
    var tearDownGitImportOptions = function() {
      $('select.git-branches').find('option').remove().end();
      $('select.git-tags').find('option').remove().end();
      $('select.git-branches').selectpicker('refresh');
      $('select.git-tags').selectpicker('refresh');

      $('.import-or-export').show();
      $('.git-import-data').hide();
      $('#git-url-import').prop('disabled', null);
    };

    $('.import-commit').click(function(event) {
      event.preventDefault();
      miqSparkleOn();
      clearMessages();

      var postData = $('#import-form').serialize();
      postData += '&';

      var treeName = $('.domain-tree').attr('name');
      var serialized = $.param($('.domain-tree').treeview(true).getChecked().map(function(node) {
        return {name: treeName, value: node.key};
      }));
      postData = postData.concat(serialized);

      $.post('import_automate_datastore', postData, function(data) {
        var flashMessage = JSON.parse(data)[0];
        if (flashMessage.level === 'error') {
          showErrorMessage(flashMessage.message);
        } else {
          showSuccessMessage(flashMessage.message);
        }

        miqSparkleOff();
      });
    });

    Automate.setUpGitRefreshClickHandlers();

    $('.git-retreive-datastore').click(function() {
      miqSparkleOn();
    });

    $('.git-import-submit').click(function(event) {
      event.preventDefault();
      miqSparkleOn();
      clearMessages();

      $.post('import_via_git', $('#git-branch-tag-form').serialize(), function(data) {
        var flashMessage = data[0];
        if (flashMessage.level === 'error') {
          showErrorMessage(flashMessage.message);
        } else {
          showSuccessMessage(flashMessage.message);
        }

        tearDownGitImportOptions();

        miqSparkleOff();
      }, 'json');
    });

    $('.import-back').click(function(event) {
      event.preventDefault();
      miqSparkleOn();
      clearMessages();

      $('.domain-tree').empty();

      $.post('cancel_import', $('#import-form').serialize(), function(data) {
        var flashMessage = JSON.parse(data)[0];
        showSuccessMessage(flashMessage.message);

        $('.import-or-export').show();
        $('.import-data').hide();
        miqSparkleOff();
      });
    });

    $('.git-import-cancel').click(function(event) {
      event.preventDefault();
      clearMessages();
      tearDownGitImportOptions();
      showSuccessMessage('Import cancelled');
    });

    $('#toggle-all').on('change', function() {
      $('#toggle-all').prop('checked') ? $('.domain-tree').treeview(true).checkAll() : $('.domain-tree').treeview(true).uncheckAll();
    });
  },

  setUpDefaultGitBranchOrTagValue: function() {
    $('.git-branch-or-tag').val($('select.git-branches').val());
  },

  setUpGitRefreshClickHandlers: function() {
    var toggleSubmitButton = function() {
      var branchOrTagSelected = $('.git-branch-or-tag').val() === '';
      $('.git-import-submit').prop('disabled', branchOrTagSelected);
    };

    $('.git-branch-or-tag-select').on('change', function(event) {
      event.preventDefault();
      if ($(event.currentTarget).val() === 'Branch') {
        $('.git-branch-group').show();
        $('.git-tag-group').hide();
        $('.git-branch-or-tag').val($('select.git-branches').val());
      } else if ($(event.currentTarget).val() === 'Tag') {
        $('.git-branch-group').hide();
        $('.git-tag-group').show();
        $('.git-branch-or-tag').val($('select.git-tags').val());
      }
      toggleSubmitButton();
    });

    $('select.git-branches').on('change', function(_event) {
      $('.git-branch-or-tag').val($('select.git-branches').val());
      toggleSubmitButton();
    });

    $('select.git-tags').on('change', function(_event) {
      $('.git-branch-or-tag').val($('select.git-tags').val());
      toggleSubmitButton();
    });
  },
};
<|endoftext|>


<commit_before>// Copyright (c) 2018, Compiler Explorer Authors
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

const exec = require('../exec'),
    _ = require('underscore'),
    logger = require('../logger').logger;

class Formatter {
    constructor(ceProps) {
        this.tools = {};
        const formatters = _.compact(ceProps('formatters').split(':'));
        _.each(formatters, formatter => {
            const exe = ceProps(`formatter.${formatter}.exe`);
            if (!exe) {
                logger.warn(`Formatter ${formatter} does not have a valid exe. Skipping...`);
                return;
            }
            const versionArg = ceProps(`formatter.${formatter}.version`, '--version');
            const versionRe = ceProps(`formatter.${formatter}.versionRe`, '.*');
            exec.execute(exe, [versionArg], {})
                .then(result => {
                    const match = result.stdout.match(versionRe);
                    this.tools[formatter] = {
                        exe: exe,
                        version: match ? match[0] : result.stdout,
                        name: ceProps(`formatter.${formatter}.name`, exe)
                    };
                });
        });
    }

    formatHandler(req, res) {
        res.setHeader('Content-Type', 'application/json');
        let requestedTool = this.tools[req.params.tool];
        if (!requestedTool) {
            return res.end(JSON.stringify({
                exit: 2,
                answer: "Tool not supported"
            }));
        }
        const args = [];
        // Only clang supported for now
        const options = req.body || {};
        let style = options.base || "Google";  // Default style
        args.push(`-style=${style}`);
        exec.execute(requestedTool.exe, args, {input: options.source || ""}).then(result => {
            return res.end(JSON.stringify({
                exit: result.code,
                answer: result.stdout,
            }));
        }).catch(ex => {
            return res.end(JSON.stringify({
                exit: 1,
                thrown: true,
                answer: ex.message
            }));
        });
    }

    listHandler(req, res) {
        res.setHeader('Content-Type', 'application/json');
        const response = [];
        _.each(this.tools, tool => {
            response.push({name: tool.name, version: tool.version});
        });
        return res.end(JSON.stringify(response));
    }
}

module.exports = Formatter;
<commit_msg>Ensure answer return param always exists<commit_after>// Copyright (c) 2018, Compiler Explorer Authors
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

const exec = require('../exec'),
    _ = require('underscore'),
    logger = require('../logger').logger;

class Formatter {
    constructor(ceProps) {
        this.tools = {};
        const formatters = _.compact(ceProps('formatters').split(':'));
        _.each(formatters, formatter => {
            const exe = ceProps(`formatter.${formatter}.exe`);
            if (!exe) {
                logger.warn(`Formatter ${formatter} does not have a valid exe. Skipping...`);
                return;
            }
            const versionArg = ceProps(`formatter.${formatter}.version`, '--version');
            const versionRe = ceProps(`formatter.${formatter}.versionRe`, '.*');
            exec.execute(exe, [versionArg], {})
                .then(result => {
                    const match = result.stdout.match(versionRe);
                    this.tools[formatter] = {
                        exe: exe,
                        version: match ? match[0] : result.stdout,
                        name: ceProps(`formatter.${formatter}.name`, exe)
                    };
                });
        });
    }

    formatHandler(req, res) {
        res.setHeader('Content-Type', 'application/json');
        let requestedTool = this.tools[req.params.tool];
        if (!requestedTool) {
            return res.end(JSON.stringify({
                exit: 2,
                answer: "Tool not supported"
            }));
        }
        const args = [];
        // Only clang supported for now
        const options = req.body || {};
        let style = options.base || "Google";  // Default style
        args.push(`-style=${style}`);
        exec.execute(requestedTool.exe, args, {input: options.source || ""}).then(result => {
            return res.end(JSON.stringify({
                exit: result.code,
                answer: result.stdout || "",
            }));
        }).catch(ex => {
            return res.end(JSON.stringify({
                exit: 1,
                thrown: true,
                answer: ex.message || ""
            }));
        });
    }

    listHandler(req, res) {
        res.setHeader('Content-Type', 'application/json');
        const response = [];
        _.each(this.tools, tool => {
            response.push({name: tool.name, version: tool.version});
        });
        return res.end(JSON.stringify(response));
    }
}

module.exports = Formatter;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import moment from 'moment';
<<<<<<>>>>>> 4c75c3b58f1a2712db810ac52d1b44492fe3db01

import './App.css';
import 'react-datepicker/dist/react-datepicker.css';

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      numberOfDays: 0,
      result: "",
      resultDays: 0,
<<<<<<>>>>>> 4c75c3b58f1a2712db810ac52d1b44492fe3db01
    }
  }

  handleChange = (date) => {
    this.setState ({
      startDate: date,
    })
  }

  isWeekday = (date) => {
    const day = date.day()
    return day !== 0 && day !== 6
  }

  getExcludedDates = () => {
    return this.state.data.map(item => item.date);
  }

  getParams = () => {
    const searchParams = window.location.search.replace('?', '');
    return searchParams;
  };

  decodeToState = () => {
    const params = this.getParams();
    const decodedData = params === ""
      ? []
      : JSON.parse(window.atob(params));

    return decodedData;
  }

  encodeState = (data) => {
    const encoded = window.btoa(JSON.stringify(data));
    return encoded;
  }

  addToUrl = () => {
    const myNewUrlQuery = this.encodeState(this.state.data);

    if (window.history.pushState) {
      const newurl = `${window.location.protocol}//${window.location.host}${window.location.pathname}?${myNewUrlQuery}`;
      window.history.pushState({ path:newurl },'',newurl);
    }
  }

  calculateDate = () => {
    const resultDays = moment().isoWeekdayCalc({
      rangeStart: moment().format('DD MMM YYYY'),
      rangeEnd: this.state.startDate.format('DD MMM YYYY'),
      weekdays: [1,2,3,4,5],
      exclusions: this.getExcludedDates()
    });

    const calculatedDate = moment(this.state.startDate).format('MM-DD-YYYY');

    this.setState({
      result: calculatedDate,
      resultDays: this.state.numberOfDays,
    });
  }

  setNumberOfDays = ({target}) => {
    this.setState({ numberOfDays: target.value });
  }

  render() {
    return (

              Excluded Dates:

            <button
              onClick={this.addToUrl}
              className="button button--ujarak button--border-medium button--round-s button--text-thick"
            >
              Save
            </button>

                Date:

                Reason:

            {this.state.data.length === 0
                ?
No dates to exclude

                : this.state.data.map(item => (

{item.date}

{item.reason}

                ))
            }

<<<<<<>>>>>> 4c75c3b58f1a2712db810ac52d1b44492fe3db01

              <DatePicker
              selected={this.state.startDate}
              onChange={this.handleChange}
              filterDate={this.isWeekday}
              excludeDates={this.getExcludedDates()}
              minDate={this.state.todayDate}
              readOnly
              />
              <button
                onClick={this.calculateDate}
                className="button button--ujarak button--border-medium button--round-s button--text-thick"
              >
                Calculate Date
              </button>

              { this.state.result &&

In {this.state.resultDays} working days it will be:

{moment(this.state.result).format('dddd, MMMM Do YYYY')}

{this.state.result}

              }

    );
  }
}

export default App;
<commit_msg>Minor corrections<commit_after>import React, { Component } from 'react';
import moment from 'moment';
/*eslint-disable no-unused-vars*/
import weekdayCalc from 'moment-weekday-calc';
/*eslint-enable no-unused-vars*/
import excludedDates from './excluded_dates.json';
import DatePicker from 'react-datepicker';

import './App.css';
import 'react-datepicker/dist/react-datepicker.css';

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      numberOfDays: 0,
      result: "",
      resultDays: 0,
      startDate: moment(),
      todayDate: moment()
    }
  }

  handleChange = (date) => {
    this.setState ({
      startDate: date,
    })
  }

  isWeekday = (date) => {
    const day = date.day()
    return day !== 0 && day !== 6
  }

  getExcludedDates = () => {
    return this.state.data.map(item => item.date);
  }

  getParams = () => {
    const searchParams = window.location.search.replace('?', '');
    return searchParams;
  };

  decodeToState = () => {
    const params = this.getParams();
    const decodedData = params === ""
      ? []
      : JSON.parse(window.atob(params));

    return decodedData;
  }

  encodeState = (data) => {
    const encoded = window.btoa(JSON.stringify(data));
    return encoded;
  }

  addToUrl = () => {
    const myNewUrlQuery = this.encodeState(this.state.data);

    if (window.history.pushState) {
      const newurl = `${window.location.protocol}//${window.location.host}${window.location.pathname}?${myNewUrlQuery}`;
      window.history.pushState({ path:newurl },'',newurl);
    }
  }

  calculateDate = () => {
    const resultDays = moment().isoWeekdayCalc({
      rangeStart: moment().format('DD MMM YYYY'),
      rangeEnd: this.state.startDate.format('DD MMM YYYY'),
      weekdays: [1,2,3,4,5],
      exclusions: this.getExcludedDates()
    });

    const calculatedDate = moment(this.state.startDate).format('MM-DD-YYYY');

    this.setState({
      result: calculatedDate,
      resultDays: this.state.numberOfDays,
    });
  }

  setNumberOfDays = ({target}) => {
    this.setState({ numberOfDays: target.value });
  }

  render() {
    return (

              Excluded Dates:

            <button
              onClick={this.addToUrl}
              className="button button--ujarak button--border-medium button--round-s button--text-thick"
            >
              Save
            </button>

                Date:

                Reason:

            {this.state.data.length === 0
                ?
No dates to exclude

                : this.state.data.map(item => (

{item.date}

{item.reason}

                ))
            }

              <DatePicker
              selected={this.state.startDate}
              onChange={this.handleChange}
              filterDate={this.isWeekday}
              excludeDates={this.getExcludedDates()}
              minDate={this.state.todayDate}
              readOnly
              />
              <button
                onClick={this.calculateDate}
                className="button button--ujarak button--border-medium button--round-s button--text-thick"
              >
                Calculate Date
              </button>

              { this.state.result &&

In {this.state.resultDays} working days it will be:

{moment(this.state.result).format('dddd, MMMM Do YYYY')}

{this.state.result}

              }

    );
  }
}

export default App;
<|endoftext|>


<commit_before>/**
 * Format for Selenium Remote Control PHP client.
 * Thanks to Sonic.
 */

load('remoteControl.js');

this.name = "php-rc";

function testMethodName(testName) {
    return "test" + capitalize(testName);
}

function assertTrue(expression) {
    return "$this->assertTrue(" + expression.toString() + ");";
}

function assertFalse(expression) {
    return "$this->assertFalse(" + expression.toString() + ");";
}

function verify(statement) {
    return "try {\n" +
        indent(1) + statement + "\n" +
        "} catch (PHPUnit_Framework_AssertionFailedError $e) {\n" +
        indent(1) + "array_push($this->verificationErrors, $e->toString());\n" +
        "}";
}

function verifyTrue(expression) {
    return verify(assertTrue(expression));
}

function verifyFalse(expression) {
    return verify(assertFalse(expression));
}

function joinExpression(expression) {
    return "implode(',', " + expression.toString() + ")";
}

function assignToVariable(type, variable, expression) {
    return variable + " = " + expression.toString();
}
function waitFor(expression) {
    return "for ($second = 0; ; $second++) {\n" +
        indent(1) + 'if ($second >= 60) $this->fail("timeout");\n' +
        indent(1) + "try {\n" +
        indent(2) + (expression.setup ? expression.setup() + " " : "") +
        indent(2) + "if (" + expression.toString() + ") break;\n" +
        indent(1) + "} catch (Exception $e) {}\n" +
        indent(1) + "sleep(1);\n" +
        "}\n";
}

function assertOrVerifyFailure(line, isAssert) {
    var message = '"expected failure"';
    var failStatement = isAssert ? "$this->fail(" + message  + ");" :
        "array_push($this->verificationErrors, " + message + ");";
    return "try { \n" +
        line + "\n" +
        failStatement + "\n" +
        "} catch (Exception $e) {}\n";
}

Equals.prototype.toString = function() {
    return this.e1.toString() + " == " + this.e2.toString();
}

Equals.prototype.assert = function() {
    return "$this->assertEquals(" + this.e1.toString() + ", " + this.e2.toString() + ");";
}

Equals.prototype.verify = function() {
    return verify(this.assert());
}

NotEquals.prototype.toString = function() {
    return this.e1.toString() + " != " + this.e2.toString();
}

NotEquals.prototype.assert = function() {
    return "$this->assertNotEquals(" + this.e1.toString() + ", " + this.e2.toString() + ");";
}

NotEquals.prototype.verify = function() {
    return verify(this.assert());
}

RegexpMatch.prototype.toString = function() {
  return "(bool)preg_match(/" + this.pattern.replace(/\//g, "\\/") + "/," + this.expression + ");";
}

RegexpNotMatch.prototype.toString = function() {
    return "(bool)preg_match(/" + this.pattern.replace(/\//g, "\\/") + "/," + this.expression + ");";
}

function pause(milliseconds) {
    return "sleep(" + (parseInt(milliseconds) / 1000) + ");";
}

function echo(message) {
    return "print(" + xlateArgument(message) + ' . "\\n");'
}

function statement(expression) {
    return expression.toString() + ';';
}

function array(value) {
    var str = 'array(';
    for (var i = 0; i < value.length; i++) {
        str += string(value[i]);
        if (i < value.length - 1) str += ", ";
    }
    str += ')';
    return str;
}

function nonBreakingSpace() {
    return "\"\\xa0\"";
}

CallSelenium.prototype.toString = function() {
    var result = '';
    if (this.negative) {
        result += '!';
    }
    if (options.receiver) {
        result += options.receiver + '->';
    }
    result += this.message;
    result += '(';
    for (var i = 0; i < this.args.length; i++) {
        result += this.args[i];
        if (i < this.args.length - 1) {
            result += ', ';
        }
    }
    result += ')';
    return result;
}

function formatComment(comment) {
    return comment.comment.replace(/.+/mg, function(str) {
            return "// " + str;
        });
}

this.options = {
    receiver: "$this",
	environment: "*chrome",
    header:
        '<?php\n' +
        '\n' +
        "require_once 'PHPUnit/Extensions/SeleniumTestCase.php';\n" +
        '\n' +
        'class Example extends PHPUnit_Extensions_SeleniumTestCase\n' +
        '{\n' +
        '  function setUp()\n' +
        '  {\n' +
        '    ${receiver}->setBrowser("${environment}");\n' +
        '    ${receiver}->setBrowserUrl("${baseURL}");\n' +
        '  }\n' +
        '\n' +
        '  function testMyTestCase()\n' +
        '  {\n',

    footer:
        '  }\n' +
        '}\n' +
        "?>",
    indent: "2",
    initialIndents: '2'
};

this.configForm =
    '<description>Variable for Selenium instance</description>' +
    '<textbox id="options_receiver" />' +
	'<description>Environment</description>' +
	'<textbox id="options_environment" />';
<commit_msg>AdamGoucher - a couple changes... - jlint warnings are a lot less - added protected / public to startup per http://www.phpunit.de/manual/current/en/selenium.html - fixing assignToVariable per http://jira.openqa.org/browse/SIDE-346<commit_after>/**
 * Format for Selenium Remote Control PHP client.
 * Thanks to Sonic.
 */

load('remoteControl.js');

this.name = "php-rc";

function testMethodName(testName) {
    return "test" + capitalize(testName);
}

function assertTrue(expression) {
    return "$this->assertTrue(" + expression.toString() + ");";
}

function assertFalse(expression) {
    return "$this->assertFalse(" + expression.toString() + ");";
}

function verify(statement) {
    return "try {\n" +
        indent(1) + statement + "\n" +
        "} catch (PHPUnit_Framework_AssertionFailedError $e) {\n" +
        indent(1) + "array_push($this->verificationErrors, $e->toString());\n" +
        "}";
}

function verifyTrue(expression) {
    return verify(assertTrue(expression));
}

function verifyFalse(expression) {
    return verify(assertFalse(expression));
}

function joinExpression(expression) {
    return "implode(',', " + expression.toString() + ")";
}

function assignToVariable(type, variable, expression) {
    return "$" + variable + " = " + expression.toString();
}
function waitFor(expression) {
    return "for ($second = 0; ; $second++) {\n" +
        indent(1) + 'if ($second >= 60) $this->fail("timeout");\n' +
        indent(1) + "try {\n" +
        indent(2) + (expression.setup ? expression.setup() + " " : "") +
        indent(2) + "if (" + expression.toString() + ") break;\n" +
        indent(1) + "} catch (Exception $e) {}\n" +
        indent(1) + "sleep(1);\n" +
        "}\n";
}

function assertOrVerifyFailure(line, isAssert) {
    var message = '"expected failure"';
    var failStatement = isAssert ? "$this->fail(" + message  + ");" :
        "array_push($this->verificationErrors, " + message + ");";
    return "try { \n" +
        line + "\n" +
        failStatement + "\n" +
        "} catch (Exception $e) {}\n";
};

Equals.prototype.toString = function() {
    return this.e1.toString() + " == " + this.e2.toString();
};

Equals.prototype.assert = function() {
    return "$this->assertEquals(" + this.e1.toString() + ", " + this.e2.toString() + ");";
};

Equals.prototype.verify = function() {
    return verify(this.assert());
};

NotEquals.prototype.toString = function() {
    return this.e1.toString() + " != " + this.e2.toString();
};

NotEquals.prototype.assert = function() {
    return "$this->assertNotEquals(" + this.e1.toString() + ", " + this.e2.toString() + ");";
};

NotEquals.prototype.verify = function() {
    return verify(this.assert());
};

RegexpMatch.prototype.toString = function() {
  return "(bool)preg_match(/" + this.pattern.replace(/\//g, "\\/") + "/," + this.expression + ");";
};

RegexpNotMatch.prototype.toString = function() {
    return "(bool)preg_match(/" + this.pattern.replace(/\//g, "\\/") + "/," + this.expression + ");";
};

function pause(milliseconds) {
    return "sleep(" + (parseInt(milliseconds) / 1000) + ");";
};

function echo(message) {
    return "print(" + xlateArgument(message) + ' . "\\n");';
};

function statement(expression) {
    return expression.toString() + ';';
};

function array(value) {
    var str = 'array(';
    for (var i = 0; i < value.length; i++) {
        str += string(value[i]);
        if (i < value.length - 1) str += ", ";
    }
    str += ')';
    return str;
};

function nonBreakingSpace() {
    return "\"\\xa0\"";
};

CallSelenium.prototype.toString = function() {
    var result = '';
    if (this.negative) {
        result += '!';
    }
    if (options.receiver) {
        result += options.receiver + '->';
    }
    result += this.message;
    result += '(';
    for (var i = 0; i < this.args.length; i++) {
        result += this.args[i];
        if (i < this.args.length - 1) {
            result += ', ';
        }
    }
    result += ')';
    return result;
};

function formatComment(comment) {
    return comment.comment.replace(/.+/mg, function(str) {
            return "// " + str;
        });
}

this.options = {
    receiver: "$this",
	environment: "*chrome",
    header:
        '<?php\n' +
        '\n' +
        "require_once 'PHPUnit/Extensions/SeleniumTestCase.php';\n" +
        '\n' +
        'class Example extends PHPUnit_Extensions_SeleniumTestCase\n' +
        '{\n' +
        '  protected function setUp()\n' +
        '  {\n' +
        '    ${receiver}->setBrowser("${environment}");\n' +
        '    ${receiver}->setBrowserUrl("${baseURL}");\n' +
        '  }\n' +
        '\n' +
        '  public function testMyTestCase()\n' +
        '  {\n',

    footer:
        '  }\n' +
        '}\n' +
        "?>",
    indent: "2",
    initialIndents: '2'
};

this.configForm =
    '<description>Variable for Selenium instance</description>' +
    '<textbox id="options_receiver" />' +
	'<description>Environment</description>' +
	'<textbox id="options_environment" />';
<|endoftext|>


<commit_before>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you 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.
 */

// load the master sakai object to access all Sakai OAE API methods
require(["jquery", "sakai/sakai.api.core", "underscore"], function($, sakai, _) {

    /**
     * @name sakai_global.collections
     *
     * @class collections
     *
     * @description
     * My Hello World is a dashboard widget that says hello to the current user
     * with text in the color of their choosing
     *
     * @version 0.0.1
     * @param {String} tuid Unique id of the widget
     * @param {Boolean} showSettings Show the settings of the widget or not
     */
    sakai_global.collections = function (tuid, showSettings) {

        var itemsToShow = 20;
        var contentToAdd = [];

        var subnavigationAddCollectionLink = "#subnavigation_add_collection_link";
        var collectorToggle = ".collector_toggle";
        var collectionsTotal = "#topnavigation_user_collections_total";
        var $collectionsWidget = $(".collections_widget");

        var collectionsNoCollections = "#collections_nocollections";
        var collectionsCollectionsList = "#collections_collections_list";

        // Buttons, links, etc.
        var collectionsCloseButton = "#collections_close_button";
        var collectionsNewButton = "#collections_new_button";
        var collectionsAddNewContainer = "#collections_add_new";
        var collectionsNewActionButtons = "#collections_new_action_buttons";
        var collectionsCancelNewButton = ".collections_cancel_new_button";
        var collectionsMainCancelNewButton = "#collections_main_cancel_new_button";
        var collectionsAddNewNextStepLabel = ".collections_add_new_nextsteplabel";
        var collectionsSeeAllButton = "#collections_see_all_button";
        var collectionsSeeAllButtonTotal = "#collections_see_all_total_count";
        var collectionsSaveNewButton = "#collections_save_new_button";
        var collectionsNewCollectionPermission = "#collections_newcollection_permissions";
        var collectionCountsContentCountsNew = "#collection_counts_content_counts_new";
        var collectionsCollectionTitle = "#collections_collection_title";

        // Classes
        var collectionsAddNewSteps = ".collections_add_new_steps";
        var collectionsScrollArrow = ".collections_scroll_arrow";
        var collectionsLargePreview = "collections_large_preview";

        // New collection steps
        var collectionsAddNewStepOne = "#collections_add_new_stepone";
        var collectionsAddNewStepTwo = "#collections_add_new_steptwo";
        var collectionsAddNewStepThree = "#collections_add_new_stepthree";

        ///////////////////////////
        // CREATE NEW COLLECTION //
        ///////////////////////////

        var resetGUI = function(){
            $(collectionsAddNewSteps).hide();
            $(collectionsAddNewContainer).hide();
            $(collectionsNewActionButtons).hide();
            $(collectionsCollectionsList).hide();
            $(collectionsScrollArrow).hide();
            $(collectionsSeeAllButton).hide();
            $(collectionsAddNewStepOne).show();
            $(collectionsNewButton).show();
        };

        /**
        * Enable creation of collection and enable elements
        */
        var initializeNewCollectionsSetup = function(ev, _contentToAdd){
            resetGUI();
            contentToAdd = _contentToAdd || [];
            $(collectionCountsContentCountsNew).text("" + contentToAdd.length);
            $(collectionsNewButton).hide();
            $(collectionsNoCollections).hide();
            $(collectionsAddNewContainer).show();
            $(collectionsNewActionButtons).show();
            if (!$collectionsWidget.is(":visible")){
                $collectionsWidget.animate({
                    'margin-bottom': 'toggle',
                    'height': 'toggle',
                    'opacity': 'toggle',
                    'padding-top': 'toggle',
                    'padding-bottom': 'toggle'
               }, 400, function(){
                 $(collectionsCollectionTitle).focus();
               });
            }
        };

        /**
        * Determine the screen to display
        */
        var switchDisplay = function(collections){
            resetGUI();
            if(collections.total){
                collections.sakai = sakai;
                sakai.api.Util.TemplateRenderer("collections_collections_list_template", collections, $(collectionsCollectionsList));
                $(collectionsCollectionsList).show();
                $("#collections_carousel").jcarousel({
                    animation: "slow",
                    easing: "swing",
                    scroll: 4,
                    start: 0,
                    initCallback: carouselBinding,
                    itemFallbackDimension: 77
                });
                if (collections.total > 4) {
                    $(collectionsScrollArrow).show();
                    $(collectionsSeeAllButton).show();
                    $(collectionsSeeAllButtonTotal).text("" + sakai.api.Content.Collections.getMyCollectionsCount());
                } else {
                    $(collectionsScrollArrow).hide();
                    $(collectionsSeeAllButton).hide();
                }
                initializeDesktopDD(collections.results);
            } else {
                $(collectionsNoCollections).show();
            }
        };

        var carouselBinding = function(carousel){
            $("#collections_scroll_right").unbind("click");
            $("#collections_scroll_right").bind("click", function(){
                carousel.next();
            });
            $("#collections_scroll_left").unbind("click");
            $("#collections_scroll_left").bind("click", function(){
                carousel.prev();
            });
        };

        var expandCollection = function(){
            if($(this).hasClass(collectionsLargePreview) && !$(this).hasClass("fixed-collapsed")){
                var pageOn = parseInt($(this).attr("data-sakai-page"), 10);
                var collectionId = $(this).attr("data-sakai-collection-id");
                $("." + collectionsLargePreview + "[data-sakai-page='" + pageOn + "']").addClass("collapsed");
                $("." + collectionsLargePreview + "[data-sakai-page='" + pageOn + "'] .collections_collection_title_short").show();
                $("." + collectionsLargePreview + "[data-sakai-page='" + pageOn + "'] .collections_collection_title_long").hide();
                $(this).removeClass("collapsed");
                $(".collections_collection_title_short", $(this)).hide();
                $(".collections_collection_title_long", $(this)).show();
                getRecentContent(collectionId);
            }
        };

        var focusCollectionTitle = function(){
            $('#collection_title_0').focus();
        };

        var createNewCollection = function(){
            $("#collections_collection_title").attr("disabled", "disabled");
            sakai.api.Util.progressIndicator.showProgressIndicator(sakai.api.i18n.getValueForKey("CREATING_YOUR_COLLECTION", "collections"), sakai.api.i18n.getValueForKey("WONT_BE_LONG", "collections"));
            var title = $.trim($("#collections_collection_title").val()) || sakai.api.i18n.getValueForKey("UNTITLED_COLLECTION", "collections");
            var permissions = $(collectionsNewCollectionPermission).val();
            sakai.api.Content.Collections.createCollection(title, "", permissions, [], contentToAdd, [], function(){
                getCollections(false);
                $("#topnavigation_user_collections_total").text("" + sakai.api.Content.Collections.getMyCollectionsCount());
                sakai.api.Util.progressIndicator.hideProgressIndicator();
                $("#collections_collection_title").val("");
                $("#collections_collection_title").removeAttr("disabled");
                sakai.api.Util.notification.show(sakai.api.i18n.getValueForKey("COLLECTION_CREATED"), sakai.api.i18n.getValueForKey("COLLECTION_CREATED_LONG"));
                var t = setTimeout(focusCollectionTitle, 1000);
            });
        };

        ///////////////////////////////////////////
        // RETRIEVE RECENT CONTENT IN COLLECTION //
        ///////////////////////////////////////////

        var getRecentContent = function(collectionIds){
            if (_.isString(collectionIds)){
                collectionIds = [collectionIds];
            }
            var batchRequest = [];
            $.each(collectionIds, function(index, collectionId){
                batchRequest.push({
                    "url": sakai.config.URL.POOLED_CONTENT_SPECIFIC_USER,
                    "method":"GET",
                    "cache":false,
                    "dataType":"json",
                    "parameters": {
                        "sortOn": "_lastModified",
                        "sortOrder": "desc",
                        "userid": sakai.api.Content.Collections.getCollectionGroupId(collectionId),
                        "items": 3,
                        "page": 0
                    }
                });
            });
            sakai.api.Server.batch(batchRequest, function(success, response){
                $.each(response.results, function(i, dataItem){
                    var contentItems = $.parseJSON(dataItem.body);
                    contentItems.sakai = sakai;
                    $("ul[data-sakai-collection-id='" + collectionIds[i] + "']").html(sakai.api.Util.TemplateRenderer("collections_collections_recentcontent_template", contentItems));
                });
            });
        };

        /////////////////////////////////////////
        // DRAG AND DROP ITEMS IN FROM DESKTOP //
        /////////////////////////////////////////

        var filesToUpload = [];

        var finishInitializeDD = function(collectionid, permissions){
            $("#collection_drop_" + collectionid).fileupload({
                url: "/system/pool/createfile",
                drop: function (ev, data) {
                    ev.stopPropagation();
                    ev.preventDefault();
                    if (($(ev.target).is("#collection_drop_" + collectionid) || $("#collection_drop_" + collectionid).find($(ev.target)).length) && data.files){
                        $.each(data.files, function (index, file) {
                            if (file.size > 0){
                                filesToUpload.push(file);
                            }
                        });
                        if (filesToUpload.length){
                            sakai.api.Util.progressIndicator.showProgressIndicator(sakai.api.i18n.getValueForKey("UPLOADING_CONTENT_ADDING_TO_COLLECTION", "collections"), sakai.api.i18n.getValueForKey("WONT_BE_LONG", "collections"));
                            uploadFile(collectionid, permissions);
                        }
                    }
                }
            });
        };

        var addToCollectionCount = function(collectionId, amount){
            var $contentCountEl = $("." + collectionsLargePreview + "[data-sakai-collection-id='" + collectionId + "'] .collections_collection_content_count");
            var currentAmount = parseInt($contentCountEl.text(), 10);
            $contentCountEl.text("" + (currentAmount + amount));
            $contentCountEl.attr("title", "" + (currentAmount + amount) + " " + sakai.api.i18n.getValueForKey("CONTENT_ITEMS"));
        };

        var uploadFile = function(collectionId, permissions){
            if (filesToUpload.length){
                var fileToUpload = filesToUpload[0];
                var splitOnDot = fileToUpload.name.split(".");
                var xhReq = new XMLHttpRequest();
                xhReq.open("POST", "/system/pool/createfile", false);
                var formData = new FormData();
                formData.append("enctype", "multipart/form-data");
                formData.append("filename", fileToUpload.name);
                formData.append("file", fileToUpload);
                xhReq.send(formData);
                if (xhReq.status == 201){
                    var data = $.parseJSON(xhReq.responseText);
                    var poolid = data[fileToUpload.name].poolId;
                    var batchRequests = [];
                    batchRequests.push({
                        "url": "/p/" + poolid,
                        "method": "POST",
                        "parameters": {
                            "sakai:pooled-content-file-name": fileToUpload.name,
                            "sakai:permissions": permissions,
                            "sakai:copyright": "creativecommons",
                            "sakai:allowcomments": "true",
                            "sakai:showcomments": "true",
                            "sakai:fileextension": splitOnDot[splitOnDot.length - 1]
                        }
                    });

                    // Set initial version
                    batchRequests.push({
                        "url": "/p/" + poolid + ".save.json",
                        "method": "POST"
                    });

                    sakai.api.Server.batch(batchRequests, function(success, response){
                        // Set the correct file permissions
                        sakai.api.Content.setFilePermissions([{"hashpath": poolid, "permissions": permissions}], function(){
                            // Add it to the collection
                            sakai.api.Content.Collections.addToCollection(collectionId, poolid, function(){
                                addToCollectionCount(collectionId, 1);
                                filesToUpload.splice(0, 1);
                                uploadFile(collectionId, permissions);
                            });
                        });
                    });
                } else {
                    filesToUpload.splice(0, 1);
                    uploadFile(collectionId, permissions);
                }
            } else {
                setTimeout(function(){
                    getRecentContent(collectionId);
                    sakai.api.Util.progressIndicator.hideProgressIndicator();
                }, 500);
            }
        };

        var initializeDesktopDD = function(collections){
            // Initialize drag and drop from desktop
            $.each(collections, function(index, collection){
                finishInitializeDD(collection["_path"], collection["sakai:permissions"]);
            });
        };

        ////////////////////////////////////////
        // DRAG AND DROP ITEMS IN FROM SYSTEM //
        ////////////////////////////////////////

        $(window).bind("drop.collections.sakai", function(ev, data, target){
            var collectionId = target.attr("data-sakai-collection-id");
            var collectedContent = [];
            var collectedCollections = [];
            $.each(data, function(index, item){
                if (item.collection){
                    collectedCollections.push(item.entityid);
                } else {
                    collectedContent.push(item.entityid);
                }
            });
            if (collectedContent.length + collectedCollections.length > 0) {
                sakai.api.Util.progressIndicator.showProgressIndicator(sakai.api.i18n.getValueForKey("UPLOADING_CONTENT_ADDING_TO_COLLECTION", "collections"), sakai.api.i18n.getValueForKey("WONT_BE_LONG", "collections"));
                sakai.api.Content.Collections.addToCollection(collectionId, collectedContent, function(){
                    sakai.api.Content.Collections.shareCollection(collectedCollections, sakai.api.Content.Collections.getCollectionGroupId(collectionId), false, function(){
                        setTimeout(function(){
                            addToCollectionCount(collectionId, collectedCollections.length + collectedContent.length);
                            getRecentContent(collectionId);
                            sakai.api.Util.progressIndicator.hideProgressIndicator();
                        }, 1000);
                    });
                });
            }
        });

        ////////////////////
        // INITIALIZATION //
        ////////////////////

        /**
         * Retrieve the collections and render the appropriate display
         */
        var getCollections = function(cache){
            // Get Collections
            sakai.api.Content.Collections.getMyCollections(0, itemsToShow, function(data){
                // Decide what screen to show depending on results
                switchDisplay(data);
                var recentContentToLoad = [];
                for (var i = 0; i < data.results.length; i = i + 4){
                    recentContentToLoad.push(data.results[i]["_path"]);
                }
                getRecentContent(recentContentToLoad);
            }, cache);
        };

        /**
         * Show/hide the collections inlay
         */
        var toggleCollectionsInlay = function(){
            $(collectionsScrollArrow).hide();
            $(collectionsCollectionsList).hide();
            $(collectionsSeeAllButton).hide();
            $(collectionsNoCollections).hide();
            $(collectionsAddNewContainer).hide();
            if (!$collectionsWidget.is(":visible")){
                getCollections();
            }
            $collectionsWidget.animate({
                'margin-bottom': 'toggle',
                height: 'toggle',
                opacity: 'toggle',
                'padding-top': 'toggle',
                'padding-bottom': 'toggle'
            }, 400, function(){
                if ($collectionsWidget.is(":visible")){
                    getCollections();
                    $("#collections_leftcolumn").focus();
                } else {
                    $(collectionsScrollArrow).hide();
                    $(collectionsCollectionsList).hide();
                    $(collectionsSeeAllButton).hide();
                    $(collectionsNoCollections).hide();
                }
            });
        };

        /**
         * Add binding to various elements in the widget
         */
        var addBinding = function(){
            $(subnavigationAddCollectionLink).live("click", initializeNewCollectionsSetup);
            $(collectionsCloseButton).live("click", toggleCollectionsInlay);
            $(collectorToggle).live("click", toggleCollectionsInlay);
            $(collectionsNewButton).live("click", initializeNewCollectionsSetup);
            $(collectionsCancelNewButton).live("click", getCollections);
            $("." + collectionsLargePreview).live("click", expandCollection);
            $(collectionsSaveNewButton).live("click", createNewCollection);
            $(window).bind("create.collections.sakai", initializeNewCollectionsSetup);
            // Save the new collection when enter is pressed
            $("#collections_collection_title").bind("keydown", function(ev, data){
                if (ev.keyCode === 13){
                    createNewCollection();
                }
            });
        };

        addBinding();

    };

    // inform Sakai OAE that this widget has loaded and is ready to run
    sakai.api.Widgets.widgetLoader.informOnLoad("collections");
});
<commit_msg>SAKIII-4809 removed duplicate request to fetch collections<commit_after>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you 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.
 */

// load the master sakai object to access all Sakai OAE API methods
require(["jquery", "sakai/sakai.api.core", "underscore"], function($, sakai, _) {

    /**
     * @name sakai_global.collections
     *
     * @class collections
     *
     * @description
     * My Hello World is a dashboard widget that says hello to the current user
     * with text in the color of their choosing
     *
     * @version 0.0.1
     * @param {String} tuid Unique id of the widget
     * @param {Boolean} showSettings Show the settings of the widget or not
     */
    sakai_global.collections = function (tuid, showSettings) {

        var itemsToShow = 20;
        var contentToAdd = [];

        var subnavigationAddCollectionLink = "#subnavigation_add_collection_link";
        var collectorToggle = ".collector_toggle";
        var collectionsTotal = "#topnavigation_user_collections_total";
        var $collectionsWidget = $(".collections_widget");

        var collectionsNoCollections = "#collections_nocollections";
        var collectionsCollectionsList = "#collections_collections_list";

        // Buttons, links, etc.
        var collectionsCloseButton = "#collections_close_button";
        var collectionsNewButton = "#collections_new_button";
        var collectionsAddNewContainer = "#collections_add_new";
        var collectionsNewActionButtons = "#collections_new_action_buttons";
        var collectionsCancelNewButton = ".collections_cancel_new_button";
        var collectionsMainCancelNewButton = "#collections_main_cancel_new_button";
        var collectionsAddNewNextStepLabel = ".collections_add_new_nextsteplabel";
        var collectionsSeeAllButton = "#collections_see_all_button";
        var collectionsSeeAllButtonTotal = "#collections_see_all_total_count";
        var collectionsSaveNewButton = "#collections_save_new_button";
        var collectionsNewCollectionPermission = "#collections_newcollection_permissions";
        var collectionCountsContentCountsNew = "#collection_counts_content_counts_new";
        var collectionsCollectionTitle = "#collections_collection_title";

        // Classes
        var collectionsAddNewSteps = ".collections_add_new_steps";
        var collectionsScrollArrow = ".collections_scroll_arrow";
        var collectionsLargePreview = "collections_large_preview";

        // New collection steps
        var collectionsAddNewStepOne = "#collections_add_new_stepone";
        var collectionsAddNewStepTwo = "#collections_add_new_steptwo";
        var collectionsAddNewStepThree = "#collections_add_new_stepthree";

        ///////////////////////////
        // CREATE NEW COLLECTION //
        ///////////////////////////

        var resetGUI = function(){
            $(collectionsAddNewSteps).hide();
            $(collectionsAddNewContainer).hide();
            $(collectionsNewActionButtons).hide();
            $(collectionsCollectionsList).hide();
            $(collectionsScrollArrow).hide();
            $(collectionsSeeAllButton).hide();
            $(collectionsAddNewStepOne).show();
            $(collectionsNewButton).show();
        };

        /**
        * Enable creation of collection and enable elements
        */
        var initializeNewCollectionsSetup = function(ev, _contentToAdd){
            resetGUI();
            contentToAdd = _contentToAdd || [];
            $(collectionCountsContentCountsNew).text("" + contentToAdd.length);
            $(collectionsNewButton).hide();
            $(collectionsNoCollections).hide();
            $(collectionsAddNewContainer).show();
            $(collectionsNewActionButtons).show();
            if (!$collectionsWidget.is(":visible")){
                $collectionsWidget.animate({
                    'margin-bottom': 'toggle',
                    'height': 'toggle',
                    'opacity': 'toggle',
                    'padding-top': 'toggle',
                    'padding-bottom': 'toggle'
               }, 400, function(){
                 $(collectionsCollectionTitle).focus();
               });
            }
        };

        /**
        * Determine the screen to display
        */
        var switchDisplay = function(collections){
            resetGUI();
            if(collections.total){
                collections.sakai = sakai;
                sakai.api.Util.TemplateRenderer("collections_collections_list_template", collections, $(collectionsCollectionsList));
                $(collectionsCollectionsList).show();
                $("#collections_carousel").jcarousel({
                    animation: "slow",
                    easing: "swing",
                    scroll: 4,
                    start: 0,
                    initCallback: carouselBinding,
                    itemFallbackDimension: 77
                });
                if (collections.total > 4) {
                    $(collectionsScrollArrow).show();
                    $(collectionsSeeAllButton).show();
                    $(collectionsSeeAllButtonTotal).text("" + sakai.api.Content.Collections.getMyCollectionsCount());
                } else {
                    $(collectionsScrollArrow).hide();
                    $(collectionsSeeAllButton).hide();
                }
                initializeDesktopDD(collections.results);
            } else {
                $(collectionsNoCollections).show();
            }
        };

        var carouselBinding = function(carousel){
            $("#collections_scroll_right").unbind("click");
            $("#collections_scroll_right").bind("click", function(){
                carousel.next();
            });
            $("#collections_scroll_left").unbind("click");
            $("#collections_scroll_left").bind("click", function(){
                carousel.prev();
            });
        };

        var expandCollection = function(){
            if($(this).hasClass(collectionsLargePreview) && !$(this).hasClass("fixed-collapsed")){
                var pageOn = parseInt($(this).attr("data-sakai-page"), 10);
                var collectionId = $(this).attr("data-sakai-collection-id");
                $("." + collectionsLargePreview + "[data-sakai-page='" + pageOn + "']").addClass("collapsed");
                $("." + collectionsLargePreview + "[data-sakai-page='" + pageOn + "'] .collections_collection_title_short").show();
                $("." + collectionsLargePreview + "[data-sakai-page='" + pageOn + "'] .collections_collection_title_long").hide();
                $(this).removeClass("collapsed");
                $(".collections_collection_title_short", $(this)).hide();
                $(".collections_collection_title_long", $(this)).show();
                getRecentContent(collectionId);
            }
        };

        var focusCollectionTitle = function(){
            $('#collection_title_0').focus();
        };

        var createNewCollection = function(){
            $("#collections_collection_title").attr("disabled", "disabled");
            sakai.api.Util.progressIndicator.showProgressIndicator(sakai.api.i18n.getValueForKey("CREATING_YOUR_COLLECTION", "collections"), sakai.api.i18n.getValueForKey("WONT_BE_LONG", "collections"));
            var title = $.trim($("#collections_collection_title").val()) || sakai.api.i18n.getValueForKey("UNTITLED_COLLECTION", "collections");
            var permissions = $(collectionsNewCollectionPermission).val();
            sakai.api.Content.Collections.createCollection(title, "", permissions, [], contentToAdd, [], function(){
                getCollections(false);
                $("#topnavigation_user_collections_total").text("" + sakai.api.Content.Collections.getMyCollectionsCount());
                sakai.api.Util.progressIndicator.hideProgressIndicator();
                $("#collections_collection_title").val("");
                $("#collections_collection_title").removeAttr("disabled");
                sakai.api.Util.notification.show(sakai.api.i18n.getValueForKey("COLLECTION_CREATED"), sakai.api.i18n.getValueForKey("COLLECTION_CREATED_LONG"));
                var t = setTimeout(focusCollectionTitle, 1000);
            });
        };

        ///////////////////////////////////////////
        // RETRIEVE RECENT CONTENT IN COLLECTION //
        ///////////////////////////////////////////

        var getRecentContent = function(collectionIds){
            if (_.isString(collectionIds)){
                collectionIds = [collectionIds];
            }
            var batchRequest = [];
            $.each(collectionIds, function(index, collectionId){
                batchRequest.push({
                    "url": sakai.config.URL.POOLED_CONTENT_SPECIFIC_USER,
                    "method":"GET",
                    "cache":false,
                    "dataType":"json",
                    "parameters": {
                        "sortOn": "_lastModified",
                        "sortOrder": "desc",
                        "userid": sakai.api.Content.Collections.getCollectionGroupId(collectionId),
                        "items": 3,
                        "page": 0
                    }
                });
            });
            sakai.api.Server.batch(batchRequest, function(success, response){
                $.each(response.results, function(i, dataItem){
                    var contentItems = $.parseJSON(dataItem.body);
                    contentItems.sakai = sakai;
                    $("ul[data-sakai-collection-id='" + collectionIds[i] + "']").html(sakai.api.Util.TemplateRenderer("collections_collections_recentcontent_template", contentItems));
                });
            });
        };

        /////////////////////////////////////////
        // DRAG AND DROP ITEMS IN FROM DESKTOP //
        /////////////////////////////////////////

        var filesToUpload = [];

        var finishInitializeDD = function(collectionid, permissions){
            $("#collection_drop_" + collectionid).fileupload({
                url: "/system/pool/createfile",
                drop: function (ev, data) {
                    ev.stopPropagation();
                    ev.preventDefault();
                    if (($(ev.target).is("#collection_drop_" + collectionid) || $("#collection_drop_" + collectionid).find($(ev.target)).length) && data.files){
                        $.each(data.files, function (index, file) {
                            if (file.size > 0){
                                filesToUpload.push(file);
                            }
                        });
                        if (filesToUpload.length){
                            sakai.api.Util.progressIndicator.showProgressIndicator(sakai.api.i18n.getValueForKey("UPLOADING_CONTENT_ADDING_TO_COLLECTION", "collections"), sakai.api.i18n.getValueForKey("WONT_BE_LONG", "collections"));
                            uploadFile(collectionid, permissions);
                        }
                    }
                }
            });
        };

        var addToCollectionCount = function(collectionId, amount){
            var $contentCountEl = $("." + collectionsLargePreview + "[data-sakai-collection-id='" + collectionId + "'] .collections_collection_content_count");
            var currentAmount = parseInt($contentCountEl.text(), 10);
            $contentCountEl.text("" + (currentAmount + amount));
            $contentCountEl.attr("title", "" + (currentAmount + amount) + " " + sakai.api.i18n.getValueForKey("CONTENT_ITEMS"));
        };

        var uploadFile = function(collectionId, permissions){
            if (filesToUpload.length){
                var fileToUpload = filesToUpload[0];
                var splitOnDot = fileToUpload.name.split(".");
                var xhReq = new XMLHttpRequest();
                xhReq.open("POST", "/system/pool/createfile", false);
                var formData = new FormData();
                formData.append("enctype", "multipart/form-data");
                formData.append("filename", fileToUpload.name);
                formData.append("file", fileToUpload);
                xhReq.send(formData);
                if (xhReq.status == 201){
                    var data = $.parseJSON(xhReq.responseText);
                    var poolid = data[fileToUpload.name].poolId;
                    var batchRequests = [];
                    batchRequests.push({
                        "url": "/p/" + poolid,
                        "method": "POST",
                        "parameters": {
                            "sakai:pooled-content-file-name": fileToUpload.name,
                            "sakai:permissions": permissions,
                            "sakai:copyright": "creativecommons",
                            "sakai:allowcomments": "true",
                            "sakai:showcomments": "true",
                            "sakai:fileextension": splitOnDot[splitOnDot.length - 1]
                        }
                    });

                    // Set initial version
                    batchRequests.push({
                        "url": "/p/" + poolid + ".save.json",
                        "method": "POST"
                    });

                    sakai.api.Server.batch(batchRequests, function(success, response){
                        // Set the correct file permissions
                        sakai.api.Content.setFilePermissions([{"hashpath": poolid, "permissions": permissions}], function(){
                            // Add it to the collection
                            sakai.api.Content.Collections.addToCollection(collectionId, poolid, function(){
                                addToCollectionCount(collectionId, 1);
                                filesToUpload.splice(0, 1);
                                uploadFile(collectionId, permissions);
                            });
                        });
                    });
                } else {
                    filesToUpload.splice(0, 1);
                    uploadFile(collectionId, permissions);
                }
            } else {
                setTimeout(function(){
                    getRecentContent(collectionId);
                    sakai.api.Util.progressIndicator.hideProgressIndicator();
                }, 500);
            }
        };

        var initializeDesktopDD = function(collections){
            // Initialize drag and drop from desktop
            $.each(collections, function(index, collection){
                finishInitializeDD(collection["_path"], collection["sakai:permissions"]);
            });
        };

        ////////////////////////////////////////
        // DRAG AND DROP ITEMS IN FROM SYSTEM //
        ////////////////////////////////////////

        $(window).bind("drop.collections.sakai", function(ev, data, target){
            var collectionId = target.attr("data-sakai-collection-id");
            var collectedContent = [];
            var collectedCollections = [];
            $.each(data, function(index, item){
                if (item.collection){
                    collectedCollections.push(item.entityid);
                } else {
                    collectedContent.push(item.entityid);
                }
            });
            if (collectedContent.length + collectedCollections.length > 0) {
                sakai.api.Util.progressIndicator.showProgressIndicator(sakai.api.i18n.getValueForKey("UPLOADING_CONTENT_ADDING_TO_COLLECTION", "collections"), sakai.api.i18n.getValueForKey("WONT_BE_LONG", "collections"));
                sakai.api.Content.Collections.addToCollection(collectionId, collectedContent, function(){
                    sakai.api.Content.Collections.shareCollection(collectedCollections, sakai.api.Content.Collections.getCollectionGroupId(collectionId), false, function(){
                        setTimeout(function(){
                            addToCollectionCount(collectionId, collectedCollections.length + collectedContent.length);
                            getRecentContent(collectionId);
                            sakai.api.Util.progressIndicator.hideProgressIndicator();
                        }, 1000);
                    });
                });
            }
        });

        ////////////////////
        // INITIALIZATION //
        ////////////////////

        /**
         * Retrieve the collections and render the appropriate display
         */
        var getCollections = function(cache){
            // Get Collections
            sakai.api.Content.Collections.getMyCollections(0, itemsToShow, function(data){
                // Decide what screen to show depending on results
                switchDisplay(data);
                var recentContentToLoad = [];
                for (var i = 0; i < data.results.length; i = i + 4){
                    recentContentToLoad.push(data.results[i]["_path"]);
                }
                getRecentContent(recentContentToLoad);
            }, cache);
        };

        /**
         * Show/hide the collections inlay
         */
        var toggleCollectionsInlay = function(){
            $(collectionsScrollArrow).hide();
            $(collectionsCollectionsList).hide();
            $(collectionsSeeAllButton).hide();
            $(collectionsNoCollections).hide();
            $(collectionsAddNewContainer).hide();
            if (!$collectionsWidget.is(":visible")){
                getCollections();
            }
            $collectionsWidget.animate({
                'margin-bottom': 'toggle',
                height: 'toggle',
                opacity: 'toggle',
                'padding-top': 'toggle',
                'padding-bottom': 'toggle'
            }, 400, function(){
                if ($collectionsWidget.is(":visible")){
                    $("#collections_leftcolumn").focus();
                } else {
                    $(collectionsScrollArrow).hide();
                    $(collectionsCollectionsList).hide();
                    $(collectionsSeeAllButton).hide();
                    $(collectionsNoCollections).hide();
                }
            });
        };

        /**
         * Add binding to various elements in the widget
         */
        var addBinding = function(){
            $(subnavigationAddCollectionLink).live("click", initializeNewCollectionsSetup);
            $(collectionsCloseButton).live("click", toggleCollectionsInlay);
            $(collectorToggle).live("click", toggleCollectionsInlay);
            $(collectionsNewButton).live("click", initializeNewCollectionsSetup);
            $(collectionsCancelNewButton).live("click", getCollections);
            $("." + collectionsLargePreview).live("click", expandCollection);
            $(collectionsSaveNewButton).live("click", createNewCollection);
            $(window).bind("create.collections.sakai", initializeNewCollectionsSetup);
            // Save the new collection when enter is pressed
            $("#collections_collection_title").bind("keydown", function(ev, data){
                if (ev.keyCode === 13){
                    createNewCollection();
                }
            });
        };

        addBinding();

    };

    // inform Sakai OAE that this widget has loaded and is ready to run
    sakai.api.Widgets.widgetLoader.informOnLoad("collections");
});
<|endoftext|>