<commit_before>#!/usr/bin/env node

var Suites = require('./suite');
var suites = new Suites();

var regexIdx = process.argv.indexOf('--regex') + 1;
if (regexIdx > 0) {
  if (regexIdx === process.argv.length) {
    console.error('Error: the "--regex" option requires a value');
    process.exit(1);
  }
  suites.filter(process.argv[regexIdx]);
}

suites.add('Select all', 'jquery.html', {
  test: function($) { $('*').length; }
});
suites.add('Select some', 'jquery.html', {
  test: function($) { $('li').length; }
});

/*
 * Manipulation Tests
 */
suites.add('manipulation - append', 'jquery.html', {
  setup: function($) {
    return $('body');
  },
  test: function($, $body) {
    $body.append(new Array(50).join('
'));
  }
});
suites.add('manipulation - prepend', 'jquery.html', {
  setup: function($) {
    return $('body');
  },
  test: function($, $body) {
    $body.prepend(new Array(50).join('
'));
  }
});
suites.add('manipulation - after', 'jquery.html', {
  setup: function($) {
    return $('body');
  },
  test: function($, $body) {
    $body.after(new Array(50).join('
'));
  }
});
suites.add('manipulation - before', 'jquery.html', {
  setup: function($) {
    return $('body');
  },
  test: function($, $body) {
    $body.before(new Array(50).join('
'));
  }
});

suites.add('manipulation - remove', 'jquery.html', {
  setup: function($) {
    return $('body');
  },
  test: function($, $lis) {
    var child = $('
');
    $lis.append(child);
    child.remove();
  }
});

suites.add('manipulation - replaceWith', 'jquery.html', {
  setup: function($) {
    $('body').append('
');
  },
  test: function($, $lis) {
    $('#foo').replaceWith('
');
  }
});

suites.add('manipulation - empty', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.empty();
  }
});
suites.add('manipulation - html', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.html();
    $lis.html('foo');
  }
});
suites.add('manipulation - text', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.text();
    $lis.text('foo');
  }
});

/*
 * Traversing Tests
 */
suites.add('traversing - Find', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.find('li').length;
  }
});
suites.add('traversing - Parent', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.parent('div').length;
  }
});
suites.add('traversing - Parents', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.parents('div').length;
  }
});
suites.add('traversing - Closest', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.closest('div').length;
  }
});
suites.add('traversing - next', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.next().length;
  }
});
suites.add('traversing - nextAll', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.nextAll('li').length;
  }
});
suites.add('traversing - nextUntil', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.nextUntil('li').length;
  }
});
suites.add('traversing - prev', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.prev().length;
  }
});
suites.add('traversing - prevAll', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.prevAll('li').length;
  }
});
suites.add('traversing - prevUntil', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.prevUntil('li').length;
  }
});
suites.add('traversing - siblings', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.siblings('li').length;
  }
});
suites.add('traversing - Children', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.children('a').length;
  }
});
suites.add('traversing - Filter', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.filter('li').length;
  }
});
suites.add('traversing - First', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.first().first().length;
  }
});
suites.add('traversing - Last', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.last().last().length;
  }
});
suites.add('traversing - Eq', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.eq(0).eq(0).length;
  }
});

/*
 * Attributes Tests
 */
suites.add('attributes - Attributes', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.attr('foo', 'bar');
    $lis.attr('foo');
    $lis.removeAttr('foo');
  }
});
suites.add('attributes - Data', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.data('foo', 'bar');
    $lis.data('foo');
  }
});
suites.add('attributes - Val', 'jquery.html', {
  setup: function($) {
    return $('select,input,textarea,option');
  },
  test: function($, $lis) {
    $lis.each(function() {
      $(this).val();
      $(this).val('foo');
    });
  }
});

suites.add('attributes - Has class', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.hasClass('foo');
  }
});
suites.add('attributes - Toggle class', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.toggleClass('foo');
  }
});
suites.add('attributes - Add Remove class', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.addClass('foo');
    $lis.removeClass('foo');
  }
});
<commit_msg>Add single element benchmark case<commit_after>#!/usr/bin/env node

var Suites = require('./suite');
var suites = new Suites();

var regexIdx = process.argv.indexOf('--regex') + 1;
if (regexIdx > 0) {
  if (regexIdx === process.argv.length) {
    console.error('Error: the "--regex" option requires a value');
    process.exit(1);
  }
  suites.filter(process.argv[regexIdx]);
}

suites.add('Select all', 'jquery.html', {
  test: function($) { $('*').length; }
});
suites.add('Select some', 'jquery.html', {
  test: function($) { $('li').length; }
});

/*
 * Manipulation Tests
 */
suites.add('manipulation - append', 'jquery.html', {
  setup: function($) {
    return $('body');
  },
  test: function($, $body) {
    $body.append(new Array(50).join('
'));
  }
});
suites.add('manipulation - prepend', 'jquery.html', {
  setup: function($) {
    return $('body');
  },
  test: function($, $body) {
    $body.prepend(new Array(50).join('
'));
  }
});
suites.add('manipulation - after', 'jquery.html', {
  setup: function($) {
    return $('body');
  },
  test: function($, $body) {
    $body.after(new Array(50).join('
'));
  }
});
suites.add('manipulation - before', 'jquery.html', {
  setup: function($) {
    return $('body');
  },
  test: function($, $body) {
    $body.before(new Array(50).join('
'));
  }
});

suites.add('manipulation - remove', 'jquery.html', {
  setup: function($) {
    return $('body');
  },
  test: function($, $lis) {
    var child = $('
');
    $lis.append(child);
    child.remove();
  }
});

suites.add('manipulation - replaceWith', 'jquery.html', {
  setup: function($) {
    $('body').append('
');
  },
  test: function($, $lis) {
    $('#foo').replaceWith('
');
  }
});

suites.add('manipulation - empty', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.empty();
  }
});
suites.add('manipulation - html', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.html();
    $lis.html('foo');
  }
});
suites.add('manipulation - text', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.text();
    $lis.text('foo');
  }
});

/*
 * Traversing Tests
 */
suites.add('traversing - Find', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.find('li').length;
  }
});
suites.add('traversing - Parent', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.parent('div').length;
  }
});
suites.add('traversing - Parents', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.parents('div').length;
  }
});
suites.add('traversing - Closest', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.closest('div').length;
  }
});
suites.add('traversing - next', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.next().length;
  }
});
suites.add('traversing - nextAll', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.nextAll('li').length;
  }
});
suites.add('traversing - nextUntil', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.nextUntil('li').length;
  }
});
suites.add('traversing - prev', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.prev().length;
  }
});
suites.add('traversing - prevAll', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.prevAll('li').length;
  }
});
suites.add('traversing - prevUntil', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.prevUntil('li').length;
  }
});
suites.add('traversing - siblings', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.siblings('li').length;
  }
});
suites.add('traversing - Children', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.children('a').length;
  }
});
suites.add('traversing - Filter', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.filter('li').length;
  }
});
suites.add('traversing - First', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.first().first().length;
  }
});
suites.add('traversing - Last', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.last().last().length;
  }
});
suites.add('traversing - Eq', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.eq(0).eq(0).length;
  }
});

/*
 * Attributes Tests
 */
suites.add('attributes - Attributes', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.attr('foo', 'bar');
    $lis.attr('foo');
    $lis.removeAttr('foo');
  }
});
suites.add('attributes - Single Attribute', 'jquery.html', {
  setup: function($) {
    return $('body');
  },
  test: function($, $lis) {
    $lis.attr('foo', 'bar');
    $lis.attr('foo');
    $lis.removeAttr('foo');
  }
});
suites.add('attributes - Data', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.data('foo', 'bar');
    $lis.data('foo');
  }
});
suites.add('attributes - Val', 'jquery.html', {
  setup: function($) {
    return $('select,input,textarea,option');
  },
  test: function($, $lis) {
    $lis.each(function() {
      $(this).val();
      $(this).val('foo');
    });
  }
});

suites.add('attributes - Has class', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.hasClass('foo');
  }
});
suites.add('attributes - Toggle class', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.toggleClass('foo');
  }
});
suites.add('attributes - Add Remove class', 'jquery.html', {
  setup: function($) {
    return $('li');
  },
  test: function($, $lis) {
    $lis.addClass('foo');
    $lis.removeClass('foo');
  }
});
<|endoftext|>


<commit_before>var benchtap = require('benchtap'),
	gen = require('../lib/test').generate,
	Frame = require('../lib/frame');

var STRINGS = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o"];
/*
N - number of rows
K - number of distinct values in id columns
M - number of id columns
*/
function createSetup(N, K, M, useStrings){
	return function(event){
		// generate data
		var columns = {
			"value" : gen.Array.int(N, 100)
		};
		var names = [];
		for (var m = 0; m < M; m++){
			var name = "id_"+m;
			columns[name] = gen.Array.int(N, K);

			// map to strings
			if(useStrings){
				columns[name] = columns[name].map(i => STRINGS[i]);
			}

			names[m] = name;
		}

		// create frame
		this.frame = new Frame(columns);
		this.frame.where("id_0", [0, 1]);
		//this.frame.where(row => row["id_1"] == 1);
		//this.frame.where("id_1", id => id == 1);
	};
}

var N = 100000,
	K = 3,
	M = 2;

var name = "where.sum: " + N + "x" + K + "x" + M;

benchtap(name, {"operations": N}, createSetup(N, K, M), function(){
	//var result = this.frame.where(row => row["id_0"] == 1);
	var result = this.frame.sum("value");
});

/*
name += " (strings)";

benchtap(name, {"operations": N}, createSetup(N, K, true), function(){
	var result = this.group.reduce("reduce-col");
});
*/

var N = 1000000;

name = "where.sum: " + N + "x" + K + "x" + M;

benchtap(name, {"operations": N}, createSetup(N, K, M), function(){
	//var result = this.frame.where(row => row["id_0"] == 1);
	var result = this.frame.sum("value");
});

/*
name += " (strings)";

benchtap(name, {"operations": N}, createSetup(N, K, true), function(){
	var result = this.group.reduce("reduce-col");
});
*/

N = 1000000;
K = 200;
M = 2;

var name = "where.sum: " + N + "x" + K + "x" + M;

benchtap(name, {"operations": N}, createSetup(N, K, M), function(){
	var result = this.frame.sum("value")
});
<commit_msg>simpler where benchmark<commit_after>var benchtap = require('benchtap'),
	gen = require('../lib/test').generate,
	Frame = require('../lib/frame');

var STRINGS = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o"];
/*
N - number of rows
K - number of distinct values in id columns
M - number of id columns
*/
function createSetup(N, K, M, useStrings){
	return function(event){
		// generate data
		var columns = {
			"value" : gen.Array.int(N, 100)
		};
		var names = [];
		for (var m = 0; m < M; m++){
			var name = "id_"+m;
			columns[name] = gen.Array.int(N, K);

			// map to strings
			if(useStrings){
				columns[name] = columns[name].map(i => STRINGS[i]);
			}

			names[m] = name;
		}

		// create frame
		this.frame = new Frame(columns);
		this.frame.where("id_0", 0);
		//this.frame.where(row => row["id_1"] == 1);
		//this.frame.where("id_1", id => id == 1);
	};
}

var N = 100000,
	K = 3,
	M = 2;

var name = "where.sum: " + N + "x" + K + "x" + M;

benchtap(name, {"operations": N}, createSetup(N, K, M), function(){
	//var result = this.frame.where(row => row["id_0"] == 1);
	var result = this.frame.sum("value");
});

/*
name += " (strings)";

benchtap(name, {"operations": N}, createSetup(N, K, true), function(){
	var result = this.group.reduce("reduce-col");
});
*/

var N = 1000000;

name = "where.sum: " + N + "x" + K + "x" + M;

benchtap(name, {"operations": N}, createSetup(N, K, M), function(){
	//var result = this.frame.where(row => row["id_0"] == 1);
	var result = this.frame.sum("value");
});

/*
name += " (strings)";

benchtap(name, {"operations": N}, createSetup(N, K, true), function(){
	var result = this.group.reduce("reduce-col");
});
*/

N = 1000000;
K = 200;
M = 2;

var name = "where.sum: " + N + "x" + K + "x" + M;

benchtap(name, {"operations": N}, createSetup(N, K, M), function(){
	var result = this.frame.sum("value")
});
<|endoftext|>


<commit_before>const { objectValues } = require("./polyfill.js");

const ENTRY_URL_TYPE_ANY = "any";
const ENTRY_URL_TYPE_GENERAL = "general";
const ENTRY_URL_TYPE_ICON = "icon";
const ENTRY_URL_TYPE_LOGIN = "login";

const URL_PROP = /(^|[a-zA-Z0-9_-]|\b)(ur[li]|UR[LI]|Ur[li])(\b|$|[_-])/;
const URL_PROP_ICON = /icon[\s_-]*ur[li]/i;

/**
 * Entry facade data field
 * @typedef {Object} EntryFacadeField
 * @property {String} title - The user-friendly title of the field
 * @property {String} field - The type of data to map back to on the Entry instance (property/attribute)
 * @property {String} property - The property name within the field type of the Entry instance
 * @property {String} value - The value of the property (read/write)
 * @property {Boolean} secret - Wether or not the value should be hidden while viewing (masked)
 * @property {Boolean} multiline - Whether the value should be edited as a multiline value or not
 * @property {Object|Boolean} formatting - Vendor formatting options object, or false if no formatting necessary
 * @property {Number} maxLength - Maximum recommended length of the value (defaults to -1)
 */

/**
 * Create a descriptor for a field to be used within a facade
 * @param {Entry} entry The entry instance to process
 * @param {String} title The field title
 * @param {String} entryPropertyType The type of entry property (property/attribute)
 * @param {String} entryPropertyName The name of the property
 * @param {Object} options The options for the field
 * @returns {EntryFacadeField} The field descriptor
 */
function createFieldDescriptor(
    entry,
    title,
    entryPropertyType,
    entryPropertyName,
    { multiline = false, secret = false, formatting = false, removeable = false } = {}
) {
    const value = getEntryValue(entry, entryPropertyType, entryPropertyName);
    return {
        title,
        field: entryPropertyType,
        property: entryPropertyName,
        value,
        secret,
        multiline,
        formatting,
        removeable
    };
}

/**
 * Get URLs from an entry's propertyies
 * Allows for preferential sorting
 * @param {Object} properties The entry properties
 * @param {*} preference
 */
function getEntryURLs(properties, preference = ENTRY_URL_TYPE_ANY) {
    const urlRef = Object.keys(properties)
        .filter(key => URL_PROP.test(key))
        .reduce(
            (output, nextKey) =>
                Object.assign(output, {
                    [nextKey]: properties[nextKey]
                }),
            {}
        );
    if (preference === ENTRY_URL_TYPE_GENERAL || preference === ENTRY_URL_TYPE_LOGIN) {
        return Object.keys(urlRef)
            .sort((a, b) => {
                if (preference === ENTRY_URL_TYPE_GENERAL) {
                    const general = /^ur[li]$/i;
                    const aVal = general.test(a) ? 1 : 0;
                    const bVal = general.test(b) ? 1 : 0;
                    return bVal - aVal;
                } else if (preference === ENTRY_URL_TYPE_LOGIN) {
                    const login = /login/i;
                    const aVal = login.test(a) ? 1 : 0;
                    const bVal = login.test(b) ? 1 : 0;
                    return bVal - aVal;
                }
                return 0;
            })
            .map(key => urlRef[key]);
    } else if (preference === ENTRY_URL_TYPE_ICON) {
        const iconProp = Object.keys(urlRef).find(key => URL_PROP_ICON.test(key));
        return iconProp ? [urlRef[iconProp]] : [];
    }
    // Default is "any" URLs
    return objectValues(urlRef);
}

function getEntryFacadeURLs(facade, preference) {
    const props = facade.fields.filter(item => item.field === "property").reduce(
        (output, field) =>
            Object.assign(output, {
                [field.property]: field.value
            }),
        {}
    );
    return getEntryURLs(props, preference);
}

/**
 * Get a value on an entry for a specific property type
 * @param {Entry} entry The entry instance
 * @param {String} property The type of entry property (property/meta/attribute)
 * @param {String} name The property name
 * @returns {String} The property value
 * @throws {Error} Throws for unknown property types
 * @deprecated Not in use - To be removed
 */
function getEntryValue(entry, property, name) {
    switch (property) {
        case "property":
            return entry.getProperty(name);
        case "meta":
            return entry.getMeta(name);
        case "attribute":
            return entry.getAttribute(name);
        default:
            throw new Error(`Cannot retrieve value: Unknown property type: ${property}`);
    }
}

/**
 * Check if a property name is valid
 * @param {String} name The name to check
 * @returns {Boolean} True if the name is valid
 */
function isValidProperty(name) {
    for (var keyName in EntryProperty) {
        if (EntryProperty.hasOwnProperty(keyName)) {
            if (EntryProperty[keyName] === name) {
                return true;
            }
        }
    }
    return false;
}

module.exports = {
    ENTRY_URL_TYPE_ANY,
    ENTRY_URL_TYPE_GENERAL,
    ENTRY_URL_TYPE_ICON,
    ENTRY_URL_TYPE_LOGIN,
    createFieldDescriptor,
    getEntryURLs,
    getEntryFacadeURLs,
    getEntryValue,
    isValidProperty
};
<commit_msg>Fix typo<commit_after>const { objectValues } = require("./polyfill.js");

const ENTRY_URL_TYPE_ANY = "any";
const ENTRY_URL_TYPE_GENERAL = "general";
const ENTRY_URL_TYPE_ICON = "icon";
const ENTRY_URL_TYPE_LOGIN = "login";

const URL_PROP = /(^|[a-zA-Z0-9_-]|\b)(ur[li]|UR[LI]|Ur[li])(\b|$|[_-])/;
const URL_PROP_ICON = /icon[\s_-]*ur[li]/i;

/**
 * Entry facade data field
 * @typedef {Object} EntryFacadeField
 * @property {String} title - The user-friendly title of the field
 * @property {String} field - The type of data to map back to on the Entry instance (property/attribute)
 * @property {String} property - The property name within the field type of the Entry instance
 * @property {String} value - The value of the property (read/write)
 * @property {Boolean} secret - Wether or not the value should be hidden while viewing (masked)
 * @property {Boolean} multiline - Whether the value should be edited as a multiline value or not
 * @property {Object|Boolean} formatting - Vendor formatting options object, or false if no formatting necessary
 * @property {Number} maxLength - Maximum recommended length of the value (defaults to -1)
 */

/**
 * Create a descriptor for a field to be used within a facade
 * @param {Entry} entry The entry instance to process
 * @param {String} title The field title
 * @param {String} entryPropertyType The type of entry property (property/attribute)
 * @param {String} entryPropertyName The name of the property
 * @param {Object} options The options for the field
 * @returns {EntryFacadeField} The field descriptor
 */
function createFieldDescriptor(
    entry,
    title,
    entryPropertyType,
    entryPropertyName,
    { multiline = false, secret = false, formatting = false, removeable = false } = {}
) {
    const value = getEntryValue(entry, entryPropertyType, entryPropertyName);
    return {
        title,
        field: entryPropertyType,
        property: entryPropertyName,
        value,
        secret,
        multiline,
        formatting,
        removeable
    };
}

/**
 * Get URLs from an entry's properties
 * Allows for preferential sorting
 * @param {Object} properties The entry properties
 * @param {*} preference
 */
function getEntryURLs(properties, preference = ENTRY_URL_TYPE_ANY) {
    const urlRef = Object.keys(properties)
        .filter(key => URL_PROP.test(key))
        .reduce(
            (output, nextKey) =>
                Object.assign(output, {
                    [nextKey]: properties[nextKey]
                }),
            {}
        );
    if (preference === ENTRY_URL_TYPE_GENERAL || preference === ENTRY_URL_TYPE_LOGIN) {
        return Object.keys(urlRef)
            .sort((a, b) => {
                if (preference === ENTRY_URL_TYPE_GENERAL) {
                    const general = /^ur[li]$/i;
                    const aVal = general.test(a) ? 1 : 0;
                    const bVal = general.test(b) ? 1 : 0;
                    return bVal - aVal;
                } else if (preference === ENTRY_URL_TYPE_LOGIN) {
                    const login = /login/i;
                    const aVal = login.test(a) ? 1 : 0;
                    const bVal = login.test(b) ? 1 : 0;
                    return bVal - aVal;
                }
                return 0;
            })
            .map(key => urlRef[key]);
    } else if (preference === ENTRY_URL_TYPE_ICON) {
        const iconProp = Object.keys(urlRef).find(key => URL_PROP_ICON.test(key));
        return iconProp ? [urlRef[iconProp]] : [];
    }
    // Default is "any" URLs
    return objectValues(urlRef);
}

function getEntryFacadeURLs(facade, preference) {
    const props = facade.fields.filter(item => item.field === "property").reduce(
        (output, field) =>
            Object.assign(output, {
                [field.property]: field.value
            }),
        {}
    );
    return getEntryURLs(props, preference);
}

/**
 * Get a value on an entry for a specific property type
 * @param {Entry} entry The entry instance
 * @param {String} property The type of entry property (property/meta/attribute)
 * @param {String} name The property name
 * @returns {String} The property value
 * @throws {Error} Throws for unknown property types
 * @deprecated Not in use - To be removed
 */
function getEntryValue(entry, property, name) {
    switch (property) {
        case "property":
            return entry.getProperty(name);
        case "meta":
            return entry.getMeta(name);
        case "attribute":
            return entry.getAttribute(name);
        default:
            throw new Error(`Cannot retrieve value: Unknown property type: ${property}`);
    }
}

/**
 * Check if a property name is valid
 * @param {String} name The name to check
 * @returns {Boolean} True if the name is valid
 */
function isValidProperty(name) {
    for (var keyName in EntryProperty) {
        if (EntryProperty.hasOwnProperty(keyName)) {
            if (EntryProperty[keyName] === name) {
                return true;
            }
        }
    }
    return false;
}

module.exports = {
    ENTRY_URL_TYPE_ANY,
    ENTRY_URL_TYPE_GENERAL,
    ENTRY_URL_TYPE_ICON,
    ENTRY_URL_TYPE_LOGIN,
    createFieldDescriptor,
    getEntryURLs,
    getEntryFacadeURLs,
    getEntryValue,
    isValidProperty
};
<|endoftext|>


<commit_before>/**
 * @file App initialisation.
 *
 * Only the "root" variable is exposed to window's context.
 */
(function($) {

"use strict";

// Define database's name & version...
window.root = {
  app: null,
  dbName: 'score_db',
  tableName: 'config',
  dbVersion: 1,
  appVersion: '1.7.0 (12 octobre 2018)',
  appData: {}
};

})();
<commit_msg>Update version<commit_after>/**
 * @file App initialisation.
 *
 * Only the "root" variable is exposed to window's context.
 */
(function($) {

"use strict";

// Define database's name & version...
window.root = {
  app: null,
  dbName: 'score_db',
  tableName: 'config',
  dbVersion: 1,
  appVersion: '1.8.0 (12 décembre 2018)',
  appData: {}
};

})();
<|endoftext|>


<commit_before>#!/usr/bin/env node
const config = require('../config/config');
const logger = require('../config/logger');
const messenger = require('../lib/messenger');

const greetingText = config.get('GDG_CEBU_DESCRIPTION');
const getStartedButtonPayload = 'get-started';
const persistentMenuItems = [
    {
        type: 'web_url',
        title: 'Visit Website',
        url: 'https://gdgcebu.org/'
    },
    {
        type: 'postback',
        title: 'Show Upcoming Events',
        payload: 'upcoming-events'
    }
];

logger.info('Setting thread settings: Greeting Text');
messenger.setGreetingText(greetingText);

logger.info('Setting thread settings: Get Started Button');
messenger.setGetStartedButton(getStartedButtonPayload);

logger.info('Setting thread settings: Persistent Menu');
messenger.setPersistentMenu(persistentMenuItems);
<commit_msg>rename GDG_CEBU_DESCRIPTION config to THREAD_GREETING_TEXT<commit_after>#!/usr/bin/env node
const config = require('../config/config');
const logger = require('../config/logger');
const messenger = require('../lib/messenger');

const greetingText = config.get('THREAD_GREETING_TEXT');
const getStartedButtonPayload = 'get-started';
const persistentMenuItems = [
    {
        type: 'web_url',
        title: 'Visit Website',
        url: 'https://gdgcebu.org/'
    },
    {
        type: 'postback',
        title: 'Show Upcoming Events',
        payload: 'upcoming-events'
    }
];

logger.info('Setting thread settings: Greeting Text');
messenger.setGreetingText(greetingText);

logger.info('Setting thread settings: Get Started Button');
messenger.setGetStartedButton(getStartedButtonPayload);

logger.info('Setting thread settings: Persistent Menu');
messenger.setPersistentMenu(persistentMenuItems);
<|endoftext|>


<commit_before>const settings = require('./../../settings.json');
const influx = require('./../../influx');
const knex = require('./../../knex');
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
async function command(params, message) {
    if (settings.owners.includes(message.author.id)) {
        let type = params.shift().toLowerCase();
        if(type === 'influx')
        {
          let res = await influx.query(params.join(' '));
          return await message.channel.send(res,{code:'js'});
        }
        else if(type === 'sql')
        {
          let res = await knex.raw(params.join(' '));
          return await message.channel.send(res,{code:'js'});
        }
        else
          return await message.reply("INVALID TYPE OF QUERY");
    }
    else
        return await message.reply('Not worthy');
}
/**
 * description of the command
 */
const description = "Execute a query (owners only)";
/**
 * Define Exports
 */
module.exports = {
    execute: command,
    description: description
};
<commit_msg>try JSON.stringify knex output<commit_after>const settings = require('./../../settings.json');
const influx = require('./../../influx');
const knex = require('./../../knex');
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
async function command(params, message) {
    if (settings.owners.includes(message.author.id)) {
        let type = params.shift().toLowerCase();
        if(type === 'influx')
        {
          let res = await influx.query(params.join(' '));
          return await message.channel.send(res,{code:'js'});
        }
        else if(type === 'sql')
        {
          let res = await knex.raw(params.join(' '));
          return await message.channel.send(JSON.stringify(res),{code:'js'});
        }
        else
          return await message.reply("INVALID TYPE OF QUERY");
    }
    else
        return await message.reply('Not worthy');
}
/**
 * description of the command
 */
const description = "Execute a query (owners only)";
/**
 * Define Exports
 */
module.exports = {
    execute: command,
    description: description
};
<|endoftext|>


<commit_before>$(document).ready(function () {
    var showid = $('h1.page-title').attr('data-showid');
    loadShowData(showid);
    $('#banner').css('background-image', 'url(' + WEBDIR + 'sickbeard/GetBanner/' + showid + ')');
});

function loadShowData(showid){
  $.ajax({
    url: WEBDIR + 'sickbeard/GetShow?tvdbid=' + showid,
    type: 'get',
    dataType: 'json',
    success: function(data){
      if (data.result != 'success') {
        notify('Error', 'Show not found.', 'error');
        return;
      }
      data = data.data;
      $('.sickbeard_showname').text(data.show_name);
      $('.sickbeard_status').append(sickbeardStatusLabel(data.status));
      $('.sickbeard_network').text(data.network);
      $('.sickbeard_location').text(data.location);
      $('.sickbeard_airs').text(data.airs);
      if (data.next_ep_airdate != '') {
        $('.sickbeard_next_air').text(data.next_ep_airdate);
      }

      var menu = $('.show-options-menu')
      $('.rescan-files', menu).click(function(evt) {
        evt.preventDefault();
        rescanFiles(showid, data.show_name);
      });

      $('.full-update', menu).click(function(evt) {
        evt.preventDefault();
        forceFullUpdate(showid, data.show_name);
      });

      renderSeasonTabs(showid, data.season_list);
    },
    error: function(){
        notify('Error', 'Error while loading show.', 'error');
    }
  });
}

function renderSeasonTabs(showid, seasons){
  list = $('#season-list');
  list.html('');

  $.each(seasons, function(index, seasonNr){
    var label = seasonNr;

    // Specials are marked as season 0
    if (label == 0) {
      label = 'Specials';
    }
    var pill = $('
').append(
      $('')
        .text(label)
        .attr('href', '#'+seasonNr)
        .attr('data-season', seasonNr)
        .attr('data-showid', showid)
    );

    list.append(pill);
  });
  list.find('a').on('click', renderSeason);

  // Trigger latest season
 list.find('li:first-child a').trigger('click');
}

function renderSeason(){
  $('#season-list li').removeClass('active');
  $(this).parent().addClass("active");

  showid = $(this).attr('data-showid');
  season = $(this).attr('data-season');

  $.ajax({
    url: WEBDIR + 'sickbeard/GetSeason?tvdbid=' + showid + '&season=' + season,
    type: 'get',
    dataType: 'json',
    success: function(data){
      var seasonContent = $('#season-content');
      seasonContent.html(''); // Clear table contents before inserting new rows

      // If result is not 'succes' it must be a failure
      if (data.result != 'success') {
        notifyError('Error', 'This is not a valid season for this show');
        return;
      }

      // Loop through data
      $.each(data.data, function(index, value){
        var row = $('
');

        var search_link = $('').addClass('btn btn-mini').attr('title', 'Search new download').append($('').addClass('icon-search')).on('click', function(){
          searchEpisode(showid, season, index, value.name);
        });

        row.append(
          $('').text(index),
          $('').text(value.name),
          $('').text(value.airdate),
          $('').append(sickbeardStatusLabel(value.status)),
          $('').text(value.quality),
          $('').append(search_link)
        );
        seasonContent.append(row);
      }); // end loop

      // Trigger tableSort update
      seasonContent.parent().trigger("update");
      seasonContent.parent().trigger("sorton",[[[0,1]]]);
    },
    error: function(){
        notify('Error', 'Error while loading season.', 'error');
    }
  });
}

function sickbeardStatusLabel(text){
  var statusOK = ['Continuing', 'Downloaded', 'HD'];
  var statusInfo = ['Snatched', 'Unaired'];
  var statusError = ['Ended'];
  var statusWarning = ['Skipped'];

  var label = $('').addClass('label').text(text);

  if (statusOK.indexOf(text) != -1) {
    label.addClass('label-success');
  }
  else if (statusInfo.indexOf(text) != -1) {
    label.addClass('label-info');
  }
  else if (statusError.indexOf(text) != -1) {
    label.addClass('label-important');
  }
  else if (statusWarning.indexOf(text) != -1) {
    label.addClass('label-warning');
  }

  var icon = sickbeardStatusIcon(text, true);
  if (icon != '') {
    label.prepend(' ').prepend(icon);
  }
  return label;
}

function sickbeardStatusIcon(iconText, white){
  var text =[
    'Downloaded',
    'Continuing',
    'Snatched',
    'Unaired',
    'Archived',
    'Skipped'
  ];
  var icons = [
    'icon-download-alt',
    'icon-repeat',
    'icon-share-alt',
    'icon-time',
    'icon-lock',
    'icon-fast-forward'
  ];

  if (text.indexOf(iconText) != -1) {
    var icon = $('').addClass(icons[text.indexOf(iconText)]);
    if (white == true) {
      icon.addClass('icon-white');
    }
    return icon;
  }
  return '';
}

function forceFullUpdate(tvdbid, name) {
  var modalcontent = $('
');
  modalcontent.append($('
').html('Queueing "' + name +' " for full TVDB information update..'));
  modalcontent.append($('
').html('

'));
  showModal('Queueing...', modalcontent, {});

  $.ajax({
    url: WEBDIR + 'sickbeard/ForceFullUpdate?tvdbid=' + tvdbid,
    type: 'get',
    dataType: 'json',
    timeout: 15000,
    success: function (data) {
      // If result is not 'succes' it must be a failure
      if (data.result != 'success') {
        notify('Error', data.message, 'error');
        return;
      } else {
        notify('OK', data.message, 'success');
        return;
      }
    },
    error: function (data) {
      notify('Error', 'Unable to queue tv show for full update.', 'error', 1);
    },
    complete: function (data) {
      hideModal();
    }
  });
}

function rescanFiles(tvdbid, name) {
  var modalcontent = $('
');
  modalcontent.append($('
').html('Queueing "' + name +' " for files rescan..'));
  modalcontent.append($('
').html('

'));
  showModal('Queueing...', modalcontent, {});

  $.ajax({
    url: WEBDIR + 'sickbeard/RescanFiles?tvdbid=' + tvdbid,
    type: 'get',
    dataType: 'json',
    timeout: 15000,
    success: function (data) {
      // If result is not 'succes' it must be a failure
      if (data.result != 'success') {
        notify('Error', data.message, 'error');
        return;
      } else {
        notify('OK', data.message, 'success');
        return;
      }
    },
    error: function (data) {
      notify('Error', 'Unable to queue tv show for files rescan.', 'error', 1);
    },
    complete: function (data) {
      hideModal();
    }
  });
}

function searchEpisode(tvdbid, season, episode, name) {
  var modalcontent = $('
');
  modalcontent.append($('
').html('Looking for episode "'+ name +'".'));
  modalcontent.append($('
').html('

'));
  showModal('Searching episode '+season + 'x'+episode, modalcontent, {});

  $.ajax({
    url: WEBDIR + 'sickbeard/SearchEpisodeDownload?tvdbid=' + tvdbid +'&season=' + season +'&episode='+episode,
    type: 'get',
    dataType: 'json',
    timeout: 40000,
    success: function (data) {
      // If result is not 'succes' it must be a failure
      if (data.result != 'success') {
        notify('Error', data.message, 'error');
        return;
      } else {
        notify('OK', name+ ' ' + season + 'x'+episode+' found. ' + data.message, 'success');
        return;
      }
    },
    error: function (data) {
      notify('Error', 'Episode not found.', 'error', 1);
    },
    complete: function (data) {
      hideModal();
      // Trigger latest season
      $('#season-list li.active a').trigger('click');
    }
  });
}
<commit_msg>Remove unaired highlight<commit_after>$(document).ready(function () {
    var showid = $('h1.page-title').attr('data-showid');
    loadShowData(showid);
    $('#banner').css('background-image', 'url(' + WEBDIR + 'sickbeard/GetBanner/' + showid + ')');
});

function loadShowData(showid){
  $.ajax({
    url: WEBDIR + 'sickbeard/GetShow?tvdbid=' + showid,
    type: 'get',
    dataType: 'json',
    success: function(data){
      if (data.result != 'success') {
        notify('Error', 'Show not found.', 'error');
        return;
      }
      data = data.data;
      $('.sickbeard_showname').text(data.show_name);
      $('.sickbeard_status').append(sickbeardStatusLabel(data.status));
      $('.sickbeard_network').text(data.network);
      $('.sickbeard_location').text(data.location);
      $('.sickbeard_airs').text(data.airs);
      if (data.next_ep_airdate != '') {
        $('.sickbeard_next_air').text(data.next_ep_airdate);
      }

      var menu = $('.show-options-menu')
      $('.rescan-files', menu).click(function(evt) {
        evt.preventDefault();
        rescanFiles(showid, data.show_name);
      });

      $('.full-update', menu).click(function(evt) {
        evt.preventDefault();
        forceFullUpdate(showid, data.show_name);
      });

      renderSeasonTabs(showid, data.season_list);
    },
    error: function(){
        notify('Error', 'Error while loading show.', 'error');
    }
  });
}

function renderSeasonTabs(showid, seasons){
  list = $('#season-list');
  list.html('');

  $.each(seasons, function(index, seasonNr){
    var label = seasonNr;

    // Specials are marked as season 0
    if (label == 0) {
      label = 'Specials';
    }
    var pill = $('
').append(
      $('')
        .text(label)
        .attr('href', '#'+seasonNr)
        .attr('data-season', seasonNr)
        .attr('data-showid', showid)
    );

    list.append(pill);
  });
  list.find('a').on('click', renderSeason);

  // Trigger latest season
 list.find('li:first-child a').trigger('click');
}

function renderSeason(){
  $('#season-list li').removeClass('active');
  $(this).parent().addClass("active");

  showid = $(this).attr('data-showid');
  season = $(this).attr('data-season');

  $.ajax({
    url: WEBDIR + 'sickbeard/GetSeason?tvdbid=' + showid + '&season=' + season,
    type: 'get',
    dataType: 'json',
    success: function(data){
      var seasonContent = $('#season-content');
      seasonContent.html(''); // Clear table contents before inserting new rows

      // If result is not 'succes' it must be a failure
      if (data.result != 'success') {
        notifyError('Error', 'This is not a valid season for this show');
        return;
      }

      // Loop through data
      $.each(data.data, function(index, value){
        var row = $('
');

        var search_link = $('').addClass('btn btn-mini').attr('title', 'Search new download').append($('').addClass('icon-search')).on('click', function(){
          searchEpisode(showid, season, index, value.name);
        });

        row.append(
          $('').text(index),
          $('').text(value.name),
          $('').text(value.airdate),
          $('').append(sickbeardStatusLabel(value.status)),
          $('').text(value.quality),
          $('').append(search_link)
        );
        seasonContent.append(row);
      }); // end loop

      // Trigger tableSort update
      seasonContent.parent().trigger("update");
      seasonContent.parent().trigger("sorton",[[[0,1]]]);
    },
    error: function(){
        notify('Error', 'Error while loading season.', 'error');
    }
  });
}

function sickbeardStatusLabel(text){
  var statusOK = ['Continuing', 'Downloaded', 'HD'];
  var statusInfo = ['Snatched'];
  var statusError = ['Ended'];
  var statusWarning = ['Skipped'];

  var label = $('').addClass('label').text(text);

  if (statusOK.indexOf(text) != -1) {
    label.addClass('label-success');
  }
  else if (statusInfo.indexOf(text) != -1) {
    label.addClass('label-info');
  }
  else if (statusError.indexOf(text) != -1) {
    label.addClass('label-important');
  }
  else if (statusWarning.indexOf(text) != -1) {
    label.addClass('label-warning');
  }

  var icon = sickbeardStatusIcon(text, true);
  if (icon != '') {
    label.prepend(' ').prepend(icon);
  }
  return label;
}

function sickbeardStatusIcon(iconText, white){
  var text =[
    'Downloaded',
    'Continuing',
    'Snatched',
    'Unaired',
    'Archived',
    'Skipped'
  ];
  var icons = [
    'icon-download-alt',
    'icon-repeat',
    'icon-share-alt',
    'icon-time',
    'icon-lock',
    'icon-fast-forward'
  ];

  if (text.indexOf(iconText) != -1) {
    var icon = $('').addClass(icons[text.indexOf(iconText)]);
    if (white == true) {
      icon.addClass('icon-white');
    }
    return icon;
  }
  return '';
}

function forceFullUpdate(tvdbid, name) {
  var modalcontent = $('
');
  modalcontent.append($('
').html('Queueing "' + name +' " for full TVDB information update..'));
  modalcontent.append($('
').html('

'));
  showModal('Queueing...', modalcontent, {});

  $.ajax({
    url: WEBDIR + 'sickbeard/ForceFullUpdate?tvdbid=' + tvdbid,
    type: 'get',
    dataType: 'json',
    timeout: 15000,
    success: function (data) {
      // If result is not 'succes' it must be a failure
      if (data.result != 'success') {
        notify('Error', data.message, 'error');
        return;
      } else {
        notify('OK', data.message, 'success');
        return;
      }
    },
    error: function (data) {
      notify('Error', 'Unable to queue tv show for full update.', 'error', 1);
    },
    complete: function (data) {
      hideModal();
    }
  });
}

function rescanFiles(tvdbid, name) {
  var modalcontent = $('
');
  modalcontent.append($('
').html('Queueing "' + name +' " for files rescan..'));
  modalcontent.append($('
').html('

'));
  showModal('Queueing...', modalcontent, {});

  $.ajax({
    url: WEBDIR + 'sickbeard/RescanFiles?tvdbid=' + tvdbid,
    type: 'get',
    dataType: 'json',
    timeout: 15000,
    success: function (data) {
      // If result is not 'succes' it must be a failure
      if (data.result != 'success') {
        notify('Error', data.message, 'error');
        return;
      } else {
        notify('OK', data.message, 'success');
        return;
      }
    },
    error: function (data) {
      notify('Error', 'Unable to queue tv show for files rescan.', 'error', 1);
    },
    complete: function (data) {
      hideModal();
    }
  });
}

function searchEpisode(tvdbid, season, episode, name) {
  var modalcontent = $('
');
  modalcontent.append($('
').html('Looking for episode "'+ name +'".'));
  modalcontent.append($('
').html('

'));
  showModal('Searching episode '+season + 'x'+episode, modalcontent, {});

  $.ajax({
    url: WEBDIR + 'sickbeard/SearchEpisodeDownload?tvdbid=' + tvdbid +'&season=' + season +'&episode='+episode,
    type: 'get',
    dataType: 'json',
    timeout: 40000,
    success: function (data) {
      // If result is not 'succes' it must be a failure
      if (data.result != 'success') {
        notify('Error', data.message, 'error');
        return;
      } else {
        notify('OK', name+ ' ' + season + 'x'+episode+' found. ' + data.message, 'success');
        return;
      }
    },
    error: function (data) {
      notify('Error', 'Episode not found.', 'error', 1);
    },
    complete: function (data) {
      hideModal();
      // Trigger latest season
      $('#season-list li.active a').trigger('click');
    }
  });
}
<|endoftext|>


<commit_before>/* @flow */
import UrlPrettifier from 'next-url-prettifier/index';
// Types
import type {RouteType, PrettyUrlPatternType} from 'next-url-prettifier/index';

const patternString: string = '/page-pretty-url-:id';
const prettyUrlPatterns: (PrettyUrlPatternType | string)[] = [
  {pattern: patternString},
  {pattern: '/page-pretty-url-one', defaultParams: {id: 1}}
];
const route: RouteType<*> = {
  page: 'pageName',
  prettyUrl: ({id}: {id: number}): string => `/page-pretty-url-${id}`,
  prettyUrlPatterns
};
const router: UrlPrettifier<*> = new UrlPrettifier([route]);

describe('UrlPrettifier options', (): void => {
  it('should use paramsToQueryString if given', (): void => {
    const routerWithCustomQs: UrlPrettifier<*> = new UrlPrettifier([route], {
      paramsToQueryString: ({id}: {id: number}): string => `/id/${id}`
    });
    expect(routerWithCustomQs.linkPage('pageName', {id: 1}))
      .toEqual({href: '/pageName/id/1', as: '/page-pretty-url-1'});
  });
});

describe('UrlPrettifier linkPage', (): void => {
  it('should return href and as for the route if prettyUrl is a function', (): void => {
    expect(router.linkPage('pageName', {id: 1}))
      .toEqual({href: '/pageName?id=1', as: '/page-pretty-url-1'});
  });

  it('should return href and as for the route if prettyUrl is a string', (): void => {
    const routerWithString: UrlPrettifier<*> = new UrlPrettifier([
      {...route, prettyUrl: '/page-pretty-url-1'}
    ]);
    expect(routerWithString.linkPage('pageName', {id: 1}))
      .toEqual({href: '/pageName?id=1', as: '/page-pretty-url-1'});
  });

  it('should return only href if the route does not exist', (): void => {
    expect(router.linkPage('unknownPage', {id: 1}))
      .toEqual({href: '/unknownPage?id=1'});
  });
});

describe('UrlPrettifier getPrettyUrlPatterns', (): void => {
  it('should return an empty list if prettyUrlPattern type is not allowed', (): void => {
    // $FlowIgnore
    expect(router.getPrettyUrlPatterns({...route, prettyUrlPatterns: {patternString}}))
      .toEqual([]);
  });

  it('should return prettyUrl if its type is string and prettyUrlPattern is undefined', (): void => {
    // eslint-disable-next-line no-unused-vars
    const {prettyUrlPatterns, ...routeWithoutPatterns}: RouteType<*> = route;
    expect(router.getPrettyUrlPatterns({...routeWithoutPatterns, prettyUrl: '/page-pretty-url-1'}))
      .toEqual([{pattern: '/page-pretty-url-1'}]);
  });

  it('should return a PrettyUrlPatternType if prettyUrlPattern is a string', (): void => {
    expect(router.getPrettyUrlPatterns({...route, prettyUrlPatterns: patternString}))
      .toEqual([{pattern: patternString}]);
  });

  it('should return a PrettyUrlPatternType if prettyUrlPattern is an array of string', (): void => {
    expect(router.getPrettyUrlPatterns({...route, prettyUrlPatterns: [patternString]}))
      .toEqual([{pattern: patternString}]);
  });

  it('should return a PrettyUrlPatternType if prettyUrlPattern is rightly typed', (): void => {
    expect(router.getPrettyUrlPatterns({...route, prettyUrlPatterns}))
      .toEqual(prettyUrlPatterns);
  });
});

describe('Router forEachPattern', (): void => {
  it('should iterate on each pattern', (): void => {
    const mockFunction = jest.fn();
    router.forEachPattern(mockFunction);
    expect(mockFunction.mock.calls.length).toBe(2);
    expect(mockFunction).toHaveBeenCalledWith(route.page, patternString, undefined);
    expect(mockFunction).toHaveBeenCalledWith(route.page, '/page-pretty-url-one', {id: 1});
  });
});
<commit_msg>Add tests for getPrettyUrl and forEachPrettyPattern<commit_after>/* @flow */
import UrlPrettifier from 'next-url-prettifier/index';
// Types
import type {RouteType, PrettyUrlPatternType} from 'next-url-prettifier/index';

const patternString: string = '/page-pretty-url-:id';
const prettyUrlPatterns: (PrettyUrlPatternType | string)[] = [
  {pattern: patternString},
  {pattern: '/page-pretty-url-one', defaultParams: {id: 1}}
];
const route: RouteType<*> = {
  page: 'pageName',
  prettyUrl: ({id}: {id: number}): string => `/page-pretty-url-${id}`,
  prettyUrlPatterns
};
const router: UrlPrettifier<*> = new UrlPrettifier([route]);

describe('UrlPrettifier options', (): void => {
  it('should use paramsToQueryString if given', (): void => {
    const routerWithCustomQs: UrlPrettifier<*> = new UrlPrettifier([route], {
      paramsToQueryString: ({id}: {id: number}): string => `/id/${id}`
    });
    expect(routerWithCustomQs.getPrettyUrl('pageName', {id: 1}))
      .toEqual({href: '/pageName/id/1', as: '/page-pretty-url-1'});
  });
});

describe('UrlPrettifier getPrettyUrl', (): void => {
  it('should return href and as for the route if prettyUrl is a function', (): void => {
    expect(router.getPrettyUrl('pageName', {id: 1}))
      .toEqual({href: '/pageName?id=1', as: '/page-pretty-url-1'});
  });

  it('should return href and as for the route if prettyUrl is a string', (): void => {
    const routerWithString: UrlPrettifier<*> = new UrlPrettifier([
      {...route, prettyUrl: '/page-pretty-url-1'}
    ]);
    expect(routerWithString.getPrettyUrl('pageName', {id: 1}))
      .toEqual({href: '/pageName?id=1', as: '/page-pretty-url-1'});
  });

  it('should return only href if the route does not exist', (): void => {
    expect(router.getPrettyUrl('unknownPage', {id: 1}))
      .toEqual({href: '/unknownPage?id=1'});
  });
});

describe('UrlPrettifier getPrettyUrlPatterns', (): void => {
  it('should return an empty list if prettyUrlPattern type is not allowed', (): void => {
    // $FlowIgnore
    expect(router.getPrettyUrlPatterns({...route, prettyUrlPatterns: {patternString}}))
      .toEqual([]);
  });

  it('should return prettyUrl if its type is string and prettyUrlPattern is undefined', (): void => {
    // eslint-disable-next-line no-unused-vars
    const {prettyUrlPatterns, ...routeWithoutPatterns}: RouteType<*> = route;
    expect(router.getPrettyUrlPatterns({...routeWithoutPatterns, prettyUrl: '/page-pretty-url-1'}))
      .toEqual([{pattern: '/page-pretty-url-1'}]);
  });

  it('should return a PrettyUrlPatternType if prettyUrlPattern is a string', (): void => {
    expect(router.getPrettyUrlPatterns({...route, prettyUrlPatterns: patternString}))
      .toEqual([{pattern: patternString}]);
  });

  it('should return a PrettyUrlPatternType if prettyUrlPattern is an array of string', (): void => {
    expect(router.getPrettyUrlPatterns({...route, prettyUrlPatterns: [patternString]}))
      .toEqual([{pattern: patternString}]);
  });

  it('should return a PrettyUrlPatternType if prettyUrlPattern is rightly typed', (): void => {
    expect(router.getPrettyUrlPatterns({...route, prettyUrlPatterns}))
      .toEqual(prettyUrlPatterns);
  });
});

describe('Router forEachPrettyPattern', (): void => {
  it('should iterate on each pattern', (): void => {
    const mockFunction = jest.fn();
    router.forEachPrettyPattern(mockFunction);
    expect(mockFunction.mock.calls.length).toBe(2);
    expect(mockFunction).toHaveBeenCalledWith(route.page, patternString, undefined);
    expect(mockFunction).toHaveBeenCalledWith(route.page, '/page-pretty-url-one', {id: 1});
  });
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

app.set('port', (process.argv[2] || 3000));
app.set('view engine', 'jsx');
app.set('views', __dirname + '/views');
app.engine('jsx', require('express-react-views').createEngine());

require('node-jsx').install();

var data = [];

app.use('/', function(req, res) {
  res.render('index', {data: data});
});

app.listen(app.get('port'), function() {});<commit_msg>added object in data<commit_after>var express = require('express');
var app = express();

app.set('port', (process.argv[2] || 3000));
app.set('view engine', 'jsx');
app.set('views', __dirname + '/views');
app.engine('jsx', require('express-react-views').createEngine());

require('node-jsx').install();

var data = ['Shopping','Hair cut'];

app.use('/', function(req, res) {
  res.render('index', {data: data});
});

app.listen(app.get('port'), function() {});<|endoftext|>


<commit_before>(function($) {
  var Wheel = (function() {
    function Wheel(fact, params) {
      this.fact = fact;
      this.opinions = $(fact).find(".opinion");
      this.authority = $(fact).find(".authority").first();
      this.params = $.extend(params, {
        "dim": 24,
        "radius": 18,
        "default_stroke": {
          "opacity": 0.2,
          "stroke": 9
        },
        "hover_stroke": {
          "opacity": 0.5,
          "stroke": 11
        }
      });
    }

    function arc(w, op, p) {
      var opacity = $(op).data("user-opinion") ? 1.0 : w.params.default_stroke.opacity;
      var the_arc = [op.display_value, p.offset, p.r];

      if (!op.raphael) {
        // set new path
        return (op.raphael = w.r.path().attr({
          arc: the_arc,
          stroke: $(op).data("color"),
          "stroke-width": w.params.default_stroke.stroke,
          opacity: opacity
        }));
      } else {
        return op.raphael.animate({
          arc: the_arc,
          opacity: opacity
        }, 200, '<>');
      }
    }

    function authority(w, authority_element) {
      var auth = authority_element.data("authority");
      var pos = w.params.dim + (w.params.dim * 0.25);
      if (!authority_element.raphael) {
        return (authority_element.raphael = w.r.text(pos, pos, auth).attr({
          "font-size": "13px",
          "fill": "#ccc"
        }));
      } else {
        return authority_element.raphael.attr({
          "text": auth
        });
      }
    }

    Wheel.prototype.calc_display = function(opinions) {
      var too_much = 0;
      var large_ones = 0;
      $(opinions).each(function() {
        var percentage = $(this).data("value");
        if (percentage < 15) {
          too_much += 15 - percentage;
        } else if (percentage > 40) {
          large_ones += percentage;
        }
      }).each(function() {
        var percentage = $(this).data("value");
        if (percentage < 15) {
          percentage = 15;
        } else if (percentage > 40) {
          percentage = percentage - percentage / large_ones * too_much;
        }
        this.display_value = percentage;
      });

    };

    Wheel.prototype.update = function() {
      var wheel = this;
      var a = authority(wheel, wheel.authority);
      wheel.calc_display(this.opinions);
      var offset = 0;
      $(this.opinions).each(function() {
        var z = arc(wheel, this, {
          offset: offset,
          val: this.display_value,
          r: wheel.params.radius
        });
        offset = offset + this.display_value;
      });
    };

    Wheel.prototype.bind_events = function() {
      var w = this;
      $(this.opinions).each(function() {
        // bind events
        var $t = $(this);
        this.raphael.mouseover(function() {
          if (!$t.data("user-opinion")) {
            this.animate({
              'stroke-width': w.params.hover_stroke.stroke,
              opacity: w.params.hover_stroke.opacity
            }, 200, '<>');
          } else {
            this.animate({
              'stroke-width': w.params.hover_stroke.stroke
            }, 200, '<>');
          }
        });
        this.raphael.mouseout(function() {
          if (!$t.data("user-opinion")) {
            this.stop().animate({
              'stroke-width': w.params.default_stroke.stroke,
              opacity: w.params.default_stroke.opacity
            }, 200, '<>');
          } else {
            this.animate({
              'stroke-width': w.params.default_stroke.stroke
            }, 200, '<>');
          }
        });
        $(this.raphael.node).bind("click", function() {
          $(w.fact).factlink("switch_opinion", $t);
        });
        $(this.raphael.node).hoverIntent({
          over: function(e) {
            optionBox = $(w.fact).find("." + $t.data("opinion") + "-box");
            $(optionBox).fadeIn("fast");
          },
          out: function() {
            $(w.fact).find("." + $t.data("opinion") + "-box").delay(500).fadeOut("fast");
          }
        });
      });
    };

    Wheel.prototype.init = function(canvas) {
      var w = this;
      w.r = Raphael(canvas, w.params.dim * 2 + 17, w.params.dim * 2 + 17);
      w.r.customAttributes.arc = function(percentage, percentage_offset, radius) {
        percentage = percentage - 2; // add padding after arc
        var large_angle = percentage > 50,
            box_dim = w.params.dim + 6,
            start_angle = percentage_offset * 2 * Math.PI / 100,
            end_angle = (percentage_offset + percentage) * 2 * Math.PI / 100,
            start_x = box_dim + radius * Math.cos(start_angle),
            start_y = box_dim - radius * Math.sin(start_angle),
            end_x = box_dim + radius * Math.cos(end_angle),
            end_y = box_dim - radius * Math.sin(end_angle);
        return {
          path: [
            ['M', start_x, start_y],
            ['A', radius, radius, 0, (large_angle ? 1 : 0), 0, end_x, end_y]
          ]
        };
      };
      this.update();
      this.bind_events();
    };
    return Wheel;
  })();

  var methods = {
    // Initialize factbubble
    init: function(options) {
      return this.each(function() {
        function stop_fade(t) {
          t.stop(true, true).css({
            "opacity": "1"
          });
        }

        function switchTabAction(active) {
          $fact.find(".tab_content[rel=" + active + "] .add-evidence").toggle();
          $fact.find(".tab_content[rel=" + active + "] .evidence").toggle();
          var action = $fact.find(".add-action[rel=" + active + "] > a");
          action.text($(action).text() === 'Add facts' ? 'Show facts' : 'Add facts');
        }

        function addEventHandlersDoAdd($fact) {
          $fact.find("a.do-add").live("click", function() {
            $fact.find('.evidence-list').hide();
            $fact.find('.evidence-search-results').show();
            return false;
          });
        }

        function addEventHandlersReturnFromAdd($fact) {
          $fact.find("a.return-from-add").bind("click", function() {
            $fact.find('.evidence-list').show();
            $fact.find('.evidence-search-results').hide();
            return false;
          });
        }

        function addEventHandlersReturnFromEvidenceAdd($fact) {
          $fact.find("a.close-evidence-add").bind("click", function() {
            $fact.find('.page').hide();
            $fact.find('.evidence-search-results').show();
            return false;
          });

        }

        function addEventHandlersSubmitButton($fact) {

          $fact.find('button.supporting').bind('click', function() {
            submitEvidence($fact, "supporting");
          });

          $fact.find('button.weakening').bind('click', function() {
            submitEvidence($fact, "weakening");
          });
        }

        function addEventHandlersTabs($fact) {
          $fact.find("ul.evidence li").click(function() {

            if ($fact.find(".dropdown-container").is(":hidden")) {
              $fact.find(".dropdown-container").slideDown();

              // AJAX call to load the FactRelations
              if (!$fact.data('loaded-evidence')) {
                getEvidence($fact);
                $fact.data('loaded-evidence', true);
              }

              $(this).addClass("active");

            } else {
              if ($(this).hasClass("active")) {
                $fact.find(".dropdown-container").slideUp(function() {
                  $fact.find("ul.evidence li").removeClass("active");
                });
              } else {
                $fact.find("ul.evidence li").removeClass("active");
                $(this).addClass("active");
              }
            }
            return false;
          });
        }

        function initialize($fact) { /* based on http://www.sohtanaka.com/web-design/simple-tabs-w-css-jquery/ */
          //On Click Event
          addEventHandlersTabs($fact);
          addEventHandlersDoAdd($fact);
          addEventHandlersReturnFromAdd($fact);
          addEventHandlersReturnFromEvidenceAdd($fact);

          addEventHandlersSubmitButton($fact);

          $fact.data('loaded-evidence', false);

          $fact.bind("factlink:switchTabAction", function(e, active) {
            switchTabAction(active);
          });
          // Evidence buttons
          $fact.find(".existing_evidence a").live("ajax:complete", function(et, e) {
            $(this).closest('ul').children().find('a').removeClass("active");
            $(this).addClass('active');
          });
          $fact.data("initialized", true);
        } /*start of method*/
        var $fact = $(this);
        $fact.data("facts", {});
        if (!$fact.data("initialized")) {
          initialize($fact);
        }
        $fact.find("article.fact").each(function() {
          var fact = init_fact(this, $fact);
          $fact.data("facts")[fact.attr("data-fact-id")] = fact;
        });

        // Prevents boxes from dissapearing on mouse over
        $fact.find(".float-box").mouseover(function() {
          stop_fade($(this));
        });
        $fact.find(".float-box").mouseout(function() {
          if (!$(this).find("input#channel_title").is(":focus")) {
            $(this).delay(500).fadeOut("fast");
          }
        });
      });
    },
    // Update
    update: function(data) {
      var $fact = $(this).data("container") || $(this);
      if ($fact.data("initialized")) {
        $(data).each(function() {
          var fact = $fact.data("facts")[this.id];
          if (fact && $(fact).data("initialized")) {
            $(fact).data("update")(this.score_dict_as_percentage); // Update the facts
          }
        });
      }
    },
    switch_opinion: function(opinion) {
      var fact = this,
          opinions = fact.data("wheel").opinions;
      opinions.each(function() {
        var current_op = this;
        if ($(current_op).data("opinion") === opinion.data("opinion")) {
          // The clicked op is the current op in the list
          if (!$(current_op).data("user-opinion")) {
            $.post("/fact_item/" + $(fact).data("fact-id") + "/opinion/" + opinion.data("opinion"), function(data) {
              data_attr(current_op, "user-opinion", true);
              fact.factlink("update", data);
            });
          }
          else {
            $.ajax({
              type: "DELETE",
              url: "/fact_item/" + $(fact).data("fact-id") + "/opinion/",
              success: function(data) {
                data_attr(current_op, "user-opinion", false);
                fact.factlink("update", data);
              }
            });
          }
        }
        else {
          data_attr(current_op, "user-opinion", false);
        }
      });
    },

    // Channels
    to_channel: function(user, channel, fact) {
      $.ajax({
        url: "/" + user + "/channels/toggle/fact",
        dataType: "script",
        type: "POST",
        data: {
          user: user,
          channel_id: channel,
          fact_id: fact
        }
      });
    }

  };

  $.fn.factlink = function(method) {
    // Method calling logic
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    }
    else if (typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments);
    }
    else {
      $.error('Method ' + method + ' does not exist on jQuery.factlink');
    }
  };

  // Private functions

  function data_attr(el, attr, data) {
    $(el).attr("data-" + attr, data);
    $(el).data(attr, data);
  }

  function getEvidence($fact) {
    var id = $fact.attr("data-fact-id");
    var loader = $fact.find('.loading-evidence');
    $.ajax({
      url: '/facts/' + id + '/fact_relations',
      type: "GET",
      dataType: "script",
      success: function(data) {
        loader.hide();
      },
      error: function(data) {}
    });
  }

  function bindEvidencePrepare($c) {
    $c.find('.results ul li.evidence').live('click', function() {
      showEvidenceAdd($c);

      var elem = $(this);
      var evidenceId = elem.data('evidence-id');
      var evidenceDisplayString = elem.html();

      // Set the evidence ID used for posting
      $c.data('evidenceId', evidenceId);

      // Set the displaystring to the evidence bubble
      $c.find('.evidence-add .evidence').html(evidenceDisplayString);
    });
  }

  function submitEvidence($c, type) {
    var factId = $c.attr("data-fact-id");
    var evidenceId = $c.data("evidence-id");
    var url_part;

    if (type === "supporting") {
      url_part = "/add_supporting_evidence/";
    } else if (type === "weakening") {
      url_part = "/add_weakening_evidence/";
    } else {
      alert('There is a problem adding the evidence to this Factlink. We are sorry for the inconvenience, please try again later.');
    }

    // TODO: This should changed to use the FactRelationController
    $.post("/factlink/" + factId + url_part + evidenceId, function(data) {});
  }

  function bindInstantSearch($c) {
    // Bind the instant search
    var is_timeout;
    $c.find('.search-area .evidence_search').keyup(function() {
      var elem = $(this);
      $('.user-search-input').html(elem.val());

      if (elem.val().length >= 2) {
        clearTimeout(is_timeout);
        is_timeout = setTimeout(function() {
          elem.closest('form').submit();
        }, 200); // <-- choose some sensible value here
      }
    });
  }

  function showEvidenceList($c) {
    hidePages($c);
    $c.find('.evidence-list').show();
  }

  function showEvidenceSearchResults($c) {
    hidePages($c);
    $c.find('.evidence-search-results').show();
  }

  function showEvidenceAdd($c) {
    hidePages($c);
    $c.find('.evidence-add').show();
  }

  function hidePages($c) {
    $c.find('.page').hide();
  }

  function init_fact(fact, container) {
    var $fact = $(fact);
    var $c = $(container);
    if (!$fact.data("initialized")) {
      $fact.find('.edit').editable('/factlink/update_title', {
        indicator: 'Saving...',
        tooltip: 'You can edit this title to place the fact in the correct context.'
      });

      $fact.data("container", container);
      $fact.data("wheel", new Wheel(fact));
      $fact.data("wheel").init($fact.find(".wheel").get(0));

      bindEvidencePrepare($c);
      bindInstantSearch($c);

      // Channels are in the container
      $fact.find(".add-to-channel").hoverIntent(function(e) {
        var channelList = $fact.find(".channel-listing");

        $(channelList).fadeIn("fast");

      }, function() {
        $fact.find(".channel-listing").delay(600).fadeOut("fast");
      }).bind('click', function(e) {
        e.preventDefault();
      });

      $fact.find(".opinion-box").find("img").tipsy({
        gravity: 's'
      });
      // Now setting a function in the jquery data to keep track of it, would be prettier with custom events
      $fact.data("update", function(data) {
        // var fact = $fact;
        $fact.data("wheel").opinions.each(function() {
          data_attr(this, "value", data[$(this).data("opinions")].percentage);
        });
        $fact.find(".authority span").text(data.authority);
        $fact.data("wheel").update();
      });

      $fact.data("initialized", true);
    }
    return $fact;
  }
})(jQuery);
<commit_msg>ALL ENTERS MUST DIE!<commit_after>(function($) {
  var Wheel = (function() {
    function Wheel(fact, params) {
      this.fact = fact;
      this.opinions = $(fact).find(".opinion");
      this.authority = $(fact).find(".authority").first();
      this.params = $.extend(params, {
        "dim": 24,
        "radius": 18,
        "default_stroke": {
          "opacity": 0.2,
          "stroke": 9
        },
        "hover_stroke": {
          "opacity": 0.5,
          "stroke": 11
        }
      });
    }

    function arc(w, op, p) {
      var opacity = $(op).data("user-opinion") ? 1.0 : w.params.default_stroke.opacity;
      var the_arc = [op.display_value, p.offset, p.r];

      if (!op.raphael) {
        // set new path
        return (op.raphael = w.r.path().attr({
          arc: the_arc,
          stroke: $(op).data("color"),
          "stroke-width": w.params.default_stroke.stroke,
          opacity: opacity
        }));
      } else {
        return op.raphael.animate({
          arc: the_arc,
          opacity: opacity
        }, 200, '<>');
      }
    }

    function authority(w, authority_element) {
      var auth = authority_element.data("authority");
      var pos = w.params.dim + (w.params.dim * 0.25);
      if (!authority_element.raphael) {
        return (authority_element.raphael = w.r.text(pos, pos, auth).attr({
          "font-size": "13px",
          "fill": "#ccc"
        }));
      } else {
        return authority_element.raphael.attr({
          "text": auth
        });
      }
    }

    Wheel.prototype.calc_display = function(opinions) {
      var too_much = 0;
      var large_ones = 0;
      $(opinions).each(function() {
        var percentage = $(this).data("value");
        if (percentage < 15) {
          too_much += 15 - percentage;
        } else if (percentage > 40) {
          large_ones += percentage;
        }
      }).each(function() {
        var percentage = $(this).data("value");
        if (percentage < 15) {
          percentage = 15;
        } else if (percentage > 40) {
          percentage = percentage - percentage / large_ones * too_much;
        }
        this.display_value = percentage;
      });

    };

    Wheel.prototype.update = function() {
      var wheel = this;
      var a = authority(wheel, wheel.authority);
      wheel.calc_display(this.opinions);
      var offset = 0;
      $(this.opinions).each(function() {
        var z = arc(wheel, this, {
          offset: offset,
          val: this.display_value,
          r: wheel.params.radius
        });
        offset = offset + this.display_value;
      });
    };

    Wheel.prototype.bind_events = function() {
      var w = this;
      $(this.opinions).each(function() {
        // bind events
        var $t = $(this);
        this.raphael.mouseover(function() {
          if (!$t.data("user-opinion")) {
            this.animate({
              'stroke-width': w.params.hover_stroke.stroke,
              opacity: w.params.hover_stroke.opacity
            }, 200, '<>');
          } else {
            this.animate({
              'stroke-width': w.params.hover_stroke.stroke
            }, 200, '<>');
          }
        });
        this.raphael.mouseout(function() {
          if (!$t.data("user-opinion")) {
            this.stop().animate({
              'stroke-width': w.params.default_stroke.stroke,
              opacity: w.params.default_stroke.opacity
            }, 200, '<>');
          } else {
            this.animate({
              'stroke-width': w.params.default_stroke.stroke
            }, 200, '<>');
          }
        });
        $(this.raphael.node).bind("click", function() {
          $(w.fact).factlink("switch_opinion", $t);
        });
        $(this.raphael.node).hoverIntent({
          over: function(e) {
            optionBox = $(w.fact).find("." + $t.data("opinion") + "-box");
            $(optionBox).fadeIn("fast");
          },
          out: function() {
            $(w.fact).find("." + $t.data("opinion") + "-box").delay(500).fadeOut("fast");
          }
        });
      });
    };

    Wheel.prototype.init = function(canvas) {
      var w = this;
      w.r = Raphael(canvas, w.params.dim * 2 + 17, w.params.dim * 2 + 17);
      w.r.customAttributes.arc = function(percentage, percentage_offset, radius) {
        percentage = percentage - 2; // add padding after arc
        var large_angle = percentage > 50,
            box_dim = w.params.dim + 6,
            start_angle = percentage_offset * 2 * Math.PI / 100,
            end_angle = (percentage_offset + percentage) * 2 * Math.PI / 100,
            start_x = box_dim + radius * Math.cos(start_angle),
            start_y = box_dim - radius * Math.sin(start_angle),
            end_x = box_dim + radius * Math.cos(end_angle),
            end_y = box_dim - radius * Math.sin(end_angle);
        return {
          path: [
            ['M', start_x, start_y],
            ['A', radius, radius, 0, (large_angle ? 1 : 0), 0, end_x, end_y]
          ]
        };
      };
      this.update();
      this.bind_events();
    };
    return Wheel;
  })();

  var methods = {
    // Initialize factbubble
    init: function(options) {
      return this.each(function() {
        function stop_fade(t) {
          t.stop(true, true).css({
            "opacity": "1"
          });
        }

        function switchTabAction(active) {
          $fact.find(".tab_content[rel=" + active + "] .add-evidence").toggle();
          $fact.find(".tab_content[rel=" + active + "] .evidence").toggle();
          var action = $fact.find(".add-action[rel=" + active + "] > a");
          action.text($(action).text() === 'Add facts' ? 'Show facts' : 'Add facts');
        }

        function addEventHandlersDoAdd($fact) {
          $fact.find("a.do-add").live("click", function() {
            $fact.find('.evidence-list').hide();
            $fact.find('.evidence-search-results').show();
            return false;
          });
        }

        function addEventHandlersReturnFromAdd($fact) {
          $fact.find("a.return-from-add").bind("click", function() {
            $fact.find('.evidence-list').show();
            $fact.find('.evidence-search-results').hide();
            return false;
          });
        }

        function addEventHandlersReturnFromEvidenceAdd($fact) {
          $fact.find("a.close-evidence-add").bind("click", function() {
            $fact.find('.page').hide();
            $fact.find('.evidence-search-results').show();
            return false;
          });
        }

        function addEventHandlersSubmitButton($fact) {
          $fact.find('button.supporting').bind('click', function() {
            submitEvidence($fact, "supporting");
          });

          $fact.find('button.weakening').bind('click', function() {
            submitEvidence($fact, "weakening");
          });
        }

        function addEventHandlersTabs($fact) {
          $fact.find("ul.evidence li").click(function() {

            if ($fact.find(".dropdown-container").is(":hidden")) {
              $fact.find(".dropdown-container").slideDown();

              // AJAX call to load the FactRelations
              if (!$fact.data('loaded-evidence')) {
                getEvidence($fact);
                $fact.data('loaded-evidence', true);
              }

              $(this).addClass("active");

            } else {
              if ($(this).hasClass("active")) {
                $fact.find(".dropdown-container").slideUp(function() {
                  $fact.find("ul.evidence li").removeClass("active");
                });
              } else {
                $fact.find("ul.evidence li").removeClass("active");
                $(this).addClass("active");
              }
            }
            return false;
          });
        }

        function initialize($fact) { /* based on http://www.sohtanaka.com/web-design/simple-tabs-w-css-jquery/ */
          //On Click Event
          addEventHandlersTabs($fact);
          addEventHandlersDoAdd($fact);
          addEventHandlersReturnFromAdd($fact);
          addEventHandlersReturnFromEvidenceAdd($fact);

          addEventHandlersSubmitButton($fact);

          $fact.data('loaded-evidence', false);

          $fact.bind("factlink:switchTabAction", function(e, active) {
            switchTabAction(active);
          });
          // Evidence buttons
          $fact.find(".existing_evidence a").live("ajax:complete", function(et, e) {
            $(this).closest('ul').children().find('a').removeClass("active");
            $(this).addClass('active');
          });
          $fact.data("initialized", true);
        } /*start of method*/
        var $fact = $(this);
        $fact.data("facts", {});
        if (!$fact.data("initialized")) {
          initialize($fact);
        }
        $fact.find("article.fact").each(function() {
          var fact = init_fact(this, $fact);
          $fact.data("facts")[fact.attr("data-fact-id")] = fact;
        });

        // Prevents boxes from dissapearing on mouse over
        $fact.find(".float-box").mouseover(function() {
          stop_fade($(this));
        });
        $fact.find(".float-box").mouseout(function() {
          if (!$(this).find("input#channel_title").is(":focus")) {
            $(this).delay(500).fadeOut("fast");
          }
        });
      });
    },
    // Update
    update: function(data) {
      var $fact = $(this).data("container") || $(this);
      if ($fact.data("initialized")) {
        $(data).each(function() {
          var fact = $fact.data("facts")[this.id];
          if (fact && $(fact).data("initialized")) {
            $(fact).data("update")(this.score_dict_as_percentage); // Update the facts
          }
        });
      }
    },
    switch_opinion: function(opinion) {
      var fact = this,
          opinions = fact.data("wheel").opinions;
      opinions.each(function() {
        var current_op = this;
        if ($(current_op).data("opinion") === opinion.data("opinion")) {
          // The clicked op is the current op in the list
          if (!$(current_op).data("user-opinion")) {
            $.post("/fact_item/" + $(fact).data("fact-id") + "/opinion/" + opinion.data("opinion"), function(data) {
              data_attr(current_op, "user-opinion", true);
              fact.factlink("update", data);
            });
          }
          else {
            $.ajax({
              type: "DELETE",
              url: "/fact_item/" + $(fact).data("fact-id") + "/opinion/",
              success: function(data) {
                data_attr(current_op, "user-opinion", false);
                fact.factlink("update", data);
              }
            });
          }
        }
        else {
          data_attr(current_op, "user-opinion", false);
        }
      });
    },

    // Channels
    to_channel: function(user, channel, fact) {
      $.ajax({
        url: "/" + user + "/channels/toggle/fact",
        dataType: "script",
        type: "POST",
        data: {
          user: user,
          channel_id: channel,
          fact_id: fact
        }
      });
    }

  };

  $.fn.factlink = function(method) {
    // Method calling logic
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    }
    else if (typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments);
    }
    else {
      $.error('Method ' + method + ' does not exist on jQuery.factlink');
    }
  };

  // Private functions

  function data_attr(el, attr, data) {
    $(el).attr("data-" + attr, data);
    $(el).data(attr, data);
  }

  function getEvidence($fact) {
    var id = $fact.attr("data-fact-id");
    var loader = $fact.find('.loading-evidence');
    $.ajax({
      url: '/facts/' + id + '/fact_relations',
      type: "GET",
      dataType: "script",
      success: function(data) {
        loader.hide();
      },
      error: function(data) {}
    });
  }

  function bindEvidencePrepare($c) {
    $c.find('.results ul li.evidence').live('click', function() {
      showEvidenceAdd($c);

      var elem = $(this);
      var evidenceId = elem.data('evidence-id');
      var evidenceDisplayString = elem.html();

      // Set the evidence ID used for posting
      $c.data('evidenceId', evidenceId);

      // Set the displaystring to the evidence bubble
      $c.find('.evidence-add .evidence').html(evidenceDisplayString);
    });
  }

  function submitEvidence($c, type) {
    var factId = $c.attr("data-fact-id");
    var evidenceId = $c.data("evidence-id");
    var url_part;

    if (type === "supporting") {
      url_part = "/add_supporting_evidence/";
    } else if (type === "weakening") {
      url_part = "/add_weakening_evidence/";
    } else {
      alert('There is a problem adding the evidence to this Factlink. We are sorry for the inconvenience, please try again later.');
    }

    // TODO: This should changed to use the FactRelationController
    $.post("/factlink/" + factId + url_part + evidenceId, function(data) {});
  }

  function bindInstantSearch($c) {
    // Bind the instant search
    var is_timeout;
    $c.find('.search-area .evidence_search').keyup(function() {
      var elem = $(this);
      $('.user-search-input').html(elem.val());

      if (elem.val().length >= 2) {
        clearTimeout(is_timeout);
        is_timeout = setTimeout(function() {
          elem.closest('form').submit();
        }, 200); // <-- choose some sensible value here
      }
    });
  }

  function showEvidenceList($c) {
    hidePages($c);
    $c.find('.evidence-list').show();
  }

  function showEvidenceSearchResults($c) {
    hidePages($c);
    $c.find('.evidence-search-results').show();
  }

  function showEvidenceAdd($c) {
    hidePages($c);
    $c.find('.evidence-add').show();
  }

  function hidePages($c) {
    $c.find('.page').hide();
  }

  function init_fact(fact, container) {
    var $fact = $(fact);
    var $c = $(container);
    if (!$fact.data("initialized")) {
      $fact.find('.edit').editable('/factlink/update_title', {
        indicator: 'Saving...',
        tooltip: 'You can edit this title to place the fact in the correct context.'
      });

      $fact.data("container", container);
      $fact.data("wheel", new Wheel(fact));
      $fact.data("wheel").init($fact.find(".wheel").get(0));

      bindEvidencePrepare($c);
      bindInstantSearch($c);

      // Channels are in the container
      $fact.find(".add-to-channel").hoverIntent(function(e) {
        var channelList = $fact.find(".channel-listing");

        $(channelList).fadeIn("fast");

      }, function() {
        $fact.find(".channel-listing").delay(600).fadeOut("fast");
      }).bind('click', function(e) {
        e.preventDefault();
      });

      $fact.find(".opinion-box").find("img").tipsy({
        gravity: 's'
      });
      // Now setting a function in the jquery data to keep track of it, would be prettier with custom events
      $fact.data("update", function(data) {
        // var fact = $fact;
        $fact.data("wheel").opinions.each(function() {
          data_attr(this, "value", data[$(this).data("opinions")].percentage);
        });
        $fact.find(".authority span").text(data.authority);
        $fact.data("wheel").update();
      });

      $fact.data("initialized", true);
    }
    return $fact;
  }
})(jQuery);
<|endoftext|>