<commit_before>define(
[
    'jQuery',
    'underscore',
    'color-thief'
],
function($, _, ColorThief) { 'use strict';

var myUpdateBackgroundFactory = function(appSettings, $http) {
    var thief = new ColorThief();

    var updateThumbnail = function(element, url){
        var background = 'url(' + url + ')';

        var thumbnail = $('.thumbnail-loading', element.parent());
        thumbnail
            .removeClass('thumbnail-loading')
            .addClass('thumbnail')
            .css('background', background);
    };

    var updateThumbnailColor = function(element){
        var color = null;
        try {
            color = thief.getColor(element.get(0));
        } catch(e) {}

        var background = color ? 'rgb(' + color.join(',') + ')' : 'white';

        var thumbnail = $('.thumbnail-loading', element.parent());
        thumbnail
          .removeClass('thumbnail-loading')
          .addClass('thumbnail')
          .css('background', background);
    };

    var requestThumbnail = function(element, url) {

        return $http({
            url: 'http://dewey-server.azurewebsites.net/screenshot?query=' +
            encodeURIComponent(url),
            method: "GET",
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            }
        }).success(function(responseData) {
            //updateThumbnail(element, responseData.image_url);
            if (responseData.status === "processing") {
                // Server processing results, let's try later in 3 seconds,
                // but not more than 40 times (120 seconds)
                if (tries <= 40) {
                    setTimeout(function() {
                        requestThumbnail(element, url, ++tries);
                    }, ((parseInt(responseData.estimated_need_time) || 2) + 1) * 1000);
                }
            } else if(responseData.status === "finished" && responseData.image_url){
                // Finished, let's update thumbnail
                updateThumbnail(element, responseData.image_url);
            }
        });
    };

    return function(scope, element, attrs) {
        // request thumbnails separately from favicons
        if (appSettings.showThumbnails) {
            requestThumbnail(element, scope.bookmark.url);
        }
        else{
            scope.$watch(attrs.dLoad, function(value) {
                element.on('load', function() {
                    updateThumbnailColor(element);
                });
            });
        }
    };
};

return [
    'appSettings',
    '$http',
    myUpdateBackgroundFactory
];

});
<commit_msg>remove content header<commit_after>define(
[
    'jQuery',
    'underscore',
    'color-thief'
],
function($, _, ColorThief) { 'use strict';

var myUpdateBackgroundFactory = function(appSettings, $http) {
    var thief = new ColorThief();

    var updateThumbnail = function(element, url){
        var background = 'url(' + url + ')';

        var thumbnail = $('.thumbnail-loading', element.parent());
        thumbnail
            .removeClass('thumbnail-loading')
            .addClass('thumbnail')
            .css('background', background);
    };

    var updateThumbnailColor = function(element){
        var color = null;
        try {
            color = thief.getColor(element.get(0));
        } catch(e) {}

        var background = color ? 'rgb(' + color.join(',') + ')' : 'white';

        var thumbnail = $('.thumbnail-loading', element.parent());
        thumbnail
          .removeClass('thumbnail-loading')
          .addClass('thumbnail')
          .css('background', background);
    };

    var requestThumbnail = function(element, url) {

        return $http({
            url: 'http://dewey-server.azurewebsites.net/screenshot?query=' +
            encodeURIComponent(url),
            method: "GET"
        }).success(function(responseData) {
            //updateThumbnail(element, responseData.image_url);
            if (responseData.status === "processing") {
                // Server processing results, let's try later in 3 seconds,
                // but not more than 40 times (120 seconds)
                if (tries <= 40) {
                    setTimeout(function() {
                        requestThumbnail(element, url, ++tries);
                    }, ((parseInt(responseData.estimated_need_time) || 2) + 1) * 1000);
                }
            } else if(responseData.status === "finished" && responseData.image_url){
                // Finished, let's update thumbnail
                updateThumbnail(element, responseData.image_url);
            }
        });
    };

    return function(scope, element, attrs) {
        // request thumbnails separately from favicons
        if (appSettings.showThumbnails) {
            requestThumbnail(element, scope.bookmark.url);
        }
        else{
            scope.$watch(attrs.dLoad, function(value) {
                element.on('load', function() {
                    updateThumbnailColor(element);
                });
            });
        }
    };
};

return [
    'appSettings',
    '$http',
    myUpdateBackgroundFactory
];

});
<|endoftext|>


<commit_before>define(
'filters/booleanSearchFilter',
[
	'underscore',
	'bookmarksApp'
],
function(_, bookmarksApp) { 'use strict';

bookmarksApp.filter('booleanSearchFilter', function($filter) {
		var standardFilter = $filter('filter');
		var orderBy = $filter('orderBy');

		this.andExpression = 'and';
		var orExpression = 'or';

		// Compress some whitespaces to one. Defaults to whitespace characters.
		var clean = function(input, characters){
			if (!angular.isString(input)) {
                return input;
            }

            if (!characters) {
                characters = '\\s';
            }

            return String(input).replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), '');
        };

        // Trims defined characters from begining and ending of the string. Defaults to whitespace characters.
        var trim = function(input, characters){
			if (!angular.isString(input)) {
                return input;
            }

            if (!characters) {
                characters = '\\s';
            }

            return String(input)
                .replace(new RegExp('^' + characters + '+|' + characters + '+$', 'g'), '');
        };

        var isBlank = function(str){
	    	if (str == null) str = '';
	    	return (/^\s*$/).test(str);
	    };

        var words = function(str, delimiter) {
	    	if (isBlank(str)) return [];
	    	return trim(str, delimiter).split(delimiter || /\s+/);
	    };

	    var comperator = function(obj){
				return true;
			};

		return function(input, search, order) {
			var searchWords = [];

			if (search) {
				var cleanSearch = clean(search);
				searchWords = words(cleanSearch);
			}

			return orderBy(standardFilter(input, function(obj, searchWords){
				return true;
			}), order, order === 'date');
		};
  });
});

<commit_msg>add underscore to filter<commit_after>define(
'filters/booleanSearchFilter',
[
    'underscore',
	'bookmarksApp'
],
function(_, bookmarksApp) { 'use strict';

bookmarksApp.filter('booleanSearchFilter', function($filter) {
		var standardFilter = $filter('filter');
		var orderBy = $filter('orderBy');

		var andExpression = 'and';
		var orExpression = 'or';

		// Compress some whitespaces to one. Defaults to whitespace characters.
		var clean = function(input, characters){
			if (!angular.isString(input)) {
                return input;
            }

            if (!characters) {
                characters = '\\s';
            }

            return String(input).replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), '');
        };

        // Trims defined characters from begining and ending of the string. Defaults to whitespace characters.
        var trim = function(input, characters){
			if (!angular.isString(input)) {
                return input;
            }

            if (!characters) {
                characters = '\\s';
            }

            return String(input)
                .replace(new RegExp('^' + characters + '+|' + characters + '+$', 'g'), '');
        };

        var isBlank = function(str){
	    	if (str == null) str = '';
	    	return (/^\s*$/).test(str);
	    };

        var words = function(str, delimiter) {
	    	if (isBlank(str)) return [];
	    	return trim(str, delimiter).split(delimiter || /\s+/);
	    };

		return function(input, search, order) {
			var expression = {};

			if (search) {
				var cleanSearch = clean(search);
				var searchWords = words(cleanSearch, ':');

			}

      		var comparator = function (obj) {
        		return true;
      		}

			return orderBy(standardFilter(input, comparator), order, order === 'date');
		};
  });
});<|endoftext|>


<commit_before>/**
 * This file implements main functionality of call4action module
 */

function init() {
    //console.log(window.sessionStorage);
    var teacher = window.sessionStorage.getItem("teacherId");

    if (teacher == null) {

        //show login dialog
        $('#loginModal').modal({

            backdrop: 'static',
            keyboard: false

        });

        $("#loginModal").on("hidden.bs.modal", function () {

            if (window.sessionStorage.getItem("teacherId") == null) {
                // put your default event here
                $("#warning-message").removeClass("hidden");
            }
            else {
                $("#warning-message").addClass("hidden");
                //show content
                $("#mainContent").removeClass("hidden");
            }

        });
    }
    else {
        //show content
        $("#mainContent").removeClass("hidden");
        $('[data-toggle="popover"]').popover();
        $(".icon_info").tooltip();

        initStudentTable();

        //Dependent Task
        //dynamically generate list of tasks
        $('input[type=radio][name=task-type]').change(function () {
            console.log(this.value);
            if (this.value === '1') {
                document.getElementById("taskDiv").classList.remove("hidden");

                getTasks(function (tasks) {
                    generateTaskTable(tasks["DATA"]);
                });
            }
            else {
                document.getElementById("taskDiv").classList.add("hidden");
            }
        });

    }

    /**
     * SUBMIT TASK
     */
    document.getElementById("submit-btn").addEventListener('click', function () {

        var form = document.getElementById("taskForm");
        if (form.checkValidity()) {

            //check if any students were selected
            if ($('table.table.table-striped :checkbox:checked').length > 0) {
                $("#select-error-message").addClass("hidden");

                var formData = $('#taskForm').serializeArray();
                //check if select all in the data, remove it
                var data = formData.filter(function (el) {
                    return el.name !== "select-all";
                });

                //prepare data to be send on server
                var taskName = formData.find(function (obj) {
                    return obj.name === "title";
                });
                var taskDescription = formData.find(function (obj) {
                    return obj.name === "description";
                });
                var studentIDs = formData.filter(function (obj) {
                    return obj.name === "student";

                }).map(function (students) {
                    return students.value;
                });
                console.log(formData);
                var taskType = formData.find(function (obj) {
                    return obj.name === "task-type";
                });

                //check if this task is Reflection task
                if ($('#reflection-checkbox').is(":checked")) {
                    taskDescription.value += "
 Please use this link to do reflection.
 ";
                }

                //check if it is dependent task, if task choosen fomr the list

                if (taskType.value === "1") {
                    if ($("#taskList").val() === "0") {
                        //show error message
                        $("#task-error-message").removeClass("hidden");

                    }
                    else {
                        $("#task-error-message").addClass("hidden");
                        var taskId = $("#taskList").val();

                        //autogenerate additional text "Note! This task can be done after Task Name"
                        var subtitle = "Note! This task can be done after " + $("#taskList option:selected").text() + "";

                        var timestamp = new Date().toISOString().slice(0, 19).replace('T', ' ');
                        var preparedData = { "subtitle": subtitle, "taskId": taskId, "func": "addTask", "type": taskType.value, "taskName": taskName.value, "taskDescription": taskDescription.value, "teacherId": window.sessionStorage.getItem("teacherId"), "pilotsite": window.sessionStorage.getItem("sessionId"), "students": studentIDs, "status": 0, "timestamp": timestamp };

                        submitTask(preparedData, function (result) {
                            //clear form data
                            $("#taskForm").find("input[type=text], textarea").val("");
                            emptyCheckboxes();

                            //show success notification
                            if (result["RESULT"] === "SUCCESS") {
                                showMessage("Task was created successfully!", "alert-success");

                            }
                            else {
                                showMessage("Some issue is occurred, please try again later.", "alert-danger");
                            }
                            document.getElementById("taskDiv").classList.add("hidden");
                        });
                    }
                }
                else {

                    var timestamp = new Date().toISOString().slice(0, 19).replace('T', ' ');
                    var preparedData = { "subtitle": "", "taskId": -1, "func": "addTask", "type": taskType.value, "taskName": taskName.value, "taskDescription": taskDescription.value, "teacherId": window.sessionStorage.getItem("teacherId"), "pilotsite": window.sessionStorage.getItem("sessionId"), "students": studentIDs, "status": 0, "timestamp": timestamp };

                    submitTask(preparedData, function (result) {
                        //clear form data
                        $("#taskForm").find("input[type=text], textarea").val("");
                        emptyCheckboxes();
                        //show success notification
                        if (result["RESULT"] === "SUCCESS") {
                            showMessage("Task was created successfully!", "alert-success");
                        }
                        else {
                            showMessage("Some issue is occurred, please try again later.", "alert-danger");
                        }
                    });
                }

            }
            else {
                $("#select-error-message").removeClass("hidden");
            }

        }
        else {

            form.querySelector('button[type="submit"]').click();
        }
    }, false);

}

function initStudentTable() {

    getStudents(function (students) {
        //console.log(students.length);
        //console.log(students);
        if (students == "error") {
            displayErrorMsg();
        } else {
            generateStudentTable(students["DATA"]);
        }
    });

    //column checkbox select all or cancel
    $("input.select-all").click(function () {
        var checked = this.checked;
        $("input.select-student").each(function (index, item) {
            item.checked = checked;
        });
        markSelectedStudents();
        $('input.select-all').tooltip('hide');
    });

    // Event delegation on tbody to minimise eventlisteners needed
    // (if list is large this might have impact)
    // Simply checks the checkbox on the row you click, event.target.closest
    // makes sure that it doesn't matter where on the element you click
    // It doesn't perform the checking logic if you click on the actual checkbox

    document.getElementById("studentTable").getElementsByTagName("tbody")[0].addEventListener("click", function (event) {
        if (event.target.tagName !== "INPUT") {
            var checkbox = event.target.closest("tr").getElementsByTagName("input")[0];
            if (checkbox.checked) {
                checkbox.checked = false;
                event.target.closest("tr").classList.remove("success");
            } else {
                checkbox.checked = true;
                event.target.closest("tr").classList.add("success");
            }
        } else {
            markSelectedStudents();
        }
    });
}

// Mark the table row of all student entries with checked checkbox
// Unmark the table row of all student entries with unchecked checkbox
function markSelectedStudents() {
    var rows = document.getElementById("studentTable").getElementsByTagName("tbody")[0].children;
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].firstElementChild.firstElementChild.checked == true) {
            rows[i].classList.add("success");
        } else {
            rows[i].classList.remove("success");
        }
    }
}

function generateStudentTable(students) {
    var table = document.getElementById("studentTable").getElementsByTagName("tbody")[0];

    for (var i = 0; i < students.length; i++) {
        var row = table.insertRow(i);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);

        //first column is checkbox
        cell1.innerHTML = '<input type="checkbox" class="select-student checkbox" name="student" value=' + students[i]["ID"] + ' />';
        //second column student name
        cell2.innerHTML = students[i]["USERNAME"];
    }

}

function displayErrorMsg() {
    $("#error-message").removeClass("hidden");
}

function generateTaskTable(tasks) {

    var taskList = document.getElementById("taskList");
    taskList.innerHTML = "";

    //none option first
    var option = document.createElement('option');
    option.value = 0;
    option.textContent = "NONE";
    taskList.appendChild(option);

    for (var i = 0; i < tasks.length; i++) {
        var option = document.createElement('option');

        option.value = tasks[i]["ID"];
        option.textContent = tasks[i]["TITLE"];

        taskList.appendChild(option);
    }
}

function emptyCheckboxes() {
    $("input.select-student").each(function (index, item) {
        item.checked = false;
    });

    markSelectedStudents();

    $('#reflection-checkbox').prop("checked", false);
    $(".select-all").prop("checked", false);
}

/**
 * USER LOGIN
 */

function userLogin() {

    var email = $('#inputEmail').val();
    var pw = $('#inputPassword').val();

    $.ajax({

        type: 'POST',
        url: 'https://cs.uef.fi/~tapanit/ecraft2learn/api/pilot_2/login_teacher_pilot_2.php',
        data: 'username=' + email + '&password=' + pw,
        success: function (data) {

            if (!isNaN(data)) {

                window.sessionStorage.setItem("teacherId", data);
                $('#loginModal').modal('hide');
                init();

            } else {

                alert('Not a valid username or a password.');

            }

        },
        error: function (error) {

        }

    });

}

function showMessage(message, type) {
    $("#alert").html('
' + message + '
');

    setTimeout(function () { // this will automatically close the alert and remove this if the users doesnt close it in 5 secs

        $("#alertdiv").remove();

    }, 5000);
}<commit_msg>fixing reflection task<commit_after>/**
 * This file implements main functionality of call4action module
 */

function init() {
    //console.log(window.sessionStorage);
    var teacher = window.sessionStorage.getItem("teacherId");

    if (teacher == null) {

        //show login dialog
        $('#loginModal').modal({

            backdrop: 'static',
            keyboard: false

        });

        $("#loginModal").on("hidden.bs.modal", function () {

            if (window.sessionStorage.getItem("teacherId") == null) {
                // put your default event here
                $("#warning-message").removeClass("hidden");
            }
            else {
                $("#warning-message").addClass("hidden");
                //show content
                $("#mainContent").removeClass("hidden");
            }

        });
    }
    else {
        //show content
        $("#mainContent").removeClass("hidden");
        $('[data-toggle="popover"]').popover();
        $(".icon_info").tooltip();

        initStudentTable();

        //Dependent Task
        //dynamically generate list of tasks
        $('input[type=radio][name=task-type]').change(function () {
            console.log(this.value);
            if (this.value === '1') {
                document.getElementById("taskDiv").classList.remove("hidden");

                getTasks(function (tasks) {
                    generateTaskTable(tasks["DATA"]);
                });
            }
            else {
                document.getElementById("taskDiv").classList.add("hidden");
            }
        });

    }

    /**
     * SUBMIT TASK
     */
    document.getElementById("submit-btn").addEventListener('click', function () {

        var form = document.getElementById("taskForm");
        if (form.checkValidity()) {

            //check if any students were selected
            if ($('table.table.table-striped :checkbox:checked').length > 0) {
                $("#select-error-message").addClass("hidden");

                var formData = $('#taskForm').serializeArray();
                //check if select all in the data, remove it
                var data = formData.filter(function (el) {
                    return el.name !== "select-all";
                });

                //prepare data to be send on server
                var taskName = formData.find(function (obj) {
                    return obj.name === "title";
                });
                var taskDescription = formData.find(function (obj) {
                    return obj.name === "description";
                });
                var studentIDs = formData.filter(function (obj) {
                    return obj.name === "student";

                }).map(function (students) {
                    return students.value;
                });

                var taskType = formData.find(function (obj) {
                    return obj.name === "task-type";
                });

                var isReflection = 0;
                //check if this task is Reflection task
                if ($('#reflection-checkbox').is(":checked")) {
                    isReflection = 1;
                }
                console.log(isReflection);

                //check if it is dependent task, if task choosen fomr the list

                if (taskType.value === "1") {
                    if ($("#taskList").val() === "0") {
                        //show error message
                        $("#task-error-message").removeClass("hidden");

                    }
                    else {
                        $("#task-error-message").addClass("hidden");
                        var taskId = $("#taskList").val();

                        //autogenerate additional text "Note! This task can be done after Task Name"
                        var subtitle = "Note! This task can be done after " + $("#taskList option:selected").text() + "";

                        var timestamp = new Date().toISOString().slice(0, 19).replace('T', ' ');
                        var preparedData = { "subtitle": subtitle, "taskId": taskId, "func": "addTask", "type": taskType.value, "taskName": taskName.value, "taskDescription": taskDescription.value, "teacherId": window.sessionStorage.getItem("teacherId"), "pilotsite": window.sessionStorage.getItem("sessionId"), "students": studentIDs, "status": 0, "timestamp": timestamp,"isReflection":isReflection };

                        console.log(preparedData);
                        submitTask(preparedData, function (result) {
                            //clear form data
                            $("#taskForm").find("input[type=text], textarea").val("");
                            emptyCheckboxes();

                            //show success notification
                            if (result["RESULT"] === "SUCCESS") {
                                showMessage("Task was created successfully!", "alert-success");

                            }
                            else {
                                showMessage("Some issue is occurred, please try again later.", "alert-danger");
                            }
                            document.getElementById("taskDiv").classList.add("hidden");
                        });
                    }
                }
                else {

                    var timestamp = new Date().toISOString().slice(0, 19).replace('T', ' ');
                    var preparedData = { "subtitle": "", "taskId": -1, "func": "addTask", "type": taskType.value, "taskName": taskName.value, "taskDescription": taskDescription.value, "teacherId": window.sessionStorage.getItem("teacherId"), "pilotsite": window.sessionStorage.getItem("sessionId"), "students": studentIDs, "status": 0, "timestamp": timestamp,"isReflection":isReflection };

                    submitTask(preparedData, function (result) {
                        //clear form data
                        $("#taskForm").find("input[type=text], textarea").val("");
                        emptyCheckboxes();
                        //show success notification
                        if (result["RESULT"] === "SUCCESS") {
                            showMessage("Task was created successfully!", "alert-success");
                        }
                        else {
                            showMessage("Some issue is occurred, please try again later.", "alert-danger");
                        }
                    });
                }

            }
            else {
                $("#select-error-message").removeClass("hidden");
            }

        }
        else {

            form.querySelector('button[type="submit"]').click();
        }
    }, false);

}

function generateReflectionLink() {
    var link = " Do Reflection";
    return link;
}

function initStudentTable() {

    getStudents(function (students) {
        //console.log(students.length);
        //console.log(students);
        if (students == "error") {
            displayErrorMsg();
        } else {
            generateStudentTable(students["DATA"]);
        }
    });

    //column checkbox select all or cancel
    $("input.select-all").click(function () {
        var checked = this.checked;
        $("input.select-student").each(function (index, item) {
            item.checked = checked;
        });
        markSelectedStudents();
        $('input.select-all').tooltip('hide');
    });

    // Event delegation on tbody to minimise eventlisteners needed
    // (if list is large this might have impact)
    // Simply checks the checkbox on the row you click, event.target.closest
    // makes sure that it doesn't matter where on the element you click
    // It doesn't perform the checking logic if you click on the actual checkbox

    document.getElementById("studentTable").getElementsByTagName("tbody")[0].addEventListener("click", function (event) {
        if (event.target.tagName !== "INPUT") {
            var checkbox = event.target.closest("tr").getElementsByTagName("input")[0];
            if (checkbox.checked) {
                checkbox.checked = false;
                event.target.closest("tr").classList.remove("success");
            } else {
                checkbox.checked = true;
                event.target.closest("tr").classList.add("success");
            }
        } else {
            markSelectedStudents();
        }
    });
}

// Mark the table row of all student entries with checked checkbox
// Unmark the table row of all student entries with unchecked checkbox
function markSelectedStudents() {
    var rows = document.getElementById("studentTable").getElementsByTagName("tbody")[0].children;
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].firstElementChild.firstElementChild.checked == true) {
            rows[i].classList.add("success");
        } else {
            rows[i].classList.remove("success");
        }
    }
}

function generateStudentTable(students) {
    var table = document.getElementById("studentTable").getElementsByTagName("tbody")[0];

    for (var i = 0; i < students.length; i++) {
        var row = table.insertRow(i);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);

        //first column is checkbox
        cell1.innerHTML = '<input type="checkbox" class="select-student checkbox" name="student" value=' + students[i]["ID"] + ' />';
        //second column student name
        cell2.innerHTML = students[i]["USERNAME"];
    }

}

function displayErrorMsg() {
    $("#error-message").removeClass("hidden");
}

function generateTaskTable(tasks) {

    var taskList = document.getElementById("taskList");
    taskList.innerHTML = "";

    //none option first
    var option = document.createElement('option');
    option.value = 0;
    option.textContent = "NONE";
    taskList.appendChild(option);

    for (var i = 0; i < tasks.length; i++) {
        var option = document.createElement('option');

        option.value = tasks[i]["ID"];
        option.textContent = tasks[i]["TITLE"];

        taskList.appendChild(option);
    }
}

function emptyCheckboxes() {
    $("input.select-student").each(function (index, item) {
        item.checked = false;
    });

    markSelectedStudents();

    $('#reflection-checkbox').prop("checked", false);
    $(".select-all").prop("checked", false);
}

/**
 * USER LOGIN
 */

function userLogin() {

    var email = $('#inputEmail').val();
    var pw = $('#inputPassword').val();

    $.ajax({

        type: 'POST',
        url: 'https://cs.uef.fi/~tapanit/ecraft2learn/api/pilot_2/login_teacher_pilot_2.php',
        data: 'username=' + email + '&password=' + pw,
        success: function (data) {

            if (!isNaN(data)) {

                window.sessionStorage.setItem("teacherId", data);
                $('#loginModal').modal('hide');
                init();

            } else {

                alert('Not a valid username or a password.');

            }

        },
        error: function (error) {

        }

    });

}

function showMessage(message, type) {
    $("#alert").html('
' + message + '
');

    setTimeout(function () { // this will automatically close the alert and remove this if the users doesnt close it in 5 secs

        $("#alertdiv").remove();

    }, 5000);
}<|endoftext|>


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

var auth0 = require('../src');
var Auth0 = require('../src/Auth0');
var ArgumentError = require('../src/exceptions').ArgumentError;

describe('Auth0 module', function () {

    it('should raise an error when no options object is provided', function () {
      expect(auth0).to.throw(ArgumentError, 'Auth0 SDK options must be an object');
    });

    it('should raise an error when the token is not valid', function () {
      var client = auth0.bind(null, { token: '' });

      expect(client).to.throw(ArgumentError, 'An access token must be provided');
    });

    it('should return an instance of Auth0 when the token is valid', function () {
      var options = { token: 'abcdefg' };
      var client = auth0(options);

      expect(client).to.be.an('Object');
      expect(client).to.be.an.instanceOf(Auth0);
    });

});
<commit_msg>Update Auth0 tests<commit_after>var expect = require('chai').expect;

var auth0 = require('../src');
var Auth0 = require('../src/Auth0');
var ArgumentError = require('../src/exceptions').ArgumentError;
var UsersManager = require('../src/UsersManager');
var BlacklistedTokensManager = require('../src/BlacklistedTokensManager');
var ClientsManager = require('../src/ClientsManager');
var ConnectionsManager = require('../src/ConnectionsManager');
var DeviceCredentialsManager = require('../src/DeviceCredentialsManager');
var EmailProviderManager = require('../src/EmailProviderManager');
var JobsManager = require('../src/JobsManager');
var RulesManager = require('../src/RulesManager');
var StatsManager = require('../src/StatsManager');
var TenantManager = require('../src/TenantManager');

describe('Auth0 module', function () {

    it('should raise an error when no options object is provided', function () {
      expect(auth0)
        .to.throw(ArgumentError, 'Auth0 SDK options must be an object');
    });

    it('should raise an error when the token is not valid', function () {
      var client = auth0.bind(null, { token: '', domain: 'tenant.auth.com' });

      expect(client)
        .to.throw(ArgumentError, 'An access token must be provided');
    });

    it('should raise an error when the domain is not valid', function () {
      var client = auth0.bind(null, { token: 'token', domain: '' });

      expect(client)
        .to.throw(ArgumentError, 'Must provide a domain');
    });

    it('should return an instance of Auth0 when the options are valid', function () {
      var options = { token: 'token', domain: 'tenant.auth0.com' };
      var client = auth0(options);

      expect(client)
        .to.be.an('Object')
        .to.be.an.instanceOf(Auth0);
    });

    describe('instance properties', function () {
      var manager;
      var managers = {
        'UsersManager': {
          property: 'users',
          cls: UsersManager
        },
        'BlacklistedTokensManager': {
          property: 'blacklistedTokens',
          cls: BlacklistedTokensManager
        },
        'ClientsManager': {
          property: 'clients',
          cls: ClientsManager
        },
        'ConnectionsManager': {
          property: 'connections',
          cls: ConnectionsManager
        },
        'DeviceCredentialsManager': {
          property: 'deviceCredentials',
          cls: DeviceCredentialsManager
        },
        'EmailProviderManager': {
          property: 'emailProvider',
          cls: EmailProviderManager
        },
        'JobsManager': {
          property: 'jobs',
          cls: JobsManager
        },
        'RulesManager': {
          property: 'rules',
          cls: RulesManager
        },
        'StatsManager': {
          property: 'stats',
          cls: StatsManager
        },
        'TenantManager': {
          property: 'tenant',
          cls: TenantManager
        }
      };

      before(function () {
        this.client = auth0({ token: 'token', domain: 'auth0.com' });
      });

      // Tests common to all managers.
      for (var name in managers) {
        manager = managers[name];

        it('should expose an instance of ' + name, function () {
          expect(this.client[manager.property])
            .to.exist
            .to.be.an.instanceOf(manager.cls);
        });
      }
    });

    describe('instance methods', function () {
      var method;
      var methods = [
        'getConnections',
        'createConnection',
        'getConnection',
        'deleteConnection',
        'updateConnection',
        'getClients',
        'getClient',
        'createClient',
        'updateClient',
        'deleteClient',
        'createDevicePublicKey',
        'getDeviceCredentials',
        'deleteDeviceCredential',
        'getRules',
        'createRule',
        'getRule',
        'deleteRule',
        'updateRule',
        'getUsers',
        'getUser',
        'deleteAllUsers',
        'deleteUsers',
        'createUser',
        'updateUser',
        'getBlacklistedTokens',
        'blacklistToken',
        'getEmailProvider',
        'configureEmailProvider',
        'deleteEmailProvider',
        'updateEmailProvider',
        'getActiveUsersCount',
        'getDailyStats',
        'getTenantSettings',
        'updateTenantSettings'
      ];

      before(function () {
        this.client = auth0({ token: 'token', domain: 'auth0.com' });
      });

      for (var i = 0, l = methods.length; i < l; i++) {
        method = methods[i];

        it('should have a ' + method + ' method', function () {
          expect(this.client[method])
            .to.exist
            .to.be.an.instanceOf(Function);
        });
      }
    });
});
<|endoftext|>


<commit_before>"use strict";

/*global module, require*/

var jsonSerialization = require("./json.js"),
    perimetaDeserialize = require("./perimeta-xml.js"),
    exportButtonFactory = require("./export-button.js"),
    fileDrop = require("./file-drop.js");

module.exports = function(body, model) {
    fileDrop(
	{
	    json: function(fileName, content) {
		model.set(
		    jsonSerialization.deserialize(
			JSON.parse(content)
		    )
		);
	    },
	    xml: function(fileName, content) {
		model.fromNodes(
		    perimetaDeserialize(content)
		);
	    }
	}
    ).drop(body);

    var exportButton;

    return {
	jsonSerialize: jsonSerialization.serialize,
	jsonDeserialize: jsonSerialization.deserialize,

	exportButton: function(fileMenu) {
	    if (fileMenu && !exportButton) {
		exportButton = exportButtonFactory(
		    fileMenu.store.getTitle,
		    fileMenu.store.onNavigate,
		    jsonSerialization.serialize,
		    model.get,
		    fileMenu.spec.button
		);
	    }

	    if (!exportButton) {
		throw new Error("Must create export button by passing in the filemenu to use before we can use the button itself.");
	    }

	    return exportButton;
	}
    };
};
<commit_msg>Fixed perimeta import.<commit_after>"use strict";

/*global module, require*/

var jsonSerialization = require("./json.js"),
    perimetaDeserialize = require("./perimeta-xml.js"),
    exportButtonFactory = require("./export-button.js"),
    fileDrop = require("./file-drop.js");

module.exports = function(body, model) {
    fileDrop(
	{
	    json: function(fileName, content) {
		model.set(
		    jsonSerialization.deserialize(
			JSON.parse(content)
		    )
		);
	    },
	    xml: function(fileName, content) {
		model.setFromNodes(
		    perimetaDeserialize(content)
		);
	    }
	}
    ).drop(body);

    var exportButton;

    return {
	jsonSerialize: jsonSerialization.serialize,
	jsonDeserialize: jsonSerialization.deserialize,

	exportButton: function(fileMenu) {
	    if (fileMenu && !exportButton) {
		exportButton = exportButtonFactory(
		    fileMenu.store.getTitle,
		    fileMenu.store.onNavigate,
		    jsonSerialization.serialize,
		    model.get,
		    fileMenu.spec.button
		);
	    }

	    if (!exportButton) {
		throw new Error("Must create export button by passing in the filemenu to use before we can use the button itself.");
	    }

	    return exportButton;
	}
    };
};
<|endoftext|>


<commit_before>/**
 * Preview.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * Internal class for generating previews styles for formats.
 *
 * Example:
 *  Preview.getCssText(editor, 'bold');
 *
 * @private
 * @class tinymce.fmt.Preview
 */
define("tinymce/fmt/Preview", [
	"tinymce/dom/DOMUtils",
	"tinymce/util/Tools",
	"tinymce/html/Schema"
], function(DOMUtils, Tools, Schema) {
	var each = Tools.each;
	var dom = DOMUtils.DOM;

	function parsedSelectorToHtml(ancestry, editor) {
		var elm, item, fragment;
		var schema = editor && editor.schema || new Schema({});

		function decorate(elm, item) {
			if (item.classes.length) {
				dom.addClass(elm, item.classes.join(' '));
			}
			dom.setAttribs(elm, item.attrs);
		}

		function createElement(sItem) {
			var elm;

			item = typeof sItem === 'string' ? {
				name: sItem,
				classes: [],
				attrs: {}
			} : sItem;

			elm = dom.create(item.name);
			decorate(elm, item);
			return elm;
		}

		function getRequiredParent(elm, candidate) {
			var name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
			var elmRule = schema.getElementRule(name);
			var parentsRequired = elmRule.parentsRequired;

			if (parentsRequired && parentsRequired.length) {
				return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
			} else {
				return false;
			}
		}

		function wrapInHtml(elm, ancestry, siblings) {
			var parent, parentCandidate, parentRequired;
			var ancestor = ancestry.length && ancestry[0];
			var ancestorName = ancestor && ancestor.name;

			parentRequired = getRequiredParent(elm, ancestorName);

			if (parentRequired) {
				if (ancestorName == parentRequired) {
					parentCandidate = ancestry[0];
					ancestry = ancestry.slice(1);
				} else {
					parentCandidate = parentRequired;
				}
			} else if (ancestor) {
				parentCandidate = ancestry[0];
				ancestry = ancestry.slice(1);
			} else if (!siblings) {
				return elm;
			}

			if (parentCandidate) {
				parent = createElement(parentCandidate);
				parent.appendChild(elm);
			}

			if (siblings) {
				if (!parent) {
					// if no more ancestry, wrap in generic div
					parent = dom.create('div');
					parent.appendChild(elm);
				}

				Tools.each(siblings, function(sibling) {
					var siblingElm = createElement(sibling);
					parent.insertBefore(siblingElm, elm);
				});
			}

			return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
		}

		if (ancestry && ancestry.length) {
			item = ancestry[0];
			elm = createElement(item);
			fragment = dom.create('div');
			fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
			return fragment;
		} else {
			return '';
		}
	}

	function selectorToHtml(selector, editor) {
		return parsedSelectorToHtml(parseSelector(selector, editor));
	}

	function parseSelectorItem(item) {
		var tagName;
		var obj = {
			classes: [],
			attrs: {}
		};

		item = obj.selector = Tools.trim(item);

		// matching IDs, CLASSes, ATTRIBUTES and PSEUDOs
		tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function($0, $1, $2, $3, $4) {
			switch ($1) {
				case '#':
					obj.attrs.id = $2;
					break;

				case '.':
					obj.classes.push($2);
					break;

				case ':':
					if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
						obj.attrs[$2] = $2;
					}
					break;
			}

			// atribute matched
			if ($3 == '[') {
				var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
				if (m) {
					obj.attrs[m[1]] = m[2];
				}
			}

			return '';
		});

		obj.name = tagName || 'div';
		return obj;
	}

	function parseSelector(selector) {
		if (!selector || typeof selector !== 'string') {
			return [];
		}

		// take into account only first one
		selector = selector.split(/\s*,\s*/)[0];

		// tighten
		selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');

		// split either on > or on space, but not the one inside brackets
		return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function(item) {
			// process each sibling selector separately
			var siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
			var obj = siblings.pop(); // the last one is our real target

			if (siblings.length) {
				obj.siblings = siblings;
			}
			return obj;
		}).reverse();
	}

	function getCssText(editor, format) {
		var name, previewFrag, previewElm, items;
		var previewCss = '', parentFontSize, previewStyles;

		previewStyles = editor.settings.preview_styles;

		// No preview forced
		if (previewStyles === false) {
			return '';
		}

		// Default preview
		if (typeof previewStyles !== 'string') {
			previewStyles = 'font-family font-size font-weight font-style text-decoration ' +
				'text-transform color background-color border border-radius outline text-shadow';
		}

		// Removes any variables since these can't be previewed
		function removeVars(val) {
			return val.replace(/%(\w+)/g, '');
		}

		// Create block/inline element to use for preview
		if (typeof format == "string") {
			format = editor.formatter.get(format);
			if (!format) {
				return;
			}

			format = format[0];
		}

		// Format specific preview override
		// TODO: This should probably be further reduced by the previewStyles option
		if ('preview' in format) {
			previewStyles = format.preview;
			if (previewStyles === false) {
				return '';
			}
		}

		name = format.block || format.inline || 'span';

		items = parseSelector(format.selector);
		if (items.length) {
			if (!items[0].name) { // e.g. something like ul > .someClass was provided
				items[0].name = name;
			}
			name = format.selector;
			previewFrag = parsedSelectorToHtml(items);
		} else {
			previewFrag = parsedSelectorToHtml([name]);
		}

		previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;

		// Add format styles to preview element
		each(format.styles, function(value, name) {
			value = removeVars(value);

			if (value) {
				dom.setStyle(previewElm, name, value);
			}
		});

		// Add attributes to preview element
		each(format.attributes, function(value, name) {
			value = removeVars(value);

			if (value) {
				dom.setAttrib(previewElm, name, value);
			}
		});

		// Add classes to preview element
		each(format.classes, function(value) {
			value = removeVars(value);

			if (!dom.hasClass(previewElm, value)) {
				dom.addClass(previewElm, value);
			}
		});

		editor.fire('PreviewFormats');

		// Add the previewElm outside the visual area
		dom.setStyles(previewFrag, {position: 'absolute', left: -0xFFFF});
		editor.getBody().appendChild(previewFrag);

		// Get parent container font size so we can compute px values out of em/% for older IE:s
		parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
		parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;

		each(previewStyles.split(' '), function(name) {
			var value = dom.getStyle(previewElm, name, true);

			// If background is transparent then check if the body has a background color we can use
			if (name == 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
				value = dom.getStyle(editor.getBody(), name, true);

				// Ignore white since it's the default color, not the nicest fix
				// TODO: Fix this by detecting runtime style
				if (dom.toHex(value).toLowerCase() == '#ffffff') {
					return;
				}
			}

			if (name == 'color') {
				// Ignore black since it's the default color, not the nicest fix
				// TODO: Fix this by detecting runtime style
				if (dom.toHex(value).toLowerCase() == '#000000') {
					return;
				}
			}

			// Old IE won't calculate the font size so we need to do that manually
			if (name == 'font-size') {
				if (/em|%$/.test(value)) {
					if (parentFontSize === 0) {
						return;
					}

					// Convert font size from em/% to px
					value = parseFloat(value, 10) / (/%$/.test(value) ? 100 : 1);
					value = (value * parentFontSize) + 'px';
				}
			}

			if (name == "border" && value) {
				previewCss += 'padding:0 2px;';
			}

			previewCss += name + ':' + value + ';';
		});

		editor.fire('AfterPreviewFormats');

		//previewCss += 'line-height:normal';

		dom.remove(previewFrag);

		return previewCss;
	}

	return {
		getCssText: getCssText,
		parseSelector: parseSelector,
		selectorToHtml: selectorToHtml
	};
});
<commit_msg>TINY-785: fix regression<commit_after>/**
 * Preview.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * Internal class for generating previews styles for formats.
 *
 * Example:
 *  Preview.getCssText(editor, 'bold');
 *
 * @private
 * @class tinymce.fmt.Preview
 */
define("tinymce/fmt/Preview", [
	"tinymce/dom/DOMUtils",
	"tinymce/util/Tools",
	"tinymce/html/Schema"
], function(DOMUtils, Tools, Schema) {
	var each = Tools.each;
	var dom = DOMUtils.DOM;

	function parsedSelectorToHtml(ancestry, editor) {
		var elm, item, fragment;
		var schema = editor && editor.schema || new Schema({});

		function decorate(elm, item) {
			if (item.classes.length) {
				dom.addClass(elm, item.classes.join(' '));
			}
			dom.setAttribs(elm, item.attrs);
		}

		function createElement(sItem) {
			var elm;

			item = typeof sItem === 'string' ? {
				name: sItem,
				classes: [],
				attrs: {}
			} : sItem;

			elm = dom.create(item.name);
			decorate(elm, item);
			return elm;
		}

		function getRequiredParent(elm, candidate) {
			var name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
			var elmRule = schema.getElementRule(name);
			var parentsRequired = elmRule.parentsRequired;

			if (parentsRequired && parentsRequired.length) {
				return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
			} else {
				return false;
			}
		}

		function wrapInHtml(elm, ancestry, siblings) {
			var parent, parentCandidate, parentRequired;
			var ancestor = ancestry.length && ancestry[0];
			var ancestorName = ancestor && ancestor.name;

			parentRequired = getRequiredParent(elm, ancestorName);

			if (parentRequired) {
				if (ancestorName == parentRequired) {
					parentCandidate = ancestry[0];
					ancestry = ancestry.slice(1);
				} else {
					parentCandidate = parentRequired;
				}
			} else if (ancestor) {
				parentCandidate = ancestry[0];
				ancestry = ancestry.slice(1);
			} else if (!siblings) {
				return elm;
			}

			if (parentCandidate) {
				parent = createElement(parentCandidate);
				parent.appendChild(elm);
			}

			if (siblings) {
				if (!parent) {
					// if no more ancestry, wrap in generic div
					parent = dom.create('div');
					parent.appendChild(elm);
				}

				Tools.each(siblings, function(sibling) {
					var siblingElm = createElement(sibling);
					parent.insertBefore(siblingElm, elm);
				});
			}

			return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
		}

		if (ancestry && ancestry.length) {
			item = ancestry[0];
			elm = createElement(item);
			fragment = dom.create('div');
			fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
			return fragment;
		} else {
			return '';
		}
	}

	function selectorToHtml(selector, editor) {
		return parsedSelectorToHtml(parseSelector(selector, editor));
	}

	function parseSelectorItem(item) {
		var tagName;
		var obj = {
			classes: [],
			attrs: {}
		};

		item = obj.selector = Tools.trim(item);

		// matching IDs, CLASSes, ATTRIBUTES and PSEUDOs
		tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function($0, $1, $2, $3, $4) {
			switch ($1) {
				case '#':
					obj.attrs.id = $2;
					break;

				case '.':
					obj.classes.push($2);
					break;

				case ':':
					if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
						obj.attrs[$2] = $2;
					}
					break;
			}

			// atribute matched
			if ($3 == '[') {
				var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
				if (m) {
					obj.attrs[m[1]] = m[2];
				}
			}

			return '';
		});

		obj.name = tagName || 'div';
		return obj;
	}

	function parseSelector(selector) {
		if (!selector || typeof selector !== 'string' || selector === '*') {
			return [];
		}

		// take into account only first one
		selector = selector.split(/\s*,\s*/)[0];

		// tighten
		selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');

		// split either on > or on space, but not the one inside brackets
		return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function(item) {
			// process each sibling selector separately
			var siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
			var obj = siblings.pop(); // the last one is our real target

			if (siblings.length) {
				obj.siblings = siblings;
			}
			return obj;
		}).reverse();
	}

	function getCssText(editor, format) {
		var name, previewFrag, previewElm, items;
		var previewCss = '', parentFontSize, previewStyles;

		previewStyles = editor.settings.preview_styles;

		// No preview forced
		if (previewStyles === false) {
			return '';
		}

		// Default preview
		if (typeof previewStyles !== 'string') {
			previewStyles = 'font-family font-size font-weight font-style text-decoration ' +
				'text-transform color background-color border border-radius outline text-shadow';
		}

		// Removes any variables since these can't be previewed
		function removeVars(val) {
			return val.replace(/%(\w+)/g, '');
		}

		// Create block/inline element to use for preview
		if (typeof format == "string") {
			format = editor.formatter.get(format);
			if (!format) {
				return;
			}

			format = format[0];
		}

		// Format specific preview override
		// TODO: This should probably be further reduced by the previewStyles option
		if ('preview' in format) {
			previewStyles = format.preview;
			if (previewStyles === false) {
				return '';
			}
		}

		name = format.block || format.inline || 'span';

		items = parseSelector(format.selector);
		if (items.length) {
			if (!items[0].name) { // e.g. something like ul > .someClass was provided
				items[0].name = name;
			}
			name = format.selector;
			previewFrag = parsedSelectorToHtml(items);
		} else {
			previewFrag = parsedSelectorToHtml([name]);
		}

		previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;

		// Add format styles to preview element
		each(format.styles, function(value, name) {
			value = removeVars(value);

			if (value) {
				dom.setStyle(previewElm, name, value);
			}
		});

		// Add attributes to preview element
		each(format.attributes, function(value, name) {
			value = removeVars(value);

			if (value) {
				dom.setAttrib(previewElm, name, value);
			}
		});

		// Add classes to preview element
		each(format.classes, function(value) {
			value = removeVars(value);

			if (!dom.hasClass(previewElm, value)) {
				dom.addClass(previewElm, value);
			}
		});

		editor.fire('PreviewFormats');

		// Add the previewElm outside the visual area
		dom.setStyles(previewFrag, {position: 'absolute', left: -0xFFFF});
		editor.getBody().appendChild(previewFrag);

		// Get parent container font size so we can compute px values out of em/% for older IE:s
		parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
		parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;

		each(previewStyles.split(' '), function(name) {
			var value = dom.getStyle(previewElm, name, true);

			// If background is transparent then check if the body has a background color we can use
			if (name == 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
				value = dom.getStyle(editor.getBody(), name, true);

				// Ignore white since it's the default color, not the nicest fix
				// TODO: Fix this by detecting runtime style
				if (dom.toHex(value).toLowerCase() == '#ffffff') {
					return;
				}
			}

			if (name == 'color') {
				// Ignore black since it's the default color, not the nicest fix
				// TODO: Fix this by detecting runtime style
				if (dom.toHex(value).toLowerCase() == '#000000') {
					return;
				}
			}

			// Old IE won't calculate the font size so we need to do that manually
			if (name == 'font-size') {
				if (/em|%$/.test(value)) {
					if (parentFontSize === 0) {
						return;
					}

					// Convert font size from em/% to px
					value = parseFloat(value, 10) / (/%$/.test(value) ? 100 : 1);
					value = (value * parentFontSize) + 'px';
				}
			}

			if (name == "border" && value) {
				previewCss += 'padding:0 2px;';
			}

			previewCss += name + ':' + value + ';';
		});

		editor.fire('AfterPreviewFormats');

		//previewCss += 'line-height:normal';

		dom.remove(previewFrag);

		return previewCss;
	}

	return {
		getCssText: getCssText,
		parseSelector: parseSelector,
		selectorToHtml: selectorToHtml
	};
});
<|endoftext|>


<commit_before>describe("Basic functions", function() {
  beforeEach(function() {

  });

  describe("ctor", function() {
    it("should return the constructor of the object", function() {
      var O = function() { this.foo = 42; };

      expect(L.ctor([])).toBe(Array);
      expect(L.ctor({})).toBe(Object);
      expect(L.ctor(new O())).toBe(O);
    });
  });

  describe("cat", function() {
    it("should concatenate two arrays", function() {
      var a = [1,2,3];
      var b = [4,5,6];

      expect(L.cat(a,b)).toEqual([1,2,3,4,5,6]);
    });

    it("should not modify the originals", function() {
      var a = [1,2,3];
      var b = [4,5,6];
      var _ = L.cat(a,b);

      expect(a).toEqual([1,2,3]);
      expect(b).toEqual([4,5,6]);
    });

    it("should concatenate two items, as long as the first is an array", function() {
      var a = [1];
      var b = 2;

      expect(L.cat(a,b)).toEqual([1,2]);
    });

    it("should concatenate 3 or more arrays", function() {
      var a = [1,2,3];
      var b = [4,5,6];
      var c = [7,8,9];
      var d = [0,0,0];

      expect(L.cat(a,b,c)).toEqual([1,2,3,4,5,6,7,8,9]);
      expect(L.cat(a,b,c,d)).toEqual([1,2,3,4,5,6,7,8,9,0,0,0]);
    });

    it("should concatenate three or more items, as long as the first is an array", function() {
      var a = [1];
      var b = 2;
      var c = 3;
      var d = [4];

      expect(L.cat(a,b,c)).toEqual([1,2,3]);
      expect(L.cat(a,b,c,d)).toEqual([1,2,3,4]);
    });

    it("should throw an exception if the first arg is not an array", function() {
      expect(function() { L.cat(1,2); }).toThrow();
      expect(function() { L.cat(1,[2]); }).toThrow();

    });
  });

  describe("pour", function() {
    it("should pour two arrays", function() {
      var a = [1,2,3];
      var b = [4,5,6];

      expect(L.pour(a,b)).toEqual([1,2,3,4,5,6]);
    });

    it("should not modify the originals", function() {
      var a = [1,2,3];
      var b = [4,5,6];
      var _ = L.pour(a,b);

      expect(a).toEqual([1,2,3]);
      expect(b).toEqual([4,5,6]);
    });

    it("should pour two items, as long as the first is an array", function() {
      var a = [1];
      var b = 2;

      expect(L.pour(a,b)).toEqual([1,2]);
    });

    it("should pour 3 or more arrays", function() {
      var a = [1,2,3];
      var b = [4,5,6];
      var c = [7,8,9];
      var d = [0,0,0];

      expect(L.pour(a,b,c)).toEqual([1,2,3,4,5,6,7,8,9]);
      expect(L.pour(a,b,c,d)).toEqual([1,2,3,4,5,6,7,8,9,0,0,0]);
    });

    it("should pour three or more items, as long as the first is an array", function() {
      var a = [1];
      var b = 2;
      var c = 3;
      var d = [4];

      expect(L.pour(a,b,c)).toEqual([1,2,3]);
      expect(L.pour(a,b,c,d)).toEqual([1,2,3,4]);
    });

    it("should throw an exception if the first arg is not an array", function() {
      expect(function() { L.pour(1,2); }).toThrow();
      expect(function() { L.pour(1,[2]); }).toThrow();

    });
  });

  describe("into", function() {
    it("should into two arrays", function() {
      var a = [1,2,3];
      var b = [4,5,6];

      expect(L.into(a,b)).toEqual([1,2,3,4,5,6]);
    });

    it("should not modify the originals", function() {
      var a = [1,2,3];
      var b = [4,5,6];
      var _ = L.into(a,b);

      expect(a).toEqual([1,2,3]);
      expect(b).toEqual([4,5,6]);
    });

    it("should throw an exception if either arg is not an array", function() {
      expect(function() { L.into(1,2); }).toThrow();
      expect(function() { L.into(1,[2]); }).toThrow();
      expect(function() { L.into(); }).toThrow();
      expect(function() { L.into([]); }).toThrow();
    });
  });

  describe("butLast", function() {
    it("should give all but the last element in an array", function() {
      var a = [1,2,3];

      expect(L.butLast(a)).toEqual([1,2]);
      expect(L.butLast([])).toEqual([]);
    });

    it("should not modify the original", function() {
      var a = [1,2,3];
      var _ = L.butLast(a);

      expect(a).toEqual([1,2,3]);
    });

    it("should throw an exception if not given an array", function() {
      expect(function() { L.butLast(1); }).toThrow();
    });
  });

  describe("cons", function() {
    it("should insert the first arg into the array given as the second arg", function() {
      var a = [1,2,3];
      var b = [0];

      expect(L.cons(0, a)).toEqual([0,1,2,3]);
      expect(L.cons(b, a)).toEqual([[0],1,2,3]);
      expect(L.cons(0, [])).toEqual([0]);
    });

    it("should create a pair if the second is not an array", function() {
      expect(L.cons(1, 2)).toEqual([1,2]);
      expect(L.cons([1], 2)).toEqual([[1],2]);
    });

    it("should not modify the original", function() {
      var a = [1,2,3];
      var _ = L.cons(0, a);

      expect(a).toEqual([1,2,3]);
    });
  });

  describe("interpose", function() {
    it("should inject the first arg in-between the elements of the second array arg", function() {
      var a = [1,2,3];
      var b = [1,2];

      expect(L.interpose(0, a)).toEqual([1,0,2,0,3]);
      expect(L.interpose(0, [])).toEqual([]);
      expect(L.interpose(0, [1])).toEqual([1]);
      expect(L.interpose(0, b)).toEqual([1,0,2]);
    });

    it("should not modify the original", function() {
      var a = [1,2,3];
      var _ = L.interpose(0, a);

      expect(a).toEqual([1,2,3]);
    });

    it("should throw an exception if not given an array", function() {
      expect(function() { L.interpose(0,1); }).toThrow();
      expect(function() { L.interpose(0); }).toThrow();
    });
  });

  describe("interleave", function() {
    it("should weave the arrays together", function() {
      var a = [1,2,3];
      var b = [1,2];
      var c = ['a', 'b', 'c'];

      expect(L.interleave(a,b)).toEqual([1,1,2,2,3]);
      expect(L.interleave(a,a)).toEqual([1,1,2,2,3,3]);
      expect(L.interleave(c,a)).toEqual(['a',1,'b',2,'c',3]);
      expect(L.interleave(a,b,c)).toEqual([1,1,'a',2,2,'b',3,'c']);
    });

    it("should not modify the original", function() {
      var a = [1,2,3];
      var _ = L.interleave(a, a);

      expect(a).toEqual([1,2,3]);
    });

    it("should throw an exception if not given arrays", function() {
      expect(function() { L.interleave(0,1); }).toThrow();
      expect(function() { L.interleave(0); }).toThrow();
      expect(function() { L.interleave(); }).toThrow();
    });
  });

  describe("repeat", function() {
    it("should build an array of some size with the specified element in each slot", function() {
      expect(L.repeat(3,1)).toEqual([1,1,1]);
      expect(L.repeat(0)).toEqual([]);
      expect(L.repeat(0,1)).toEqual([]);
    });

    it("should throw an exception if not given a number as the first arg", function() {
      expect(function() { L.repeat(); }).toThrow();
    });
  });

  describe("second", function() {
    it("should return the second element of the array given, undefined if outside of the bounds", function() {
      var a = [1,2,3];

      expect(L.second(a)).toEqual(2);
      expect(L.second([1])).toEqual(undefined);
      expect(L.second([])).toEqual(undefined);
    });

    it("should throw an exception if not given a number as the first arg", function() {
      expect(function() { L.second(1); }).toThrow();
    });
  });

  describe("increasing / increasingOrEq / decreasing / decreasingOrEq", function() {
    it("should recognize if the arguments are monotonically increasing or decreasing", function() {
      var inc = [1,2,3];
      var incAlso = [1,2,3,3,4];
      var dec = [5,4,3,2,1];
      var decAlso = [5,4,3,3,2,1];

      expect(L.increasing.apply(null, inc)).toBeTruthy();
      expect(L.increasingOrEq.apply(null, incAlso)).toBeTruthy();
      expect(L.increasing.apply(null, dec)).toBeFalsy();
      expect(L.decreasing.apply(null, dec)).toBeTruthy();
      expect(L.decreasingOrEq.apply(null, decAlso)).toBeTruthy();
      expect(L.decreasing.apply(null, inc)).toBeFalsy();
    });
  });

  describe("meth", function() {
    it("should wrap a method as a function and allow the target as the first arg", function() {
      var str = L.meth(Array.prototype.toString);

      expect(str([1])).toEqual('1');
    });
  });

  describe("assoc", function() {
    it("should allow the placement of a value at any depth in an associative structure", function() {
      var obj = {a: {b: {c: 42, d: 108}}};
      var ary = ['a', ['b', ['c', 'd'], 'e']];

      expect(L.assoc(obj, ['a', 'b', 'c'], 9)).toEqual({a: {b: {c: 9, d: 108}}});
      expect(L.assoc(ary, [1, 1, 0], 9)).toEqual(['a', ['b', [9, 'd'], 'e']]);

      expect(L.assoc(obj, 'a', 9)).toEqual({a: 9});
      expect(L.assoc(ary, 1, 9)).toEqual(['a', 9]);
    });

    it("should not modify the original", function() {
      var obj = {a: {b: {c: 42, d: 108}}};
      var ary = ['a', ['b', ['c', 'd'], 'e']];
      var _   = L.assoc(obj, ['a', 'b', 'c'], 9);
      var __  = L.assoc(ary, [1, 1, 0], 9);

      expect(obj).toEqual({a: {b: {c: 42, d: 108}}});
      expect(ary).toEqual(['a', ['b', ['c', 'd'], 'e']]);
    });
  });

  describe("splitAt", function() {
    it("should bifurcate an array at a given index, returning an array of the parts", function() {
      var a = [1,2,3,4,5];

      expect(L.splitAt(2, a)).toEqual([[1,2], [3,4,5]]);
      expect(L.splitAt(0, a)).toEqual([[], [1,2,3,4,5]]);
      expect(L.splitAt(5, a)).toEqual([[1,2,3,4,5], []]);
      expect(L.splitAt(2, [])).toEqual([[], []]);
    });

    it("should not modify the original", function() {
      var a = [1,2,3,4,5];
      var _ = L.splitAt(2, a);

      expect(a).toEqual([1,2,3,4,5]);
    });

    it("should throw an exception if not given a number as the first arg or an array as the second", function() {
      expect(function() { L.splitAt('a', []); }).toThrow();
      expect(function() { L.splitAt(1); }).toThrow();
      expect(function() { L.splitAt(); }).toThrow();
    });
  });

  describe("takeSkipping", function() {
    it("should take every nth element in an array", function() {
      var a = _.range(10);

      expect(L.takeSkipping(2, a)).toEqual([0, 2, 4, 6, 8]);
    });

    it("should not modify the original", function() {
      var a = [1,2,3];
      var _ = L.takeSkipping(2, a);

      expect(a).toEqual([1,2,3]);
    });

    it("should throw an exception if not given a number as the first arg or an array as the second", function() {
      expect(function() { L.takeSkipping('a', []); }).toThrow();
      expect(function() { L.takeSkipping(1); }).toThrow();
      expect(function() { L.takeSkipping(); }).toThrow();
    });
  });
});
<commit_msg>ctor of null is null<commit_after>describe("Basic functions", function() {
  beforeEach(function() {

  });

  describe("ctor", function() {
    it("should return the constructor of the object", function() {
      var O = function() { this.foo = 42; };

      expect(L.ctor([])).toBe(Array);
      expect(L.ctor({})).toBe(Object);
      expect(L.ctor(new O())).toBe(O);
      expect(L.ctor(null)).toBe(null);
    });
  });

  describe("cat", function() {
    it("should concatenate two arrays", function() {
      var a = [1,2,3];
      var b = [4,5,6];

      expect(L.cat(a,b)).toEqual([1,2,3,4,5,6]);
    });

    it("should not modify the originals", function() {
      var a = [1,2,3];
      var b = [4,5,6];
      var _ = L.cat(a,b);

      expect(a).toEqual([1,2,3]);
      expect(b).toEqual([4,5,6]);
    });

    it("should concatenate two items, as long as the first is an array", function() {
      var a = [1];
      var b = 2;

      expect(L.cat(a,b)).toEqual([1,2]);
    });

    it("should concatenate 3 or more arrays", function() {
      var a = [1,2,3];
      var b = [4,5,6];
      var c = [7,8,9];
      var d = [0,0,0];

      expect(L.cat(a,b,c)).toEqual([1,2,3,4,5,6,7,8,9]);
      expect(L.cat(a,b,c,d)).toEqual([1,2,3,4,5,6,7,8,9,0,0,0]);
    });

    it("should concatenate three or more items, as long as the first is an array", function() {
      var a = [1];
      var b = 2;
      var c = 3;
      var d = [4];

      expect(L.cat(a,b,c)).toEqual([1,2,3]);
      expect(L.cat(a,b,c,d)).toEqual([1,2,3,4]);
    });

    it("should throw an exception if the first arg is not an array", function() {
      expect(function() { L.cat(1,2); }).toThrow();
      expect(function() { L.cat(1,[2]); }).toThrow();

    });
  });

  describe("pour", function() {
    it("should pour two arrays", function() {
      var a = [1,2,3];
      var b = [4,5,6];

      expect(L.pour(a,b)).toEqual([1,2,3,4,5,6]);
    });

    it("should not modify the originals", function() {
      var a = [1,2,3];
      var b = [4,5,6];
      var _ = L.pour(a,b);

      expect(a).toEqual([1,2,3]);
      expect(b).toEqual([4,5,6]);
    });

    it("should pour two items, as long as the first is an array", function() {
      var a = [1];
      var b = 2;

      expect(L.pour(a,b)).toEqual([1,2]);
    });

    it("should pour 3 or more arrays", function() {
      var a = [1,2,3];
      var b = [4,5,6];
      var c = [7,8,9];
      var d = [0,0,0];

      expect(L.pour(a,b,c)).toEqual([1,2,3,4,5,6,7,8,9]);
      expect(L.pour(a,b,c,d)).toEqual([1,2,3,4,5,6,7,8,9,0,0,0]);
    });

    it("should pour three or more items, as long as the first is an array", function() {
      var a = [1];
      var b = 2;
      var c = 3;
      var d = [4];

      expect(L.pour(a,b,c)).toEqual([1,2,3]);
      expect(L.pour(a,b,c,d)).toEqual([1,2,3,4]);
    });

    it("should throw an exception if the first arg is not an array", function() {
      expect(function() { L.pour(1,2); }).toThrow();
      expect(function() { L.pour(1,[2]); }).toThrow();

    });
  });

  describe("into", function() {
    it("should into two arrays", function() {
      var a = [1,2,3];
      var b = [4,5,6];

      expect(L.into(a,b)).toEqual([1,2,3,4,5,6]);
    });

    it("should not modify the originals", function() {
      var a = [1,2,3];
      var b = [4,5,6];
      var _ = L.into(a,b);

      expect(a).toEqual([1,2,3]);
      expect(b).toEqual([4,5,6]);
    });

    it("should throw an exception if either arg is not an array", function() {
      expect(function() { L.into(1,2); }).toThrow();
      expect(function() { L.into(1,[2]); }).toThrow();
      expect(function() { L.into(); }).toThrow();
      expect(function() { L.into([]); }).toThrow();
    });
  });

  describe("butLast", function() {
    it("should give all but the last element in an array", function() {
      var a = [1,2,3];

      expect(L.butLast(a)).toEqual([1,2]);
      expect(L.butLast([])).toEqual([]);
    });

    it("should not modify the original", function() {
      var a = [1,2,3];
      var _ = L.butLast(a);

      expect(a).toEqual([1,2,3]);
    });

    it("should throw an exception if not given an array", function() {
      expect(function() { L.butLast(1); }).toThrow();
    });
  });

  describe("cons", function() {
    it("should insert the first arg into the array given as the second arg", function() {
      var a = [1,2,3];
      var b = [0];

      expect(L.cons(0, a)).toEqual([0,1,2,3]);
      expect(L.cons(b, a)).toEqual([[0],1,2,3]);
      expect(L.cons(0, [])).toEqual([0]);
    });

    it("should create a pair if the second is not an array", function() {
      expect(L.cons(1, 2)).toEqual([1,2]);
      expect(L.cons([1], 2)).toEqual([[1],2]);
    });

    it("should not modify the original", function() {
      var a = [1,2,3];
      var _ = L.cons(0, a);

      expect(a).toEqual([1,2,3]);
    });
  });

  describe("interpose", function() {
    it("should inject the first arg in-between the elements of the second array arg", function() {
      var a = [1,2,3];
      var b = [1,2];

      expect(L.interpose(0, a)).toEqual([1,0,2,0,3]);
      expect(L.interpose(0, [])).toEqual([]);
      expect(L.interpose(0, [1])).toEqual([1]);
      expect(L.interpose(0, b)).toEqual([1,0,2]);
    });

    it("should not modify the original", function() {
      var a = [1,2,3];
      var _ = L.interpose(0, a);

      expect(a).toEqual([1,2,3]);
    });

    it("should throw an exception if not given an array", function() {
      expect(function() { L.interpose(0,1); }).toThrow();
      expect(function() { L.interpose(0); }).toThrow();
    });
  });

  describe("interleave", function() {
    it("should weave the arrays together", function() {
      var a = [1,2,3];
      var b = [1,2];
      var c = ['a', 'b', 'c'];

      expect(L.interleave(a,b)).toEqual([1,1,2,2,3]);
      expect(L.interleave(a,a)).toEqual([1,1,2,2,3,3]);
      expect(L.interleave(c,a)).toEqual(['a',1,'b',2,'c',3]);
      expect(L.interleave(a,b,c)).toEqual([1,1,'a',2,2,'b',3,'c']);
    });

    it("should not modify the original", function() {
      var a = [1,2,3];
      var _ = L.interleave(a, a);

      expect(a).toEqual([1,2,3]);
    });

    it("should throw an exception if not given arrays", function() {
      expect(function() { L.interleave(0,1); }).toThrow();
      expect(function() { L.interleave(0); }).toThrow();
      expect(function() { L.interleave(); }).toThrow();
    });
  });

  describe("repeat", function() {
    it("should build an array of some size with the specified element in each slot", function() {
      expect(L.repeat(3,1)).toEqual([1,1,1]);
      expect(L.repeat(0)).toEqual([]);
      expect(L.repeat(0,1)).toEqual([]);
    });

    it("should throw an exception if not given a number as the first arg", function() {
      expect(function() { L.repeat(); }).toThrow();
    });
  });

  describe("second", function() {
    it("should return the second element of the array given, undefined if outside of the bounds", function() {
      var a = [1,2,3];

      expect(L.second(a)).toEqual(2);
      expect(L.second([1])).toEqual(undefined);
      expect(L.second([])).toEqual(undefined);
    });

    it("should throw an exception if not given a number as the first arg", function() {
      expect(function() { L.second(1); }).toThrow();
    });
  });

  describe("increasing / increasingOrEq / decreasing / decreasingOrEq", function() {
    it("should recognize if the arguments are monotonically increasing or decreasing", function() {
      var inc = [1,2,3];
      var incAlso = [1,2,3,3,4];
      var dec = [5,4,3,2,1];
      var decAlso = [5,4,3,3,2,1];

      expect(L.increasing.apply(null, inc)).toBeTruthy();
      expect(L.increasingOrEq.apply(null, incAlso)).toBeTruthy();
      expect(L.increasing.apply(null, dec)).toBeFalsy();
      expect(L.decreasing.apply(null, dec)).toBeTruthy();
      expect(L.decreasingOrEq.apply(null, decAlso)).toBeTruthy();
      expect(L.decreasing.apply(null, inc)).toBeFalsy();
    });
  });

  describe("meth", function() {
    it("should wrap a method as a function and allow the target as the first arg", function() {
      var str = L.meth(Array.prototype.toString);

      expect(str([1])).toEqual('1');
    });
  });

  describe("assoc", function() {
    it("should allow the placement of a value at any depth in an associative structure", function() {
      var obj = {a: {b: {c: 42, d: 108}}};
      var ary = ['a', ['b', ['c', 'd'], 'e']];

      expect(L.assoc(obj, ['a', 'b', 'c'], 9)).toEqual({a: {b: {c: 9, d: 108}}});
      expect(L.assoc(ary, [1, 1, 0], 9)).toEqual(['a', ['b', [9, 'd'], 'e']]);

      expect(L.assoc(obj, 'a', 9)).toEqual({a: 9});
      expect(L.assoc(ary, 1, 9)).toEqual(['a', 9]);
    });

    it("should not modify the original", function() {
      var obj = {a: {b: {c: 42, d: 108}}};
      var ary = ['a', ['b', ['c', 'd'], 'e']];
      var _   = L.assoc(obj, ['a', 'b', 'c'], 9);
      var __  = L.assoc(ary, [1, 1, 0], 9);

      expect(obj).toEqual({a: {b: {c: 42, d: 108}}});
      expect(ary).toEqual(['a', ['b', ['c', 'd'], 'e']]);
    });
  });

  describe("splitAt", function() {
    it("should bifurcate an array at a given index, returning an array of the parts", function() {
      var a = [1,2,3,4,5];

      expect(L.splitAt(2, a)).toEqual([[1,2], [3,4,5]]);
      expect(L.splitAt(0, a)).toEqual([[], [1,2,3,4,5]]);
      expect(L.splitAt(5, a)).toEqual([[1,2,3,4,5], []]);
      expect(L.splitAt(2, [])).toEqual([[], []]);
    });

    it("should not modify the original", function() {
      var a = [1,2,3,4,5];
      var _ = L.splitAt(2, a);

      expect(a).toEqual([1,2,3,4,5]);
    });

    it("should throw an exception if not given a number as the first arg or an array as the second", function() {
      expect(function() { L.splitAt('a', []); }).toThrow();
      expect(function() { L.splitAt(1); }).toThrow();
      expect(function() { L.splitAt(); }).toThrow();
    });
  });

  describe("takeSkipping", function() {
    it("should take every nth element in an array", function() {
      var a = _.range(10);

      expect(L.takeSkipping(2, a)).toEqual([0, 2, 4, 6, 8]);
    });

    it("should not modify the original", function() {
      var a = [1,2,3];
      var _ = L.takeSkipping(2, a);

      expect(a).toEqual([1,2,3]);
    });

    it("should throw an exception if not given a number as the first arg or an array as the second", function() {
      expect(function() { L.takeSkipping('a', []); }).toThrow();
      expect(function() { L.takeSkipping(1); }).toThrow();
      expect(function() { L.takeSkipping(); }).toThrow();
    });
  });
});
<|endoftext|>


<commit_before>var tape = require("tape"),
    jsdom = require("jsdom"),
    d3_selection = require("d3-selection"),
    d3_component = require("../"),
    d3 = Object.assign(d3_selection, d3_component);

var paragraphDatum,
    paragraph = d3.component("p")
      .render(function (d){
        paragraphDatum = d;
        d3.select(this).text(d);
      });

var createIndex,
    renderIndex,
    destroyIndex,
    createNodes,
    renderNodes,
    destroyNodes,
    argsTester = d3.component("div")
      .create(function (d, i, nodes){
        createIndex = i;
        createNodes = nodes;
      })
      .render(function (d, i, nodes){
        renderIndex = i;
        renderNodes = nodes;
      })
      .destroy(function (d, i, nodes){
        destroyIndex = i;
        destroyNodes = nodes;
      });

tape("A component should render a single instance.", function(test) {
  var div = d3.select(jsdom.jsdom().body).append("div");
  div.call(paragraph, "Hello Component");
  test.equal(div.html(), "
Hello Component
");
  test.end();
});

tape("A component should render multiple instances.", function(test) {
  var div = d3.select(jsdom.jsdom().body).append("div");

  // Enter
  div.call(paragraph, [ "foo", "bar" ]);
  test.equal(div.html(), "
foo

bar
");

  // Update + Enter
  div.call(paragraph, [ "fooz", "barz", "baz" ])
  test.equal(div.html(), "
fooz

barz

baz
");

  // Update + Exit
  div.call(paragraph, [ "fooz", "baz" ])
  test.equal(div.html(), "
fooz

baz
");

  // Exit
  div.call(paragraph, []);
  test.equal(div.html(), "");

  test.end();
});

tape("A component should be passed undefined as datum when data not specified.", function(test) {
  var div = d3.select(jsdom.jsdom().body).append("div");
  div.call(paragraph);
  test.equal(div.html(), '

');
  test.equal(typeof paragraphDatum, "undefined");
  test.end();
});

tape("A component should be passed the index and nodes in callbacks.", function(test) {
  var div = d3.select(jsdom.jsdom().body).append("div");

  createIndex = renderIndex = destroyIndex = null;
  createNodes = renderNodes = destroyNodes = null;
  div.call(argsTester);
  test.equal(createIndex, 0)
  test.equal(renderIndex, 0)
  test.equal(destroyIndex, null);
  test.equal(createNodes.length, 1);
  test.equal(renderNodes.length, 1)
  test.equal(destroyNodes, null);

  createIndex = renderIndex = destroyIndex = null;
  createNodes = renderNodes = destroyNodes = null;
  div.call(argsTester, ["a", "b"]);
  test.equal(createIndex, 1)
  test.equal(renderIndex, 1)
  test.equal(destroyIndex, null);
  test.equal(createNodes.length, 2);
  test.equal(renderNodes.length, 2)
  test.equal(destroyNodes, null);

  createIndex = renderIndex = destroyIndex = null;
  createNodes = renderNodes = destroyNodes = null;
  div.call(argsTester, ["a", "b"]);
  test.equal(createIndex, null)
  test.equal(renderIndex, 1)
  test.equal(destroyIndex, null);
  test.equal(createNodes, null);
  test.equal(renderNodes.length, 2)
  test.equal(destroyNodes, null);

  createIndex = renderIndex = destroyIndex = null;
  createNodes = renderNodes = destroyNodes = null;
  div.call(argsTester, ["a"]);
  test.equal(createIndex, null)
  test.equal(renderIndex, 0)
  test.equal(destroyIndex, 1);
  test.equal(createNodes, null);
  test.equal(renderNodes.length, 1)
  test.equal(destroyNodes.length, 2);

  createIndex = renderIndex = destroyIndex = null;
  createNodes = renderNodes = destroyNodes = null;
  div.call(argsTester, []);
  test.equal(createIndex, null)
  test.equal(renderIndex, null)
  test.equal(destroyIndex, 0);
  test.equal(createNodes, null);
  test.equal(renderNodes, null);
  test.equal(destroyNodes.length, 1);

  test.end();
});

tape("A component should return its merged Enter + Update selection.", function(test) {
  var div = d3.select(jsdom.jsdom().body).append("div");
  test.equal(paragraph(div, "Text").text(), "Text"); // Enter
  test.equal(paragraph(div, "Text").text(), "Text"); // Update
  test.end();
});
<commit_msg>Add failing test for accepting DOM node<commit_after>var tape = require("tape"),
    jsdom = require("jsdom"),
    d3_selection = require("d3-selection"),
    d3_component = require("../"),
    d3 = Object.assign(d3_selection, d3_component);

var paragraphDatum,
    paragraph = d3.component("p")
      .render(function (d){
        paragraphDatum = d;
        d3.select(this).text(d);
      });

var createIndex,
    renderIndex,
    destroyIndex,
    createNodes,
    renderNodes,
    destroyNodes,
    argsTester = d3.component("div")
      .create(function (d, i, nodes){
        createIndex = i;
        createNodes = nodes;
      })
      .render(function (d, i, nodes){
        renderIndex = i;
        renderNodes = nodes;
      })
      .destroy(function (d, i, nodes){
        destroyIndex = i;
        destroyNodes = nodes;
      });

tape("A component should render a single instance.", function(test) {
  var div = d3.select(jsdom.jsdom().body).append("div");
  div.call(paragraph, "Hello Component");
  test.equal(div.html(), "
Hello Component
");
  test.end();
});

tape("A component should accept a DOM node in place of a selection.", function(test) {
  var div = d3.select(jsdom.jsdom().body).append("div");
  paragraph(div.node(), "Hello Component");
  test.equal(div.html(), "
Hello Component
");
  test.end();
});

tape("A component should render multiple instances.", function(test) {
  var div = d3.select(jsdom.jsdom().body).append("div");

  // Enter
  div.call(paragraph, [ "foo", "bar" ]);
  test.equal(div.html(), "
foo

bar
");

  // Update + Enter
  div.call(paragraph, [ "fooz", "barz", "baz" ])
  test.equal(div.html(), "
fooz

barz

baz
");

  // Update + Exit
  div.call(paragraph, [ "fooz", "baz" ])
  test.equal(div.html(), "
fooz

baz
");

  // Exit
  div.call(paragraph, []);
  test.equal(div.html(), "");

  test.end();
});

tape("A component should be passed undefined as datum when data not specified.", function(test) {
  var div = d3.select(jsdom.jsdom().body).append("div");
  div.call(paragraph);
  test.equal(div.html(), '

');
  test.equal(typeof paragraphDatum, "undefined");
  test.end();
});

tape("A component should be passed the index and nodes in callbacks.", function(test) {
  var div = d3.select(jsdom.jsdom().body).append("div");

  createIndex = renderIndex = destroyIndex = null;
  createNodes = renderNodes = destroyNodes = null;
  div.call(argsTester);
  test.equal(createIndex, 0)
  test.equal(renderIndex, 0)
  test.equal(destroyIndex, null);
  test.equal(createNodes.length, 1);
  test.equal(renderNodes.length, 1)
  test.equal(destroyNodes, null);

  createIndex = renderIndex = destroyIndex = null;
  createNodes = renderNodes = destroyNodes = null;
  div.call(argsTester, ["a", "b"]);
  test.equal(createIndex, 1)
  test.equal(renderIndex, 1)
  test.equal(destroyIndex, null);
  test.equal(createNodes.length, 2);
  test.equal(renderNodes.length, 2)
  test.equal(destroyNodes, null);

  createIndex = renderIndex = destroyIndex = null;
  createNodes = renderNodes = destroyNodes = null;
  div.call(argsTester, ["a", "b"]);
  test.equal(createIndex, null)
  test.equal(renderIndex, 1)
  test.equal(destroyIndex, null);
  test.equal(createNodes, null);
  test.equal(renderNodes.length, 2)
  test.equal(destroyNodes, null);

  createIndex = renderIndex = destroyIndex = null;
  createNodes = renderNodes = destroyNodes = null;
  div.call(argsTester, ["a"]);
  test.equal(createIndex, null)
  test.equal(renderIndex, 0)
  test.equal(destroyIndex, 1);
  test.equal(createNodes, null);
  test.equal(renderNodes.length, 1)
  test.equal(destroyNodes.length, 2);

  createIndex = renderIndex = destroyIndex = null;
  createNodes = renderNodes = destroyNodes = null;
  div.call(argsTester, []);
  test.equal(createIndex, null)
  test.equal(renderIndex, null)
  test.equal(destroyIndex, 0);
  test.equal(createNodes, null);
  test.equal(renderNodes, null);
  test.equal(destroyNodes.length, 1);

  test.end();
});

tape("A component should return its merged Enter + Update selection.", function(test) {
  var div = d3.select(jsdom.jsdom().body).append("div");
  test.equal(paragraph(div, "Text").text(), "Text"); // Enter
  test.equal(paragraph(div, "Text").text(), "Text"); // Update
  test.end();
});
<|endoftext|>