<commit_before>'use strict';

//////////////////////////////
// Requires
//////////////////////////////
var gutil = require('gulp-util'),
    lint = require('gulp-scss-lint');

//////////////////////////////
// Internal Vars
//////////////////////////////
var toSassLint = [
  'patterns/**/*.scss',
  'patterns/**/*.sass'
];

//////////////////////////////
// Export
//////////////////////////////
module.exports = function (gulp, sassLintPaths) {
  // Set value of paths to either the default or user entered
  sassLintPaths = sassLintPaths || toSassLint;

  //////////////////////////////
  // Encapsulate task in function to choose path to work on
  //////////////////////////////
  var sassLintTask = function (path) {
    return gulp.src(path)
      .pipe(lint({
        'bundleExec': true
      }));
  }

  //////////////////////////////
  // Core Task
  //////////////////////////////
  gulp.task('sass-lint', function () {
    return sassLintTask(sassLintPaths);
  });

  //////////////////////////////
  // Watch Task
  //////////////////////////////
  gulp.task('sass-lint-watch', function () {
    return gulp.watch(eslintPaths)
      .on('change', function (event) {
        // Add absolute and relative (to Gulpfile) paths
        event.path = {
          absolute: event.path,
          relative: event.path.replace(__dirname.replace('/tasks', '') + '/', '')
        }

        // Notify user of the change
        gutil.log('File ' + gutil.colors.magenta(event.path.relative) + ' was ' + event.type);

        // Call the task
        return sassLintTask(event.path.absolute);
      });
  });
}
<commit_msg>Wrong paths<commit_after>'use strict';

//////////////////////////////
// Requires
//////////////////////////////
var gutil = require('gulp-util'),
    lint = require('gulp-scss-lint');

//////////////////////////////
// Internal Vars
//////////////////////////////
var toSassLint = [
  'patterns/**/*.scss',
  'patterns/**/*.sass'
];

//////////////////////////////
// Export
//////////////////////////////
module.exports = function (gulp, sassLintPaths) {
  // Set value of paths to either the default or user entered
  sassLintPaths = sassLintPaths || toSassLint;

  //////////////////////////////
  // Encapsulate task in function to choose path to work on
  //////////////////////////////
  var sassLintTask = function (path) {
    return gulp.src(path)
      .pipe(lint({
        'bundleExec': true
      }));
  }

  //////////////////////////////
  // Core Task
  //////////////////////////////
  gulp.task('sass-lint', function () {
    return sassLintTask(sassLintPaths);
  });

  //////////////////////////////
  // Watch Task
  //////////////////////////////
  gulp.task('sass-lint-watch', function () {
    return gulp.watch(sassLintPaths)
      .on('change', function (event) {
        // Add absolute and relative (to Gulpfile) paths
        event.path = {
          absolute: event.path,
          relative: event.path.replace(__dirname.replace('/tasks', '') + '/', '')
        }

        // Notify user of the change
        gutil.log('File ' + gutil.colors.magenta(event.path.relative) + ' was ' + event.type);

        // Call the task
        return sassLintTask(event.path.absolute);
      });
  });
}
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/* eslint-disable no-underscore-dangle */

'use strict';

// MODULES //

var logger = require( 'debug' );
var objectKeys = require( '@stdlib/utils/keys' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var fsRegExp = require( './regexp_fs_aliases.js' );
var requireRegExp = require( './regexp_require.js' );
var workspaceRegExp = require( './regexp_workspace.js' );
var completeRequire = require( './complete_require.js' );
var completeFS = require( './complete_fs.js' );
var completeWorkspace = require( './complete_workspace.js' );
var completeExpression = require( './complete_expression.js' );

// VARIABLES //

var debug = logger( 'repl:completer' );

// FUNCTIONS //

/**
* Normalizes a completion list.
*
* @private
* @param {Array} list - completion list
* @returns {Array} normalized completion list
*/
function normalize( list ) {
	var hash;
	var i;

	// Get unique values...
	hash = {};
	for ( i = 0; i < list.length; i++ ) {
		if ( !hasOwnProp( hash, list[ i ] ) ) {
			hash[ list[ i ] ] = true;
		}
	}
	list = objectKeys( hash );

	// TODO: sort such that printed columns are in lexicographic order, not rows, similar to bash behavior!

	// Sort the values in lexicographic order:
	list = list.sort();

	return list;
}

// MAIN //

/**
* Returns a callback for supporting TAB completion in a REPL environment.
*
* @private
* @param {REPL} repl - REPL instance
* @returns {Function} TAB completion callback
*/
function completer( repl ) {
	return complete;

	/**
	* Callback invoked upon a user entering the TAB character at the command prompt.
	*
	* @private
	* @param {string} line - current line
	* @returns {Array} completion results
	*/
	function complete( line ) {
		var match;
		var exts;
		var res;

		debug( 'Line: %s', line );

		// Initialize an array for storing completion results:
		res = [];

		// Test if the line has an incomplete `require` expression:
		match = line.match( requireRegExp() );
		if ( match ) {
			debug( 'Detected incomplete `require` expression.' );

			exts = objectKeys( repl._context.require.extensions );
			debug( 'Supported `require` filename extensions: %s', exts.join( ', ' ) );

			line = completeRequire( res, match[ 1 ], repl._context.module.paths, exts ); // eslint-disable-line max-len
			res = normalize( res );

			debug( 'Completion filter: %s', line );
			debug( 'Results: %s', res.join( ', ' ) );
			return [ res, line ];
		}
		// Test if the line has an incomplete file system expression:
		match = line.match( fsRegExp() );
		if ( match ) {
			debug( 'Detected incomplete file system expression.' );

			debug( 'Expression: %s', match[ 0 ] );
			debug( 'File system API: %s', match[ 1 ] );
			debug( 'Path to complete: %s', match[ 3 ] );
			line = completeFS( res, match[ 0 ], match[ 1 ], match[ 3 ] );
			res = normalize( res );

			debug( 'Completion filter: %s', line );
			debug( 'Results: %s', res.join( ', ' ) );
			return [ res, line ];
		}
		// Test if the line has an incomplete workspace expression:
		match = line.match( workspaceRegExp() );
		if ( match ) {
			debug( 'Detected incomplete workspace expression.' );

			debug( 'Expression: %s', match[ 0 ] );
			debug( 'Workspace API: %s', match[ 1 ] );
			debug( 'Value to complete: %s', match[ 3 ] );
			line = completeWorkspace( res, repl, match[ 0 ], match[ 1 ], match[ 3 ] ); // eslint-disable-line max-len
			res = normalize( res );

			debug( 'Completion filter: %s', line );
			debug( 'Results: %s', res.join( ', ' ) );
			return [ res, line ];
		}
		debug( 'Attempting to complete an incomplete expression.' );
		line = completeExpression( res, repl._context, line );
		res = normalize( res );
		debug( 'Results: %s', res.join( ', ' ) );
		return [ res, line ];
	}
}

// EXPORTS //

module.exports = completer;
<commit_msg>Use asynchronous completion API<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/* eslint-disable no-underscore-dangle */

'use strict';

// MODULES //

var logger = require( 'debug' );
var objectKeys = require( '@stdlib/utils/keys' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var fsRegExp = require( './regexp_fs_aliases.js' );
var requireRegExp = require( './regexp_require.js' );
var workspaceRegExp = require( './regexp_workspace.js' );
var completeRequire = require( './complete_require.js' );
var completeFS = require( './complete_fs.js' );
var completeWorkspace = require( './complete_workspace.js' );
var completeExpression = require( './complete_expression.js' );

// VARIABLES //

var debug = logger( 'repl:completer' );

// FUNCTIONS //

/**
* Normalizes a completion list.
*
* @private
* @param {Array} list - completion list
* @returns {Array} normalized completion list
*/
function normalize( list ) {
	var hash;
	var i;

	// Get unique values...
	hash = {};
	for ( i = 0; i < list.length; i++ ) {
		if ( !hasOwnProp( hash, list[ i ] ) ) {
			hash[ list[ i ] ] = true;
		}
	}
	list = objectKeys( hash );

	// TODO: sort such that printed columns are in lexicographic order, not rows, similar to bash behavior!

	// Sort the values in lexicographic order:
	list = list.sort();

	return list;
}

// MAIN //

/**
* Returns a callback for supporting TAB completion in a REPL environment.
*
* @private
* @param {REPL} repl - REPL instance
* @returns {Function} TAB completion callback
*/
function completer( repl ) {
	return complete;

	/**
	* Callback invoked upon a user entering the TAB character at the command prompt.
	*
	* @private
	* @param {string} line - current line
	* @param {Function} clbk - completion callback
	* @returns {void}
	*/
	function complete( line, clbk ) {
		var match;
		var exts;
		var res;

		debug( 'Line: %s', line );

		// Initialize an array for storing completion results:
		res = [];

		// Test if the line has an incomplete `require` expression:
		match = line.match( requireRegExp() );
		if ( match ) {
			debug( 'Detected incomplete `require` expression.' );

			exts = objectKeys( repl._context.require.extensions );
			debug( 'Supported `require` filename extensions: %s', exts.join( ', ' ) );

			line = completeRequire( res, match[ 1 ], repl._context.module.paths, exts ); // eslint-disable-line max-len
			res = normalize( res );

			debug( 'Completion filter: %s', line );
			debug( 'Results: %s', res.join( ', ' ) );
			return clbk( null, [ res, line ] );
		}
		// Test if the line has an incomplete file system expression:
		match = line.match( fsRegExp() );
		if ( match ) {
			debug( 'Detected incomplete file system expression.' );

			debug( 'Expression: %s', match[ 0 ] );
			debug( 'File system API: %s', match[ 1 ] );
			debug( 'Path to complete: %s', match[ 3 ] );
			line = completeFS( res, match[ 0 ], match[ 1 ], match[ 3 ] );
			res = normalize( res );

			debug( 'Completion filter: %s', line );
			debug( 'Results: %s', res.join( ', ' ) );
			return clbk( null, [ res, line ] );
		}
		// Test if the line has an incomplete workspace expression:
		match = line.match( workspaceRegExp() );
		if ( match ) {
			debug( 'Detected incomplete workspace expression.' );

			debug( 'Expression: %s', match[ 0 ] );
			debug( 'Workspace API: %s', match[ 1 ] );
			debug( 'Value to complete: %s', match[ 3 ] );
			line = completeWorkspace( res, repl, match[ 0 ], match[ 1 ], match[ 3 ] ); // eslint-disable-line max-len
			res = normalize( res );

			debug( 'Completion filter: %s', line );
			debug( 'Results: %s', res.join( ', ' ) );
			return clbk( null, [ res, line ] );
		}
		debug( 'Attempting to complete an incomplete expression.' );
		line = completeExpression( res, repl._context, line );
		res = normalize( res );
		debug( 'Results: %s', res.join( ', ' ) );
		return clbk( null, [ res, line ] );
	}
}

// EXPORTS //

module.exports = completer;
<|endoftext|>


<commit_before>/*
 * grunt-sequelize
 * https://github.com/webcast-io/grunt-sequelize
 *
 * Copyright (c) 2013 Ben Evans
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var Sequelize = require('sequelize');
var _ = Sequelize.Utils._;
var fs = require('fs');

module.exports = function (grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerTask('sequelize', 'Sequelize migrations from Grunt', function (cmd, arg1) {
    var done;

    var options = this.options({
      environment: process.env.NODE_ENV || 'development',
      // As a default value, assume __dirname is `/<some path>/node_modules/grunt-sequelize/tasks`
      migrationsPath: __dirname + '/../../../migrations',
      logging: false,
      modelsDir: __dirname + '/../../../models'
    });

    if (options.config) {
      _.extend(options, require(options.config)[options.environment]);
    }

    var sequelize = new Sequelize(options.database, options.username, options.password, options);
    var migratorOptions = { path: options.migrationsPath };
    var migrator = sequelize.getMigrator(migratorOptions);

    function getCurrentMigrationId(callback) {
      var migrationVersionEmitter = sequelize.migrator.getLastMigrationIdFromDatabase();
      migrationVersionEmitter.on('success', function (serverMigrationId) {
        callback(null, serverMigrationId);
      });
      migrationVersionEmitter.on('error', function (error) {
        callback(error);
      });
    }

    if (cmd === 'migrate') {
      done = this.async();

      grunt.log.writeln('Migrating database ' + options.database + '...');

      getCurrentMigrationId(function (err, serverMigrationId) {

        if (err) {
          grunt.log.writeln('Error:');
          grunt.log.writeln(err);
          return done();
        }

        if (serverMigrationId === arg1) {
          grunt.log.writeln('There are no pending migrations.');
          return done();
        }

        if (arg1) {
          migratorOptions.to = arg1;
          migratorOptions.from = serverMigrationId;
          migratorOptions.method = (parseInt(migratorOptions.to, 10) >= parseInt(migratorOptions.from, 10)) ? 'up' : 'down';
          migrator = sequelize.getMigrator(migratorOptions);
        }

        sequelize.migrate(migratorOptions).success(done).error(function (err) {
          grunt.log.error(err);
          done(false);
        });

      });

    } else if (cmd === 'undo') {
      done = this.async();

      migrator.findOrCreateSequelizeMetaDAO().success(function (Meta) {
        Meta.find({ order: 'id DESC' }).success(function (meta) {
          if (meta) {
            migrator = sequelize.getMigrator(_.extend(migratorOptions, meta.values), true);
            migrator.migrate({ method: 'down' }).success(done).error(function (err) {
              grunt.log.error(err);
              done(false);
            });
          } else {
            grunt.log.writeln('There are no pending migrations.');
            done();
          }
        });
      });

    } else if (cmd === 'current') {
      done = this.async();

      getCurrentMigrationId(function (err, serverMigrationId) {
        if (err) {
          return done(err);
        }
        grunt.log.write('Current Migration: ', serverMigrationId);
        done();
      });

    } else if (cmd === 'sync') {
      done = this.async();

      grunt.log.writeln('Syncing database ' + options.database + '...');

      var models = [];
      var fileArray = fs
        .readdirSync(options.modelsDir)
        .filter(function (file) {
          return (file.indexOf('.') !== 0) && (file !== 'index.js');
        })
        .forEach(function (file) {
          grunt.log.writeln('Importing... ' + path.join(options.modelsDir, file));

          var model = sequelize.import(path.join(options.modelsDir, file));
          models[model.name] = model;
        });

      var allModels = Object.keys(models);

      var count = 0;
      allModels.forEach(function (modelName) {
        grunt.log.writeln('Cheking associate for ' + modelName + '...');
        if (models[modelName].options.hasOwnProperty('associate')) {
          models[modelName].options.associate(models);
        }

        count++;
        if (count == allModels.length) { // check if all callbacks have been called
          grunt.log.writeln('Now, syncing...');
          sequelize
            .sync()
            .complete(function (err) {
              if (err) {
                grunt.log.writeln('Error:');
                grunt.log.writeln(err);
              } else {
                grunt.log.writeln('Done!');
              }
              done();
            });
        }
      });

    } else if (cmd === 'migration') {
      done = this.async();

      if (!grunt.option('name')) {
        grunt.log.error('No migration name specified!');
        done(false);
      } else {
        var pad = function (n) {
          return n < 10 ? '0' + n : n;
        };

        var date = new Date();
        var migrationTimestamp = date.getFullYear().toString() + (pad(date.getMonth() + 1)).toString() + pad(date.getDate()).toString() + pad(date.getHours()).toString() + pad(date.getMinutes()).toString() + pad(date.getSeconds()).toString();
        var migrationFileName = migrationTimestamp + '-' + grunt.option('name') + '.js';

        var skeleton = fs.readFileSync(__dirname + '/../data/migration.js').toString();

        fs.writeFileSync(options.migrationsPath + '/' + migrationFileName, skeleton);

        grunt.log.writeln('Migration created: ' + migrationFileName);
      }
    } else {
      throw new Error('Unknown grunt-sequelize command: ' + cmd);
    }

  });

};
<commit_msg>Use strict equality<commit_after>/*
 * grunt-sequelize
 * https://github.com/webcast-io/grunt-sequelize
 *
 * Copyright (c) 2013 Ben Evans
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var Sequelize = require('sequelize');
var _ = Sequelize.Utils._;
var fs = require('fs');

module.exports = function (grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerTask('sequelize', 'Sequelize migrations from Grunt', function (cmd, arg1) {
    var done;

    var options = this.options({
      environment: process.env.NODE_ENV || 'development',
      // As a default value, assume __dirname is `/<some path>/node_modules/grunt-sequelize/tasks`
      migrationsPath: __dirname + '/../../../migrations',
      logging: false,
      modelsDir: __dirname + '/../../../models'
    });

    if (options.config) {
      _.extend(options, require(options.config)[options.environment]);
    }

    var sequelize = new Sequelize(options.database, options.username, options.password, options);
    var migratorOptions = { path: options.migrationsPath };
    var migrator = sequelize.getMigrator(migratorOptions);

    function getCurrentMigrationId(callback) {
      var migrationVersionEmitter = sequelize.migrator.getLastMigrationIdFromDatabase();
      migrationVersionEmitter.on('success', function (serverMigrationId) {
        callback(null, serverMigrationId);
      });
      migrationVersionEmitter.on('error', function (error) {
        callback(error);
      });
    }

    if (cmd === 'migrate') {
      done = this.async();

      grunt.log.writeln('Migrating database ' + options.database + '...');

      getCurrentMigrationId(function (err, serverMigrationId) {

        if (err) {
          grunt.log.writeln('Error:');
          grunt.log.writeln(err);
          return done();
        }

        if (serverMigrationId === arg1) {
          grunt.log.writeln('There are no pending migrations.');
          return done();
        }

        if (arg1) {
          migratorOptions.to = arg1;
          migratorOptions.from = serverMigrationId;
          migratorOptions.method = (parseInt(migratorOptions.to, 10) >= parseInt(migratorOptions.from, 10)) ? 'up' : 'down';
          migrator = sequelize.getMigrator(migratorOptions);
        }

        sequelize.migrate(migratorOptions).success(done).error(function (err) {
          grunt.log.error(err);
          done(false);
        });

      });

    } else if (cmd === 'undo') {
      done = this.async();

      migrator.findOrCreateSequelizeMetaDAO().success(function (Meta) {
        Meta.find({ order: 'id DESC' }).success(function (meta) {
          if (meta) {
            migrator = sequelize.getMigrator(_.extend(migratorOptions, meta.values), true);
            migrator.migrate({ method: 'down' }).success(done).error(function (err) {
              grunt.log.error(err);
              done(false);
            });
          } else {
            grunt.log.writeln('There are no pending migrations.');
            done();
          }
        });
      });

    } else if (cmd === 'current') {
      done = this.async();

      getCurrentMigrationId(function (err, serverMigrationId) {
        if (err) {
          return done(err);
        }
        grunt.log.write('Current Migration: ', serverMigrationId);
        done();
      });

    } else if (cmd === 'sync') {
      done = this.async();

      grunt.log.writeln('Syncing database ' + options.database + '...');

      var models = [];
      var fileArray = fs
        .readdirSync(options.modelsDir)
        .filter(function (file) {
          return (file.indexOf('.') !== 0) && (file !== 'index.js');
        })
        .forEach(function (file) {
          grunt.log.writeln('Importing... ' + path.join(options.modelsDir, file));

          var model = sequelize.import(path.join(options.modelsDir, file));
          models[model.name] = model;
        });

      var allModels = Object.keys(models);

      var count = 0;
      allModels.forEach(function (modelName) {
        grunt.log.writeln('Cheking associate for ' + modelName + '...');
        if (models[modelName].options.hasOwnProperty('associate')) {
          models[modelName].options.associate(models);
        }

        count++;
        if (count === allModels.length) { // check if all callbacks have been called
          grunt.log.writeln('Now, syncing...');
          sequelize
            .sync()
            .complete(function (err) {
              if (err) {
                grunt.log.writeln('Error:');
                grunt.log.writeln(err);
              } else {
                grunt.log.writeln('Done!');
              }
              done();
            });
        }
      });

    } else if (cmd === 'migration') {
      done = this.async();

      if (!grunt.option('name')) {
        grunt.log.error('No migration name specified!');
        done(false);
      } else {
        var pad = function (n) {
          return n < 10 ? '0' + n : n;
        };

        var date = new Date();
        var migrationTimestamp = date.getFullYear().toString() + (pad(date.getMonth() + 1)).toString() + pad(date.getDate()).toString() + pad(date.getHours()).toString() + pad(date.getMinutes()).toString() + pad(date.getSeconds()).toString();
        var migrationFileName = migrationTimestamp + '-' + grunt.option('name') + '.js';

        var skeleton = fs.readFileSync(__dirname + '/../data/migration.js').toString();

        fs.writeFileSync(options.migrationsPath + '/' + migrationFileName, skeleton);

        grunt.log.writeln('Migration created: ' + migrationFileName);
      }
    } else {
      throw new Error('Unknown grunt-sequelize command: ' + cmd);
    }

  });

};
<|endoftext|>


<commit_before>
module.exports = function(gulp) {

  gulp.task('templates', function() {
    var gutil = gulp.plugin.util,
        prod  = gutil.env.prod;

    return gulp.src('./src/views/*.jade')
      .pipe( gulp.plugin.plumber() )
      .pipe( gulp.plugin.jade({pretty: !prod}) )
      .on('error', gulp.plugin.notify.onError(function(error){
        return error.message.split('\n').pop();
      }))
      .pipe( gulp.dest(prod ? './dist/' : './dev/') )
      .pipe( prod ? gutil.noop() : gulp.plugin.connect.reload() );
  });

};
<commit_msg>Inject data to jade files<commit_after>
module.exports = function(gulp) {

  gulp.task('templates', function() {
    var gutil = gulp.plugin.util,
        prod  = gutil.env.prod,
        data = {
          'env': prod ? 'production' : 'development',
          'flags': gutil.env
        };

    return gulp.src('./src/views/*.jade')
      .pipe( gulp.plugin.plumber() )
      .pipe( gulp.plugin.jade({pretty: !prod, data: data}) )
      .on('error', gulp.plugin.notify.onError(function(error){
        return error.message.split('\n').pop();
      }))
      .pipe( gulp.dest(prod ? './dist/' : './dev/') )
      .pipe( prod ? gutil.noop() : gulp.plugin.connect.reload() );
  });

};
<|endoftext|>


<commit_before>import React, { Component, Fragment } from 'react';
import EsriMap from 'esri/Map';
import MapView from './MapView';
import './App.css';

var map = new EsriMap({
  basemap: 'streets',
});

class App extends Component {
  state = {
    center: {
      spatialReference: { latestWkid: 3857, wkid: 102100 },
      x: 15047024.975994881,
      y: -2875028.188734928,
    },
  };
  render() {
    return (
      <Fragment>

          center = x:{this.state.center.x} ,y:{this.state.center.y}

        <MapView
          map={map}
          onCenterChange={center => {
            this.setState({ center });
          }}
        />
      </Fragment>
    );
  }
}

export default App;
<commit_msg>Minor change<commit_after>import React, { Component, Fragment } from 'react';
import EsriMap from 'esri/Map';
import MapView from './MapView';
import './App.css';

var map = new EsriMap({
  basemap: 'streets',
});

class App extends Component {
  state = {
    center: {
      spatialReference: { latestWkid: 3857, wkid: 102100 },
      x: 15047024.975994881,
      y: -2875028.188734928,
    },
  };
  render() {
    return (
      <Fragment>

          center :
 x={this.state.center.x}
y={this.state.center.y}

        <MapView
          map={map}
          onCenterChange={center => {
            this.setState({ center });
          }}
        />
      </Fragment>
    );
  }
}

export default App;
<|endoftext|>


<commit_before>/**
 * Copyright IBM Corp. 2016, 2018
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import { settings } from 'carbon-components';
import { ChevronLeft16, ChevronRight16 } from '@carbon/icons-react';
import debounce from 'lodash.debounce';
import { keys, match, matches } from '../../internal/keyboard';
import TabContent from '../TabContent';

const { prefix } = settings;

export default class Tabs extends React.Component {
  static propTypes = {
    /**
     * Pass in a collection of <Tab> children to be rendered depending on the
     * currently selected tab
     */
    children: PropTypes.node,

    /**
     * Provide a className that is applied to the root
 component for the
     * <Tabs>
     */
    className: PropTypes.string,

    /**
     * Specify whether the Tab content is hidden
     */
    hidden: PropTypes.bool,

    /**
     * Provide the props that describe the left overflow button
     */
    leftOverflowButtonProps: PropTypes.object,

    /**
     * Specify whether or not to use the light component variant
     */
    light: PropTypes.bool,

    /**
     * Optionally provide an `onClick` handler that is invoked when a <Tab> is
     * clicked
     */
    onClick: PropTypes.func,

    /**
     * Optionally provide an `onKeyDown` handler that is invoked when keyed
     * navigation is triggered
     */
    onKeyDown: PropTypes.func,

    /**
     * Provide an optional handler that is called whenever the selection
     * changes. This method is called with the index of the tab that was
     * selected
     */
    onSelectionChange: PropTypes.func,

    /**
     * Provide the props that describe the right overflow button
     */
    rightOverflowButtonProps: PropTypes.object,

    /**
     * Choose whether or not to automatically scroll to newly selected tabs
     * on component rerender
     */
    scrollIntoView: PropTypes.bool,

    /**
     * Optionally provide an index for the currently selected <Tab>
     */
    selected: PropTypes.number,

    /**
     * Choose whether or not to automatically change selection on focus
     */
    selectionMode: PropTypes.oneOf(['automatic', 'manual']),

    /**
     * Provide a className that is applied to the <TabContent> components
     */
    tabContentClassName: PropTypes.string,

    /**
     * Provide the type of Tab
     */
    type: PropTypes.oneOf(['default', 'container']),
  };

  static defaultProps = {
    type: 'default',
    scrollIntoView: true,
    selected: 0,
    selectionMode: 'automatic',
  };

  state = {
    horizontalOverflow: false,
  };

  tablist = React.createRef();
  leftOverflowNavButton = React.createRef();
  rightOverflowNavButton = React.createRef();
  // width of the overflow buttons
  OVERFLOW_BUTTON_OFFSET = 40;

  static getDerivedStateFromProps({ selected }, state) {
    const { prevSelected } = state;
    return prevSelected === selected
      ? null
      : {
          selected,
          prevSelected: selected,
        };
  }

  /**
   * `scroll` event handler to save tablist clientWidth, scrollWidth, and
   * scrollLeft
   */
  handleScroll = () => {
    if (!this.tablist?.current) {
      return;
    }
    const {
      clientWidth: tablistClientWidth,
      scrollLeft: tablistScrollLeft,
      scrollWidth: tablistScrollWidth,
    } = this.tablist.current;
    this.setState({
      tablistClientWidth,
      horizontalOverflow: tablistScrollWidth > tablistClientWidth,
      tablistScrollWidth,
      tablistScrollLeft,
    });
  };

  /**
   * The debounced version of the `resize` event handler.
   * @type {Function}
   * @private
   */
  _debouncedHandleWindowResize = null;

  _handleWindowResize = this.handleScroll;

  componentDidMount() {
    if (!this._debouncedHandleWindowResize) {
      this._debouncedHandleWindowResize = debounce(
        this._handleWindowResize,
        200
      );
    }

    this._handleWindowResize();
    window.addEventListener('resize', this._debouncedHandleWindowResize);

    // scroll selected tab into view on mount
    const {
      clientWidth: tablistClientWidth,
      scrollLeft: tablistScrollLeft,
      scrollWidth: tablistScrollWidth,
    } = this.tablist?.current || {};
    const tab = this.getTabAt(this.state.selected);
    const horizontalOverflow = tablistScrollWidth > tablistClientWidth;

    if (horizontalOverflow) {
      const leftOverflowNavButtonHidden =
        tab?.tabAnchor?.getBoundingClientRect().right <
        tab?.tabAnchor?.offsetParent.getBoundingClientRect().right;
      const rightOverflowNavButtonHidden =
        tablistScrollLeft + tablistClientWidth === tablistScrollWidth;
      tab?.tabAnchor?.scrollIntoView({ block: 'nearest', inline: 'nearest' });

      // account for overflow buttons in scroll position on mount
      if (!leftOverflowNavButtonHidden && !rightOverflowNavButtonHidden) {
        this.tablist.current.scrollLeft += this.OVERFLOW_BUTTON_OFFSET * 2;
      }
    }
  }

  componentWillUnmount() {
    if (this._debouncedHandleWindowResize) {
      this._debouncedHandleWindowResize.cancel();
    }
    window.removeEventListener('resize', this._debouncedHandleWindowResize);
  }

  componentDidUpdate(_, prevState) {
    // compare current tablist properties to current state
    const {
      clientWidth: tablistClientWidth,
      scrollLeft: tablistScrollLeft,
      scrollWidth: tablistScrollWidth,
    } = this.tablist.current;
    const {
      tablistClientWidth: currentStateClientWidth,
      tablistScrollLeft: currentStateScrollLeft,
      tablistScrollWidth: currentStateScrollWidth,
      selected,
    } = this.state;

    if (
      tablistClientWidth !== currentStateClientWidth ||
      tablistScrollLeft !== currentStateScrollLeft ||
      tablistScrollWidth !== currentStateScrollWidth
    ) {
      this.setState({
        horizontalOverflow: tablistScrollWidth > tablistClientWidth,
        tablistClientWidth,
        tablistScrollLeft,
        tablistScrollWidth,
      });
    }

    if (this.props.scrollIntoView && prevState.selected !== selected) {
      this.getTabAt(selected)?.tabAnchor?.scrollIntoView({
        block: 'nearest',
        inline: 'nearest',
      });
    }
  }

  getEnabledTabs = () =>
    React.Children.toArray(this.props.children).reduce(
      (enabledTabs, tab, index) =>
        !tab.props.disabled ? enabledTabs.concat(index) : enabledTabs,
      []
    );

  getNextIndex = (index, direction) => {
    const enabledTabs = this.getEnabledTabs();
    const nextIndex = Math.max(
      enabledTabs.indexOf(index) + direction,
      // For `tab` not found in `enabledTabs`
      -1
    );
    const nextIndexLooped =
      nextIndex >= 0 && nextIndex < enabledTabs.length
        ? nextIndex
        : nextIndex - Math.sign(nextIndex) * enabledTabs.length;
    return enabledTabs[nextIndexLooped];
  };

  getDirection = (evt) => {
    if (match(evt, keys.ArrowLeft)) {
      return -1;
    }
    if (match(evt, keys.ArrowRight)) {
      return 1;
    }
    return 0;
  };

  getTabAt = (index, useFresh) =>
    (!useFresh && this[`tab${index}`]) ||
    React.Children.toArray(this.props.children)[index];

  scrollTabIntoView = (event, { index }) => {
    const tab = this.getTabAt(index);
    if (
      matches(event, [keys.ArrowLeft, keys.ArrowRight]) ||
      event.type === 'click'
    ) {
      const currentScrollLeft = this.state.tablistScrollLeft;
      tab?.tabAnchor?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
      const newScrollLeft = this.tablist.current.scrollLeft;
      if (newScrollLeft > currentScrollLeft) {
        this.tablist.current.scrollLeft += this.OVERFLOW_BUTTON_OFFSET;
      }
    }
  };

  selectTabAt = (event, { index, onSelectionChange }) => {
    this.scrollTabIntoView(event, { index });
    if (this.state.selected !== index) {
      this.setState({
        selected: index,
      });
      if (typeof onSelectionChange === 'function') {
        onSelectionChange(index);
      }
    }
  };

  handleTabKeyDown = (onSelectionChange) => {
    return (index, evt) => {
      if (matches(evt, [keys.Enter, keys.Space])) {
        this.selectTabAt(evt, { index, onSelectionChange });
      }

      const nextIndex = (() => {
        if (matches(evt, [keys.ArrowLeft, keys.ArrowRight])) {
          return this.getNextIndex(index, this.getDirection(evt));
        }
        if (match(evt, keys.Home)) {
          return 0;
        }
        if (match(evt, keys.End)) {
          return this.getEnabledTabs().pop();
        }
      })();
      const tab = this.getTabAt(nextIndex);

      if (
        matches(evt, [keys.ArrowLeft, keys.ArrowRight, keys.Home, keys.End])
      ) {
        evt.preventDefault();
        if (this.props.selectionMode !== 'manual') {
          this.selectTabAt(evt, { index: nextIndex, onSelectionChange });
        } else {
          this.scrollTabIntoView(evt, { index: nextIndex });
        }
        tab?.tabAnchor?.focus();
      }
    };
  };

  getTabs = () => React.Children.map(this.props.children, (tab) => tab);

  // following functions (handle*) are Props on Tab.js, see Tab.js for parameters
  handleTabClick = (onSelectionChange) => (index, evt) => {
    evt.preventDefault();
    this.selectTabAt(evt, { index, onSelectionChange });
  };

  setTabAt = (index, tabRef) => {
    this[`tab${index}`] = tabRef;
  };

  overflowNavInterval = null;

  handleOverflowNavClick = (_, { direction, multiplier = 10 }) => {
    // account for overflow button appearing and causing tablist width change
    const { clientWidth, scrollLeft, scrollWidth } = this.tablist?.current;
    if (direction === 1 && !scrollLeft) {
      this.tablist.current.scrollLeft += this.OVERFLOW_BUTTON_OFFSET;
    }

    this.tablist.current.scrollLeft += direction * multiplier;

    const leftEdgeReached =
      direction === -1 && scrollLeft < this.OVERFLOW_BUTTON_OFFSET;
    const rightEdgeReached =
      direction === 1 &&
      scrollLeft + clientWidth >= scrollWidth - this.OVERFLOW_BUTTON_OFFSET;
    if (leftEdgeReached || rightEdgeReached) {
      if (leftEdgeReached) {
        this.rightOverflowNavButton?.current?.focus();
      }
      if (rightEdgeReached) {
        this.leftOverflowNavButton?.current?.focus();
      }
    }
  };

  handleOverflowNavMouseDown = (event, { direction }) => {
    // disregard mouse buttons aside from LMB
    if (event.buttons !== 1) {
      return;
    }
    this.overflowNavInterval = setInterval(() => {
      const { clientWidth, scrollLeft, scrollWidth } = this.tablist?.current;

      // clear interval if scroll reaches left or right edge
      const leftEdgeReached =
        direction === -1 && scrollLeft < this.OVERFLOW_BUTTON_OFFSET;
      const rightEdgeReached =
        direction === 1 &&
        scrollLeft + clientWidth >= scrollWidth - this.OVERFLOW_BUTTON_OFFSET;
      if (leftEdgeReached || rightEdgeReached) {
        clearInterval(this.overflowNavInterval);
      }

      // account for overflow button appearing and causing tablist width change
      this.handleOverflowNavClick(event, { direction });
    });
  };

  handleOverflowNavMouseUp = () => {
    clearInterval(this.overflowNavInterval);
  };

  render() {
    const {
      className,
      type,
      light,
      onSelectionChange,
      scrollIntoView, // eslint-disable-line no-unused-vars
      selectionMode, // eslint-disable-line no-unused-vars
      tabContentClassName,
      leftOverflowButtonProps,
      rightOverflowButtonProps,
      ...other
    } = this.props;

    /**
     * The tab panel acts like a tab panel when the screen is wider, but acts
     * like a select list when the screen is narrow.  In the wide case we want
     * to allow the user to use the tab key to set the focus in the tab panel
     * and then use the left and right arrow keys to navigate the tabs.  In the
     * narrow case we want to use the tab key to select different options in
     * the list.
     *
     * We set the tab index based on the different states so the browser will treat
     * the whole tab panel as a single focus component when it looks like a tab
     * panel and separate components when it looks like a select list.
     */
    const tabsWithProps = this.getTabs().map((tab, index) => {
      const tabIndex = index === this.state.selected ? 0 : -1;
      const newTab = React.cloneElement(tab, {
        index,
        selected: index === this.state.selected,
        handleTabClick: this.handleTabClick(onSelectionChange),
        tabIndex,
        ref: (e) => {
          this.setTabAt(index, e);
        },
        handleTabKeyDown: this.handleTabKeyDown(onSelectionChange),
      });

      return newTab;
    });

    const tabContentWithProps = React.Children.map(tabsWithProps, (tab) => {
      const {
        id: tabId,
        children,
        selected,
        renderContent: Content = TabContent,
      } = tab.props;

      return (
        <Content
          id={tabId && `${tabId}__panel`}
          className={tabContentClassName}
          hidden={!selected}
          selected={selected}
          aria-labelledby={tabId}>
          {children}
        </Content>
      );
    });

    const leftOverflowNavButtonHidden =
      !this.state.horizontalOverflow || !this.state.tablistScrollLeft;
    const rightOverflowNavButtonHidden =
      !this.state.horizontalOverflow ||
      this.state.tablistScrollLeft + this.state.tablistClientWidth ===
        this.state.tablistScrollWidth;
    const classes = {
      // TODO: remove scrollable from classnames in next major release and uncomment classnames that don't contain scrollable
      tabs: classNames(
        className,
        // `${prefix}--tabs`,
        `${prefix}--tabs--scrollable`,
        {
          // [`${prefix}--tabs--container`]: type === 'container',
          [`${prefix}--tabs--scrollable--container`]: type === 'container',
          // [`${prefix}--tabs--light`]: light,
          [`${prefix}--tabs--scrollable--light`]: light,
        }
      ),
      // TODO: remove scrollable from classnames in next major release and uncomment classnames that don't contain scrollable
      tablist: classNames(
        // `${prefix}--tabs__nav`,
        `${prefix}--tabs--scrollable__nav`
      ),
      leftOverflowButtonClasses: classNames({
        [`${prefix}--tab--overflow-nav-button`]: this.state.horizontalOverflow,
        [`${prefix}--tab--overflow-nav-button--hidden`]: leftOverflowNavButtonHidden,
      }),
      rightOverflowButtonClasses: classNames({
        [`${prefix}--tab--overflow-nav-button`]: this.state.horizontalOverflow,
        [`${prefix}--tab--overflow-nav-button--hidden`]: rightOverflowNavButtonHidden,
      }),
    };

    return (
      <>

          <button
            aria-hidden="true"
            aria-label="Scroll left"
            className={classes.leftOverflowButtonClasses}
            onClick={(_) => this.handleOverflowNavClick(_, { direction: -1 })}
            onMouseDown={(event) =>
              this.handleOverflowNavMouseDown(event, { direction: -1 })
            }
            onMouseUp={this.handleOverflowNavMouseUp}
            ref={this.leftOverflowNavButton}
            tabIndex="-1"
            type="button"
            {...leftOverflowButtonProps}>
            <ChevronLeft16 />
          </button>
          {!leftOverflowNavButtonHidden && (
            <div className={`${prefix}--tabs__overflow-indicator--left`} />
          )}

            {tabsWithProps}

          {!rightOverflowNavButtonHidden && (
            <div className={`${prefix}--tabs__overflow-indicator--right`} />
          )}
          <button
            aria-hidden="true"
            aria-label="Scroll right"
            className={classes.rightOverflowButtonClasses}
            onClick={(_) => this.handleOverflowNavClick(_, { direction: 1 })}
            onMouseDown={(event) =>
              this.handleOverflowNavMouseDown(event, { direction: 1 })
            }
            onMouseUp={this.handleOverflowNavMouseUp}
            ref={this.rightOverflowNavButton}
            tabIndex="-1"
            type="button"
            {...rightOverflowButtonProps}>
            <ChevronRight16 />
          </button>

        {tabContentWithProps}
      </>
    );
  }
}
<commit_msg>fix(Tabs): apply `scrollIntoView` prop on mount (#7543)<commit_after>/**
 * Copyright IBM Corp. 2016, 2018
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import { settings } from 'carbon-components';
import { ChevronLeft16, ChevronRight16 } from '@carbon/icons-react';
import debounce from 'lodash.debounce';
import { keys, match, matches } from '../../internal/keyboard';
import TabContent from '../TabContent';

const { prefix } = settings;

export default class Tabs extends React.Component {
  static propTypes = {
    /**
     * Pass in a collection of <Tab> children to be rendered depending on the
     * currently selected tab
     */
    children: PropTypes.node,

    /**
     * Provide a className that is applied to the root
 component for the
     * <Tabs>
     */
    className: PropTypes.string,

    /**
     * Specify whether the Tab content is hidden
     */
    hidden: PropTypes.bool,

    /**
     * Provide the props that describe the left overflow button
     */
    leftOverflowButtonProps: PropTypes.object,

    /**
     * Specify whether or not to use the light component variant
     */
    light: PropTypes.bool,

    /**
     * Optionally provide an `onClick` handler that is invoked when a <Tab> is
     * clicked
     */
    onClick: PropTypes.func,

    /**
     * Optionally provide an `onKeyDown` handler that is invoked when keyed
     * navigation is triggered
     */
    onKeyDown: PropTypes.func,

    /**
     * Provide an optional handler that is called whenever the selection
     * changes. This method is called with the index of the tab that was
     * selected
     */
    onSelectionChange: PropTypes.func,

    /**
     * Provide the props that describe the right overflow button
     */
    rightOverflowButtonProps: PropTypes.object,

    /**
     * Choose whether or not to automatically scroll to newly selected tabs
     * on component rerender
     */
    scrollIntoView: PropTypes.bool,

    /**
     * Optionally provide an index for the currently selected <Tab>
     */
    selected: PropTypes.number,

    /**
     * Choose whether or not to automatically change selection on focus
     */
    selectionMode: PropTypes.oneOf(['automatic', 'manual']),

    /**
     * Provide a className that is applied to the <TabContent> components
     */
    tabContentClassName: PropTypes.string,

    /**
     * Provide the type of Tab
     */
    type: PropTypes.oneOf(['default', 'container']),
  };

  static defaultProps = {
    type: 'default',
    scrollIntoView: true,
    selected: 0,
    selectionMode: 'automatic',
  };

  state = {
    horizontalOverflow: false,
  };

  tablist = React.createRef();
  leftOverflowNavButton = React.createRef();
  rightOverflowNavButton = React.createRef();
  // width of the overflow buttons
  OVERFLOW_BUTTON_OFFSET = 40;

  static getDerivedStateFromProps({ selected }, state) {
    const { prevSelected } = state;
    return prevSelected === selected
      ? null
      : {
          selected,
          prevSelected: selected,
        };
  }

  /**
   * `scroll` event handler to save tablist clientWidth, scrollWidth, and
   * scrollLeft
   */
  handleScroll = () => {
    if (!this.tablist?.current) {
      return;
    }
    const {
      clientWidth: tablistClientWidth,
      scrollLeft: tablistScrollLeft,
      scrollWidth: tablistScrollWidth,
    } = this.tablist.current;
    this.setState({
      tablistClientWidth,
      horizontalOverflow: tablistScrollWidth > tablistClientWidth,
      tablistScrollWidth,
      tablistScrollLeft,
    });
  };

  /**
   * The debounced version of the `resize` event handler.
   * @type {Function}
   * @private
   */
  _debouncedHandleWindowResize = null;

  _handleWindowResize = this.handleScroll;

  componentDidMount() {
    if (!this._debouncedHandleWindowResize) {
      this._debouncedHandleWindowResize = debounce(
        this._handleWindowResize,
        200
      );
    }

    this._handleWindowResize();
    window.addEventListener('resize', this._debouncedHandleWindowResize);

    // scroll selected tab into view on mount
    const {
      clientWidth: tablistClientWidth,
      scrollLeft: tablistScrollLeft,
      scrollWidth: tablistScrollWidth,
    } = this.tablist?.current || {};
    const tab = this.getTabAt(this.state.selected);
    const horizontalOverflow = tablistScrollWidth > tablistClientWidth;

    if (horizontalOverflow) {
      const leftOverflowNavButtonHidden =
        tab?.tabAnchor?.getBoundingClientRect().right <
        tab?.tabAnchor?.offsetParent.getBoundingClientRect().right;
      const rightOverflowNavButtonHidden =
        tablistScrollLeft + tablistClientWidth === tablistScrollWidth;
      this.props.scrollIntoView &&
        tab?.tabAnchor?.scrollIntoView({ block: 'nearest', inline: 'nearest' });

      // account for overflow buttons in scroll position on mount
      if (!leftOverflowNavButtonHidden && !rightOverflowNavButtonHidden) {
        this.tablist.current.scrollLeft += this.OVERFLOW_BUTTON_OFFSET * 2;
      }
    }
  }

  componentWillUnmount() {
    if (this._debouncedHandleWindowResize) {
      this._debouncedHandleWindowResize.cancel();
    }
    window.removeEventListener('resize', this._debouncedHandleWindowResize);
  }

  componentDidUpdate(_, prevState) {
    // compare current tablist properties to current state
    const {
      clientWidth: tablistClientWidth,
      scrollLeft: tablistScrollLeft,
      scrollWidth: tablistScrollWidth,
    } = this.tablist.current;
    const {
      tablistClientWidth: currentStateClientWidth,
      tablistScrollLeft: currentStateScrollLeft,
      tablistScrollWidth: currentStateScrollWidth,
      selected,
    } = this.state;

    if (
      tablistClientWidth !== currentStateClientWidth ||
      tablistScrollLeft !== currentStateScrollLeft ||
      tablistScrollWidth !== currentStateScrollWidth
    ) {
      this.setState({
        horizontalOverflow: tablistScrollWidth > tablistClientWidth,
        tablistClientWidth,
        tablistScrollLeft,
        tablistScrollWidth,
      });
    }

    if (this.props.scrollIntoView && prevState.selected !== selected) {
      this.getTabAt(selected)?.tabAnchor?.scrollIntoView({
        block: 'nearest',
        inline: 'nearest',
      });
    }
  }

  getEnabledTabs = () =>
    React.Children.toArray(this.props.children).reduce(
      (enabledTabs, tab, index) =>
        !tab.props.disabled ? enabledTabs.concat(index) : enabledTabs,
      []
    );

  getNextIndex = (index, direction) => {
    const enabledTabs = this.getEnabledTabs();
    const nextIndex = Math.max(
      enabledTabs.indexOf(index) + direction,
      // For `tab` not found in `enabledTabs`
      -1
    );
    const nextIndexLooped =
      nextIndex >= 0 && nextIndex < enabledTabs.length
        ? nextIndex
        : nextIndex - Math.sign(nextIndex) * enabledTabs.length;
    return enabledTabs[nextIndexLooped];
  };

  getDirection = (evt) => {
    if (match(evt, keys.ArrowLeft)) {
      return -1;
    }
    if (match(evt, keys.ArrowRight)) {
      return 1;
    }
    return 0;
  };

  getTabAt = (index, useFresh) =>
    (!useFresh && this[`tab${index}`]) ||
    React.Children.toArray(this.props.children)[index];

  scrollTabIntoView = (event, { index }) => {
    const tab = this.getTabAt(index);
    if (
      matches(event, [keys.ArrowLeft, keys.ArrowRight]) ||
      event.type === 'click'
    ) {
      const currentScrollLeft = this.state.tablistScrollLeft;
      tab?.tabAnchor?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
      const newScrollLeft = this.tablist.current.scrollLeft;
      if (newScrollLeft > currentScrollLeft) {
        this.tablist.current.scrollLeft += this.OVERFLOW_BUTTON_OFFSET;
      }
    }
  };

  selectTabAt = (event, { index, onSelectionChange }) => {
    this.scrollTabIntoView(event, { index });
    if (this.state.selected !== index) {
      this.setState({
        selected: index,
      });
      if (typeof onSelectionChange === 'function') {
        onSelectionChange(index);
      }
    }
  };

  handleTabKeyDown = (onSelectionChange) => {
    return (index, evt) => {
      if (matches(evt, [keys.Enter, keys.Space])) {
        this.selectTabAt(evt, { index, onSelectionChange });
      }

      const nextIndex = (() => {
        if (matches(evt, [keys.ArrowLeft, keys.ArrowRight])) {
          return this.getNextIndex(index, this.getDirection(evt));
        }
        if (match(evt, keys.Home)) {
          return 0;
        }
        if (match(evt, keys.End)) {
          return this.getEnabledTabs().pop();
        }
      })();
      const tab = this.getTabAt(nextIndex);

      if (
        matches(evt, [keys.ArrowLeft, keys.ArrowRight, keys.Home, keys.End])
      ) {
        evt.preventDefault();
        if (this.props.selectionMode !== 'manual') {
          this.selectTabAt(evt, { index: nextIndex, onSelectionChange });
        } else {
          this.scrollTabIntoView(evt, { index: nextIndex });
        }
        tab?.tabAnchor?.focus();
      }
    };
  };

  getTabs = () => React.Children.map(this.props.children, (tab) => tab);

  // following functions (handle*) are Props on Tab.js, see Tab.js for parameters
  handleTabClick = (onSelectionChange) => (index, evt) => {
    evt.preventDefault();
    this.selectTabAt(evt, { index, onSelectionChange });
  };

  setTabAt = (index, tabRef) => {
    this[`tab${index}`] = tabRef;
  };

  overflowNavInterval = null;

  handleOverflowNavClick = (_, { direction, multiplier = 10 }) => {
    // account for overflow button appearing and causing tablist width change
    const { clientWidth, scrollLeft, scrollWidth } = this.tablist?.current;
    if (direction === 1 && !scrollLeft) {
      this.tablist.current.scrollLeft += this.OVERFLOW_BUTTON_OFFSET;
    }

    this.tablist.current.scrollLeft += direction * multiplier;

    const leftEdgeReached =
      direction === -1 && scrollLeft < this.OVERFLOW_BUTTON_OFFSET;
    const rightEdgeReached =
      direction === 1 &&
      scrollLeft + clientWidth >= scrollWidth - this.OVERFLOW_BUTTON_OFFSET;
    if (leftEdgeReached || rightEdgeReached) {
      if (leftEdgeReached) {
        this.rightOverflowNavButton?.current?.focus();
      }
      if (rightEdgeReached) {
        this.leftOverflowNavButton?.current?.focus();
      }
    }
  };

  handleOverflowNavMouseDown = (event, { direction }) => {
    // disregard mouse buttons aside from LMB
    if (event.buttons !== 1) {
      return;
    }
    this.overflowNavInterval = setInterval(() => {
      const { clientWidth, scrollLeft, scrollWidth } = this.tablist?.current;

      // clear interval if scroll reaches left or right edge
      const leftEdgeReached =
        direction === -1 && scrollLeft < this.OVERFLOW_BUTTON_OFFSET;
      const rightEdgeReached =
        direction === 1 &&
        scrollLeft + clientWidth >= scrollWidth - this.OVERFLOW_BUTTON_OFFSET;
      if (leftEdgeReached || rightEdgeReached) {
        clearInterval(this.overflowNavInterval);
      }

      // account for overflow button appearing and causing tablist width change
      this.handleOverflowNavClick(event, { direction });
    });
  };

  handleOverflowNavMouseUp = () => {
    clearInterval(this.overflowNavInterval);
  };

  render() {
    const {
      className,
      type,
      light,
      onSelectionChange,
      scrollIntoView, // eslint-disable-line no-unused-vars
      selectionMode, // eslint-disable-line no-unused-vars
      tabContentClassName,
      leftOverflowButtonProps,
      rightOverflowButtonProps,
      ...other
    } = this.props;

    /**
     * The tab panel acts like a tab panel when the screen is wider, but acts
     * like a select list when the screen is narrow.  In the wide case we want
     * to allow the user to use the tab key to set the focus in the tab panel
     * and then use the left and right arrow keys to navigate the tabs.  In the
     * narrow case we want to use the tab key to select different options in
     * the list.
     *
     * We set the tab index based on the different states so the browser will treat
     * the whole tab panel as a single focus component when it looks like a tab
     * panel and separate components when it looks like a select list.
     */
    const tabsWithProps = this.getTabs().map((tab, index) => {
      const tabIndex = index === this.state.selected ? 0 : -1;
      const newTab = React.cloneElement(tab, {
        index,
        selected: index === this.state.selected,
        handleTabClick: this.handleTabClick(onSelectionChange),
        tabIndex,
        ref: (e) => {
          this.setTabAt(index, e);
        },
        handleTabKeyDown: this.handleTabKeyDown(onSelectionChange),
      });

      return newTab;
    });

    const tabContentWithProps = React.Children.map(tabsWithProps, (tab) => {
      const {
        id: tabId,
        children,
        selected,
        renderContent: Content = TabContent,
      } = tab.props;

      return (
        <Content
          id={tabId && `${tabId}__panel`}
          className={tabContentClassName}
          hidden={!selected}
          selected={selected}
          aria-labelledby={tabId}>
          {children}
        </Content>
      );
    });

    const leftOverflowNavButtonHidden =
      !this.state.horizontalOverflow || !this.state.tablistScrollLeft;
    const rightOverflowNavButtonHidden =
      !this.state.horizontalOverflow ||
      this.state.tablistScrollLeft + this.state.tablistClientWidth ===
        this.state.tablistScrollWidth;
    const classes = {
      // TODO: remove scrollable from classnames in next major release and uncomment classnames that don't contain scrollable
      tabs: classNames(
        className,
        // `${prefix}--tabs`,
        `${prefix}--tabs--scrollable`,
        {
          // [`${prefix}--tabs--container`]: type === 'container',
          [`${prefix}--tabs--scrollable--container`]: type === 'container',
          // [`${prefix}--tabs--light`]: light,
          [`${prefix}--tabs--scrollable--light`]: light,
        }
      ),
      // TODO: remove scrollable from classnames in next major release and uncomment classnames that don't contain scrollable
      tablist: classNames(
        // `${prefix}--tabs__nav`,
        `${prefix}--tabs--scrollable__nav`
      ),
      leftOverflowButtonClasses: classNames({
        [`${prefix}--tab--overflow-nav-button`]: this.state.horizontalOverflow,
        [`${prefix}--tab--overflow-nav-button--hidden`]: leftOverflowNavButtonHidden,
      }),
      rightOverflowButtonClasses: classNames({
        [`${prefix}--tab--overflow-nav-button`]: this.state.horizontalOverflow,
        [`${prefix}--tab--overflow-nav-button--hidden`]: rightOverflowNavButtonHidden,
      }),
    };

    return (
      <>

          <button
            aria-hidden="true"
            aria-label="Scroll left"
            className={classes.leftOverflowButtonClasses}
            onClick={(_) => this.handleOverflowNavClick(_, { direction: -1 })}
            onMouseDown={(event) =>
              this.handleOverflowNavMouseDown(event, { direction: -1 })
            }
            onMouseUp={this.handleOverflowNavMouseUp}
            ref={this.leftOverflowNavButton}
            tabIndex="-1"
            type="button"
            {...leftOverflowButtonProps}>
            <ChevronLeft16 />
          </button>
          {!leftOverflowNavButtonHidden && (
            <div className={`${prefix}--tabs__overflow-indicator--left`} />
          )}

            {tabsWithProps}

          {!rightOverflowNavButtonHidden && (
            <div className={`${prefix}--tabs__overflow-indicator--right`} />
          )}
          <button
            aria-hidden="true"
            aria-label="Scroll right"
            className={classes.rightOverflowButtonClasses}
            onClick={(_) => this.handleOverflowNavClick(_, { direction: 1 })}
            onMouseDown={(event) =>
              this.handleOverflowNavMouseDown(event, { direction: 1 })
            }
            onMouseUp={this.handleOverflowNavMouseUp}
            ref={this.rightOverflowNavButton}
            tabIndex="-1"
            type="button"
            {...rightOverflowButtonProps}>
            <ChevronRight16 />
          </button>

        {tabContentWithProps}
      </>
    );
  }
}
<|endoftext|>


<commit_before>var http = require('http');

HttpRequest = Delegator.clone().setProtoType("HttpRequest").newSlots({
	url: null,
	httpMethod: "get",
	response: null,
	headers: null,
	cookies: null,
	body: null,
	urlString: null,
	throttlePeriod: 0,
	debug: false
}).setSlots({
	init: function()
	{
		Delegator.init.call(this);

		this.setUrl(Url.clone());
		this.setHeaders({});
		this.setCookies({});
		this.setBody("");
	},

	setUrlString :function(urlString)
	{
		this._urlString = urlString;
		this.url().parse(urlString);
		return this;
	},

	generateHeaders: function()
	{
		this.setHeader("Host", this.url().host());
		this.setHeader("Content-Length", this.body().byteLength());
		if(!Object_isEmpty(this.cookies()))
		{
			this.setHeader("Cookie", Object_mapSlots_(this.cookies(), function(k, v){ return k + "=" + v }).join("&")); //TODO properly escape this
		}
	},

	_throttleTimes: {},

	_inProgress: {},

	start: function()
	{
		var lastTime = HttpRequest._throttleTimes[this.url().host()];

		if (lastTime)
		{
			var diff = (lastTime + this.throttlePeriod() * 1000) - (new Date).getTime();

			if(diff > 0)
			{
				var self = this;
				setTimeout(function() { self.start() }, diff);
			}
			else
			{
				this.justStart();
			}
		}
		else
		{
			this.justStart();
		}

		return this;
	},

	complete: function()
	{
		Log.writeln("HttpRequest complete: ", this.uniqueId(), ": ", this.urlString());
		delete HttpRequest._inProgress[this.uniqueId()];
	},

	justStart: function()
	{
		Log.writeln("HttpRequest start: ", this.uniqueId(), ": ",  this.urlString());

		HttpRequest._inProgress[this.uniqueId()] = this;

		HttpRequest._throttleTimes[this.url().host()] = (new Date).getTime();

		var self = this;

		var port = this.url().port() || 80;
		this.generateHeaders();

		var client = http.createClient(port, this.url().host());
client._emit = client.emit;
client.emit = function(name)
{
	Log.writeln("HttpRequest client emit: ", self.uniqueId(), ": ",  name);
	return this._emit.apply(this, arguments);
}

		client.on("error", function(e)
		{
			self.complete();
			self.sendDelegates("httpRequestError", e);
		});
		client.on("upgrade", function(e){
			writeln("HttpClient upgrade ... exiting");
			process.exit();
		});
		client.on("continue", function(e){
			writeln("HttpClient continue ... exiting");
			process.exit();
		});
		var request = client.request(this.httpMethod().toUpperCase(), this.url().resource(), this.headers());
request._emit = request.emit;
request.emit = function(name)
{
	Log.writeln("HttpRequest request emit: ", self.uniqueId(), ": ",  name);
	return this._emit.apply(this, arguments);
}
		request.on("error", function(e){
			self.complete();
			self.sendDelegates("httpRequestError", e);
		});
		request.on("close", function()
		{
			self.complete();
			Log.writeln("HttpRequest request close: ", self.uniqueId());
			self.sendDelegates("httpRequestError", new Error("request closed"));
		});
		request.end(this.body(), 'utf8');

		request.on('response', function(response){
response._emit = response.emit;
response.emit = function(name)
{
	Log.writeln("HttpRequest response emit: ", self.uniqueId(), ": ",  name);
	return this._emit.apply(this, arguments);
}
			response.on("error", function(e)
			{
				self.complete();
				self.sendDelegates("httpRequestError", e);
			});
			response.on("close", function()
			{
				Log.writeln("HttpRequest response close: ", self.uniqueId());
				self.complete();
				self.sendDelegates("httpRequestError", new Error("response closed"));
			});
			self.setResponse(HttpResponse.clone().setHeaders(response.headers).setStatusCode(response.statusCode));
			response.on('data', function(chunk){
				self.response().setBody(self._response.body() + chunk);
			});

			response.on('end', function(){
				Log.writeln("HttpRequest response end: ", self.uniqueId());
//writeln(self.response().body());
				self.complete();
				self.sendDelegates("httpRequestCompleted");
			});
		});
		return this;
	},

	setHeader: function(name, value)
	{
		this.headers()[name] = value;
		return this;
	},

	setContentType: function(contentType)
	{
		return this.setHeader("Content-Type", contentType);
	},

	setCookie: function(name, value)
	{
		this.cookies()[name] = value;
	}
});

//HttpResponse

HttpResponse = Proto.clone().setProtoType("HttpResponse").newSlots({
	statusCode: null,
	headers: null,
	body: null
}).setSlots({
	init: function()
	{
		this._body = "";
	}
})

//String+HttpRequest

Object_shallowCopyFrom_(String.prototype,{
	getWithDelegate: function(aDelegate)
	{
		return HttpRequest.clone().setUrlString(this).setHttpMethod("GET").addDelegate(aDelegate).start();
	}
});<commit_msg>Handle http.Client close event<commit_after>var http = require('http');

HttpRequest = Delegator.clone().setProtoType("HttpRequest").newSlots({
	url: null,
	httpMethod: "get",
	response: null,
	headers: null,
	cookies: null,
	body: null,
	urlString: null,
	throttlePeriod: 0,
	debug: false,
	didComplete: false
}).setSlots({
	init: function()
	{
		Delegator.init.call(this);

		this.setUrl(Url.clone());
		this.setHeaders({});
		this.setCookies({});
		this.setBody("");
	},

	setUrlString :function(urlString)
	{
		this._urlString = urlString;
		this.url().parse(urlString);
		return this;
	},

	generateHeaders: function()
	{
		this.setHeader("Host", this.url().host());
		this.setHeader("Content-Length", this.body().byteLength());
		if(!Object_isEmpty(this.cookies()))
		{
			this.setHeader("Cookie", Object_mapSlots_(this.cookies(), function(k, v){ return k + "=" + v }).join("&")); //TODO properly escape this
		}
	},

	_throttleTimes: {},

	_inProgress: {},

	start: function()
	{
		if(this.didComplete())
		{
			throw new Error("Request already completed");
		}

		this.setDidComplete(false);
		var lastTime = HttpRequest._throttleTimes[this.url().host()];

		if (lastTime)
		{
			var diff = (lastTime + this.throttlePeriod() * 1000) - (new Date).getTime();

			if(diff > 0)
			{
				var self = this;
				setTimeout(function() { self.start() }, diff);
			}
			else
			{
				this.justStart();
			}
		}
		else
		{
			this.justStart();
		}

		return this;
	},

	complete: function()
	{
		this.setDidComplete(true);
//Log.writeln("HttpRequest complete: ", this.uniqueId(), ": ", this.urlString());
		delete HttpRequest._inProgress[this.uniqueId()];
	},

	sendError: function(e)
	{
		this.complete();
		this.sendDelegates("httpRequestError", e);
	},

	sendCompleted: function()
	{
		if(!this.didComplete())
		{
			this.complete();
			this.sendDelegates("httpRequestCompleted");
		}
	},

	patchEmitter: function(emitter, tag)
	{
		var self = this;
		emitter._emit = emitter.emit;
		emitter.emit = function(name)
		{
			Log.writeln("HttpRequest request ", tag, ": ", self.uniqueId(), ": ",  name);
			return this._emit.apply(this, arguments);
		}

		return emitter;
	},

	justStart: function()
	{
//Log.writeln("HttpRequest start: ", this.uniqueId(), ": ",  this.urlString());

		HttpRequest._inProgress[this.uniqueId()] = this;

		HttpRequest._throttleTimes[this.url().host()] = (new Date).getTime();

		var self = this;

		var port = this.url().port() || 80;
		this.generateHeaders();

		var client = http.createClient(port, this.url().host());
//this.patchEmitter(client, "client");
		client.on("error", function(e)
		{
			self.sendError(e);
		});
		client.on("upgrade", function(e){
			self.sendError(new Error("can't handle client upgrade"));
		});
		client.on("continue", function(e){
			self.sendError(new Error("can't handle client continue"));
		});
		client.on("close", function(e){
			self.sendCompleted();
		});

		var request = client.request(this.httpMethod().toUpperCase(), this.url().resource(), this.headers());
//this.patchEmitter(request, "request");
		request.on("error", function(e){
			self.sendError(e);
		});
		request.on("close", function()
		{
			self.sendError(new Error("request closed"));
		});
		request.end(this.body(), 'utf8');

		request.on('response', function(response){
//self.patchEmitter(response, "response");
			self.setResponse(HttpResponse.clone().setHeaders(response.headers).setStatusCode(response.statusCode));
			response.on("error", function(e)
			{
				self.sendError(e);
			});
			response.on("close", function()
			{
				self.sendError(new Error("response closed"));
			});
			response.on('data', function(chunk){
				self.response().setBody(self._response.body() + chunk);
			});

			response.on('end', function(){
//Log.writeln("HttpRequest response end: ", self.uniqueId());
//writeln(self.response().body());
				self.sendCompleted();
			});
		});
		return this;
	},

	setHeader: function(name, value)
	{
		this.headers()[name] = value;
		return this;
	},

	setContentType: function(contentType)
	{
		return this.setHeader("Content-Type", contentType);
	},

	setCookie: function(name, value)
	{
		this.cookies()[name] = value;
	}
});

//HttpResponse

HttpResponse = Proto.clone().setProtoType("HttpResponse").newSlots({
	statusCode: null,
	headers: null,
	body: null
}).setSlots({
	init: function()
	{
		this._body = "";
	}
})

//String+HttpRequest

Object_shallowCopyFrom_(String.prototype,{
	getWithDelegate: function(aDelegate)
	{
		return HttpRequest.clone().setUrlString(this).setHttpMethod("GET").addDelegate(aDelegate).start();
	}
});<|endoftext|>


<commit_before>var nodeclass = require("nodeclass");
nodeclass.registerExtension = function() {};

require("../shared/Model.class.test.js");<commit_msg>- old test<commit_after><|endoftext|>


<commit_before>$(function () {
    // Hide unnecessary divs for DTM
    var newLabelsLocation = $('#normalize-options').parent()
    var newNormalizeLocation = $('#temp-label-div').parent()
    var tempNormalize = $('#normalize-options').html()
    var tempLabels = $('#temp-label-div').html()
    $('#normalize-options').remove()
    $('#temp-label-div').remove()
  newLabels = $('<fieldset class="analyze-advanced-options" id="temp-label-div"></fieldset>').append(tempLabels)
  newNormalize = $('<fieldset class="analyze-advanced-options" id="normalize-options"></fieldset>').append(tempNormalize)
  newLabelsLocation.append(newLabels)
  newNormalizeLocation.append(newNormalize)

  $('#normalize-options').hide()
  /* $("#culling-options").hide(); */

  //   $("#normalize-options").empty().html($("#temp-label-div").html());
  //   $("#temp-label-div").empty().html(tempContent);
  // $("#temp-label-div").css("position","relative").css("left","-10px").css("top","0px");

  // Error handling before submit
  $('#getsims').click(function () {
    if ($('#num_active_files').val() < 2) {
      $('#error-message').text('You must have at least 2 active documents to proceed!')
      $('#error-message').show().fadeOut(3000)
      return false
    } else {
      $('#status-analyze').css({ 'visibility': 'visible', 'z-index': '400000' })
      return true
    }
  })

  // Display selected document name on screen
  function makeFilenameStr(fileID) {
    var selectedFilename = 'Selected Document: ' + documentLabels[fileID]
    $('#selectedDocument').text(selectedFilename)
  }

  if ($('input[type=radio]').is(':checked')) {
    makeFilenameStr($('input[type=radio]:checked').val())
  }

  function createList() {
    var columnValues = []
    var rows = (docsListScore.length - 1)
    for (i = 0; i < rows; i++) {
      j = i + 1
      columnValues[i] = [j.toString(), docsListName[i], docsListScore[i].toString()]
      valStr = '
' + j.toString() + '	' + docsListName[i] + '	' + docsListScore[i].toString() + '
'
      $('#simtable tbody').append(valStr)
    }
    // $("#status-analyze").css({"visibility":"hidden"});

    $('#simtable').DataTable({
      'paging': true,
      'searching': true,
      'ordering': true,
      'info': true,
      'language': {
        'lengthMenu': 'Display _MENU_ documents per page'
      }
    })
  }

  if (docsListScore != '') {
    createList()
  }
})

	// Code to try and make the tokenize box look pretty on simQ page.  Only works in firefox? Makes templabels disappear in chromium
	// var brow, usrAG = navigator.userAgent;		// Catch browser info
	// if (usrAG.indexOf("Firefox") > -1) {        // if 'firefox' in browser name then apply this style stuff
	// 	$("#temp-label-div").css("position","relative").css("top","-126px").css("left","-10px");
	// 	$("#analyze-advanced").css("max-height","150px").css("overflow","hidden");

	// 	$("input[name='tokenType']").click(function(){
	// 		if ($(this).val() == 'word'){
	// 			$("#temp-label-div").css("top","-126px");
	// 		} else {
	// 			$("#temp-label-div").css("top","-161px");
	// 		}
	// 	});
	// }

// Old createList function
/*	function createList() {

		mytable = $('

').attr({id: "basicTable"});

		// title row
		var titleRow = $('

').appendTo(mytable);
		$('	').text("Rank").appendTo(titleRow);
		$('	').text("Filename").appendTo(titleRow);
		$('	').text("Cosine Similarity").appendTo(titleRow);

		// rankings
		var rows = (docsListScore.length - 1);
		var cols = 3;
		var tr = [];
		for (var i = 0; i < rows; i++) {
			var row = $('

').appendTo(mytable);
			for (var j = 0; j < cols; j++) {

				if (j == 0) {
					$('	').text(i + 1).appendTo(row);
				} else if (j == 1) {
					$('	').text(docsListName[i]).appendTo(row);
				} else {
					$('	').text(docsListScore[i]).appendTo(row);
				}
			}//for
		}//for

		mytable.appendTo("#simstable");
	} */
// End old createList function
<commit_msg>Finish unit test<commit_after>$(function () {
  // Hide unnecessary divs for DTM
  var newLabelsLocation = $('#normalize-options').parent()
  var newNormalizeLocation = $('#temp-label-div').parent()
  var tempNormalize = $('#normalize-options').html()
  var tempLabels = $('#temp-label-div').html()
  $('#normalize-options').remove()
  $('#temp-label-div').remove()
  newLabels = $('<fieldset class="analyze-advanced-options" id="temp-label-div"></fieldset>').append(tempLabels)
  newNormalize = $('<fieldset class="analyze-advanced-options" id="normalize-options"></fieldset>').append(tempNormalize)
  newLabelsLocation.append(newLabels)
  newNormalizeLocation.append(newNormalize)

  $('#normalize-options').hide()
  /* $("#culling-options").hide(); */

  //   $("#normalize-options").empty().html($("#temp-label-div").html());
  //   $("#temp-label-div").empty().html(tempContent);
  // $("#temp-label-div").css("position","relative").css("left","-10px").css("top","0px");

  // Error handling before submit
  $('#getsims').click(function () {
    if ($('#num_active_files').val() < 2) {
      $('#error-message').text('You must have at least 2 active documents to proceed!')
      $('#error-message').show().fadeOut(3000)
      return false
    } else {
      $('#status-analyze').css({ 'visibility': 'visible', 'z-index': '400000' })
      return true
    }
  })

  // Display selected document name on screen
  function makeFilenameStr(fileID) {
    var selectedFilename = 'Selected Document: ' + documentLabels[fileID]
    $('#selectedDocument').text(selectedFilename)
  }

  if ($('input[type=radio]').is(':checked')) {
    makeFilenameStr($('input[type=radio]:checked').val())
  }

  function createList() {
    var columnValues = []
    var rows = (docsListScore.length - 1)
    for (i = 0; i < rows; i++) {
      j = i + 1
      columnValues[i] = [j.toString(), docsListName[i], docsListScore[i].toString()]
      valStr = '
' + j.toString() + '	' + docsListName[i] + '	' + docsListScore[i].toString() + '
'
      $('#simtable tbody').append(valStr)
    }
    // $("#status-analyze").css({"visibility":"hidden"});

    $('#simtable').DataTable({
      'paging': true,
      'searching': true,
      'ordering': true,
      'info': true,
      'language': {
        'lengthMenu': 'Display _MENU_ documents per page'
      }
    })
  }

  if (docsListScore != '') {
    createList()
  }
})

	// Code to try and make the tokenize box look pretty on simQ page.  Only works in firefox? Makes templabels disappear in chromium
	// var brow, usrAG = navigator.userAgent;		// Catch browser info
	// if (usrAG.indexOf("Firefox") > -1) {        // if 'firefox' in browser name then apply this style stuff
	// 	$("#temp-label-div").css("position","relative").css("top","-126px").css("left","-10px");
	// 	$("#analyze-advanced").css("max-height","150px").css("overflow","hidden");

	// 	$("input[name='tokenType']").click(function(){
	// 		if ($(this).val() == 'word'){
	// 			$("#temp-label-div").css("top","-126px");
	// 		} else {
	// 			$("#temp-label-div").css("top","-161px");
	// 		}
	// 	});
	// }

// Old createList function
/*	function createList() {

		mytable = $('

').attr({id: "basicTable"});

		// title row
		var titleRow = $('

').appendTo(mytable);
		$('	').text("Rank").appendTo(titleRow);
		$('	').text("Filename").appendTo(titleRow);
		$('	').text("Cosine Similarity").appendTo(titleRow);

		// rankings
		var rows = (docsListScore.length - 1);
		var cols = 3;
		var tr = [];
		for (var i = 0; i < rows; i++) {
			var row = $('

').appendTo(mytable);
			for (var j = 0; j < cols; j++) {

				if (j == 0) {
					$('	').text(i + 1).appendTo(row);
				} else if (j == 1) {
					$('	').text(docsListName[i]).appendTo(row);
				} else {
					$('	').text(docsListScore[i]).appendTo(row);
				}
			}//for
		}//for

		mytable.appendTo("#simstable");
	} */
// End old createList function
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import {List, Map} from 'immutable';
import {expect} from 'chai';

import Results from '../../src/components/Results';

describe('Results', () => {
  it('renders entries with vote counts or zero', () => {
    const pair = List.of('first', 'second');
    const tally = Map({'first': 5});
    const component = ReactTestUtils.renderIntoDocument(
      <Results pair={pair} tally={tally} />
    );
    const entries = ReactTestUtils.scryRenderedDOMComponentsWithClass(component, 'entry');
    const [first, second] = entries.map( e => e.textContent );

    expect(entries.length).to.equal(2);
    expect(first).to.contain('first');
    expect(first).to.contain('5');
    expect(second).to.contain('second');
    expect(second).to.contain('0');
  })

  it('invokes the next callback when next button is clicked', (done) => {
    const pair = List.of('Trainspotting', '28 Days Later');
    const component = ReactTestUtils.renderIntoDocument(
      <Results
        pair={pair}
        tally={Map()}
        next={() => done()}
      />
    );
    ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(component.refs.next));
  })

  it('renders the winner when there is one', () => {
    const component = ReactTestUtils.renderIntoDocument(
      <Results
        winner="Trainspotting"
        pair={["Trainspotting", "28 Days Later"]}
        tally={Map()}
      />
    );
    const winner = ReactDOM.findDOMNode(component.refs.winner);
    expect(winner).to.be.ok;
    expect(winner.textContent).to.contain('Trainspotting');
  })
})
<commit_msg>[fixed] exporting of 'Results' component for its specs<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import {List, Map} from 'immutable';
import {expect} from 'chai';

import {Results} from '../../src/components/Results';

describe('Results', () => {
  it('renders entries with vote counts or zero', () => {
    const pair = List.of('first', 'second');
    const tally = Map({'first': 5});
    const component = ReactTestUtils.renderIntoDocument(
      <Results pair={pair} tally={tally} />
    );
    const entries = ReactTestUtils.scryRenderedDOMComponentsWithClass(component, 'entry');
    const [first, second] = entries.map( e => e.textContent );

    expect(entries.length).to.equal(2);
    expect(first).to.contain('first');
    expect(first).to.contain('5');
    expect(second).to.contain('second');
    expect(second).to.contain('0');
  })

  it('invokes the next callback when next button is clicked', (done) => {
    const pair = List.of('Trainspotting', '28 Days Later');
    const component = ReactTestUtils.renderIntoDocument(
      <Results
        pair={pair}
        tally={Map()}
        next={() => done()}
      />
    );
    ReactTestUtils.Simulate.click(ReactDOM.findDOMNode(component.refs.next));
  })

  it('renders the winner when there is one', () => {
    const component = ReactTestUtils.renderIntoDocument(
      <Results
        winner="Trainspotting"
        pair={["Trainspotting", "28 Days Later"]}
        tally={Map()}
      />
    );
    const winner = ReactDOM.findDOMNode(component.refs.winner);
    expect(winner).to.be.ok;
    expect(winner.textContent).to.contain('Trainspotting');
  })
})
<|endoftext|>


<commit_before>'use strict';

var defineProperty = Object.defineProperty
  , descriptor = { configurable: false, enumerable: false, value: true,
		writable: false };

module.exports = function (fn) {
	return defineProperty(fn, 'returnsPromise', descriptor);
};
<commit_msg>Workaround for v8 bug (eminent in Node v0.6)<commit_after>'use strict';

var defineProperty = Object.defineProperty
  , descriptor = { configurable: false, enumerable: false, value: true,
		writable: false };

module.exports = function (fn) {
	fn.returnsPromise = true;
	return defineProperty(fn, 'returnsPromise', descriptor);
};
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2012, Ajax.org B.V.
 * 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.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * 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 AJAX.ORG B.V. 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.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var AppleScriptHighlightRules = require("./applescript_highlight_rules").AppleScriptHighlightRules;
// TODO: pick appropriate fold mode
var FoldMode = require("./folding/cstyle").FoldMode;

var Mode = function() {
    this.HighlightRules = AppleScriptHighlightRules;
    this.foldingRules = new FoldMode();
};
oop.inherits(Mode, TextMode);

(function() {
    this.lineCommentStart = "--";
    this.blockComment = {start: "(*", end: "*)"};
    // Extra logic goes here.
}).call(Mode.prototype);

exports.Mode = Mode;
});
<commit_msg>mode/applescript : set the `$id` to the correct value<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2012, Ajax.org B.V.
 * 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.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * 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 AJAX.ORG B.V. 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.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var AppleScriptHighlightRules = require("./applescript_highlight_rules").AppleScriptHighlightRules;
// TODO: pick appropriate fold mode
var FoldMode = require("./folding/cstyle").FoldMode;

var Mode = function() {
    this.HighlightRules = AppleScriptHighlightRules;
    this.foldingRules = new FoldMode();
};
oop.inherits(Mode, TextMode);

(function() {
    this.lineCommentStart = "--";
    this.blockComment = {start: "(*", end: "*)"};
    this.$id = "ace/mode/applescript";
    // Extra logic goes here.
}).call(Mode.prototype);

exports.Mode = Mode;
});
<|endoftext|>