<commit_before>/*
This file is part of Archivematica.

Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>

Archivematica is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Archivematica is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Archivematica.  If not, see <http://www.gnu.org/licenses/>.
*/

var TransferComponentFormView = Backbone.View.extend({
  initialize: function(options) {
    this.form_layout_template = _.template(options.form_layout_template);
    this.modal_template = options.modal_template;
    this.sourceDirectories = options.sourceDirectories;
  },

  showSelector: function(sourceDir) {

   // display action selector in modal window
    $(this.modal_template).modal({show: true});

    // make it destroy rather than hide modal
    $('#transfer-component-select-close, #transfer-component-select-cancel')
      .click(function() {
        $('#transfer-component-select-modal').remove();
      });

    // add directory selector
    createDirectoryPicker(
      sourceDir,
      'transfer-component-select-modal',
      'path_container'
    );
  },

  addedPaths: function() {
    var paths = [];
    $('.transfer_path').each(function() {
      paths.push($(this).text());
    });
    return paths;
  },

  startTransfer: function(transfer) {
    var path;

    $('.transfer-component-activity-indicator').show();
    // get path to temp directory in which to copy individual transfer
    // components
    $.ajax({
      url: '/filesystem/get_temp_directory/',
      type: 'GET',
      cache: false,
      success: function(results) {

        var tempDir = results.tempDir;

        // copy each transfer component to the temp directory
        for (var index in transfer.sourcePaths) {
          path = transfer.sourcePaths[index];

          $.ajax({
            url: '/filesystem/copy_transfer_component/',
            type: 'POST',
            async: false,
            cache: false,
            data: {
              name:        transfer.name,
              path:        path,
              destination: tempDir
            },
            success: function(results) {
              if (results['error']) {
                alert(results.message);
              }
            }
          });
        }

        // move from temp directory to appropriate watchdir
        var url = '/filesystem/ransfer/'
          , isZipFile = path.toLowerCase().indexOf('.zip') != -1
          , filepath;

        // if transfer is a ZIP file, then extract basename add to temporary directory
        if (isZipFile) {
          filepath = tempDir + '/' + path.replace(/\\/g,'/').replace( /.*\//, '' );
        } else {
          filepath = tempDir + '/' + transfer.name;
        }

        $.ajax({
          url: url,
          type: 'POST',
          async: false,
          cache: false,
          data: {
            filepath:  filepath,
            type:      transfer.type,
            accession: transfer.accessionNumber
          },
          success: function(results) {
            if (results['error']) {
              alert(results.message);
            }

            $('#transfer-name').val('');
            $('#transfer-name-container').show();
            $('#transfer-type').val('standard');
            $('#path_container').html('');
            $('.transfer-component-activity-indicator').hide();
          }
        });
        // report progress
      }
    });
  },

  render: function() {
    var $pathAreaEl = $('

')
       , $pathContainerEl = $('

');

    this.pathContainerEl = $pathContainerEl;

    // add button to add paths via a pop-up selector
    var $buttonContainer = $('

')
      , $addButton = $('Browse')
      , $sourceDirSelect = $('<select id="path_source_select"></select>')
      , $startTransferButton = $('Start transfer')
      , self = this;

    $buttonContainer
      .append($sourceDirSelect)
      .append($addButton)
      .append($startTransferButton);

    $pathAreaEl.append($buttonContainer);

    // add path container to parent container
    $pathAreaEl.append($pathContainerEl);

    // populate select with source directory values
    $.each(this.sourceDirectories, function(id, path) {
      $sourceDirSelect
        .append($("<option></option>")
        .attr("value", id)
        .text(path));
    });

    // populate view's DOM element with template output
    var context = {
      transfer_paths: $pathAreaEl.html()
    };
    $(this.el).html(this.form_layout_template(context));

    // make add button clickable
    $('#path_add_button').click(function() {
      // add modal containing directory selector
      // selecting makes modal disappear, adds directory, and re-renders
      self.showSelector($('#path_source_select').children(':selected').text());
    });

    // add logic to determine whether or not transfer name needs to be
    // visible if transfer type changed
    $('#transfer-type').change(function() {
      if ($(this).val() == 'zipped bag') {
        $('#transfer-name-container').hide('slide', {direction: 'left'}, 250);
      } else {
        $('#transfer-name-container').show('slide', {direction: 'left'}, 250);
      }
    });

    // make start transfer button clickable
    $('#start_transfer_button').click(function() {
      var transferName = $('#transfer-name').val();

      // if transfering a zipped bag, give it a dummy name
      if ($('#transfer-type').val() == 'zipped bag') {
        transferName = 'ZippedBag';
      }

      if (!transferName)
      {
        alert('Please enter a transfer name');
      } else {
        if (!self.addedPaths().length) {
          alert('Please click "Browse" to add one or more paths from the source directory.');
        } else {
          var transferData = {
            'name':            transferName,
            'type':            $('#transfer-type').val(),
            'accessionNumber': $('#transfer-accession-number').val(),
            'sourcePaths':     self.addedPaths()
          };
          self.startTransfer(transferData);
        }
      }
    });
  }
});
<commit_msg>Blank accession number after starting transfer.<commit_after>/*
This file is part of Archivematica.

Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>

Archivematica is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Archivematica is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Archivematica.  If not, see <http://www.gnu.org/licenses/>.
*/

var TransferComponentFormView = Backbone.View.extend({
  initialize: function(options) {
    this.form_layout_template = _.template(options.form_layout_template);
    this.modal_template = options.modal_template;
    this.sourceDirectories = options.sourceDirectories;
  },

  showSelector: function(sourceDir) {

   // display action selector in modal window
    $(this.modal_template).modal({show: true});

    // make it destroy rather than hide modal
    $('#transfer-component-select-close, #transfer-component-select-cancel')
      .click(function() {
        $('#transfer-component-select-modal').remove();
      });

    // add directory selector
    createDirectoryPicker(
      sourceDir,
      'transfer-component-select-modal',
      'path_container'
    );
  },

  addedPaths: function() {
    var paths = [];
    $('.transfer_path').each(function() {
      paths.push($(this).text());
    });
    return paths;
  },

  startTransfer: function(transfer) {
    var path;

    $('.transfer-component-activity-indicator').show();
    // get path to temp directory in which to copy individual transfer
    // components
    $.ajax({
      url: '/filesystem/get_temp_directory/',
      type: 'GET',
      cache: false,
      success: function(results) {

        var tempDir = results.tempDir;

        // copy each transfer component to the temp directory
        for (var index in transfer.sourcePaths) {
          path = transfer.sourcePaths[index];

          $.ajax({
            url: '/filesystem/copy_transfer_component/',
            type: 'POST',
            async: false,
            cache: false,
            data: {
              name:        transfer.name,
              path:        path,
              destination: tempDir
            },
            success: function(results) {
              if (results['error']) {
                alert(results.message);
              }
            }
          });
        }

        // move from temp directory to appropriate watchdir
        var url = '/filesystem/ransfer/'
          , isZipFile = path.toLowerCase().indexOf('.zip') != -1
          , filepath;

        // if transfer is a ZIP file, then extract basename add to temporary directory
        if (isZipFile) {
          filepath = tempDir + '/' + path.replace(/\\/g,'/').replace( /.*\//, '' );
        } else {
          filepath = tempDir + '/' + transfer.name;
        }

        $.ajax({
          url: url,
          type: 'POST',
          async: false,
          cache: false,
          data: {
            filepath:  filepath,
            type:      transfer.type,
            accession: transfer.accessionNumber
          },
          success: function(results) {
            if (results['error']) {
              alert(results.message);
            }

            $('#transfer-name').val('');
            $('#transfer-accession-number').val('');
            $('#transfer-name-container').show();
            $('#transfer-type').val('standard');
            $('#path_container').html('');
            $('.transfer-component-activity-indicator').hide();
          }
        });
        // report progress
      }
    });
  },

  render: function() {
    var $pathAreaEl = $('

')
       , $pathContainerEl = $('

');

    this.pathContainerEl = $pathContainerEl;

    // add button to add paths via a pop-up selector
    var $buttonContainer = $('

')
      , $addButton = $('Browse')
      , $sourceDirSelect = $('<select id="path_source_select"></select>')
      , $startTransferButton = $('Start transfer')
      , self = this;

    $buttonContainer
      .append($sourceDirSelect)
      .append($addButton)
      .append($startTransferButton);

    $pathAreaEl.append($buttonContainer);

    // add path container to parent container
    $pathAreaEl.append($pathContainerEl);

    // populate select with source directory values
    $.each(this.sourceDirectories, function(id, path) {
      $sourceDirSelect
        .append($("<option></option>")
        .attr("value", id)
        .text(path));
    });

    // populate view's DOM element with template output
    var context = {
      transfer_paths: $pathAreaEl.html()
    };
    $(this.el).html(this.form_layout_template(context));

    // make add button clickable
    $('#path_add_button').click(function() {
      // add modal containing directory selector
      // selecting makes modal disappear, adds directory, and re-renders
      self.showSelector($('#path_source_select').children(':selected').text());
    });

    // add logic to determine whether or not transfer name needs to be
    // visible if transfer type changed
    $('#transfer-type').change(function() {
      if ($(this).val() == 'zipped bag') {
        $('#transfer-name-container').hide('slide', {direction: 'left'}, 250);
      } else {
        $('#transfer-name-container').show('slide', {direction: 'left'}, 250);
      }
    });

    // make start transfer button clickable
    $('#start_transfer_button').click(function() {
      var transferName = $('#transfer-name').val();

      // if transfering a zipped bag, give it a dummy name
      if ($('#transfer-type').val() == 'zipped bag') {
        transferName = 'ZippedBag';
      }

      if (!transferName)
      {
        alert('Please enter a transfer name');
      } else {
        if (!self.addedPaths().length) {
          alert('Please click "Browse" to add one or more paths from the source directory.');
        } else {
          var transferData = {
            'name':            transferName,
            'type':            $('#transfer-type').val(),
            'accessionNumber': $('#transfer-accession-number').val(),
            'sourcePaths':     self.addedPaths()
          };
          self.startTransfer(transferData);
        }
      }
    });
  }
});
<|endoftext|>


<commit_before>const chai = require('chai');
const expect = chai.expect;
const sinon  = require('sinon');

const kindOfRegularResponse = require('./fake-api/kind-of-regular-response.json');

const SuperRepo = require('../lib/index.js');
const defaultConfiguration = {
    storage: 'LOCAL_VARIABLE',
    name: 'test',
    outOfDateAfter: 3 * 1000, // 3 seconds
    request: () => new Promise(resolve => resolve(kindOfRegularResponse))
};

describe('Library import', function() {
    it('Should make SuperRepo instance available.', function() {
        expect(new SuperRepo(defaultConfiguration)).to.be.an.instanceof(SuperRepo);
    });
});

describe('Data Management', () => {
    var repository;

    before(() => {
        repository = new SuperRepo(defaultConfiguration);
    });

    it('Should resolve to the server-side data', done => {
        repository.getData().then( result => {
            expect(result).to.equal(kindOfRegularResponse);
        }).then(done, done);
    });

    it('Should resolve the same data, no matter if it is taken from cache or from a network request', done => {
        repository.getData().then( () => {
            repository.getData().then( () => {

                repository.getData().then( result => {
                    expect(result).to.equal(kindOfRegularResponse);
                }).then(done, done);
            });
        });
    });

    it('Should do a network request only once', done => {
        var networkRequestsCount = 0;

        const repo = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: 60 * 1000, // 1 min
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve(kindOfRegularResponse));
            }
        });

        repo.getData().then( () => {
            repo.getData().then( () => {

                repo.getData().then( result => {
                    expect(networkRequestsCount).to.equal(1);
                }).then(done, done);

            });
        });
    });

    it('Should wait if there is a Promise pending and should NOT fire another one', done => {
        let networkRequestsCount = 0;

        const repo = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: 60 * 1000, // 1 min
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve =>
                    setTimeout(() => resolve(kindOfRegularResponse), 1000)
                );
            }
        });

        repo.getData();
        repo.getData();
        repo.getData();

        repo.getData().then( result => {
            expect(networkRequestsCount).to.equal(1);
        }).then(done, done);
    });

});

describe('Data Sync', () => {
    var clock;

    beforeEach(() => {
        clock = sinon.useFakeTimers();
    });
    afterEach(() => {
        clock.restore();
    });

    it('Should initiate a background data sync process that fires a network request as soon as the data gets out of date. Initially, data is outdated, therefore, the process should start with a network request. ', done => {
        const TIMEFRAME = 60 * 1000; // 1 min
        let networkRequestsCount = 0;

        const repository = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: TIMEFRAME,
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve(kindOfRegularResponse));
            }
        });

        expect(networkRequestsCount).to.equal(0);

        repository.initSyncer().then( () => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(TIMEFRAME - 1);
            expect(networkRequestsCount).to.equal(1);

            clock.tick(1);
            expect(networkRequestsCount).to.equal(2);

            clock.tick(TIMEFRAME);
            expect(networkRequestsCount).to.equal(3);

            clock.tick(5 * TIMEFRAME);
            expect(networkRequestsCount).to.equal(8);
        }).then(done, done);
    });

    it('Should initiate a background data sync process that fires a network request as soon as the data gets out of date. Initially, data is NOT outdated, therefore, the process should NOT start with a network request. Case: there is NO delay between getting the data and initiating the sync process.', done => {
        const TIMEFRAME = 60 * 1000; // 1 min
        let networkRequestsCount = 0;

        const repo = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: TIMEFRAME,
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve(kindOfRegularResponse));
            }
        });

        repo.getData().then(() => {

            expect(networkRequestsCount).to.equal(1);

            repo.initSyncer().then( () => {
                expect(networkRequestsCount).to.equal(1);

                clock.tick(TIMEFRAME - 1);

                expect(networkRequestsCount).to.equal(1);

                clock.tick(1);
                expect(networkRequestsCount).to.equal(2);

                clock.tick(TIMEFRAME);
                expect(networkRequestsCount).to.equal(3);

                clock.tick(10 * TIMEFRAME);
                expect(networkRequestsCount).to.equal(13);
            }).then(done, done);

        });
    });

    it('Should initiate a background data sync process that fires a network request as soon as the data gets out of date. Initially, data is NOT outdated, therefore, the process should NOT start with a network request. Case: there is delay between getting the data and initiating the sync process.', done => {
        const TIMEFRAME = 60 * 1000; // 1 min
        let networkRequestsCount = 0;

        const repo = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: TIMEFRAME,
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve(kindOfRegularResponse));
            }
        });

        repo.getData().then(() => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(TIMEFRAME - 1000);

            repo.initSyncer().then( () => {
                expect(networkRequestsCount).to.equal(1);

                clock.tick(1000);
                expect(networkRequestsCount).to.equal(2);

                clock.tick(TIMEFRAME);
                expect(networkRequestsCount).to.equal(3);

                clock.tick(100 * TIMEFRAME);
                expect(networkRequestsCount).to.equal(103);
            }).then(done, done);
        });
    });
});
<commit_msg>Change: naming<commit_after>const chai = require('chai');
const expect = chai.expect;
const sinon  = require('sinon');

const kindOfRegularResponse = require('./fake-api/kind-of-regular-response.json');

const SuperRepo = require('../lib/index.js');
const defaultConfiguration = {
    storage: 'LOCAL_VARIABLE',
    name: 'test',
    outOfDateAfter: 3 * 1000, // 3 seconds
    request: () => new Promise(resolve => resolve(kindOfRegularResponse))
};

describe('Library import', function() {
    it('Should make SuperRepo instance available.', function() {
        expect(new SuperRepo(defaultConfiguration)).to.be.an.instanceof(SuperRepo);
    });
});

describe('Data Management', () => {
    var repository;

    before(() => {
        repository = new SuperRepo(defaultConfiguration);
    });

    it('Should resolve to the server-side data', done => {
        repository.getData().then( result => {
            expect(result).to.equal(kindOfRegularResponse);
        }).then(done, done);
    });

    it('Should resolve the same data, no matter if it is taken from cache or from a network request', done => {
        repository.getData().then( () => {
            repository.getData().then( () => {

                repository.getData().then( result => {
                    expect(result).to.equal(kindOfRegularResponse);
                }).then(done, done);
            });
        });
    });

    it('Should do a network request only once', done => {
        var networkRequestsCount = 0;

        const repo = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: 60 * 1000, // 1 min
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve(kindOfRegularResponse));
            }
        });

        repo.getData().then( () => {
            repo.getData().then( () => {

                repo.getData().then( result => {
                    expect(networkRequestsCount).to.equal(1);
                }).then(done, done);

            });
        });
    });

    it('Should wait if there is a Promise pending and should NOT fire another one', done => {
        let networkRequestsCount = 0;

        const repo = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: 60 * 1000, // 1 min
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve =>
                    setTimeout(() => resolve(kindOfRegularResponse), 1000)
                );
            }
        });

        repo.getData();
        repo.getData();
        repo.getData();

        repo.getData().then( result => {
            expect(networkRequestsCount).to.equal(1);
        }).then(done, done);
    });

});

describe('Data Sync', () => {
    var clock;

    beforeEach(() => {
        clock = sinon.useFakeTimers();
    });
    afterEach(() => {
        clock.restore();
    });

    it('Should initiate a background data sync process that fires a network request as soon as the data gets out of date. Initially, data is outdated, therefore, the process should start with a network request. ', done => {
        const TIMEFRAME = 60 * 1000; // 1 min
        let networkRequestsCount = 0;

        const repository = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: TIMEFRAME,
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve(kindOfRegularResponse));
            }
        });

        expect(networkRequestsCount).to.equal(0);

        repository.initSyncer().then( () => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(TIMEFRAME - 1);
            expect(networkRequestsCount).to.equal(1);

            clock.tick(1);
            expect(networkRequestsCount).to.equal(2);

            clock.tick(TIMEFRAME);
            expect(networkRequestsCount).to.equal(3);

            clock.tick(5 * TIMEFRAME);
            expect(networkRequestsCount).to.equal(8);
        }).then(done, done);
    });

    it('Should initiate a background data sync process that fires a network request as soon as the data gets out of date. Initially, data is NOT outdated, therefore, the process should NOT start with a network request. Case: there is NO delay between getting the data and initiating the sync process.', done => {
        const TIMEFRAME = 60 * 1000; // 1 min
        let networkRequestsCount = 0;

        const repository = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: TIMEFRAME,
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve(kindOfRegularResponse));
            }
        });

        repository.getData().then(() => {

            expect(networkRequestsCount).to.equal(1);

            repository.initSyncer().then( () => {
                expect(networkRequestsCount).to.equal(1);

                clock.tick(TIMEFRAME - 1);

                expect(networkRequestsCount).to.equal(1);

                clock.tick(1);
                expect(networkRequestsCount).to.equal(2);

                clock.tick(TIMEFRAME);
                expect(networkRequestsCount).to.equal(3);

                clock.tick(10 * TIMEFRAME);
                expect(networkRequestsCount).to.equal(13);
            }).then(done, done);

        });
    });

    it('Should initiate a background data sync process that fires a network request as soon as the data gets out of date. Initially, data is NOT outdated, therefore, the process should NOT start with a network request. Case: there is delay between getting the data and initiating the sync process.', done => {
        const TIMEFRAME = 60 * 1000; // 1 min
        let networkRequestsCount = 0;

        const repository = new SuperRepo({
            storage: 'LOCAL_VARIABLE',
            name: 'test',
            outOfDateAfter: TIMEFRAME,
            request: () => {
                networkRequestsCount++;

                return new Promise(resolve => resolve(kindOfRegularResponse));
            }
        });

        repository.getData().then(() => {
            expect(networkRequestsCount).to.equal(1);

            clock.tick(TIMEFRAME - 1000);

            repository.initSyncer().then( () => {
                expect(networkRequestsCount).to.equal(1);

                clock.tick(1000);
                expect(networkRequestsCount).to.equal(2);

                clock.tick(TIMEFRAME);
                expect(networkRequestsCount).to.equal(3);

                clock.tick(100 * TIMEFRAME);
                expect(networkRequestsCount).to.equal(103);
            }).then(done, done);
        });
    });
});
<|endoftext|>


<commit_before>const supertest = require('supertest')
const expect = require('chai').expect
const REFRESH_ORG_HIERARCHY_URI = '/refresh'
const app = require('../../../app/app')
const _ = require('underscore')

const workloadCapactiyHelper = require('../../helpers/data/aggregated-data-helper')
const organisationalHierarchyTree = require('../../../app/services/organisational-hierarchy-tree')

var inserts = []

describe(`${REFRESH_ORG_HIERARCHY_URI}`, function () {
  before(function (done) {
    workloadCapactiyHelper.addWorkloadCapacitiesForOffenderManager()
      .then(function (builtInserts) {
        inserts = builtInserts
        done()
      })
  })

  it('should refresh the hierarchy and the new inserts should appear', function (done) {
    var oldTree = organisationalHierarchyTree.get()
    console.log(oldTree)
    supertest(app)
        .get(REFRESH_ORG_HIERARCHY_URI)
        .expect(200)
        .then(function () {
          var tree = organisationalHierarchyTree.get()
          expect(oldTree).to.not.eql(tree)
          done()
        })
  })

  after(function (done) {
    workloadCapactiyHelper.removeInsertedData(inserts)
      .then(() => done())
  })
})
<commit_msg>699: Removing console.log and resolving standard issues.<commit_after>const supertest = require('supertest')
const expect = require('chai').expect
const REFRESH_ORG_HIERARCHY_URI = '/refresh'
const app = require('../../../app/app')

const workloadCapactiyHelper = require('../../helpers/data/aggregated-data-helper')
const organisationalHierarchyTree = require('../../../app/services/organisational-hierarchy-tree')

var inserts = []

describe(REFRESH_ORG_HIERARCHY_URI, function () {
  before(function (done) {
    workloadCapactiyHelper.addWorkloadCapacitiesForOffenderManager()
      .then(function (builtInserts) {
        inserts = builtInserts
        done()
      })
  })

  it('should refresh the hierarchy and the new inserts should appear', function (done) {
    var oldTree = organisationalHierarchyTree.get()
    supertest(app)
        .get(REFRESH_ORG_HIERARCHY_URI)
        .expect(200)
        .then(function () {
          var tree = organisationalHierarchyTree.get()
          expect(oldTree).to.not.eql(tree)
          done()
        })
  })

  after(function (done) {
    workloadCapactiyHelper.removeInsertedData(inserts)
      .then(() => done())
  })
})
<|endoftext|>


<commit_before>import _ from 'lodash';
import React from 'react';

import NodeDetailsTableNodeLink from './node-details-table-node-link';
import { formatMetric } from '../../utils/string-utils';

export default class NodeDetailsTable extends React.Component {

  constructor(props, context) {
    super(props, context);
    this.DEFAULT_LIMIT = 5;
    this.state = {
      limit: this.DEFAULT_LIMIT,
      sortedDesc: true,
      sortBy: null
    };
    this.handleLimitClick = this.handleLimitClick.bind(this);
    this.getValueForSortBy = this.getValueForSortBy.bind(this);
  }

  handleHeaderClick(ev, headerId) {
    ev.preventDefault();
    const sortedDesc = headerId === this.state.sortBy ? !this.state.sortedDesc : this.state.sortedDesc;
    const sortBy = headerId;
    this.setState({sortBy, sortedDesc});
  }

  handleLimitClick(ev) {
    ev.preventDefault();
    const limit = this.state.limit ? 0 : this.DEFAULT_LIMIT;
    this.setState({limit});
  }

  getDefaultSortBy() {
    // first metric
    return _.get(this.props.nodes, [0, 'metrics', 0, 'id']);
  }

  getMetaDataSorters() {
    // returns an array of sorters that will take a node
    return _.get(this.props.nodes, [0, 'metadata'], []).map((field, index) => {
      return node => node.metadata[index] ? node.metadata[index].value : null;
    });
  }

  getValueForSortBy(node) {
    // return the node's value based on the sortBy field
    const sortBy = this.state.sortBy || this.getDefaultSortBy();
    if (sortBy !== null) {
      const field = _.union(node.metrics, node.metadata).find(f => f.id === sortBy);
      if (field) {
        return field.value;
      }
    }
    return -1e-10; // just under 0 to treat missing values differently from 0
  }

  getValuesForNode(node) {
    const values = {};
    ['metrics', 'metadata'].forEach(collection => {
      if (node[collection]) {
        node[collection].forEach(field => {
          values[field.id] = field;
        });
      }
    });
    return values;
  }

  renderHeaders() {
    if (this.props.nodes && this.props.nodes.length > 0) {
      let headers = [{id: 'label', label: this.props.label}];
      // gather header labels from metrics and metadata
      const nodeValues = this.props.nodes.map(this.getValuesForNode);
      headers = headers.concat(this.props.columns.map(column => {
        // look for a node that has the column label
        const valuesWithField = nodeValues.find(values => values[column] !== undefined);
        if (valuesWithField) {
          return {id: column, label: valuesWithField[column].label};
        }
        // fall back on column id as label
        return {id: column, label: column};
      }));
      const defaultSortBy = this.getDefaultSortBy();

      return (

          {headers.map(header => {
            const headerClasses = ['node-details-table-header', 'truncate'];
            const onHeaderClick = ev => {
              this.handleHeaderClick(ev, header.id);
            };
            // sort by first metric by default
            const isSorted = this.state.sortBy !== null ? header.id === this.state.sortBy : header.id === defaultSortBy;
            const isSortedDesc = isSorted && this.state.sortedDesc;
            const isSortedAsc = isSorted && !isSortedDesc;
            if (isSorted) {
              headerClasses.push('node-details-table-header-sorted');
            }
            return (

                {isSortedAsc && }
                {isSortedDesc && }
                {header.label}

            );
          })}

      );
    }
    return '';
  }

  renderValues(node) {
    const fields = this.getValuesForNode(node);
    return this.props.columns.map(col => {
      const field = fields[col];
      if (field) {
        return (

            {formatMetric(field.value, field)}

        );
      }
    });
  }

  render() {
    const headers = this.renderHeaders();
    let nodes = _.sortByAll(this.props.nodes, this.getValueForSortBy, 'label', this.getMetaDataSorters());
    const limited = nodes && this.state.limit > 0 && nodes.length > this.state.limit;
    const showLimitAction = nodes && (limited || (this.state.limit === 0 && nodes.length > this.DEFAULT_LIMIT));
    const limitActionText = limited ? 'Show more' : 'Show less';
    if (this.state.sortedDesc) {
      nodes.reverse();
    }
    if (nodes && limited) {
      nodes = nodes.slice(0, this.state.limit);
    }

    return (

            {headers}

          {nodes && nodes.map(node => {
            const values = this.renderValues(node);
            return (

                  <NodeDetailsTableNodeLink topologyId={this.props.topologyId} {...node} />

                {values}

            );
          })}

        {showLimitAction &&
{limitActionText}
}

    );
  }
}
<commit_msg>dont format metadata<commit_after>import _ from 'lodash';
import React from 'react';

import NodeDetailsTableNodeLink from './node-details-table-node-link';
import { formatMetric } from '../../utils/string-utils';

export default class NodeDetailsTable extends React.Component {

  constructor(props, context) {
    super(props, context);
    this.DEFAULT_LIMIT = 5;
    this.state = {
      limit: this.DEFAULT_LIMIT,
      sortedDesc: true,
      sortBy: null
    };
    this.handleLimitClick = this.handleLimitClick.bind(this);
    this.getValueForSortBy = this.getValueForSortBy.bind(this);
  }

  handleHeaderClick(ev, headerId) {
    ev.preventDefault();
    const sortedDesc = headerId === this.state.sortBy ? !this.state.sortedDesc : this.state.sortedDesc;
    const sortBy = headerId;
    this.setState({sortBy, sortedDesc});
  }

  handleLimitClick(ev) {
    ev.preventDefault();
    const limit = this.state.limit ? 0 : this.DEFAULT_LIMIT;
    this.setState({limit});
  }

  getDefaultSortBy() {
    // first metric
    return _.get(this.props.nodes, [0, 'metrics', 0, 'id']);
  }

  getMetaDataSorters() {
    // returns an array of sorters that will take a node
    return _.get(this.props.nodes, [0, 'metadata'], []).map((field, index) => {
      return node => node.metadata[index] ? node.metadata[index].value : null;
    });
  }

  getValueForSortBy(node) {
    // return the node's value based on the sortBy field
    const sortBy = this.state.sortBy || this.getDefaultSortBy();
    if (sortBy !== null) {
      const field = _.union(node.metrics, node.metadata).find(f => f.id === sortBy);
      if (field) {
        return field.value;
      }
    }
    return -1e-10; // just under 0 to treat missing values differently from 0
  }

  getValuesForNode(node) {
    const values = {};
    ['metrics', 'metadata'].forEach(collection => {
      if (node[collection]) {
        node[collection].forEach(field => {
          field.valueType = collection;
          values[field.id] = field;
        });
      }
    });
    return values;
  }

  renderHeaders() {
    if (this.props.nodes && this.props.nodes.length > 0) {
      let headers = [{id: 'label', label: this.props.label}];
      // gather header labels from metrics and metadata
      const nodeValues = this.props.nodes.map(this.getValuesForNode);
      headers = headers.concat(this.props.columns.map(column => {
        // look for a node that has the column label
        const valuesWithField = nodeValues.find(values => values[column] !== undefined);
        if (valuesWithField) {
          return {id: column, label: valuesWithField[column].label};
        }
        // fall back on column id as label
        return {id: column, label: column};
      }));
      const defaultSortBy = this.getDefaultSortBy();

      return (

          {headers.map(header => {
            const headerClasses = ['node-details-table-header', 'truncate'];
            const onHeaderClick = ev => {
              this.handleHeaderClick(ev, header.id);
            };
            // sort by first metric by default
            const isSorted = this.state.sortBy !== null ? header.id === this.state.sortBy : header.id === defaultSortBy;
            const isSortedDesc = isSorted && this.state.sortedDesc;
            const isSortedAsc = isSorted && !isSortedDesc;
            if (isSorted) {
              headerClasses.push('node-details-table-header-sorted');
            }
            return (

                {isSortedAsc && }
                {isSortedDesc && }
                {header.label}

            );
          })}

      );
    }
    return '';
  }

  renderValues(node) {
    const fields = this.getValuesForNode(node);
    return this.props.columns.map(col => {
      const field = fields[col];
      if (field) {
        return (

            {field.valueType === 'metadata' ? field.value : formatMetric(field.value, field)}

        );
      }
    });
  }

  render() {
    const headers = this.renderHeaders();
    let nodes = _.sortByAll(this.props.nodes, this.getValueForSortBy, 'label', this.getMetaDataSorters());
    const limited = nodes && this.state.limit > 0 && nodes.length > this.state.limit;
    const showLimitAction = nodes && (limited || (this.state.limit === 0 && nodes.length > this.DEFAULT_LIMIT));
    const limitActionText = limited ? 'Show more' : 'Show less';
    if (this.state.sortedDesc) {
      nodes.reverse();
    }
    if (nodes && limited) {
      nodes = nodes.slice(0, this.state.limit);
    }

    return (

            {headers}

          {nodes && nodes.map(node => {
            const values = this.renderValues(node);
            return (

                  <NodeDetailsTableNodeLink topologyId={this.props.topologyId} {...node} />

                {values}

            );
          })}

        {showLimitAction &&
{limitActionText}
}

    );
  }
}
<|endoftext|>


<commit_before>define({
    "appid": "",
    "webmap": "8dd583ea3de64e40b92ea5a261d0c6c8",
    "oauthappid": null,
    "proxyurl": "",
    "bingmapskey": null,
    "sharinghost": location.protocol + "//" + "www.arcgis.com",
    "scalebarUnits": "dual",
    //Set config properties for all of these
    "geocoder": false,  //false in config values
    "searchExtent": true,
    "searchLayers":[{
        "id": "",
        "fields": []
    }],
    "locationSearch": false,
    "titleInHeader": true,  //true in config values
    "displaypopups": true, //true in config values
    "showHelpOnLoad": true, //true in config values
    //end set config
    "helperServices": {
    "geometry": {
      "url": null
    },
    "printTask": {
      "url": null
    },
    "elevationSync": {
      "url": null
    },
    "geocode": [{
      "url": null
        }]
  }
});

<commit_msg>fouth try<commit_after>define({
    "appid": "",
    "webmap": "6b5586ae5c514d9ca6765d9f14250846",
    "oauthappid": null,
    "proxyurl": "",
    "bingmapskey": null,
    "sharinghost": location.protocol + "//" + "www.arcgis.com",
    "scalebarUnits": "dual",
    //Set config properties for all of these
    "geocoder": false,  //false in config values
    "searchExtent": true,
    "searchLayers":[{
        "id": "",
        "fields": []
    }],
    "locationSearch": false,
    "titleInHeader": true,  //true in config values
    "displaypopups": true, //true in config values
    "showHelpOnLoad": true, //true in config values
    //end set config
    "helperServices": {
    "geometry": {
      "url": null
    },
    "printTask": {
      "url": null
    },
    "elevationSync": {
      "url": null
    },
    "geocode": [{
      "url": null
        }]
  }
});

<|endoftext|>


<commit_before>//TODO: Change these for actual group names

var groups = ['Group A', 'Group B','Group C'];
var activities = ['Outdoor recreation', 'Stretching/resistence training', 'Sensory stimulation',
            'Pet therapy','Gardening', 'Sewing','Painting'];

var facilitatorRoles = ['Caregiver', 'Volunteer', 'Family', 'Self'];

function randomDate(start, end) {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

function insert(collection, args, amount, insertFunctionOutcome) {
  //make copy of the object so we can get different faker data every time
  var argsWithValues;
  for (var i = 0; i < amount; i++) {
     argsWithValues = Object.assign({},args);

    for (var key in args) {
      if (insertFunctionOutcome) {
        if (typeof args[key] === 'function') {
          var func = args[key];
          argsWithValues[key] = func();
        }
      }
    }
    collection.insert(argsWithValues);

  }
}
function createMockGroups () {
  console.log('Creating mock groups');

  for (var i = 0; i < groups.length; i++) {
    var groupName = groups[i];
    console.log(groupName);
    Groups.insert({'name': groupName});
  }
}

function createMockRoles() {
  console.log('Creating mock roles');

  for (var i = 0; i < facilitatorRoles.length; i++) {
    var roleName = facilitatorRoles[i];
    console.log(roleName);
    Roles.createRole(roleName);
  }
}

function createMockHomes() {
  console.log('Creating mock homes');
  var amount = 3;
  var address = function() {return faker.address.city();};

  for (var i = 0; i < groups.length; i++) {
    var groupName = groups[i];
    console.log(groupName);
    var Group = Groups.findOne({'name': groupName});
    var args = {'name': address,'groupId': Group._id};
    insert(Homes, args, amount, true);
  }

}

function createMockResidents() {
  console.log('Creating mock residents');
  var amount = 6;
  var homes = Homes.find().fetch();
  var firstName = function() {return faker.name.firstName();};
  var lastInitial =  function() {return faker.name.lastName().charAt(0);};
  for (var i = 0; i < homes.length; i++) {
    var args = {'firstName': firstName, 'lastInitial': lastInitial, 'homeId': homes[i]._id};
    insert(Residents, args, amount,true);
  }

}
function createMockActivityTypes() {
  console.log('Creating mock activiity types');
  for (var i = 0; i < activities.length; i++) {
    ActivityTypes.insert({'name': activities[i]});
  }
}

function createMockActivities() {
  console.log('Creating mock activies');
  // Number of activities to create per resident
  var amount =  25;

  // Number, in days, for the earliest activity date
  var earliestActivityDate = 30;

  // Get list of residents
  var residents = Residents.find().fetch();

  // Get list of activity types
  var activityTypes = ActivityTypes.find().fetch();

  // Get a list of all roles
  var roles = Roles.getAllRoles().fetch();

  // Select a random facilitator role (ID)
  var roleId = function () {
    return roles[Math.floor(Math.random() * roles.length)]._id;
  }

  // Get a random activity type (ID)
  var activityType = function() {
    return activityTypes[Math.floor(Math.random() * activityTypes.length)]._id;
  };

  // Get random activity date
  var date = function() {
    var endDate = new Date();
    var startDate = new Date();
    startDate.setDate(endDate.getDate() - earliestActivityDate);
    return randomDate(endDate, startDate);
  };

  // Set random activity duration
  var duration = function() {
    return Math.floor((Math.random() * 60) + 1);
  };

  for (var i = 0; i < residents.length; i++) {
    var residentId = residents[i]._id;
    var args = {'activityTypeId': activityType, 'activityDate': date,'facilitatorRoleId': roleId,'duration': duration,'residentIds': [residentId]};
    insert(Activities, args, amount, true);
  }
}

Meteor.methods({
  'createMockData': function() {
    createMockGroups();
    createMockRoles();
    createMockHomes();
    createMockResidents();
    createMockActivityTypes();
    createMockActivities();
  },
  'removeAllData': function() {
    Groups._dropCollection();
    Homes._dropCollection();
    Residents._dropCollection();
    ActivityTypes._dropCollection();
    Activities._dropCollection();
  },
});
<commit_msg>Disable mongo validation<commit_after>//TODO: Change these for actual group names

var groups = ['Group A', 'Group B','Group C'];
var activities = ['Outdoor recreation', 'Stretching/resistence training', 'Sensory stimulation',
            'Pet therapy','Gardening', 'Sewing','Painting'];

var facilitatorRoles = ['Caregiver', 'Volunteer', 'Family', 'Self'];

function randomDate(start, end) {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

function insert(collection, args, amount, insertFunctionOutcome) {
  //make copy of the object so we can get different faker data every time
  var argsWithValues;
  for (var i = 0; i < amount; i++) {
     argsWithValues = Object.assign({},args);

    for (var key in args) {
      if (insertFunctionOutcome) {
        if (typeof args[key] === 'function') {
          var func = args[key];
          argsWithValues[key] = func();
        }
      }
    }
    collection.insert(argsWithValues, {validate: false});

  }
}
function createMockGroups () {
  console.log('Creating mock groups');

  for (var i = 0; i < groups.length; i++) {
    var groupName = groups[i];
    console.log(groupName);
    Groups.insert({'name': groupName});
  }
}

function createMockRoles() {
  console.log('Creating mock roles');

  for (var i = 0; i < facilitatorRoles.length; i++) {
    var roleName = facilitatorRoles[i];
    console.log(roleName);
    Roles.createRole(roleName);
  }
}

function createMockHomes() {
  console.log('Creating mock homes');
  var amount = 3;
  var address = function() {return faker.address.city();};

  for (var i = 0; i < groups.length; i++) {
    var groupName = groups[i];
    console.log(groupName);
    var Group = Groups.findOne({'name': groupName});
    var args = {'name': address,'groupId': Group._id};
    insert(Homes, args, amount, true);
  }

}

function createMockResidents() {
  console.log('Creating mock residents');
  var amount = 6;
  var homes = Homes.find().fetch();
  var firstName = function() {return faker.name.firstName();};
  var lastInitial =  function() {return faker.name.lastName().charAt(0);};
  for (var i = 0; i < homes.length; i++) {
    var args = {'firstName': firstName, 'lastInitial': lastInitial, 'homeId': homes[i]._id};
    insert(Residents, args, amount,true);
  }

}
function createMockActivityTypes() {
  console.log('Creating mock activiity types');
  for (var i = 0; i < activities.length; i++) {
    ActivityTypes.insert({'name': activities[i]});
  }
}

function createMockActivities() {
  console.log('Creating mock activies');
  // Number of activities to create per resident
  var amount =  25;

  // Number, in days, for the earliest activity date
  var earliestActivityDate = 30;

  // Get list of residents
  var residents = Residents.find().fetch();

  // Get list of activity types
  var activityTypes = ActivityTypes.find().fetch();

  // Get a list of all roles
  var roles = Roles.getAllRoles().fetch();

  // Select a random facilitator role (ID)
  var roleId = function () {
    return roles[Math.floor(Math.random() * roles.length)]._id;
  }

  // Get a random activity type (ID)
  var activityType = function() {
    return activityTypes[Math.floor(Math.random() * activityTypes.length)]._id;
  };

  // Get random activity date
  var date = function() {
    var endDate = new Date();
    var startDate = new Date();
    startDate.setDate(endDate.getDate() - earliestActivityDate);
    return randomDate(endDate, startDate);
  };

  // Set random activity duration
  var duration = function() {
    return Math.floor((Math.random() * 60) + 1);
  };

  for (var i = 0; i < residents.length; i++) {
    var residentId = residents[i]._id;
    var args = {'activityTypeId': activityType, 'activityDate': date,'facilitatorRoleId': roleId,'duration': duration,'residentIds': [residentId]};
    insert(Activities, args, amount, true);
  }
}

Meteor.methods({
  'createMockData': function() {
    createMockGroups();
    createMockRoles();
    createMockHomes();
    createMockResidents();
    createMockActivityTypes();
    createMockActivities();
  },
  'removeAllData': function() {
    Groups._dropCollection();
    Homes._dropCollection();
    Residents._dropCollection();
    ActivityTypes._dropCollection();
    Activities._dropCollection();
  },
});
<|endoftext|>


<commit_before>var dropchop = (function(dc) {

  'use strict';

  dc = dc || {};
  dc.ops = dc.ops || {};

  dc.ops.file = {
    upload: {
      description: 'Upload from your computer (.shp, .geojson)',
      icon: '',
      execute: function() {
        // inspired from geojson.io
        // https://github.com/mapbox/geojson.io/blob/gh-pages/src/ui/file_bar.js#L390
        var $blindInput = $('<input>')
          .attr('type', 'file')
          .attr('multiple', 'true')
          .css('visibility', 'hidden')
          .css('position', 'absolute')
          .css('height', '0')
          .on('change', function() {
            var files = this.files;
            $(files).each(function(i) {
              // var ext = dc.util.getFileExtension(files[i].name);

              // // if it is a shapefile or zip file
              // if (ext === 'shp' || ext === 'zip') {
              //   // upload a shapefile and add the layer
              //   dc.util.readShpFile
              //   shp("files/pandr").then(function(geojson){
              //     //do something with your geojson
              //   });
              // } else {
                dc.util.readFile(files[i]);
              // }

            });
            $blindInput.remove();
          });
        $('body').append($blindInput);
        $blindInput.click();
      }
    },

    'load-url': {
      description: 'Import file from a URL',
      icon: '',
      parameters: [
        {
          name: 'url',
          description :'URL',
          type: 'text',
          default: 'http://',
        },
      ],
      execute: function() {
        // https://gist.githubusercontent.com/mapsam/eace9bf13d3853bdf273/raw/3cd4b92accd1e04394840ceb93b8d4dd03038611/locations.geojson
        $(dc.form).trigger('form:file', ['load-url']);
      },
      get: function(event, name, parameters) {
        var url = parameters[0];
        dc.util.xhr(url, dc.ops.file[name].callback);
      },
      callback: function(xhr, xhrEvent) {
        if (xhr.status === 200) {
          var data = JSON.parse(xhr.responseText);
          // get filename based on the end of the url - not sure if this is sustainable
          var name = xhr.responseURL.substring(xhr.responseURL.lastIndexOf('/')+1);
          $(dc.layers).trigger('file:added', [name, data]);
        } else {
          dc.notify('error', xhr.status + ': could not retrieve Gist. Please check your URL');
        }
      }
    },

    'load-gist': {
      description: 'Import files from Gist',
      icon: '',
      parameters: [
        {
          name: 'gist',
          description :'Gist ID or URL',
          type: 'text',
          default: 'https://gist.github.com/'
        },
      ],
      execute: function() {
        $(dc.form).trigger('form:file', ['load-gist']);
      },
      get: function(event, name, parameters) {
        var gist = parameters[0].split('/')[parameters[0].split('/').length-1];
        var url = 'https://api.github.com/gists/' + gist;
        dc.util.xhr(url, dc.ops.file[name].callback);
      },
      callback: function(xhr, xhrEvent) {
        if (xhr.status === 200) {
          var data = JSON.parse(xhr.responseText);
          for (var f in data.files) {
            var name = data.files[f].filename;
            $(dc.layers).trigger('file:added', [name, JSON.parse(data.files[f].content)]);
          }
          // dc.notify('success', 'Succesfully retrieved gist')
        } else {
          dc.notify('error', xhr.status + ': could not retrieve Gist. Please check your URL');
        }
      }
    },

    'load-overpass': {
      description: 'Query the Overpass API',
      icon: '',
      _temp: {},
      parameters: [
        {
          name: 'query',
          description :'Learn more about the query language.',
          type: 'text',
          default: 'amenity=bar'
        },
        {
          name: 'layer name',
          description :'Name of the layer added if results are found.',
          type: 'text',
          default: 'overpass_layer_name'
        }
      ],
      execute: function() {
        $(dc.form).trigger('form:file', ['load-overpass']);
      },
      get: function(event, name, parameters) {
        // set layer name to _temp for later usage
        dc.ops.file['load-overpass']._temp.layerName = parameters[1]; // this is ugly

        // build the query with bounding box
        var bbox = dc.util.getBBox();
        dc.util.xhr('http://overpass-api.de/api/interpreter?[out:json];node('+bbox+')['+parameters[0]+'];out;', dc.ops.file['load-overpass'].callback);
      },
      callback: function(xhr, xhrEvent) {
        if (xhr.status === 200) {
          var data = JSON.parse(xhr.responseText);
          var geojson = osmtogeojson(data);
          if (!data.elements.length) {
            dc.notify('info', 'No elements found in your query.');
          } else {
            $(dc.layers).trigger('file:added', [dc.ops.file['load-overpass']._temp.layerName, geojson]);
            dc.notify('success', 'Found ' + data.elements.length + ' elements from the Overpass API');
          }
        } else {
          dc.notify('error', xhr.status + ': could not query the Overpass API');
        }
      }
    },

    'break1': { type: 'break' },

    'save-geojson': {
      minFeatures: 1,
      description: 'Save as GeoJSON',
      icon: '',
      parameters: [
        {
          name: 'filename',
          description :'Filename prefix to write',
          default: 'dnc'
        }
      ],
      createsLayer: false,
      execute: function() {
        $(dc.selection.list).each(function(i) {
          var content = JSON.stringify(dc.selection.list[i].raw);
          var title = 'dropchop_' + dc.selection.list[i].name + '.geojson';
          saveAs(new Blob([content], {
            type: 'text/plain;charset=utf-8'
          }), title);

        });
      }
    },

    'save-shapefile': {
      minFeatures: 1,
      description: 'Save as Shapefile',
      icon: '',
      execute: function() {
        $(dc.selection.list).each(function(i) {
          try {
            var options = {
              folder: 'dropchop_' + dc.selection.list[i].name,
              types: {
                point: 'dropchop_' + dc.selection.list[i].name + '_point',
                polygon: 'dropchop_' + dc.selection.list[i].name + '_poly',
                line: 'dropchop_' + dc.selection.list[i].name + '_line'
              }
            };
            shpwrite.download(dc.selection.list[i].raw, options);
          } catch (err) {
            dc.notify('Error', 'There was a problem downloading the shapefile.' + err);
            throw err;
          }
        });
      },
      createsLayer: false
    },

    'break2': { type: 'break' },

    extent: {
      minFeatures: 1,
      description: 'View extent of layers',
      icon: '',
      execute: function() {
        if(!dc.selection.list.length) {
          // extent of entire layer list if nothing selected
          dc.map.m.fitBounds(dc.map.layergroup.getBounds());
        } else {
          // otherwise build the bounds based on selected layers
          var bounds;
          $(dc.selection.list).each(function(l) {
            var fl = dc.selection.list[l].featurelayer;
            if(!l) bounds = fl.getBounds();
            else bounds.extend(fl.getBounds());
          });
          dc.map.m.fitBounds(bounds);
        }

      }
    },

    expand: {
      minFeatures: 1,
      description: 'Convert FeatureCollection into separate features',
      icon: '',
      execute: function() {
        var count = 0;
        if (dc.selection.list.length === 1) {
          var fc = dc.selection.list[0];
          if (fc.raw.type === 'FeatureCollection') {
            $(fc.raw.features).each(function(f) {
              count++;
              $(dc.layers).trigger('file:added', [fc.name + count + '_' + fc.raw.features[f].geometry.type, fc.raw.features[f]]);
            });
          } else {
            var err = new Error('That needs to be a feature collection!');
            dc.notify('error', 'Layer is not a FeatureCollection.');
            throw err;
          }
        } else {
          dc.notify('info', 'Please select a single layer!');
        }
      }
    },

    combine: {
      minFeatures: 1,
      description: 'Combines selected features into a single FeatureCollection',
      icon: '',
      execute: function() {
        var fc = {
          type: 'FeatureCollection',
          features: []
        };
        if (dc.selection.list.length > 0) {
          $(dc.selection.list).each(function(f) {
            if (dc.selection.list[f].raw.type !== 'FeatureCollection') {
              fc.features.push(dc.selection.list[f].raw);
            } else {
              dc.notify('info', dc.selection.list[f].name + ' was not added because it is already a FeatureCollection');
            }
          });
          $(dc.layers).trigger('file:added', ['new_FeatureCollection', fc]);
        } else {
          dc.notify('info', 'No layers selected!');
        }
      }
    },

    'break3': { type: 'break' },

    remove: {
      minFeatures: 1,
      description: 'Remove selected layers',
      icon: '',
      execute: function() {
        $(dc.selection.list).each(function(i) {
          $(dc.layers).trigger('layer:removed', [dc.selection.list[i].stamp]);
        });
        dc.selection.clear();
      },
      disableForm: true,
    },

    info: {
      type: 'info',
      description: 'Learn more about dropchop',
      icon: '',
      execute: function() {
        window.location = '/about.html';
      }
    }
  };

  return dc;

})(dropchop || {});<commit_msg>playing with query syntax<commit_after>var dropchop = (function(dc) {

  'use strict';

  dc = dc || {};
  dc.ops = dc.ops || {};

  dc.ops.file = {
    upload: {
      description: 'Upload from your computer (.shp, .geojson)',
      icon: '',
      execute: function() {
        // inspired from geojson.io
        // https://github.com/mapbox/geojson.io/blob/gh-pages/src/ui/file_bar.js#L390
        var $blindInput = $('<input>')
          .attr('type', 'file')
          .attr('multiple', 'true')
          .css('visibility', 'hidden')
          .css('position', 'absolute')
          .css('height', '0')
          .on('change', function() {
            var files = this.files;
            $(files).each(function(i) {
              // var ext = dc.util.getFileExtension(files[i].name);

              // // if it is a shapefile or zip file
              // if (ext === 'shp' || ext === 'zip') {
              //   // upload a shapefile and add the layer
              //   dc.util.readShpFile
              //   shp("files/pandr").then(function(geojson){
              //     //do something with your geojson
              //   });
              // } else {
                dc.util.readFile(files[i]);
              // }

            });
            $blindInput.remove();
          });
        $('body').append($blindInput);
        $blindInput.click();
      }
    },

    'load-url': {
      description: 'Import file from a URL',
      icon: '',
      parameters: [
        {
          name: 'url',
          description :'URL',
          type: 'text',
          default: 'http://',
        },
      ],
      execute: function() {
        $(dc.form).trigger('form:file', ['load-url']);
      },
      get: function(event, name, parameters) {
        var url = parameters[0];
        dc.util.xhr(url, dc.ops.file[name].callback);
      },
      callback: function(xhr, xhrEvent) {
        if (xhr.status === 200) {
          var data = JSON.parse(xhr.responseText);
          // get filename based on the end of the url - not sure if this is sustainable
          var name = xhr.responseURL.substring(xhr.responseURL.lastIndexOf('/')+1);
          $(dc.layers).trigger('file:added', [name, data]);
        } else {
          dc.notify('error', xhr.status + ': could not retrieve Gist. Please check your URL');
        }
      }
    },

    'load-gist': {
      description: 'Import files from Gist',
      icon: '',
      parameters: [
        {
          name: 'gist',
          description :'Gist ID or URL',
          type: 'text',
          default: 'https://gist.github.com/'
        },
      ],
      execute: function() {
        $(dc.form).trigger('form:file', ['load-gist']);
      },
      get: function(event, name, parameters) {
        var gist = parameters[0].split('/')[parameters[0].split('/').length-1];
        var url = 'https://api.github.com/gists/' + gist;
        dc.util.xhr(url, dc.ops.file[name].callback);
      },
      callback: function(xhr, xhrEvent) {
        if (xhr.status === 200) {
          var data = JSON.parse(xhr.responseText);
          for (var f in data.files) {
            var name = data.files[f].filename;
            $(dc.layers).trigger('file:added', [name, JSON.parse(data.files[f].content)]);
          }
          // dc.notify('success', 'Succesfully retrieved gist')
        } else {
          dc.notify('error', xhr.status + ': could not retrieve Gist. Please check your URL');
        }
      }
    },

    'load-overpass': {
      description: 'Query the Overpass API',
      icon: '',
      _temp: {},
      parameters: [
        {
          name: 'query',
          description :'Learn more about the query language.',
          type: 'text',
          default: 'amenity=bar'
        },
        {
          name: 'layer name',
          description :'Name of the layer added if results are found.',
          type: 'text',
          default: 'overpass_layer_name'
        }
      ],
      execute: function() {
        $(dc.form).trigger('form:file', ['load-overpass']);
      },
      get: function(event, name, parameters) {
        // set layer name to _temp for later usage
        dc.ops.file['load-overpass']._temp.layerName = parameters[1]; // this is ugly

        // build the query with bounding box
        var bbox = dc.util.getBBox();
        dc.util.xhr('http://overpass-api.de/api/interpreter?[out:json];[timeout:3600];way['+parameters[0]+']('+bbox+');out;', dc.ops.file['load-overpass'].callback);
      },
      callback: function(xhr, xhrEvent) {
        if (xhr.status === 200) {
          var data = JSON.parse(xhr.responseText);
          var geojson = osmtogeojson(data);
          console.log(data, geojson);
          if (!data.elements.length) {
            dc.notify('info', 'No elements found in your query.');
          } else {
            $(dc.layers).trigger('file:added', [dc.ops.file['load-overpass']._temp.layerName, geojson]);
            dc.notify('success', 'Found ' + data.elements.length + ' elements from the Overpass API');
          }
        } else {
          dc.notify('error', xhr.status + ': could not query the Overpass API');
        }
      }
    },

    'break1': { type: 'break' },

    'save-geojson': {
      minFeatures: 1,
      description: 'Save as GeoJSON',
      icon: '',
      parameters: [
        {
          name: 'filename',
          description :'Filename prefix to write',
          default: 'dnc'
        }
      ],
      createsLayer: false,
      execute: function() {
        $(dc.selection.list).each(function(i) {
          var content = JSON.stringify(dc.selection.list[i].raw);
          var title = 'dropchop_' + dc.selection.list[i].name + '.geojson';
          saveAs(new Blob([content], {
            type: 'text/plain;charset=utf-8'
          }), title);

        });
      }
    },

    'save-shapefile': {
      minFeatures: 1,
      description: 'Save as Shapefile',
      icon: '',
      execute: function() {
        $(dc.selection.list).each(function(i) {
          try {
            var options = {
              folder: 'dropchop_' + dc.selection.list[i].name,
              types: {
                point: 'dropchop_' + dc.selection.list[i].name + '_point',
                polygon: 'dropchop_' + dc.selection.list[i].name + '_poly',
                line: 'dropchop_' + dc.selection.list[i].name + '_line'
              }
            };
            shpwrite.download(dc.selection.list[i].raw, options);
          } catch (err) {
            dc.notify('Error', 'There was a problem downloading the shapefile.' + err);
            throw err;
          }
        });
      },
      createsLayer: false
    },

    'break2': { type: 'break' },

    extent: {
      minFeatures: 1,
      description: 'View extent of layers',
      icon: '',
      execute: function() {
        if(!dc.selection.list.length) {
          // extent of entire layer list if nothing selected
          dc.map.m.fitBounds(dc.map.layergroup.getBounds());
        } else {
          // otherwise build the bounds based on selected layers
          var bounds;
          $(dc.selection.list).each(function(l) {
            var fl = dc.selection.list[l].featurelayer;
            if(!l) bounds = fl.getBounds();
            else bounds.extend(fl.getBounds());
          });
          dc.map.m.fitBounds(bounds);
        }

      }
    },

    expand: {
      minFeatures: 1,
      description: 'Convert FeatureCollection into separate features',
      icon: '',
      execute: function() {
        var count = 0;
        if (dc.selection.list.length === 1) {
          var fc = dc.selection.list[0];
          if (fc.raw.type === 'FeatureCollection') {
            $(fc.raw.features).each(function(f) {
              count++;
              $(dc.layers).trigger('file:added', [fc.name + count + '_' + fc.raw.features[f].geometry.type, fc.raw.features[f]]);
            });
          } else {
            var err = new Error('That needs to be a feature collection!');
            dc.notify('error', 'Layer is not a FeatureCollection.');
            throw err;
          }
        } else {
          dc.notify('info', 'Please select a single layer!');
        }
      }
    },

    combine: {
      minFeatures: 1,
      description: 'Combines selected features into a single FeatureCollection',
      icon: '',
      execute: function() {
        var fc = {
          type: 'FeatureCollection',
          features: []
        };
        if (dc.selection.list.length > 0) {
          $(dc.selection.list).each(function(f) {
            if (dc.selection.list[f].raw.type !== 'FeatureCollection') {
              fc.features.push(dc.selection.list[f].raw);
            } else {
              dc.notify('info', dc.selection.list[f].name + ' was not added because it is already a FeatureCollection');
            }
          });
          $(dc.layers).trigger('file:added', ['new_FeatureCollection', fc]);
        } else {
          dc.notify('info', 'No layers selected!');
        }
      }
    },

    'break3': { type: 'break' },

    remove: {
      minFeatures: 1,
      description: 'Remove selected layers',
      icon: '',
      execute: function() {
        $(dc.selection.list).each(function(i) {
          $(dc.layers).trigger('layer:removed', [dc.selection.list[i].stamp]);
        });
        dc.selection.clear();
      },
      disableForm: true,
    },

    info: {
      type: 'info',
      description: 'Learn more about dropchop',
      icon: '',
      execute: function() {
        window.location = '/about.html';
      }
    }
  };

  return dc;

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


<commit_before>// Karma configuration
// Generated on Mon Apr 03 2017 21:01:21 GMT+0200 (CEST)

module.exports = function(config) {

    let cl = {}
    let testBrowsers = ["Opera", "Chromium", "Firefox"]
    if (process.env.TRAVIS && process.env.TRAVIS_OS_NAME === "linux") {
        testBrowsers = ["PhantomJS", "Chrome", "Firefox", "Opera"]
        cl = {
            Chrome_without_sandbox: {
                base: "Chrome",
                flags: ["--no-sandbox"]
            },
            Firefox_without_sandbox: {
                base: "Firefox",
                flags: ["--no-sandbox"]
            },
            Opera_without_sandbox: {
                base: "Opera",
                flags: ["--no-sandbox"]
            }
        }
    }
    else if (process.env.TRAVIS && process.env.TRAVIS_OS_NAME === "osx") {
        testBrowsers = ["Safari", "Firefox", "Chrome"]
    }
    else if (process.env.APPVEYOR) {
        testBrowsers = ["IE", "Firefox", "Chrome"]
    }

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: "",

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ["mocha", "browserify"],

        // list of files / patterns to load in the browser
        files: [
            {pattern: "src/**/*.js", included: true},
            {pattern: "test/**/*.js", included: true}
        ],

        // list of files to exclude
        exclude: [
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            "src/**/*.js": ["browserify"],
            "test/**/*.js": ["browserify"]
        },

        // Browserify configuration
        // The coverage command goes here instead of the preprocessor because we need it to work with browserify
        browserify: {
            debug: true,
            transform: [
                [
                    "babelify",
                    {
                        presets: "es2015"
                    }
                ],
                [
                    "browserify-istanbul",
                    {
                        instrumenterConfig: {
                            embedSource: true
                        }
                    }
                ]
            ]
        },

        coverageReporter: {
            reporters: [
                {"type": "text"},
                {"type": "html", dir: "coverage"},
                {"type": "lcov"}
            ]
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ["progress", "mocha", "coverage"],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: testBrowsers,

        // docker build supposedly fails chrome builds with sandbox active
        customLaunchers: cl,

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true,

        // Increase timeout to accommodate Travis CI issue.
        browserNoActivityTimeout: 60000,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity
    })
}
<commit_msg>[karma.conf] concurrency=1 to avoid test crashes<commit_after>// Karma configuration
// Generated on Mon Apr 03 2017 21:01:21 GMT+0200 (CEST)

module.exports = function(config) {

    let cl = {}
    let testBrowsers = ["Opera", "Chromium", "Firefox"]
    if (process.env.TRAVIS && process.env.TRAVIS_OS_NAME === "linux") {
        testBrowsers = ["PhantomJS", "Chrome", "Firefox", "Opera"]
        cl = {
            Chrome_without_sandbox: {
                base: "Chrome",
                flags: ["--no-sandbox"]
            },
            Firefox_without_sandbox: {
                base: "Firefox",
                flags: ["--no-sandbox"]
            },
            Opera_without_sandbox: {
                base: "Opera",
                flags: ["--no-sandbox"]
            }
        }
    }
    else if (process.env.TRAVIS && process.env.TRAVIS_OS_NAME === "osx") {
        testBrowsers = ["Safari", "Firefox", "Chrome"]
    }
    else if (process.env.APPVEYOR) {
        testBrowsers = ["IE", "Firefox", "Chrome"]
    }

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: "",

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ["mocha", "browserify"],

        // list of files / patterns to load in the browser
        files: [
            {pattern: "src/**/*.js", included: true},
            {pattern: "test/**/*.js", included: true}
        ],

        // list of files to exclude
        exclude: [
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            "src/**/*.js": ["browserify"],
            "test/**/*.js": ["browserify"]
        },

        // Browserify configuration
        // The coverage command goes here instead of the preprocessor because we need it to work with browserify
        browserify: {
            debug: true,
            transform: [
                [
                    "babelify",
                    {
                        presets: "es2015"
                    }
                ],
                [
                    "browserify-istanbul",
                    {
                        instrumenterConfig: {
                            embedSource: true
                        }
                    }
                ]
            ]
        },

        coverageReporter: {
            reporters: [
                {"type": "text"},
                {"type": "html", dir: "coverage"},
                {"type": "lcov"}
            ]
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ["progress", "mocha", "coverage"],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: testBrowsers,

        // docker build supposedly fails chrome builds with sandbox active
        customLaunchers: cl,

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true,

        // Increase timeout to accommodate Travis CI issue.
        browserNoActivityTimeout: 60000,

        // Concurrency level
        // how many browser should be started simultaneous
        // Keep this at one at a time. Travis tests might randomly
        // crash with the message "Some of your tests did a full page reload!"
        // when concurrency is set to "Infinity".
        concurrency: 1
    })
}
<|endoftext|>


<commit_before>/**
 * @file IReadableStream interface
 * @since 0.1.9
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfDefineInterface*/ // Internal interface definition helper
/*global _gpfSyncReadSourceJSON*/ // Reads a source json file (only in source mode)
/*exported _gpfIReadableStream*/ // gpf.interfaces.IReadableStream
/*#endif*/

/**
 * The Readable stream interface is the abstraction for a source of data that you are reading from.
 * In other words, data comes out of a Readable stream.
 *
 * @interface gpf.interfaces.IReadableStream
 * @since 0.1.9
 */

/**
 * Read all data from the underlying source. Chunk of data is passed to the {@link gpf.interfaces.IWritableStream}.
 *
 * @method gpf.interfaces.IReadableStream#read
 * @param {gpf.interfaces.IWritableStream} output Stream that receives chunk of data
 * @return {Promise} Resolved when the stream has ended
 * @since 0.1.9
 */

/**
 * IReadableStream interface specifier
 *
 * @type {gpf.interfaces.IReadableStream}
 * @since 0.1.9
 */
var _gpfIReadableStream = _gpfDefineInterface("ReadableStream",
    _gpfSyncReadSourceJSON("interfaces/readablestream.json"));

/*#ifndef(UMD)*/

// Generates an empty function to reflect the null complexity of this module
function _gpfInterfacesReadablestream () {}
/*exported _gpfInterfacesReadablestream*/

/*#endif*/

<commit_msg>Also consider coverage (#240)<commit_after>/**
 * @file IReadableStream interface
 * @since 0.1.9
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfDefineInterface*/ // Internal interface definition helper
/*global _gpfSyncReadSourceJSON*/ // Reads a source json file (only in source mode)
/*exported _gpfIReadableStream*/ // gpf.interfaces.IReadableStream
/*#endif*/

/**
 * The Readable stream interface is the abstraction for a source of data that you are reading from.
 * In other words, data comes out of a Readable stream.
 *
 * @interface gpf.interfaces.IReadableStream
 * @since 0.1.9
 */

/**
 * Read all data from the underlying source. Chunk of data is passed to the {@link gpf.interfaces.IWritableStream}.
 *
 * @method gpf.interfaces.IReadableStream#read
 * @param {gpf.interfaces.IWritableStream} output Stream that receives chunk of data
 * @return {Promise} Resolved when the stream has ended
 * @since 0.1.9
 */

/**
 * IReadableStream interface specifier
 *
 * @type {gpf.interfaces.IReadableStream}
 * @since 0.1.9
 */
var _gpfIReadableStream = _gpfDefineInterface("ReadableStream",
    _gpfSyncReadSourceJSON("interfaces/readablestream.json"));

/*#ifndef(UMD)*/

// Generates an empty function to reflect the null complexity of this module
(function _gpfInterfacesReadablestream () {}());

/*#endif*/
<|endoftext|>


<commit_before>import {exec}                       from 'child_process';
import fs                           from 'fs';
import fse                          from 'fs-extra';
import path                         from 'path';
import test                         from 'ava';
import nightmare                    from 'nightmare';

const runner = nightmare({
    show : false,
    waitTimeout : 60000
});

test.serial('import-use-tag', async t => {

    t.plan(2);

    let pathProjectRoot = path.resolve(__dirname, '../../../');
    let pathMroningJs = path.resolve(pathProjectRoot, 'dist/morning-ui.js');
    let pathMroningCss = path.resolve(pathProjectRoot, 'dist/morning-ui.css');
    let pathTmp = path.resolve(pathProjectRoot, '.tmp');
    let pathDir = path.resolve(pathTmp, 'import-use-tag/');
    let pathHtml = path.resolve(pathDir, 'index.html');
    let pathJs = path.resolve(pathDir, 'morning-ui.js');
    let pathCss = path.resolve(pathDir, 'morning-ui.css');

    fse.emptyDirSync(pathTmp);
    fse.emptyDirSync(pathDir);

    fs.writeFileSync(pathHtml, `

            <title>e2e test : import-use-tag</title>
            <link rel="stylesheet" href="./morning-ui.css" />

    `);
    fse.copySync(pathMroningJs, pathJs);
    fse.copySync(pathMroningCss, pathCss);

    const result = await runner
        .goto(`file://${pathHtml}`)
        .wait('mor-link')
        .evaluate(() => ({
            morning : window.morning,
            style : window.getComputedStyle(document.querySelector('mor-link'))
        }));

    // circleci
    delete result.style.inlineSize;
    delete result.style.perspectiveOrigin;
    delete result.style.transformOrigin;
    delete result.style.webkitLogicalWidth;
    delete result.style.webkitTapHighlightColor;
    delete result.style.width;

    t.is(result.morning.isMorning, true);
    t.snapshot(result.style);

});

test.serial('import-use-webpack', async t => {

    t.plan(2);

    const maxBuffer = 1024000;

    let pathProjectRoot = path.resolve(__dirname, '../../../');
    let pathTmp = path.resolve(pathProjectRoot, '.tmp');
    let pathDir = path.resolve(pathTmp, 'import-use-webpack/');
    let pathPackage = path.resolve(pathDir, 'package.json');
    let pathWebpack = path.resolve(pathDir, 'webpack.config.js');
    let pathSrc = path.resolve(pathDir, 'src/');
    let pathDist = path.resolve(pathDir, 'dist/');
    let pathHtml = path.resolve(pathDist, 'index.html');
    let pathJs = path.resolve(pathSrc, 'index.js');

    fse.emptyDirSync(pathTmp);
    fse.emptyDirSync(pathDir);
    fse.emptyDirSync(pathSrc);
    fse.emptyDirSync(pathDist);

    fs.writeFileSync(pathPackage, `{}`);

    fs.writeFileSync(pathWebpack, `
    const path = require('path');

    module.exports = {
        entry: './src/index.js',
        output: {
            filename: 'bundle.js',
            path: '${pathDist}'
        },
        module: {
            rules: [
                {
                    test: /\\.css$/,
                    use: [
                       'style-loader',
                       'css-loader'
                    ]
                }
            ]
        }
    };
    `);

    fs.writeFileSync(pathJs, `
    import Vue from 'vue/dist/vue.esm.js';
    import morning from 'morning-ui';
    import 'morning-ui/dist/morning-ui.css';

    window.morning = morning;
    Vue.use(morning);
    new Vue({
        el : '#vue',
        template : '<ui-link>link</ui-link>'
    });
    `);

    fs.writeFileSync(pathHtml, `

            <title>e2e test : import-use-webpack</title>

    `);

    await new Promise((resolve, reject) => {

        exec(
            `cd ${pathDir} && npm install morning-ui webpack@4.6.0 style-loader css-loader vue`,
            {
                maxBuffer : maxBuffer
            },
            (error, stdout) => {

                    console.log(70, error);

                if (error) {

                    reject(error);

                }

                resolve();

            }
        );

    });

    await new Promise((resolve, reject) => {

        exec(
            `cd ${pathDir} && node_modules/.bin/webpack webpack.config.js`,
            {
                maxBuffer : maxBuffer
            },
            (error, stdout) => {

                    console.log(71, error);

                if (error) {

                    reject(error);

                }

                resolve();

            }
        );

    });

    console.log('c', pathHtml, fs.readdirSync(pathDist).forEach(file => {
        console.log(90, file);
    }));

    const result = await runner
        .goto(`file://${pathHtml}`)
        .wait('mor-link')
        .evaluate(() => ({
            morning : window.morning,
            style : window.getComputedStyle(document.querySelector('mor-link'))
        }));

    console.log(1919);

    // circleci
    delete result.style.inlineSize;
    delete result.style.perspectiveOrigin;
    delete result.style.transformOrigin;
    delete result.style.webkitLogicalWidth;
    delete result.style.webkitTapHighlightColor;
    delete result.style.width;

    t.is(result.morning.isMorning, true);
    t.snapshot(result.style);

});
<commit_msg>update13<commit_after>import {exec}                       from 'child_process';
import fs                           from 'fs';
import fse                          from 'fs-extra';
import path                         from 'path';
import test                         from 'ava';
import nightmare                    from 'nightmare';

const runner = nightmare({
    show : false
});

// test.serial('import-use-tag', async t => {

//     t.plan(2);

//     let pathProjectRoot = path.resolve(__dirname, '../../../');
//     let pathMroningJs = path.resolve(pathProjectRoot, 'dist/morning-ui.js');
//     let pathMroningCss = path.resolve(pathProjectRoot, 'dist/morning-ui.css');
//     let pathTmp = path.resolve(pathProjectRoot, '.tmp');
//     let pathDir = path.resolve(pathTmp, 'import-use-tag/');
//     let pathHtml = path.resolve(pathDir, 'index.html');
//     let pathJs = path.resolve(pathDir, 'morning-ui.js');
//     let pathCss = path.resolve(pathDir, 'morning-ui.css');

//     fse.emptyDirSync(pathTmp);
//     fse.emptyDirSync(pathDir);

//     fs.writeFileSync(pathHtml, `
//
//
//             <title>e2e test : import-use-tag</title>
//             <link rel="stylesheet" href="./morning-ui.css" />
//
//
//

//
//
//
//
//
//     `);
//     fse.copySync(pathMroningJs, pathJs);
//     fse.copySync(pathMroningCss, pathCss);

//     const result = await runner
//         .goto(`file://${pathHtml}`)
//         .wait('mor-link')
//         .evaluate(() => ({
//             morning : window.morning,
//             style : window.getComputedStyle(document.querySelector('mor-link'))
//         }));

//     // circleci
//     delete result.style.inlineSize;
//     delete result.style.perspectiveOrigin;
//     delete result.style.transformOrigin;
//     delete result.style.webkitLogicalWidth;
//     delete result.style.webkitTapHighlightColor;
//     delete result.style.width;

//     t.is(result.morning.isMorning, true);
//     t.snapshot(result.style);

// });

test.serial('import-use-webpack', async t => {

    t.plan(2);

    const maxBuffer = 1024000;

    let pathProjectRoot = path.resolve(__dirname, '../../../');
    let pathTmp = path.resolve(pathProjectRoot, '.tmp');
    let pathDir = path.resolve(pathTmp, 'import-use-webpack/');
    let pathPackage = path.resolve(pathDir, 'package.json');
    let pathWebpack = path.resolve(pathDir, 'webpack.config.js');
    let pathSrc = path.resolve(pathDir, 'src/');
    let pathDist = path.resolve(pathDir, 'dist/');
    let pathHtml = path.resolve(pathDist, 'index.html');
    let pathJs = path.resolve(pathSrc, 'index.js');

    fse.emptyDirSync(pathTmp);
    fse.emptyDirSync(pathDir);
    fse.emptyDirSync(pathSrc);
    fse.emptyDirSync(pathDist);

    fs.writeFileSync(pathPackage, `{}`);

    fs.writeFileSync(pathWebpack, `
    const path = require('path');

    module.exports = {
        entry: './src/index.js',
        output: {
            filename: 'bundle.js',
            path: '${pathDist}'
        },
        mode : 'production',
        module: {
            rules: [
                {
                    test: /\\.css$/,
                    use: [
                       'style-loader',
                       'css-loader'
                    ]
                }
            ]
        }
    };
    `);

    fs.writeFileSync(pathJs, `
    import Vue from 'vue/dist/vue.esm.js';
    import morning from 'morning-ui';
    import 'morning-ui/dist/morning-ui.css';

    window.morning = morning;
    Vue.use(morning);
    new Vue({
        el : '#vue',
        template : '<ui-link>link</ui-link>'
    });
    `);

    fs.writeFileSync(pathHtml, `

            <title>e2e test : import-use-webpack</title>

    `);

    await new Promise((resolve, reject) => {

        exec(
            `cd ${pathDir} && npm install morning-ui webpack@4.6.0 style-loader css-loader vue`,
            {
                maxBuffer : maxBuffer
            },
            (error, stdout) => {

                if (error) {

                    reject(error);

                }

                resolve();

            }
        );

    });

    await new Promise((resolve, reject) => {

        exec(
            `cd ${pathDir} && node_modules/.bin/webpack --config webpack.config.js`,
            {
                maxBuffer : maxBuffer
            },
            (error, stdout) => {

                if (error) {

                    reject(error);

                }

                resolve();

            }
        );

    });

    console.log('c', pathHtml);
    fs.readdirSync(pathDist).forEach(file => {
        console.log(90, file);
    })

    // const runner = nightmare({
    //     show : true,
    //     waitTimeout : 60000
    // });
    const result = await runner
        .goto(`file://${pathHtml}`)
        .wait('mor-link')
        .evaluate(() => ({
            morning : window.morning,
            style : window.getComputedStyle(document.querySelector('mor-link'))
        }));

    console.log(1919);

    // circleci
    delete result.style.inlineSize;
    delete result.style.perspectiveOrigin;
    delete result.style.transformOrigin;
    delete result.style.webkitLogicalWidth;
    delete result.style.webkitTapHighlightColor;
    delete result.style.width;

    t.is(result.morning.isMorning, true);
    t.snapshot(result.style);

});
<|endoftext|>