<commit_before>/* Copyright 2017 Mozilla Foundation
 *
 * 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.
 */
/*
 Copyright (c) 2008-2016 Pivotal Labs

 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
 "Software"), to deal in the Software without restriction, including
 without limitation the rights to use, copy, modify, merge, publish,
 distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to
 the following conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/* globals jasmineRequire, TestReporter */

// Modified jasmine's boot.js file to load PDF.js libraries async.

'use strict';

function initializePDFJS(callback) {
  Promise.all([
    'pdfjs/display/global', 'pdfjs-test/unit/annotation_spec',
    'pdfjs-test/unit/api_spec', 'pdfjs-test/unit/bidi_spec',
    'pdfjs-test/unit/cff_parser_spec', 'pdfjs-test/unit/cmap_spec',
    'pdfjs-test/unit/crypto_spec', 'pdfjs-test/unit/custom_spec',
    'pdfjs-test/unit/document_spec', 'pdfjs-test/unit/dom_utils_spec',
    'pdfjs-test/unit/evaluator_spec', 'pdfjs-test/unit/fonts_spec',
    'pdfjs-test/unit/function_spec', 'pdfjs-test/unit/metadata_spec',
    'pdfjs-test/unit/murmurhash3_spec', 'pdfjs-test/unit/network_spec',
    'pdfjs-test/unit/parser_spec', 'pdfjs-test/unit/primitives_spec',
    'pdfjs-test/unit/stream_spec', 'pdfjs-test/unit/type1_parser_spec',
    'pdfjs-test/unit/ui_utils_spec', 'pdfjs-test/unit/unicode_spec',
    'pdfjs-test/unit/util_spec', 'pdfjs-test/unit/util_stream_spec'
  ].map(function (moduleName) {
    return SystemJS.import(moduleName);
  })).then(function (modules) {
    var displayGlobal = modules[0];

    // Configure the worker.
    displayGlobal.PDFJS.workerSrc = '../../build/generic/build/pdf.worker.js';
    // Opt-in to using the latest API.
    displayGlobal.PDFJS.pdfjsNext = true;

    callback();
  });
}

(function() {
  window.jasmine = jasmineRequire.core(jasmineRequire);

  jasmineRequire.html(jasmine);

  var env = jasmine.getEnv();

  var jasmineInterface = jasmineRequire.interface(jasmine, env);
  extend(window, jasmineInterface);

  // Runner Parameters
  var queryString = new jasmine.QueryString({
    getWindowLocation() {
      return window.location;
    },
  });

  var catchingExceptions = queryString.getParam('catch');
  env.catchExceptions(typeof catchingExceptions === 'undefined' ?
                      true : catchingExceptions);

  var throwingExpectationFailures = queryString.getParam('throwFailures');
  env.throwOnExpectationFailure(throwingExpectationFailures);

  var random = queryString.getParam('random');
  env.randomizeTests(random);

  var seed = queryString.getParam('seed');
  if (seed) {
    env.seed(seed);
  }

  // Reporters
  var htmlReporter = new jasmine.HtmlReporter({
    env,
    onRaiseExceptionsClick() {
      queryString.navigateWithNewParam('catch', !env.catchingExceptions());
    },
    onThrowExpectationsClick() {
      queryString.navigateWithNewParam('throwFailures',
                                       !env.throwingExpectationFailures());
    },
    onRandomClick() {
      queryString.navigateWithNewParam('random', !env.randomTests());
    },
    addToExistingQueryString(key, value) {
      return queryString.fullStringWithNewParam(key, value);
    },
    getContainer() {
      return document.body;
    },
    createElement() {
      return document.createElement.apply(document, arguments);
    },
    createTextNode() {
      return document.createTextNode.apply(document, arguments);
    },
    timer: new jasmine.Timer(),
  });

  env.addReporter(htmlReporter);

  if (queryString.getParam('browser')) {
    var testReporter = new TestReporter(queryString.getParam('browser'),
                                        queryString.getParam('path'));
    env.addReporter(testReporter);
  }

  // Filter which specs will be run by matching the start of the full name
  // against the `spec` query param.
  var specFilter = new jasmine.HtmlSpecFilter({
    filterString() {
      return queryString.getParam('spec');
    },
  });

  env.specFilter = function(spec) {
    return specFilter.matches(spec.getFullName());
  };

  // Sets longer timeout.
  jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;

  // Replace the browser window's `onload`, ensure it's called, and then run
  // all of the loaded specs. This includes initializing the `HtmlReporter`
  // instance and then executing the loaded Jasmine environment.
  var currentWindowOnload = window.onload;

  window.onload = function() {
    if (currentWindowOnload) {
      currentWindowOnload();
    }

    initializePDFJS(function () {
      htmlReporter.initialize();
      env.execute();
    });
  };

  function extend(destination, source) {
    for (var property in source) {
      destination[property] = source[property];
    }
    return destination;
  }
}());
<commit_msg>Put every test file on a separate lint in jasmine-boot.js<commit_after>/* Copyright 2017 Mozilla Foundation
 *
 * 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.
 */
/*
 Copyright (c) 2008-2016 Pivotal Labs

 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
 "Software"), to deal in the Software without restriction, including
 without limitation the rights to use, copy, modify, merge, publish,
 distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to
 the following conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/* globals jasmineRequire, TestReporter */

// Modified jasmine's boot.js file to load PDF.js libraries async.

'use strict';

function initializePDFJS(callback) {
  Promise.all([
    'pdfjs/display/global',
    'pdfjs-test/unit/annotation_spec',
    'pdfjs-test/unit/api_spec',
    'pdfjs-test/unit/bidi_spec',
    'pdfjs-test/unit/cff_parser_spec',
    'pdfjs-test/unit/cmap_spec',
    'pdfjs-test/unit/crypto_spec',
    'pdfjs-test/unit/custom_spec',
    'pdfjs-test/unit/document_spec',
    'pdfjs-test/unit/dom_utils_spec',
    'pdfjs-test/unit/evaluator_spec',
    'pdfjs-test/unit/fonts_spec',
    'pdfjs-test/unit/function_spec',
    'pdfjs-test/unit/metadata_spec',
    'pdfjs-test/unit/murmurhash3_spec',
    'pdfjs-test/unit/network_spec',
    'pdfjs-test/unit/parser_spec',
    'pdfjs-test/unit/primitives_spec',
    'pdfjs-test/unit/stream_spec',
    'pdfjs-test/unit/type1_parser_spec',
    'pdfjs-test/unit/ui_utils_spec',
    'pdfjs-test/unit/unicode_spec',
    'pdfjs-test/unit/util_spec',
    'pdfjs-test/unit/util_stream_spec',
  ].map(function (moduleName) {
    return SystemJS.import(moduleName);
  })).then(function (modules) {
    var displayGlobal = modules[0];

    // Configure the worker.
    displayGlobal.PDFJS.workerSrc = '../../build/generic/build/pdf.worker.js';
    // Opt-in to using the latest API.
    displayGlobal.PDFJS.pdfjsNext = true;

    callback();
  });
}

(function() {
  window.jasmine = jasmineRequire.core(jasmineRequire);

  jasmineRequire.html(jasmine);

  var env = jasmine.getEnv();

  var jasmineInterface = jasmineRequire.interface(jasmine, env);
  extend(window, jasmineInterface);

  // Runner Parameters
  var queryString = new jasmine.QueryString({
    getWindowLocation() {
      return window.location;
    },
  });

  var catchingExceptions = queryString.getParam('catch');
  env.catchExceptions(typeof catchingExceptions === 'undefined' ?
                      true : catchingExceptions);

  var throwingExpectationFailures = queryString.getParam('throwFailures');
  env.throwOnExpectationFailure(throwingExpectationFailures);

  var random = queryString.getParam('random');
  env.randomizeTests(random);

  var seed = queryString.getParam('seed');
  if (seed) {
    env.seed(seed);
  }

  // Reporters
  var htmlReporter = new jasmine.HtmlReporter({
    env,
    onRaiseExceptionsClick() {
      queryString.navigateWithNewParam('catch', !env.catchingExceptions());
    },
    onThrowExpectationsClick() {
      queryString.navigateWithNewParam('throwFailures',
                                       !env.throwingExpectationFailures());
    },
    onRandomClick() {
      queryString.navigateWithNewParam('random', !env.randomTests());
    },
    addToExistingQueryString(key, value) {
      return queryString.fullStringWithNewParam(key, value);
    },
    getContainer() {
      return document.body;
    },
    createElement() {
      return document.createElement.apply(document, arguments);
    },
    createTextNode() {
      return document.createTextNode.apply(document, arguments);
    },
    timer: new jasmine.Timer(),
  });

  env.addReporter(htmlReporter);

  if (queryString.getParam('browser')) {
    var testReporter = new TestReporter(queryString.getParam('browser'),
                                        queryString.getParam('path'));
    env.addReporter(testReporter);
  }

  // Filter which specs will be run by matching the start of the full name
  // against the `spec` query param.
  var specFilter = new jasmine.HtmlSpecFilter({
    filterString() {
      return queryString.getParam('spec');
    },
  });

  env.specFilter = function(spec) {
    return specFilter.matches(spec.getFullName());
  };

  // Sets longer timeout.
  jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;

  // Replace the browser window's `onload`, ensure it's called, and then run
  // all of the loaded specs. This includes initializing the `HtmlReporter`
  // instance and then executing the loaded Jasmine environment.
  var currentWindowOnload = window.onload;

  window.onload = function() {
    if (currentWindowOnload) {
      currentWindowOnload();
    }

    initializePDFJS(function () {
      htmlReporter.initialize();
      env.execute();
    });
  };

  function extend(destination, source) {
    for (var property in source) {
      destination[property] = source[property];
    }
    return destination;
  }
}());
<|endoftext|>


<commit_before>$(function(){
    module('jquery.countdown.js');

    test('jQuery utils core tests', function() {
        expect(33);

        // integrity check
        ok(typeof $.ui             == 'object',   'jQuery UI is defined')
        ok(typeof $.ctrl           == 'object',   'jQuery CTRL is defined')
        ok(typeof $.isRegExp       == 'function', 'jQuery isRegExp is defined')
        ok(typeof $.isArray        == 'function', 'jQuery isArray is defined')
        ok(typeof $.toCurrency     == 'function', 'jQuery toCurrency is defined')
        ok(typeof $.fn.selectRange == 'function', 'jQuery.fn selectRange is defined')

        // isRegExp
        ok(!$.isRegExp(''),    '"" !isRegExp');
        ok(!$.isRegExp('a'),   'a !isRegExp');
        ok(!$.isRegExp(1),     '1 !isRegExp');
        ok(!$.isRegExp(null),  'null !isRegExp');
        ok(!$.isRegExp(true),  'true !isRegExp');
        ok(!$.isRegExp(false), 'false !isRegExp');
        ok($.isRegExp(/a/),  '/a/ isRegExp');
        ok($.isRegExp((new RegExp("\\d+"))), 'new RegExp("\\d+") isRegExp');

        // isArray
        ok(!$.isArray(''),    '"" !isArray');
        ok(!$.isArray('a'),   'a !isArray');
        ok(!$.isArray(1),     '1 !isArray');
        ok(!$.isArray(null),  'null !isArray');
        ok(!$.isArray(true),  'true !isArray');
        ok(!$.isArray(false), 'false !isArray');
        ok($.isArray([]),  '[] isArray');
        ok($.isArray((new Array())), 'new Array() isArray');

        // toCurrency
        ok($.toCurrency(''),       '"" -> 0.00');
        ok($.toCurrency(null),     'null -> 0.00');
        ok($.toCurrency(true),     'true -> 0.00');
        ok($.toCurrency(false),    'false -> 0.00');
        ok($.toCurrency('-1'),     '-1 -> -1.00');
        ok($.toCurrency('0'),      '0 -> 0.00');
        ok($.toCurrency('.'),      '. -> 0.00');
        ok($.toCurrency('1.234'),  '1.234 -> 1.23');
        ok($.toCurrency('123.45'), '123.45 -> 123.45');

        // selectRange
        $('body').append($('<textarea id="select-range">abcdefg</textarea>')
            .css({position:'absolute',top:-1000, left:-1000})); // wont work on hidden elements
        $('#select-range').selectRange(0, 3);
        // Gotta love IE
        if( document.selection ){
            var range = document.selection.createRange();
            var stored_range = range.duplicate();
            stored_range.moveToElementText($('#select-range').get(0));
            stored_range.setEndPoint( 'EndToEnd', range );
            $('#select-range').get(0).selectionStart = stored_range.text.length - range.text.length;
            $('#select-range').get(0).selectionEnd = $('#select-range').get(0).selectionStart + range.text.length;
        }

        ok($('#select-range').get(0).selectionStart == 0, 'Range start == 0');
        ok($('#select-range').get(0).selectionEnd   == 3, 'Range end === 3');
        $('#select-range').remove();
    });

    $('#fixtures').html('');
});
<commit_msg>- Unit tests cleanup<commit_after>$(function(){
    module('jquery.utils.js');

    test('jQuery utils core tests', function() {
        expect(33);

        // integrity check
        ok(typeof $.ui             == 'object',   'jQuery UI is defined')
        ok(typeof $.ctrl           == 'object',   'jQuery CTRL is defined')
        ok(typeof $.isRegExp       == 'function', 'jQuery isRegExp is defined')
        ok(typeof $.isArray        == 'function', 'jQuery isArray is defined')
        ok(typeof $.toCurrency     == 'function', 'jQuery toCurrency is defined')
        ok(typeof $.fn.selectRange == 'function', 'jQuery.fn selectRange is defined')

        // isRegExp
        ok(!$.isRegExp(''),    '"" !isRegExp');
        ok(!$.isRegExp('a'),   'a !isRegExp');
        ok(!$.isRegExp(1),     '1 !isRegExp');
        ok(!$.isRegExp(null),  'null !isRegExp');
        ok(!$.isRegExp(true),  'true !isRegExp');
        ok(!$.isRegExp(false), 'false !isRegExp');
        ok($.isRegExp(/a/),  '/a/ isRegExp');
        ok($.isRegExp((new RegExp("\\d+"))), 'new RegExp("\\d+") isRegExp');

        // isArray
        ok(!$.isArray(''),    '"" !isArray');
        ok(!$.isArray('a'),   'a !isArray');
        ok(!$.isArray(1),     '1 !isArray');
        ok(!$.isArray(null),  'null !isArray');
        ok(!$.isArray(true),  'true !isArray');
        ok(!$.isArray(false), 'false !isArray');
        ok($.isArray([]),  '[] isArray');
        ok($.isArray((new Array())), 'new Array() isArray');

        // toCurrency
        ok($.toCurrency(''),       '"" -> 0.00');
        ok($.toCurrency(null),     'null -> 0.00');
        ok($.toCurrency(true),     'true -> 0.00');
        ok($.toCurrency(false),    'false -> 0.00');
        ok($.toCurrency('-1'),     '-1 -> -1.00');
        ok($.toCurrency('0'),      '0 -> 0.00');
        ok($.toCurrency('.'),      '. -> 0.00');
        ok($.toCurrency('1.234'),  '1.234 -> 1.23');
        ok($.toCurrency('123.45'), '123.45 -> 123.45');

        // selectRange
        $('body').append($('<textarea id="select-range">abcdefg</textarea>')
            .css({position:'absolute',top:-1000, left:-1000})); // wont work on hidden elements
        $('#select-range').selectRange(0, 3);
        // Gotta love IE
        if( document.selection ){
            var range = document.selection.createRange();
            var stored_range = range.duplicate();
            stored_range.moveToElementText($('#select-range').get(0));
            stored_range.setEndPoint( 'EndToEnd', range );
            $('#select-range').get(0).selectionStart = stored_range.text.length - range.text.length;
            $('#select-range').get(0).selectionEnd = $('#select-range').get(0).selectionStart + range.text.length;
        }

        ok($('#select-range').get(0).selectionStart == 0, 'Range start == 0');
        ok($('#select-range').get(0).selectionEnd   == 3, 'Range end === 3');
        $('#select-range').remove();
    });

    $('#fixtures').html('');
});
<|endoftext|>


<commit_before>

assert.suite('Object: phantom', function() {

	var fs = require('fs');

	// --------------------------------------------
	assert.section('Object availability');

	assert(this.hasOwnProperty('phantom'), 'this.phantom exists');
	assert(typeof this.phantom === 'object', 'this.phantom is an object');
	assert(window.hasOwnProperty('phantom'), 'window.phantom exists');
	assert(typeof window.phantom === 'object', 'window.phantom is an object');

	// --------------------------------------------
	assert.section('Properties & methods');

	assert(phantom.args instanceof Array, 'phantom.args is an array');
	//assert(phantom.cookies instanceof Array, 'phantom.cookies is an array');
	assert(typeof phantom.cookiesEnabled === 'boolean', 'phantom.cookiesEnabled is a boolean');
	assert(phantom.cookiesEnabled === true, 'phantom.cookiesEnabled is true');
	assert(typeof phantom.outputEncoding === 'string', 'phantom.outputEncoding is a string');
	assert(phantom.outputEncoding === 'UTF-8', 'phantom.outputEncoding is "UTF-8"');
	assert(typeof phantom.libraryPath === 'string', 'phantom.libraryPath is a string');
	assert(phantom.libraryPath === fs.workingDirectory, 'phantom.libraryPath is equal to fs.workingDirectory');
	assert(typeof phantom.scriptName === 'string', 'phantom.scriptName is a string');
	assert(typeof phantom.version === 'object', 'phantom.version is an object');
	assert(typeof phantom.version.major === 'number', 'phantom.version.major is a number');
	assert(typeof phantom.version.minor === 'number', 'phantom.version.minor is a number');
	//assert(typeof phantom.addCookie === 'function', 'phantom.addCookie is a function');
	//assert(typeof phantom.clearCookies === 'function', 'phantom.clearCookies is a function');
	//assert(typeof phantom.deleteCookie === 'function', 'phantom.deleteCookie is a function');
	assert(typeof phantom.exit === 'function', 'phantom.exit is a function');
	assert(typeof phantom.injectJs === 'function', 'phantom.injectJs is a function');

	// --------------------------------------------
	assert.section('Functionality');

	phantom.libraryPath = "..";

	assert(phantom.scriptName === 'test/unit/spec/phantom.js', 'phantom.scriptName is the currently executing script');
	assert(phantom.libraryPath !== fs.workingDirectory, 'changing phantom.libraryPath does not alter fs.workingDirectory');
	assert(phantom.version.major === 1, 'phantom.version.major is 1');

	var injection = phantom.injectJs('..\\..\\test\\unit\\ref\\script.js');

	assert(injection === true, 'phantom.injectJs() returned true when pointing to file');
	assert(___test190234 === true, 'phantom.injectJs() executes a script in current V8 context');

	// Tear down
	phantom.libraryPath = fs.workingDirectory;

});<commit_msg>Reviewing API for phantom object<commit_after>

assert.suite('Object: phantom', function() {

	var fs = require('fs');

	// --------------------------------------------
	assert.section('Object availability');

	assert(this.hasOwnProperty('phantom'), 'this.phantom exists');
	assert(typeof this.phantom === 'object', 'this.phantom is an object');
	assert(window.hasOwnProperty('phantom'), 'window.phantom exists');
	assert(typeof window.phantom === 'object', 'window.phantom is an object');

	// --------------------------------------------
	assert.section('Properties & methods');

	assert(phantom.args instanceof Array, 'phantom.args is an array');
	//assert(phantom.cookies instanceof Array, 'phantom.cookies is an array');
	assert(typeof phantom.cookiesEnabled === 'boolean', 'phantom.cookiesEnabled is a boolean');
	assert(phantom.cookiesEnabled === true, 'phantom.cookiesEnabled is true');
	assert(typeof phantom.outputEncoding === 'string', 'phantom.outputEncoding is a string');
	assert(phantom.outputEncoding === 'UTF-8', 'phantom.outputEncoding is "UTF-8"');
	assert(typeof phantom.libraryPath === 'string', 'phantom.libraryPath is a string');
	assert(phantom.libraryPath === fs.workingDirectory, 'phantom.libraryPath is equal to fs.workingDirectory');
	assert(typeof phantom.scriptName === 'string', 'phantom.scriptName is a string');
	assert(typeof phantom.version === 'object', 'phantom.version is an object');
	assert(typeof phantom.version.major === 'number', 'phantom.version.major is a number');
	assert(typeof phantom.version.minor === 'number', 'phantom.version.minor is a number');
	//assert(typeof phantom.addCookie === 'function', 'phantom.addCookie is a function');
	//assert(typeof phantom.clearCookies === 'function', 'phantom.clearCookies is a function');
	//assert(typeof phantom.deleteCookie === 'function', 'phantom.deleteCookie is a function');
	assert(typeof phantom.exit === 'function', 'phantom.exit is a function');
	assert(typeof phantom.injectJs === 'function', 'phantom.injectJs is a function');

	// --------------------------------------------
	assert.section('Functionality');

	phantom.libraryPath = "..\\..\\test\\unit\\ref\\";

	assert(phantom.scriptName === 'test/unit/spec/phantom.js', 'phantom.scriptName is the currently executing script');
	assert(phantom.libraryPath !== fs.workingDirectory, 'changing phantom.libraryPath does not alter fs.workingDirectory');
	assert(phantom.version.major === 1, 'phantom.version.major is 1');

	var injection = phantom.injectJs('script.js');

	assert(injection === true, 'phantom.injectJs() returned true when pointing to file');
	assert(___test190234 === true, 'phantom.injectJs() executes a script in current V8 context');

	// Tear down
	phantom.libraryPath = fs.workingDirectory;

});<|endoftext|>


<commit_before>'use strict';

var logger = require('../../../src/utils/logger.js'),
    config = require('../../../src/config/config'),
    chai = require('chai'),
    expect = chai.expect,
    assert = chai.assert,
    fs = require('fs'),
    sinon = require('sinon');

var logFile = config.logFile ? config.logFile : 'logs/composr.log';

describe('Log file creation', function(){

  //Delete the logs if exists
  before(function(done){
    if(fs.existsSync(logFile)){
      fs.unlink(logFile, function (err) {
        if (err) throw err;
        done(err);
      });
    }else{
      done();
    }
  });

  it('creates a log file', function(done){
    logger.error('bob el silencioso', function(){
      fs.exists(logFile, function (exists) {
        expect(exists).to.equals(true);
        done();
      });
    });
  });

  it('logs the message', function(done){
    logger.error('thenew error', function(){
      fs.readFile(logFile, 'utf8', function (err, data) {
        if (err) throw err;
        expect(data.indexOf('thenew error')).to.not.equals(-1);
        done(err);
      });
    });
  });
});
<commit_msg>try adding a timeout to the logs test<commit_after>'use strict';

var logger = require('../../../src/utils/logger.js'),
    config = require('../../../src/config/config'),
    chai = require('chai'),
    expect = chai.expect,
    assert = chai.assert,
    fs = require('fs'),
    sinon = require('sinon');

var logFile = config.logFile ? config.logFile : 'logs/composr.log';

describe('Log file creation', function(){

  //Delete the logs if exists
  before(function(done){
    if(fs.existsSync(logFile)){
      fs.unlink(logFile, function (err) {
        if (err) throw err;
        done(err);
      });
    }else{
      done();
    }
  });

  it('creates a log file', function(done){
    this.timeout(30000);
    logger.error('bob el silencioso', function(){
      setTimeout(function(){
        fs.exists(logFile, function (exists) {
          expect(exists).to.equals(true);
          done();
        });
      }, 2000);

    });
  });

  it('logs the message', function(done){
    logger.error('thenew error', function(){
      fs.readFile(logFile, 'utf8', function (err, data) {
        if (err) throw err;
        expect(data.indexOf('thenew error')).to.not.equals(-1);
        done(err);
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * 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.
 */

const path = require('path');
const request = require('supertest');

// load default variables for testing
require('dotenv').config({ path: path.join(__dirname, '../../.env.example') });

const app = require('../../app');

describe('express', () => {
  it('load home page when GET /', () => request(app).get('/').expect(200));

  it('404 when page not found', () => request(app).get('/foo/bar').expect(404));
});
<commit_msg>fix(Express Tests): expect an Error when route does not exist<commit_after>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * 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.
 */

const path = require('path');
const request = require('supertest');

// load default variables for testing
require('dotenv').config({ path: path.join(__dirname, '../../.env.example') });

const app = require('../../app');

describe('express', () => {
  it('load home page when GET /', () => {
    request(app).get('/').expect(200);
  });

  it('404 when page not found', () => {
    request(app)
      .get('/foo/bar')
      .expect(new Error('Not Found'));
  });
});
<|endoftext|>


<commit_before>var util = require('../util.test');

module.exports = function() {
  util.request('http://test.local.whistlejs.com/index.html?doNotParseJson', function(res, body) {
    body.should.equal('uiServer');
  });

  util.request('http://plugin.whistlejs.com:1234/index.html', function(res, data) {
    data.should.have.property('type', 'server');
  });

  util.request('wss://321.whistlejs.com/index.html', function(data) {
    data.ruleValue.should.equal('abc');
  });

  util.request('wss://321.ws1.whistlejs.com:2222/index.html', function(data) {
    data.host.should.equal('127.0.0.1:9999');
  });
};
<commit_msg>test: res.response<commit_after>var util = require('../util.test');

module.exports = function() {
  util.request('http://test.local.whistlejs.com/index.html?doNotParseJson', function(res, body) {
    body.should.equal('uiServer');
  });
  util.request('http://test1.local.whistlejs.com/index.html?doNotParseJson', function(res, body) {
    res.statusCode.should.equal(501);
    body.should.equal('Not implemented');
  });
  util.request('http://plugin.whistlejs.com:1234/index.html', function(res, data) {
    data.should.have.property('type', 'server');
  });

  util.request('wss://321.whistlejs.com/index.html', function(data) {
    data.ruleValue.should.equal('abc');
  });

  util.request('wss://321.ws1.whistlejs.com:2222/index.html', function(data) {
    data.host.should.equal('127.0.0.1:9999');
  });
};
<|endoftext|>


<commit_before>var util = require('../util.test');

module.exports = function() {
  util.request('http://weinre1.test.whistlejs.com/index.html?resBody=_', function(res, body) {
    body.should.containEql('<script>window.WeinreServerURL="/...whistle-path.5b6af7b9884e1165...///weinre.6668";</script>\r\n<script src="/...whistle-path.5b6af7b9884e1165...///weinre.6668/target/target-script-min.js#xxx"></script>');
  });

  util.request({
    url: 'http://weinre2.test.whistlejs.com/index.html',
    method: 'post',
    body: 'sssssss'
  });

  util.request('https://weinre3.test.whistlejs.com/index.html');

  util.request({
    url: 'https://weinre4.test.whistlejs.com/index.html',
    method: 'post',
    body: 'sssssss'
  });

  util.request('http://weinre1.test.whistlejs.com:1234/index.html?resBody=_', function(res, body) {
    body.should.containEql('<script>window.WeinreServerURL="/...whistle-path.5b6af7b9884e1165...///weinre.6668";</script>\r\n<script src="/...whistle-path.5b6af7b9884e1165...///weinre.6668/target/target-script-min.js#xxx"></script>');
  });

  util.request({
    url: 'http://weinre2.test.whistlejs.com:2345/index.html',
    method: 'post',
    body: 'sssssss'
  });

  util.request('https://weinre3.test.whistlejs.com:3456/index.html');

  util.request({
    url: 'https://weinre4.test.whistlejs.com:4567/index.html',
    method: 'post',
    body: 'sssssss'
  });
};
<commit_msg>test: weinre<commit_after>var util = require('../util.test');

module.exports = function() {
  util.request('http://weinre1.test.whistlejs.com/index.html?resBody=_', function(res, body) {
    body.should.containEql('http://local.whistlejs.com/...whistle-path.5b6af7b9884e1165...///weinre.6668/target/target-script-min.js#xxx');
  });

  util.request({
    url: 'http://weinre2.test.whistlejs.com/index.html',
    method: 'post',
    body: 'sssssss'
  });

  util.request('https://weinre3.test.whistlejs.com/index.html');

  util.request({
    url: 'https://weinre4.test.whistlejs.com/index.html',
    method: 'post',
    body: 'sssssss'
  });

  util.request('http://weinre1.test.whistlejs.com:1234/index.html?resBody=_', function(res, body) {
    body.should.containEql('http://local.whistlejs.com/...whistle-path.5b6af7b9884e1165...///weinre.6668/target/target-script-min.js#xxx');
  });

  util.request({
    url: 'http://weinre2.test.whistlejs.com:2345/index.html',
    method: 'post',
    body: 'sssssss'
  });

  util.request('https://weinre3.test.whistlejs.com:3456/index.html');

  util.request({
    url: 'https://weinre4.test.whistlejs.com:4567/index.html',
    method: 'post',
    body: 'sssssss'
  });
};
<|endoftext|>


<commit_before>import { getUrlExtension } from '../src/utilities/urlExtension.js';

describe( 'getUrlExtension', () => {

	it.each( [
		'https://nasa.gov/foo/bar/baz.qux/tileset.json',
		'https://nasa.gov/foo/bar/baz.qux/tileset.json?foo=bar',
		'https://nasa.gov/foo/bar/baz.qux/tileset.json?a.b=c.d',
		'https://nasa.gov/tileset.json',
		'https://nasa.gov//tileset.json',
		'file:///Users/JaneScientist/code/3DTilesRendererJS/example/b3dmExample.json',
		'foo.json',
		'/foo/bar.json',
		'foo.json?a=b',
		'/foo.json',
		'/foo/bar.json',
	] )( 'parses the json extension out of %s', url => {

		expect( getUrlExtension( url ) ).toBe( 'json' );

	} );

	it.each( [
		'https://nasa.gov',
		'https://nasa.gov/',
		'https://nasa.gov/tileset',
		'https://nasa.gov/foo/bar/baz.qux/tileset?foo=bar',
		'https://nasa.gov/foo/bar/baz.qux/tileset?a.b=c.d',
		'https://nasa.gov/tileset',
		'https://nasa.gov/tileset.',
		'Pleiades',
	] )( 'returns null for strings that are not URLs with extensions %s', url => {

		expect( getUrlExtension( url ) ).toBeNull();

	} );

} );
<commit_msg>Improve test cases.<commit_after>import { getUrlExtension } from '../src/utilities/urlExtension.js';

describe( 'getUrlExtension', () => {

	it.each( [
		'https://nasa.gov/foo/bar.baz/tileset.json',
		'https://nasa.gov/foo/bar.baz/tileset.json?foo=bar',
		'https://nasa.gov/foo/bar.baz/tileset.json?a.b=c.d',
		'https://nasa.gov/foo/bar.baz/tileset.json?a.b=c.d#e.f',
		'https://nasa.gov/tileset.json',
		'https://nasa.gov//tileset.json',
		'file:///Users/JaneScientist/code/3DTilesRendererJS/example/b3dmExample.json',
		'foo.json',
		'/foo/bar.json',
		'foo.json?a=b',
		'/foo.json',
		'/foo/bar.json',
		'png.svg.json'
	] )( 'parses extensions (%s)', url => {

		expect( getUrlExtension( url ) ).toBe( 'json' );

	} );

	it.each( [
		'https://nasa.gov',
		'https://nasa.gov/',
		'https://nasa.gov/tileset',
		'https://nasa.gov/foo/bar.baz/tileset?foo=bar',
		'https://nasa.gov/foo/bar.baz/tileset?a.b=c.d',
		'https://nasa.gov/tileset',
		'https://nasa.gov/tileset.',
		'Pleiades',
		'.',
		'..',
		'',
		undefined,
	] )( 'returns null for values that are not URLs with extensions (%s)', url => {

		expect( getUrlExtension( url ) ).toBeNull();

	} );

} );
<|endoftext|>


<commit_before>var document = require("global/document")
var isObject = require("is-object")

module.exports = makeElements

function makeElements(hash) {
    return Object.keys(hash).reduce(function (acc, key) {
        var value = hash[key]

        if (Array.isArray(value)) {
            var tagName = value[0]
            var content = value[1]

            var elem = document.createElement(tagName)

            if (tagName === "input") {
                elem.value = content

                acc[key] = elem
            } else if (tagName === "select") {
                content.options.forEach(function (text) {
                    var option = document.createElement("option")
                    option.textContent = text
                    option.value = text
                    elem.appendChild(option)
                })

                elem.selectedIndex = content.selected

                acc[key] = elem
            } else if (tagName === "radio") {
                var res = content.as === Array ? [] : {}

                content.radios.forEach(function (text, index) {
                    var input = document.createElement("input")
                    input.type = "radio"
                    input.value = text

                    if (content.checked === index) {
                        input.checked = true
                    }

                    input.name = content.name
                    elem.appendChild(input)

                    if (content.as === Array) {
                        res.push(input)
                    } else {
                        res[text] = input
                    }
                })

                acc[key] = res
            }
        } else if (isObject(value)) {
            acc[key] = makeElements(value)
        }

        return acc
    }, {})
}
<commit_msg>fuck util<commit_after><|endoftext|>


<commit_before>describe("VglRenderer component", function() {
    const {VglRenderer, VglNamespace} = VueGL;
    const assert = chai.assert;
    const webgl = (() => {
        const canvas = document.createElement("canvas");
        let gl;
        try {
            gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
            return typeof gl.getSupportedExtensions === "function";
        } catch(e) {}
        return false;
    })();
    let pvm;
    if (!webgl) {
        console.log("WebGL is not supported. Skip tests for the VglRenderer.");
    } else {
        pvm = new Vue(VglRenderer).$mount();
    }
    beforeEach(function() {
        // Skip all tests when the WebGL is not supported.
        if (!webgl) this.skip();
    });
    describe("Namespace injection", function() {
        describe("Should be able to access vglCameras", function() {
            it("When the component is the root namespace.", function() {
                assert.isObject(pvm.vglCameras);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-renderer ref="renderer" /></vgl-namespace>`,
                    components: {
                        VglNamespace,
                        VglRenderer
                    }
                }).$mount();
                assert.isObject(vm.$refs.renderer.vglCameras);
            });
        });
        describe("Should be able to access vglScenes", function() {
            it("When the component is the root namespace.", function() {
                assert.isObject(pvm.vglScenes);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-renderer ref="renderer" /></vgl-namespace>`,
                    components: {
                        VglNamespace,
                        VglRenderer
                    }
                }).$mount();
                assert.isObject(vm.$refs.renderer.vglScenes);
            });
        });
    });
    describe("Creating a renderer", function() {
        describe("Output canvas", function() {
            it("The domElement property of WebGLRenderer instance should be the Vue created canvas.", function() {
                assert.strictEqual(pvm.$refs.rdr, pvm.inst.domElement);
            });
        });
        describe("Context attributes", function() {
            describe("The alpha property should affect the alpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.getContextAttributes().alpha);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {alpha: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().alpha);
                });
            });
            describe("The disableDepth property should affect the depth attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isTrue(pvm.inst.getContextAttributes().depth);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableDepth: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().depth);
                });
            });
            describe("The disableStencil property should affect the stencil attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isTrue(pvm.inst.getContextAttributes().stencil);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableStencil: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().stencil);
                });
            });
            describe("The antialias property should affect the antialias attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.getContextAttributes().antialias);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {antialias: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().antialias);
                });
            });
            describe("The disablePremultipliedAlpha property should affect the premultipliedAlpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isTrue(pvm.inst.getContextAttributes().premultipliedAlpha);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disablePremultipliedAlpha: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().premultipliedAlpha);
                });
            });
            describe("The preserveDrawingBuffer property should affect the preserveDrawingBuffer attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.getContextAttributes().preserveDrawingBuffer);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {preserveDrawingBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().preserveDrawingBuffer);
                });
            });
        });
        describe("Capabilities", function() {
            describe("The logarithmicDepthBuffer property should affect the logarithmicDepthBuffer capability.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.capabilities.logarithmicDepthBuffer);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {logarithmicDepthBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.capabilities.logarithmicDepthBuffer);
                });
            });
            describe("The precision property should affect the precision capability.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.strictEqual(pvm.inst.capabilities.precision, "highp");
                });
                it("When the property is \"lowp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "lowp"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "lowp");
                });
                it("When the property is \"mediump\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "mediump"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "mediump");
                });
                it("When the property is \"highp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "highp"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "highp");
                });
            });
        });
    });
    describe("When any properties are changed", function() {
        describe("Output canvas", function() {
            it("The canvas element should be replaced.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                const oldCanvas = vm.$refs.rdr;
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.notEqual(oldCanvas, vm.$refs.rdr);
                        done();
                    } catch(e) {
                        done(e);
                    }
                });
            });
            it("The WebGLRenderer instance should be newly created.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                const oldInst = vm.inst;
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.notEqual(oldInst, vm.inst);
                        done();
                    } catch(e) {
                        done(e);
                    }
                });
            });
            it("The domElement property of WebGLRenderer instance should be the replaced canvas.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.strictEqual(vm.inst.domElement, vm.$refs.rdr);
                        done();
                    } catch(e) {
                        done(e);
                    }
                });
            });
        });
    });
});
<commit_msg>Skip property testing when the antialias function is not supported.<commit_after>describe("VglRenderer component", function() {
    const {VglRenderer, VglNamespace} = VueGL;
    const assert = chai.assert;
    const webgl = (() => {
        const canvas = document.createElement("canvas");
        const opts = {
            antialias: true
        };
        try {
            return canvas.getContext("webgl", opts) || canvas.getContext("experimental-webgl", opts);
        } catch(e) {}
        return false;
    })();
    let pvm;
    if (!webgl) {
        console.log("WebGL is not supported. Skip tests for the VglRenderer.");
    } else {
        pvm = new Vue(VglRenderer).$mount();
    }
    beforeEach(function() {
        // Skip all tests when the WebGL is not supported.
        if (!webgl) this.skip();
    });
    describe("Namespace injection", function() {
        describe("Should be able to access vglCameras", function() {
            it("When the component is the root namespace.", function() {
                assert.isObject(pvm.vglCameras);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-renderer ref="renderer" /></vgl-namespace>`,
                    components: {
                        VglNamespace,
                        VglRenderer
                    }
                }).$mount();
                assert.isObject(vm.$refs.renderer.vglCameras);
            });
        });
        describe("Should be able to access vglScenes", function() {
            it("When the component is the root namespace.", function() {
                assert.isObject(pvm.vglScenes);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-renderer ref="renderer" /></vgl-namespace>`,
                    components: {
                        VglNamespace,
                        VglRenderer
                    }
                }).$mount();
                assert.isObject(vm.$refs.renderer.vglScenes);
            });
        });
    });
    describe("Creating a renderer", function() {
        describe("Output canvas", function() {
            it("The domElement property of WebGLRenderer instance should be the Vue created canvas.", function() {
                assert.strictEqual(pvm.$refs.rdr, pvm.inst.domElement);
            });
        });
        describe("Context attributes", function() {
            describe("The alpha property should affect the alpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.getContextAttributes().alpha);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {alpha: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().alpha);
                });
            });
            describe("The disableDepth property should affect the depth attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isTrue(pvm.inst.getContextAttributes().depth);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableDepth: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().depth);
                });
            });
            describe("The disableStencil property should affect the stencil attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isTrue(pvm.inst.getContextAttributes().stencil);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableStencil: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().stencil);
                });
            });
            describe("The antialias property should affect the antialias attribute.", function() {
                const enable = webgl.getContextAttributes().antialias;
                if (!enable) console.log("Antialiasing is not supported. Skip tests for the antialias property.");
                beforeEach(function() {
                    if (!enable) this.skip();
                });
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.getContextAttributes().antialias);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {antialias: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().antialias);
                });
            });
            describe("The disablePremultipliedAlpha property should affect the premultipliedAlpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isTrue(pvm.inst.getContextAttributes().premultipliedAlpha);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disablePremultipliedAlpha: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().premultipliedAlpha);
                });
            });
            describe("The preserveDrawingBuffer property should affect the preserveDrawingBuffer attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.getContextAttributes().preserveDrawingBuffer);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {preserveDrawingBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().preserveDrawingBuffer);
                });
            });
        });
        describe("Capabilities", function() {
            describe("The logarithmicDepthBuffer property should affect the logarithmicDepthBuffer capability.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.capabilities.logarithmicDepthBuffer);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {logarithmicDepthBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.capabilities.logarithmicDepthBuffer);
                });
            });
            describe("The precision property should affect the precision capability.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.strictEqual(pvm.inst.capabilities.precision, "highp");
                });
                it("When the property is \"lowp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "lowp"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "lowp");
                });
                it("When the property is \"mediump\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "mediump"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "mediump");
                });
                it("When the property is \"highp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "highp"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "highp");
                });
            });
        });
    });
    describe("When any properties are changed", function() {
        describe("Output canvas", function() {
            it("The canvas element should be replaced.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                const oldCanvas = vm.$refs.rdr;
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.notEqual(oldCanvas, vm.$refs.rdr);
                        done();
                    } catch(e) {
                        done(e);
                    }
                });
            });
            it("The WebGLRenderer instance should be newly created.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                const oldInst = vm.inst;
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.notEqual(oldInst, vm.inst);
                        done();
                    } catch(e) {
                        done(e);
                    }
                });
            });
            it("The domElement property of WebGLRenderer instance should be the replaced canvas.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.strictEqual(vm.inst.domElement, vm.$refs.rdr);
                        done();
                    } catch(e) {
                        done(e);
                    }
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

//
//  The MIT License (MIT)
//
//  Copyright (c) 2015-2016 Microsoft
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//
//  Thali Cordova Plugin
//  thali_main.js
//

(function () {
  var inter = setInterval(function () {
    if (typeof jxcore == 'undefined') { return; }

    clearInterval(inter);

    jxcore.isReady(function () {
      if (window.ThaliPermissions) {
        // requestLocationPermission ensures that the application has
        // the required ACCESS_COARSE_LOCATION permission in Android.
        window.ThaliPermissions.requestLocationPermission(function () {
          console.log('Application has the required permission.');
          loadMainFile();
        }, function (error) {
          console.log('Location permission not granted. Error: ' + error);
          console.log('****TEST_LOGGER:[PROCESS_ON_EXIT_FAILED]****');
          navigator.app.exitApp();
        });
      } else {
        loadMainFile();
      }
    });
  }, 5);

  function loadMainFile() {
    jxcore('app.js').loadMainFile(function (ret, err) {
      if (err) {
        console.log('app.js file failed to load : ' + JSON.stringify(err));
        // This is an error scenario, which occurs in CI, but should not
        // be an issue with the app code so inform CI that this was a
        // success case. This can be made an error after this is fixed:
        // https://github.com/thaliproject/Thali_CordovaPlugin/issues/594
        console.log('****TEST_LOGGER:[PROCESS_ON_EXIT_SUCCESS]****');
        navigator.app.exitApp();
      } else {
        jxcore_ready();
      }
    });
  }

  function jxcore_ready() {
    jxcore('setMyNameCallback').call(nameCallback);
    jxcore('setLogCallback').call(logCallback);
    document.getElementById('ClearLogButton').addEventListener('click', ClearLog);
    console.log('UIApp is all set and ready!');
  }

  function nameCallback(name) {
    document.getElementById('nameTag').innerHTML = name;
  }

  function ClearLog() {
    document.getElementById('LogBox').value = '';
  }

  function logCallback(data) {
    var logBox = document.getElementById('LogBox');
    logBox.value = data + '\n' + logBox.value;
  }
}());
<commit_msg>Removed success log when app.js failed to load. Added failure log<commit_after>'use strict';

//
//  The MIT License (MIT)
//
//  Copyright (c) 2015-2016 Microsoft
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//
//  Thali Cordova Plugin
//  thali_main.js
//

(function () {
  var inter = setInterval(function () {
    if (typeof jxcore == 'undefined') { return; }

    clearInterval(inter);

    jxcore.isReady(function () {
      if (window.ThaliPermissions) {
        // requestLocationPermission ensures that the application has
        // the required ACCESS_COARSE_LOCATION permission in Android.
        window.ThaliPermissions.requestLocationPermission(function () {
          console.log('Application has the required permission.');
          loadMainFile();
        }, function (error) {
          console.log('Location permission not granted. Error: ' + error);
          exitWithFailureLog();
        });
      } else {
        loadMainFile();
      }
    });
  }, 5);

  function loadMainFile() {
    jxcore('app.js').loadMainFile(function (ret, err) {
      if (err) {
        console.log('app.js file failed to load : ' + JSON.stringify(err));
        exitWithFailureLog();
      } else {
        jxcore_ready();
      }
    });
  }

  function jxcore_ready() {
    jxcore('setMyNameCallback').call(nameCallback);
    jxcore('setLogCallback').call(logCallback);
    document.getElementById('ClearLogButton').addEventListener('click', ClearLog);
    console.log('UIApp is all set and ready!');
  }

  function exitWithFailureLog() {
    console.log('****TEST_LOGGER:[PROCESS_ON_EXIT_FAILED]****');
    navigator.app.exitApp();
  }

  function nameCallback(name) {
    document.getElementById('nameTag').innerHTML = name;
  }

  function ClearLog() {
    document.getElementById('LogBox').value = '';
  }

  function logCallback(data) {
    var logBox = document.getElementById('LogBox');
    logBox.value = data + '\n' + logBox.value;
  }
}());
<|endoftext|>


<commit_before>angular.module('os.biospecimen.specimenlist.addedit', ['os.biospecimen.models'])
  .controller('AddEditSpecimenListCtrl', function(
    $scope, $state, list, barcodingEnabled, SpecimenList, SpecimensHolder, DeleteUtil, SpecimenUtil, Util) {

    function init() {
      $scope.list = list;
      $scope.list.isAllowedToDeleteList = isAllowedToDeleteList();

      $scope.input = {
        labelText: '',
        barcodingEnabled: barcodingEnabled,
        useBarcode: false
      };

      if (SpecimensHolder.getSpecimens() != undefined) {
        $scope.isQueryOrSpecimenPage =  true;
        $scope.input.specimenIds = SpecimensHolder.getSpecimens().map(function(spmn) { return spmn.id; });
        SpecimensHolder.setSpecimens(undefined);
      }

    }

    function isAllowedToDeleteList() {
       return !!$scope.list.id &&
              !$scope.list.defaultList &&
              ($scope.list.owner.id == $scope.currentUser.id || $scope.currentUser.admin)
    }

    function updateSpecimenList(specimenList, labels) {
      if (!labels || labels.length == 0) {
        return specimenList.$saveOrUpdate();
      }

      var filterOpts = {};
      if (!!$scope.input.useBarcode) {
        filterOpts.barcode = labels;
        labels = undefined;
      }

      return SpecimenUtil.getSpecimens(labels, filterOpts).then(
        function(specimens) {
          if (!specimens) {
            return undefined;
          }

          specimenList.specimenIds = specimens.map(function(spmn) { return spmn.id; });
          return specimenList.$saveOrUpdate();
        }
      );
    }

    $scope.saveOrUpdateList = function() {
      var labels = Util.splitStr($scope.input.labelText, /,|\t|\n/);
      var promise = undefined;

      var sharedWith = $scope.list.sharedWith.map(
        function(user) {
          return {id: user.id}
        }
      );

      var specimenList =  new SpecimenList({
        id: $scope.list.id,
        name: $scope.list.name,
        description: $scope.list.description,
        sharedWith: sharedWith,
        specimenIds: $scope.input.specimenIds || []
      });

      var promise = updateSpecimenList(specimenList, labels);
      promise.then(
        function(savedList) {
          if (!savedList) {
            return;
          }

          if ($scope.isQueryOrSpecimenPage) {
            $scope.back();
          } else {
            $state.go('specimen-list', {listId: savedList.id});
          }
        }
      );
    }

    $scope.deleteList = function() {
      DeleteUtil.delete($scope.list, {
        onDeleteState: 'specimen-lists',
        deleteWithoutCheck: true
      });
    }

    init();
  }
);
<commit_msg>OPSMN-2135: Displayed success messages whenever specimens are added to a new cart from query results view or specimen tree widget.<commit_after>angular.module('os.biospecimen.specimenlist.addedit', ['os.biospecimen.models'])
  .controller('AddEditSpecimenListCtrl', function(
    $scope, $state, list, barcodingEnabled,
    Alerts, SpecimenList, SpecimensHolder, DeleteUtil, SpecimenUtil, Util) {

    function init() {
      $scope.list = list;
      $scope.list.isAllowedToDeleteList = isAllowedToDeleteList();

      $scope.input = {
        labelText: '',
        barcodingEnabled: barcodingEnabled,
        useBarcode: false
      };

      if (SpecimensHolder.getSpecimens() != undefined) {
        $scope.isQueryOrSpecimenPage =  true;
        $scope.input.specimenIds = SpecimensHolder.getSpecimens().map(function(spmn) { return spmn.id; });
        SpecimensHolder.setSpecimens(undefined);
      }

    }

    function isAllowedToDeleteList() {
       return !!$scope.list.id &&
              !$scope.list.defaultList &&
              ($scope.list.owner.id == $scope.currentUser.id || $scope.currentUser.admin)
    }

    function updateSpecimenList(specimenList, labels) {
      if (!labels || labels.length == 0) {
        return specimenList.$saveOrUpdate();
      }

      var filterOpts = {};
      if (!!$scope.input.useBarcode) {
        filterOpts.barcode = labels;
        labels = undefined;
      }

      return SpecimenUtil.getSpecimens(labels, filterOpts).then(
        function(specimens) {
          if (!specimens) {
            return undefined;
          }

          specimenList.specimenIds = specimens.map(function(spmn) { return spmn.id; });
          return specimenList.$saveOrUpdate();
        }
      );
    }

    $scope.saveOrUpdateList = function() {
      var labels = Util.splitStr($scope.input.labelText, /,|\t|\n/);
      var promise = undefined;

      var sharedWith = $scope.list.sharedWith.map(
        function(user) {
          return {id: user.id}
        }
      );

      var specimenList =  new SpecimenList({
        id: $scope.list.id,
        name: $scope.list.name,
        description: $scope.list.description,
        sharedWith: sharedWith,
        specimenIds: $scope.input.specimenIds || []
      });

      var promise = updateSpecimenList(specimenList, labels);
      promise.then(
        function(savedList) {
          if (!savedList) {
            return;
          }

          if ($scope.isQueryOrSpecimenPage) {
            var type = savedList.getListType($scope.currentUser);
            Alerts.success('specimen_list.specimens_added_to_' + type, savedList);

            $scope.back();
          } else {
            $state.go('specimen-list', {listId: savedList.id});
          }
        }
      );
    }

    $scope.deleteList = function() {
      DeleteUtil.delete($scope.list, {
        onDeleteState: 'specimen-lists',
        deleteWithoutCheck: true
      });
    }

    init();
  }
);
<|endoftext|>


<commit_before>var mapzen = mapzen || {};
mapzen.whosonfirst = mapzen.whosonfirst || {};

/*

To do:

- tab/keyboard controls
- flags/callback functions to render certains values as something other than text (a link, as code, etc.)

Open questions:

- to sort or not
- to bucket (by prefix) or not
- update existing assertions or alert or just allow multiple (conflicting?) assertions for the same path

 */

mapzen.whosonfirst.yesnofix = (function(){

    var fix = -1;
    var no = 0;
    var yes = 1;

    var _custom_renderers = {
	'dict': function(d, ctx){ return null; },
	'text': function(d, ctx){ return null; },
    };

    var assertions = [];

    var self = {

	'set_custom_renderers': function(t, r){

	    if (! _custom_renderers[t]){
		return;
	    }

	    if (! r){
		return;
	    }

	    _custom_renderers[t] = r;
	},

	'get_custom_renderer': function(t, d, ctx){

	    if (! _custom_renderers[t]){
		return null;
	    }

	    var custom = _custom_renderers[t];
	    return custom(d, ctx);
	},

	// please do not call these 'engage' or 'makeitso' ...

	'makeitso': function(data, target){

	    var el = document.getElementById(target);

	    if (! el){
		return false;
	    }

	    var pretty = self.engage(data);
	    el.appendChild(pretty);

	    return true;
	},

	'engage': function(props){

	    var pretty = document.createElement("div");
	    pretty.setAttribute("id", "props-pretty");

	    buckets = self.bucket_props(props);

	    var namespaces = Object.keys(buckets);
	    namespaces = namespaces.sort();

	    var count_ns = namespaces.length;

	    for (var i=0; i < count_ns; i++){
		var ns = namespaces[i];
		var dom = self.render_bucket(ns, buckets[ns]);
		pretty.appendChild(dom);
	    }

	    return pretty;
	},

	'render_bucket': function(ns, bucket){

	    var wrapper = document.createElement("div");

	    var header = document.createElement("h3");
	    var content = document.createTextNode(ns);
	    header.appendChild(content);

	    var sorted = self.sort_bucket(bucket);
	    var body = self.render(sorted, ns);

	    wrapper.appendChild(header);
	    wrapper.appendChild(body);

	    return wrapper;
	},

	'render': function(d, ctx){

	    // console.log("render context is " + ctx);
	    // console.log(d);

	    if (Array.isArray(d)){
		// console.log("render list for " + ctx);
		return self.render_list(d, ctx);
	    }

	    else if (typeof(d) == "object"){
		// console.log("render dict for " + ctx);
		return self.render_dict(d, ctx);
	    }

	    else {
		// console.log("render text for " + ctx);

		var wrapper = document.createElement("span");
		wrapper.setAttribute("class", "props-content");

		var content;

		var renderer = self.get_custom_renderer('text', d, ctx);
		// console.log("rendered for " + ctx + " : " + typeof(renderer));

		if (renderer){
		    try {
			content = renderer(d, ctx);
		    } catch (e) {
			console.log("UNABLE TO RENDER " + ctx + " BECAUSE " + e);
		    }
		}

		else {
		    content = self.render_text(d, ctx);
		}

		wrapper.appendChild(content);

		var trigger = self.render_trigger(ctx);
		wrapper.appendChild(trigger);

		return wrapper;
	    }
	},

	'render_dict': function(d, ctx){

	    var table = document.createElement("table");
	    table.setAttribute("class", "table");

	    for (k in d){

		var row = document.createElement("tr");
		var label_text = k;

		var _ctx = (ctx) ? ctx + "." + k : k;

		var renderer = self.get_custom_renderer('dict', d, _ctx);

		if (renderer){
		    try {
			label_text = renderer(d, _ctx);
		    } catch (e) {
			console.log("UNABLE TO RENDER " + _ctx + " BECAUSE " + e);
		    }
		}

		/*
		  unclear if the rule should just be only text (as it currently is)
		  or whether custom markup is allowed... smells like feature quicksand
		  so moving along for now (20160211/thisisaaronland)
		 */

		var header = document.createElement("th");
		var label = document.createTextNode(mapzen.whosonfirst.php.htmlspecialchars(label_text));
		header.appendChild(label);

		var content = document.createElement("td");

		var body = self.render(d[k], _ctx);
		content.appendChild(body);

		row.appendChild(header);
		row.appendChild(content);

		table.appendChild(row);
	    }

	    return table;
	},

	'render_list': function(d, ctx){

	    var count = d.length;

	    if (count == 0){
		return self.render_text("–", ctx);
	    }

	    if (count <= 1){
		return self.render(d[0], ctx);
	    }

	    var list = document.createElement("ul");

	    for (var i=0; i < count; i++){

		var item = document.createElement("li");
		var body = self.render(d[i], ctx + "#" + i);

		item.appendChild(body);
		list.appendChild(item);
	    }

	    return list;
	},

	'render_editable': function(d){
	    // please write me
	},

	'render_text': function(d, ctx){

	    var text = mapzen.whosonfirst.php.htmlspecialchars(d);

	    var span = document.createElement("span");
	    span.setAttribute("id", ctx);
	    span.setAttribute("title", ctx);
	    span.setAttribute("class", "props-uoc");

	    // span.onclick = mapzen.whosonfirst.yesnofix.onclick;

	    var el = document.createTextNode(text);
	    span.appendChild(el);

	    return span;
	},

	'render_link': function(link, text, ctx){

	    var anchor = document.createElement("a");
	    anchor.setAttribute("href", link);
	    anchor.setAttribute("target", "_wof");
	    var body = self.render_text(text, ctx);
	    anchor.appendChild(body);

	    return anchor;
	},

	/*
	  .trigger { display:none; padding-left: 1em; }
	  .props-content:hover .trigger { display:inline; }
	*/

	'render_trigger': function(ctx){

	    var edit = document.createTextNode("📝");	// http://emojipedia.org/memo/

	    var trigger = document.createElement("span");
	    trigger.setAttribute("trigger-id", ctx);
	    trigger.setAttribute("class", "trigger");
	    trigger.appendChild(edit);

	    trigger.onclick = mapzen.whosonfirst.yesnofix.ontrigger;
	    return trigger;
	},

	'render_code': function(text, ctx){

	    var code = document.createElement("code");
	    var body = self.render_text(text, ctx);
	    code.appendChild(body);
	    return code;
	},

	'render_timestamp': function(text, ctx){
	    var dt = new Date(parseInt(text) * 1000);
	    return self.render_text(dt.toISOString(), ctx);
	},

	'bucket_props': function(props){

	    buckets = {};

	    for (k in props){
		parts = k.split(":", 2);

		ns = parts[0];
		pred = parts[1];

		if (parts.length != 2){
		    ns = "global";
		    pred = k;
		}

		if (! buckets[ns]){
		    buckets[ns] = {};
		}

		buckets[ns][pred] = props[k];
	    }

	    return buckets;
	},

	'sort_bucket': function(bucket){

	    var sorted = {};

	    var keys = Object.keys(bucket);
	    keys = keys.sort();

	    var count_keys = keys.length;

	    for (var j=0; j < count_keys; j++){
		var k = keys[j];
		sorted[k] = bucket[k];
	    }

	    return sorted;
	},

	'ontrigger': function(e) {

	    var target = e.target;
	    var id = target.getAttribute("trigger-id");
	    var value = target.textContent;

	    var enc_id = mapzen.whosonfirst.php.htmlspecialchars(id);
	    var enc_value = mapzen.whosonfirst.php.htmlspecialchars(value);

	    //alert("you clicked " + enc_id + " whose value is \"" + enc_value + "\"");

	    var parent = target.parentElement;

	    if (! parent){
		// PLEASE TO MAKE ERRORS...
		return;
	    }

	    var input = self.render_input(id);
	    parent.appendChild(input);
	},

	'render_input': function(id){

	    var input = document.createElement("div");
	    input.setAttribute("id", "assert-" + id);

	    var yes = document.createElement("button");
	    yes.setAttribute("data-id", id);
	    yes.setAttribute("data-assertion", 1);

	    var no = document.createElement("button");
	    no.setAttribute("data-id", id);
	    no.setAttribute("data-assertion", 0);

	    var fix = document.createElement("button");
	    fix.setAttribute("data-id", id);
	    fix.setAttribute("data-assertion", 0);

	    var cancel = document.createElement("button");
	    cancel.setAttribute("data-id", id);

	    yes.appendChild(document.createTextNode("yes"));
	    no.appendChild(document.createTextNode("no"));
	    fix.appendChild(document.createTextNode("fix"));
	    cancel.appendChild(document.createTextNode("cancel"));

	    yes.onclick = mapzen.whosonfirst.yesnofix.onassert;
	    no.onclick = mapzen.whosonfirst.yesnofix.onassert;
	    fix.onclick = mapzen.whosonfirst.yesnofix.onassert;
	    cancel.onclick = mapzen.whosonfirst.yesnofix.oncancel;

	    input.appendChild(yes);
	    input.appendChild(no);
	    input.appendChild(fix);
	    input.appendChild(cancel);

	    return input;
	},

	'onassert' : function(e){

	    var target = e.target;
	    var id = target.getAttribute("data-id");

	    if (! id){
		return false;
	    }

	    var el = document.getElementById(id);

	    if (! el){
		return false;
	    }

	    var path = id;
	    var value = el.textContent;
	    var assertion = target.getAttribute("data-assertion");

	    self.assert(path, value, assertion);

	    alert("Okay, thanks!");

	    var input = document.getElementById("assert-" + id);

	    var parent = input.parentElement;
	    parent.removeChild(input);
	},

	'oncancel': function(e){

	    var target = e.target;
	    var id = target.getAttribute("data-id");

	    if (! id){
		return false;
	    }

	    var input = document.getElementById("assert-" + id);

	    var parent = input.parentElement;
	    parent.removeChild(input);
	},

	// note the lack of validation... we're assuming that kind of sanity
	// checking is happening above?

	'assert': function(path, value, assertion){
	    var dt = new Date();
	    assertions.push({'path': path, 'value': value, 'assertion': assertion, 'date': dt});
	},

	'report': function(){

	    var report = [];
	    var count = assertions.length;

	    for (var i=0; i < count; i++){

		var a = assertions[i];

		var row = [ a['path'], a['value'], a['assertion'], a['date'].toISOString() ];
		row = row.join(",");

		report.push(row);
	    }

	    report = report.join("\n");
	    return report;
	},
    }

    return self;

})();
<commit_msg>only display a single set of controls at a time<commit_after>var mapzen = mapzen || {};
mapzen.whosonfirst = mapzen.whosonfirst || {};

/*

To do:

- tab/keyboard controls
- flags/callback functions to render certains values as something other than text (a link, as code, etc.)

Open questions:

- to sort or not
- to bucket (by prefix) or not
- update existing assertions or alert or just allow multiple (conflicting?) assertions for the same path

 */

mapzen.whosonfirst.yesnofix = (function(){

    var fix = -1;
    var no = 0;
    var yes = 1;

    var _custom_renderers = {
	'dict': function(d, ctx){ return null; },
	'text': function(d, ctx){ return null; },
    };

    var assertions = [];

    var current = null;

    var self = {

	'set_custom_renderers': function(t, r){

	    if (! _custom_renderers[t]){
		return;
	    }

	    if (! r){
		return;
	    }

	    _custom_renderers[t] = r;
	},

	'get_custom_renderer': function(t, d, ctx){

	    if (! _custom_renderers[t]){
		return null;
	    }

	    var custom = _custom_renderers[t];
	    return custom(d, ctx);
	},

	// please do not call these 'engage' or 'makeitso' ...

	'makeitso': function(data, target){

	    var el = document.getElementById(target);

	    if (! el){
		return false;
	    }

	    var pretty = self.engage(data);
	    el.appendChild(pretty);

	    return true;
	},

	'engage': function(props){

	    var pretty = document.createElement("div");
	    pretty.setAttribute("id", "props-pretty");

	    buckets = self.bucket_props(props);

	    var namespaces = Object.keys(buckets);
	    namespaces = namespaces.sort();

	    var count_ns = namespaces.length;

	    for (var i=0; i < count_ns; i++){
		var ns = namespaces[i];
		var dom = self.render_bucket(ns, buckets[ns]);
		pretty.appendChild(dom);
	    }

	    return pretty;
	},

	'render_bucket': function(ns, bucket){

	    var wrapper = document.createElement("div");

	    var header = document.createElement("h3");
	    var content = document.createTextNode(ns);
	    header.appendChild(content);

	    var sorted = self.sort_bucket(bucket);
	    var body = self.render(sorted, ns);

	    wrapper.appendChild(header);
	    wrapper.appendChild(body);

	    return wrapper;
	},

	'render': function(d, ctx){

	    // console.log("render context is " + ctx);
	    // console.log(d);

	    if (Array.isArray(d)){
		// console.log("render list for " + ctx);
		return self.render_list(d, ctx);
	    }

	    else if (typeof(d) == "object"){
		// console.log("render dict for " + ctx);
		return self.render_dict(d, ctx);
	    }

	    else {
		// console.log("render text for " + ctx);

		var wrapper = document.createElement("span");
		wrapper.setAttribute("class", "props-content");

		var content;

		var renderer = self.get_custom_renderer('text', d, ctx);
		// console.log("rendered for " + ctx + " : " + typeof(renderer));

		if (renderer){
		    try {
			content = renderer(d, ctx);
		    } catch (e) {
			console.log("UNABLE TO RENDER " + ctx + " BECAUSE " + e);
		    }
		}

		else {
		    content = self.render_text(d, ctx);
		}

		wrapper.appendChild(content);

		var trigger = self.render_trigger(ctx);
		wrapper.appendChild(trigger);

		return wrapper;
	    }
	},

	'render_dict': function(d, ctx){

	    var table = document.createElement("table");
	    table.setAttribute("class", "table");

	    for (k in d){

		var row = document.createElement("tr");
		var label_text = k;

		var _ctx = (ctx) ? ctx + "." + k : k;

		var renderer = self.get_custom_renderer('dict', d, _ctx);

		if (renderer){
		    try {
			label_text = renderer(d, _ctx);
		    } catch (e) {
			console.log("UNABLE TO RENDER " + _ctx + " BECAUSE " + e);
		    }
		}

		/*
		  unclear if the rule should just be only text (as it currently is)
		  or whether custom markup is allowed... smells like feature quicksand
		  so moving along for now (20160211/thisisaaronland)
		 */

		var header = document.createElement("th");
		var label = document.createTextNode(mapzen.whosonfirst.php.htmlspecialchars(label_text));
		header.appendChild(label);

		var content = document.createElement("td");

		var body = self.render(d[k], _ctx);
		content.appendChild(body);

		row.appendChild(header);
		row.appendChild(content);

		table.appendChild(row);
	    }

	    return table;
	},

	'render_list': function(d, ctx){

	    var count = d.length;

	    if (count == 0){
		return self.render_text("–", ctx);
	    }

	    if (count <= 1){
		return self.render(d[0], ctx);
	    }

	    var list = document.createElement("ul");

	    for (var i=0; i < count; i++){

		var item = document.createElement("li");
		var body = self.render(d[i], ctx + "#" + i);

		item.appendChild(body);
		list.appendChild(item);
	    }

	    return list;
	},

	'render_editable': function(d){
	    // please write me
	},

	'render_text': function(d, ctx){

	    var text = mapzen.whosonfirst.php.htmlspecialchars(d);

	    var span = document.createElement("span");
	    span.setAttribute("id", ctx);
	    span.setAttribute("title", ctx);
	    span.setAttribute("class", "props-uoc");

	    var el = document.createTextNode(text);
	    span.appendChild(el);

	    return span;
	},

	'render_link': function(link, text, ctx){

	    var anchor = document.createElement("a");
	    anchor.setAttribute("href", link);
	    anchor.setAttribute("target", "_wof");
	    var body = self.render_text(text, ctx);
	    anchor.appendChild(body);

	    return anchor;
	},

	/*
	  .trigger { display:none; padding-left: 1em; }
	  .props-content:hover .trigger { display:inline; }
	*/

	'render_trigger': function(ctx){

	    var edit = document.createTextNode("📝");	// http://emojipedia.org/memo/

	    var trigger = document.createElement("span");
	    trigger.setAttribute("trigger-id", ctx);
	    trigger.setAttribute("class", "trigger");
	    trigger.appendChild(edit);

	    trigger.onclick = mapzen.whosonfirst.yesnofix.ontrigger;
	    return trigger;
	},

	'render_code': function(text, ctx){

	    var code = document.createElement("code");
	    var body = self.render_text(text, ctx);
	    code.appendChild(body);
	    return code;
	},

	'render_timestamp': function(text, ctx){
	    var dt = new Date(parseInt(text) * 1000);
	    return self.render_text(dt.toISOString(), ctx);
	},

	'bucket_props': function(props){

	    buckets = {};

	    for (k in props){
		parts = k.split(":", 2);

		ns = parts[0];
		pred = parts[1];

		if (parts.length != 2){
		    ns = "global";
		    pred = k;
		}

		if (! buckets[ns]){
		    buckets[ns] = {};
		}

		buckets[ns][pred] = props[k];
	    }

	    return buckets;
	},

	'sort_bucket': function(bucket){

	    var sorted = {};

	    var keys = Object.keys(bucket);
	    keys = keys.sort();

	    var count_keys = keys.length;

	    for (var j=0; j < count_keys; j++){
		var k = keys[j];
		sorted[k] = bucket[k];
	    }

	    return sorted;
	},

	'ontrigger': function(e) {

	    var target = e.target;
	    var id = target.getAttribute("trigger-id");
	    var value = target.textContent;

	    if (id == self.current){
		return;
	    }

	    if (self.current){
		self.collapse(self.current);
	    }

	    var enc_id = mapzen.whosonfirst.php.htmlspecialchars(id);
	    var enc_value = mapzen.whosonfirst.php.htmlspecialchars(value);

	    //alert("you clicked " + enc_id + " whose value is \"" + enc_value + "\"");

	    var parent = target.parentElement;

	    if (! parent){
		// PLEASE TO MAKE ERRORS...
		return;
	    }

	    var input = self.render_input(id);
	    parent.appendChild(input);

	    self.current = id;
	},

	'render_input': function(id){

	    var input = document.createElement("div");
	    input.setAttribute("id", "assert-" + id);

	    var yes = document.createElement("button");
	    yes.setAttribute("data-id", id);
	    yes.setAttribute("data-assertion", 1);

	    var no = document.createElement("button");
	    no.setAttribute("data-id", id);
	    no.setAttribute("data-assertion", 0);

	    var fix = document.createElement("button");
	    fix.setAttribute("data-id", id);
	    fix.setAttribute("data-assertion", 0);

	    var cancel = document.createElement("button");
	    cancel.setAttribute("data-id", id);

	    yes.appendChild(document.createTextNode("yes"));
	    no.appendChild(document.createTextNode("no"));
	    fix.appendChild(document.createTextNode("fix"));
	    cancel.appendChild(document.createTextNode("cancel"));

	    yes.onclick = mapzen.whosonfirst.yesnofix.onassert;
	    no.onclick = mapzen.whosonfirst.yesnofix.onassert;
	    fix.onclick = mapzen.whosonfirst.yesnofix.onassert;
	    cancel.onclick = mapzen.whosonfirst.yesnofix.oncancel;

	    input.appendChild(yes);
	    input.appendChild(no);
	    input.appendChild(fix);
	    input.appendChild(cancel);

	    return input;
	},

	'onassert' : function(e){

	    var target = e.target;
	    var id = target.getAttribute("data-id");

	    if (! id){
		return false;
	    }

	    var el = document.getElementById(id);

	    if (! el){
		return false;
	    }

	    var path = id;
	    var value = el.textContent;
	    var assertion = target.getAttribute("data-assertion");

	    self.assert(path, value, assertion);

	    alert("Okay, thanks!");

	    self.collapse(id);
	},

	'oncancel': function(e){

	    var target = e.target;
	    var id = target.getAttribute("data-id");

	    if (! id){
		return false;
	    }

	    self.collapse(id);
	},

	// this is a bad name... (20160211/thisisaaronland)

	'collapse': function(id){

	    var input = document.getElementById("assert-" + id);

	    var parent = input.parentElement;
	    parent.removeChild(input);

	    self.current = null;
	},

	// note the lack of validation... we're assuming that kind of sanity
	// checking is happening above?

	'assert': function(path, value, assertion){
	    var dt = new Date();
	    assertions.push({'path': path, 'value': value, 'assertion': assertion, 'date': dt});
	},

	'report': function(){

	    var report = [];
	    var count = assertions.length;

	    for (var i=0; i < count; i++){

		var a = assertions[i];

		var row = [ a['path'], a['value'], a['assertion'], a['date'].toISOString() ];
		row = row.join(",");

		report.push(row);
	    }

	    report = report.join("\n");
	    return report;
	},
    }

    return self;

})();
<|endoftext|>


<commit_before>/**
 * A component handler interface using the revealing module design pattern.
 * More details on this pattern design here:
 * https://github.com/jasonmayes/wsk-component-design-pattern
 * @author Jason Mayes.
 */
 /* exported componentHandler */
var componentHandler = (function() {
  'use strict';

  var registeredComponents_ = [];
  var createdComponents_ = [];

  /**
   * Searches registered components for a class we are interested in using.
   * Optionally replaces a match with passed object if specified.
   * @param {string} name The name of a class we want to use.
   * @param {object} optReplace Optional object to replace match with.
   * @return {object | false}
   * @private
   */
  function findRegisteredClass_(name, optReplace) {
    for (var i = 0; i < registeredComponents_.length; i++) {
      if (registeredComponents_[i].className === name) {
        if (optReplace !== undefined) {
          registeredComponents_[i] = optReplace;
        }
        return registeredComponents_[i];
      }
    }
    return false;
  }

  /**
   * Searches existing DOM for elements of our component type and upgrades them
   * if they have not already been upgraded.
   * @param {string} jsClass the programatic name of the element class we need
   * to create a new instance of.
   * @param {string} cssClass the name of the CSS class elements of this type
   * will have.
   */
  function upgradeDomInternal(jsClass, cssClass) {
    if (jsClass === undefined && cssClass === undefined) {
      for (var i = 0; i < registeredComponents_.length; i++) {
        upgradeDomInternal(registeredComponents_[i].className,
            registeredComponents_[i].cssClass);
      }
    } else {
      if (cssClass === undefined) {
        var registeredClass = findRegisteredClass_(jsClass);
        if (registeredClass) {
          cssClass = registeredClass.cssClass;
        }
      }

      var elements = document.querySelectorAll('.' + cssClass);
      for (var n = 0; n < elements.length; n++) {
        upgradeElementInternal(elements[n], jsClass);
      }
    }
  }

  /**
   * Upgrades a specific element rather than all in the DOM.
   * @param {HTMLElement} element The element we wish to upgrade.
   * @param {string} jsClass The name of the class we want to upgrade
   * the element to.
   */
  function upgradeElementInternal(element, jsClass) {
    // Only upgrade elements that have not already been upgraded.
    var dataUpgraded = element.getAttribute('data-upgraded');

    if (dataUpgraded === null || dataUpgraded.indexOf(jsClass) === -1) {
      // Upgrade element.
      if (dataUpgraded === null) {
        dataUpgraded = '';
      }
      element.setAttribute('data-upgraded', dataUpgraded + ',' + jsClass);
      var registeredClass = findRegisteredClass_(jsClass);
      if (registeredClass) {
        // new
        var instance = new registeredClass.classConstructor(element);
        createdComponents_.push(instance);
        // Call any callbacks the user has registered with this component type.
        registeredClass.callbacks.forEach(function (callback) {
          callback(element);
        });

        // Assign per element instance for control over API
        element.widget = instance;
      } else {
        // If component creator forgot to register, try and see if
        // it is in global scope.
        createdComponents_.push(new window[jsClass](element));
      }
    }
  }

  /**
   * Registers a class for future use and attempts to upgrade existing DOM.
   * @param {object} config An object containing:
   * {constructor: Constructor, classAsString: string, cssClass: string}
   */
  function registerInternal(config) {
    var newConfig = {
      'classConstructor': config.constructor,
      'className': config.classAsString,
      'cssClass': config.cssClass,
      'callbacks': []
    };

    var found = findRegisteredClass_(config.classAsString, newConfig);

    if (!found) {
      registeredComponents_.push(newConfig);
    }
  }

  /**
   * Allows user to be alerted to any upgrades that are performed for a given
   * component type
   * @param {string} jsClass The class name of the WSK component we wish
   * to hook into for any upgrades performed.
   * @param {function} callback The function to call upon an upgrade. This
   * function should expect 1 parameter - the HTMLElement which got upgraded.
   */
  function registerUpgradedCallbackInternal(jsClass, callback) {
    var regClass = findRegisteredClass_(jsClass);
    if (regClass) {
      regClass.callbacks.push(callback);
    }
  }

  /**
   * Upgrades all registered components found in the current DOM. This is
   * automatically called on window load.
   */
  function upgradeAllRegisteredInternal() {
    for (var n = 0; n < registeredComponents_.length; n++) {
      upgradeDomInternal(registeredComponents_[n].className);
    }
  }

  // Now return the functions that should be made public with their publicly
  // facing names...
  return {
    upgradeDom: upgradeDomInternal,
    upgradeElement: upgradeElementInternal,
    upgradeAllRegistered: upgradeAllRegisteredInternal,
    registerUpgradedCallback: registerUpgradedCallbackInternal,
    register: registerInternal
  };
})();

window.addEventListener('load', function() {
  'use strict';

  /**
   * Performs a "Cutting the mustard" test. If the browser supports the features
   * tested, adds a wsk-js class to the <html> element. It then upgrades all WSK
   * components requiring JavaScript.
   */
  if ('classList' in document.createElement('div') && 'querySelector' in document &&
      'addEventListener' in window && Array.prototype.forEach) {
    document.documentElement.classList.add('wsk-js');
    componentHandler.upgradeAllRegistered();
  } else {
    componentHandler.upgradeElement = componentHandler.register = function () { };
  }
});
<commit_msg>Emit event on upgrade<commit_after>/**
 * A component handler interface using the revealing module design pattern.
 * More details on this pattern design here:
 * https://github.com/jasonmayes/wsk-component-design-pattern
 * @author Jason Mayes.
 */
 /* exported componentHandler */
var componentHandler = (function() {
  'use strict';

  var registeredComponents_ = [];
  var createdComponents_ = [];

  /**
   * Searches registered components for a class we are interested in using.
   * Optionally replaces a match with passed object if specified.
   * @param {string} name The name of a class we want to use.
   * @param {object} optReplace Optional object to replace match with.
   * @return {object | false}
   * @private
   */
  function findRegisteredClass_(name, optReplace) {
    for (var i = 0; i < registeredComponents_.length; i++) {
      if (registeredComponents_[i].className === name) {
        if (optReplace !== undefined) {
          registeredComponents_[i] = optReplace;
        }
        return registeredComponents_[i];
      }
    }
    return false;
  }

  /**
   * Searches existing DOM for elements of our component type and upgrades them
   * if they have not already been upgraded.
   * @param {string} jsClass the programatic name of the element class we need
   * to create a new instance of.
   * @param {string} cssClass the name of the CSS class elements of this type
   * will have.
   */
  function upgradeDomInternal(jsClass, cssClass) {
    if (jsClass === undefined && cssClass === undefined) {
      for (var i = 0; i < registeredComponents_.length; i++) {
        upgradeDomInternal(registeredComponents_[i].className,
            registeredComponents_[i].cssClass);
      }
    } else {
      if (cssClass === undefined) {
        var registeredClass = findRegisteredClass_(jsClass);
        if (registeredClass) {
          cssClass = registeredClass.cssClass;
        }
      }

      var elements = document.querySelectorAll('.' + cssClass);
      for (var n = 0; n < elements.length; n++) {
        upgradeElementInternal(elements[n], jsClass);
      }
    }
  }

  /**
   * Upgrades a specific element rather than all in the DOM.
   * @param {HTMLElement} element The element we wish to upgrade.
   * @param {string} jsClass The name of the class we want to upgrade
   * the element to.
   */
  function upgradeElementInternal(element, jsClass) {
    // Only upgrade elements that have not already been upgraded.
    var dataUpgraded = element.getAttribute('data-upgraded');

    if (dataUpgraded === null || dataUpgraded.indexOf(jsClass) === -1) {
      // Upgrade element.
      if (dataUpgraded === null) {
        dataUpgraded = '';
      }
      element.setAttribute('data-upgraded', dataUpgraded + ',' + jsClass);
      var registeredClass = findRegisteredClass_(jsClass);
      if (registeredClass) {
        // new
        var instance = new registeredClass.classConstructor(element);
        createdComponents_.push(instance);
        // Call any callbacks the user has registered with this component type.
        registeredClass.callbacks.forEach(function (callback) {
          callback(element);
        });

        // Assign per element instance for control over API
        element.widget = instance;
      } else {
        // If component creator forgot to register, try and see if
        // it is in global scope.
        createdComponents_.push(new window[jsClass](element));
      }

      var ev = document.createEvent('Events');
      ev.initEvent('componentupgraded', true, true);
      element.dispatchEvent(ev);
    }
  }

  /**
   * Registers a class for future use and attempts to upgrade existing DOM.
   * @param {object} config An object containing:
   * {constructor: Constructor, classAsString: string, cssClass: string}
   */
  function registerInternal(config) {
    var newConfig = {
      'classConstructor': config.constructor,
      'className': config.classAsString,
      'cssClass': config.cssClass,
      'callbacks': []
    };

    var found = findRegisteredClass_(config.classAsString, newConfig);

    if (!found) {
      registeredComponents_.push(newConfig);
    }
  }

  /**
   * Allows user to be alerted to any upgrades that are performed for a given
   * component type
   * @param {string} jsClass The class name of the WSK component we wish
   * to hook into for any upgrades performed.
   * @param {function} callback The function to call upon an upgrade. This
   * function should expect 1 parameter - the HTMLElement which got upgraded.
   */
  function registerUpgradedCallbackInternal(jsClass, callback) {
    var regClass = findRegisteredClass_(jsClass);
    if (regClass) {
      regClass.callbacks.push(callback);
    }
  }

  /**
   * Upgrades all registered components found in the current DOM. This is
   * automatically called on window load.
   */
  function upgradeAllRegisteredInternal() {
    for (var n = 0; n < registeredComponents_.length; n++) {
      upgradeDomInternal(registeredComponents_[n].className);
    }
  }

  // Now return the functions that should be made public with their publicly
  // facing names...
  return {
    upgradeDom: upgradeDomInternal,
    upgradeElement: upgradeElementInternal,
    upgradeAllRegistered: upgradeAllRegisteredInternal,
    registerUpgradedCallback: registerUpgradedCallbackInternal,
    register: registerInternal
  };
})();

window.addEventListener('load', function() {
  'use strict';

  /**
   * Performs a "Cutting the mustard" test. If the browser supports the features
   * tested, adds a wsk-js class to the <html> element. It then upgrades all WSK
   * components requiring JavaScript.
   */
  if ('classList' in document.createElement('div') && 'querySelector' in document &&
      'addEventListener' in window && Array.prototype.forEach) {
    document.documentElement.classList.add('wsk-js');
    componentHandler.upgradeAllRegistered();
  } else {
    componentHandler.upgradeElement = componentHandler.register = function () { };
  }
});
<|endoftext|>