<commit_before>/* Copyright (c) 2012-2013 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
define(function(require, exports, module) {
"use strict";

	console.log("Loading core.ui.js ...");

	var TSCORE = require("tscore");

    var editor = undefined;
	var formatter = undefined;

	var fileContent = undefined;
	var fileType = undefined;

	var showAlertDialog = function(message, title) {
	    if (!title) { title = 'Alert'; }
	    if (!message) { message = 'No Message to Display.'; }

	    var alertModal =
	      $('

' +
	          '
' +
	            '×' +
	            '

' +
	          '
' +
              '

' +
	          '
' +
	            '<button id="okButton" class="btn btn-primary">Ok</button>' +
	          '
' +
	        '

');

        alertModal.find('h4').text(title);
        alertModal.find('.modal-body').append(message);
	    alertModal.find('#okButton').click(function(event) {
	      alertModal.modal('hide');
	    });

	    alertModal.modal('show');
	};

	var showConfirmDialog = function(title, message, callback) {
	    if (!title) { title = 'Confirm'; }
	    if (!message) { message = 'No Message to Display.'; }

	    var confirmModal =
	      $('

' +
	          '
' +
	            '×' +
	            '

' +
	          '
' +
	          '

' +
	          '
' +
	            '<button class="btn" data-dismiss="modal">Cancel</button>' +
	            '<button id="okButton" class="btn btn-primary">Ok</button>' +
	          '
' +
	        '

');

        confirmModal.find('h4').text(title);
	    confirmModal.find('.modal-body').text(message);
	    confirmModal.find('#okButton').click(function(event) {
	      callback();
	      confirmModal.modal('hide');
	    });

	    confirmModal.modal('show');
	};

    var showFileCreateDialog = function() {
        fileContent = TSCORE.Config.getNewTextFileContent(); // Default new file in text file
        fileType = "txt";

        $('#newFileNameTags').select2('data', null);
		$("#newFileNameTags").select2({
	        //minimumInputLength: 1,
	        multiple: true,
			tags: TSCORE.Config.getAllTags(),
		});

		$("#newFileName").val("");
		$("#tagWithCurrentDate").prop('checked', false);

        $( '#dialogFileCreate' ).modal({show: true});
        $( '#txtFileTypeButton' ).button('toggle');

		$('#dialogFileCreate').on('shown', function () {
		    $('#newFileName').focus();
		});
    };

    var showFileRenameDialog = function() {
        $( "#renamedFileName" ).val(TSCORE.TagUtils.extractFileName(TSCORE.selectedFiles[0]));
        $( '#dialogFileRename' ).modal({show: true});
    };

    var showTagEditDialog = function() {
        $( "#newTagName" ).val(TSCORE.selectedTag);
        $( '#dialogEditTag' ).modal({show: true});
    };

	var initUI = function() {

	    $( "#openAboutBox" ).tooltip();

	    $( "#toggleLeftPanel" ).click(function() {
			TSCORE.toggleLeftPanel();
	    });

	    $( "#txtFileTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        fileContent = TSCORE.Config.getNewTextFileContent();
	        fileType = "txt";

	    });

	    $( "#htmlFileTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        fileContent = TSCORE.Config.getNewHTMLFileContent();
			fileType = "html";
	    });

	    $( "#mdFileTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        fileContent = TSCORE.Config.getNewMDFileContent();
			fileType = "md";
	    });

	    $( '#fileCreateConfirmButton' ).click(function() {
	    	var fileTags = "";
	    	var rawTags = $( "#newFileNameTags" ).val().split(",");

		    rawTags.forEach(function (value, index) {
	            if(index == 0) {
	                fileTags = value;
	            } else {
	                fileTags = fileTags + TSCORE.TagUtils.tagDelimiter + value;
	            }
	        });

			if($("#tagWithCurrentDate").prop("checked")) {
	            if(fileTags.length < 1) {
	                fileTags = TSCORE.TagUtils.formatDateTime4Tag(new Date());
	            } else {
	                fileTags = fileTags + TSCORE.TagUtils.tagDelimiter + TSCORE.TagUtils.formatDateTime4Tag(new Date());
	            }
			}

			if(fileTags.length > 0) {
				fileTags = TSCORE.TagUtils.beginTagContainer + fileTags + TSCORE.TagUtils.endTagContainer;
			}

			var fileName = TSCORE.currentPath+TSCORE.TagUtils.DIR_SEPARATOR+$( "#newFileName" ).val()+fileTags+"."+fileType;

            TSCORE.IO.saveTextFile(fileName,fileContent);
            TSCORE.IO.listDirectory(TSCORE.currentPath);

        });

        $( '#renameFileButton' ).click(function() {
            var bValid = true;
    //        bValid = bValid && checkLength( $( "#renamedFileName" ).val(), "filename", 3, 200 );
    //        bValid = bValid && checkRegexp( renamedFileName, /^[a-z]([0-9a-z_.])+$/i, "Filename may consist of a-z, 0-9, underscores, begin with a letter." );
            if ( bValid ) {
                var containingDir = TSCORE.TagUtils.extractContainingDirectoryPath(TSCORE.selectedFiles[0]);
                TSCORE.IO.renameFile(
                        TSCORE.selectedFiles[0],
                        containingDir+TSCORE.TagUtils.DIR_SEPARATOR+$( "#renamedFileName" ).val()
                    );
            }
        });

        // Edit Tag Dialog

	    $( "#plainTagTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        TSCORE.selectedTag, $( "#newTagName" ).datepicker( "destroy" ).val("");
	    });

	    $( "#dateTagTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        TSCORE.selectedTag, $( "#newTagName" ).datepicker({
	            showWeek: true,
	            firstDay: 1,
	            dateFormat: "yymmdd"
	        });
	    });

	    $( "#currencyTagTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        TSCORE.selectedTag, $( "#newTagName" ).datepicker( "destroy" ).val("XEUR");
	    });

        $( "#editTagButton" ).click(function() {
            TSCORE.TagUtils.renameTag(TSCORE.selectedFiles[0], TSCORE.selectedTag, $( "#newTagName" ).val());
            TSCORE.startTime = new Date().getTime();
            TSCORE.IO.listDirectory(TSCORE.currentPath);
        });

	    // End Edit Tag Dialog

        $( "#startNewInstanceBack" ).click(function() {
            window.open(window.location.href,'_blank');
        });

	    $( "#aboutDialogBack" ).click(function() {
            $("#aboutIframe").attr("src","about.html");
        });

        // Open About Dialog
        $( "#openAboutBox" ).click(function() {
           $('#dialogAbout').modal('show');
        });

        // Open Options Dialog
        $( "#openOptions" ).click(function() {
            require(['tsoptions'], function () {
                $('#dialogOptions').modal('show');
            });
        });

	    // Advanced Settings
        $( "#advancedSettings" ).click(function() {
            $('#dialogOptions').modal('hide');
            require(['jsoneditor'], function () {
                editor = new JSONEditor(document.getElementById("settingsEditor"));
                formatter = new JSONFormatter(document.getElementById("settingsPlainJSON"));
                $("#settingsPlainJSON").hide();
                editor.set(TSCORE.Config.Settings);
                $('#dialogAdvancedSetting').modal('show');
            });
        });

        $( "#editorButton" ).click(function() {
            if($("#settingsEditor").is(":hidden") ) {
                $("#settingsPlainJSON").hide();
                $("#settingsEditor").show();
                editor.set(formatter.get());
            }
        });

        $( "#importExportButton" ).click(function() {
            if($("#settingsPlainJSON").is(":hidden") ) {
                formatter.set(editor.get());
                $("#settingsPlainJSON").show();
                $("#settingsEditor").hide();
            }
        });

        $( "#defaultSettingsButton" ).click(function() {
            TSCORE.showConfirmDialog(
                "Warning",
                "Are you sure you want to restore the default application settings?\n"+
                "All manually made changes such as tags and taggroups will be lost.",
                function() {
                    TSCORE.Config.loadDefaultSettings();
                }
            );
        });

        $( "#saveSettingsButton" ).click(function() {
            TSCORE.Config.Settings = editor.get();
            TSCORE.Config.saveSettings();
            TSCORE.reloadUI();
        });
        // End Advanced Settings

	    // File Menu
        $( "#fileMenuAddTag" ).click( function() {
            TSCORE.showAddTagsDialog();
        });

        $( "#fileMenuOpenFile" ).click( function() {
            TSCORE.FileOpener.openFile(TSCORE.selectedFiles[0]);
        });

        $( "#fileMenuOpenDirectory" ).click( function() {
            TSCORE.IO.openDirectory(TSCORE.currentPath);
        });

        $( "#fileMenuRenameFile" ).click( function() {
            TSCORE.showFileRenameDialog();
        });

        $( "#fileMenuDeleteFile" ).click( function() {
            console.log("Deleting file...");
            TSCORE.showConfirmDialog(
                "Delete File(s)",
                "These items will be permanently deleted and cannot be recovered. Are you sure?",
                function() {
                    TSCORE.IO.deleteElement(TSCORE.selectedFiles[0]);
                    TSCORE.IO.listDirectory(TSCORE.currentPath);
                }
            );
        });
        // End File Menu

		$('#switchLang').click(function(e) {
			$.i18n.setLng('de', function(t) {
				$('[data-i18n]').i18n();
			});
	    });

		$('#showLocations').click(function(e) {
			showLocationsPanel();
			console.log("Show Directories");
	    });

		$('#showTagGroups').click(function(e) {
			showTagsPanel();
			console.log("Show Tags");
	    });

	    // Hide the taggroups by default
	    $('#tagGroupsContent').hide();

	    // Hide drop downs by click and drag
	    $(document).click(function () {
			TSCORE.hideAllDropDownMenus();
	    });

	/*    $(document).drag(function () {
			TSCORE.hideAllDropDownMenus();
	    });*/

	};

	var showContextMenu = function(menuId, sourceObject) {
        var leftPos = sourceObject.offset().left;
        var topPos = sourceObject.offset().top+sourceObject.height()+5;
        if (sourceObject.offset().top+sourceObject.height()+$(menuId).height() > window.innerHeight) {
	        topPos = window.innerHeight-$("#tagMenu").height();
	        leftPos = sourceObject.offset().left+15;
        }

        if (sourceObject.offset().left+sourceObject.width()+$(menuId).width() > window.innerWidth) {
	        leftPos = window.innerWidth-$("#tagMenu").width();
        }

        $(menuId).css({
            display: "block",
            left:  leftPos,
            top: topPos
        });
	};

	var hideAllDropDownMenus = function() {
        $('#tagGroupMenu').hide();
        $('#tagTreeMenu').hide();
        $('#directoryMenu').hide();
        $('#tagMenu').hide();
        $('#fileMenu').hide();
	};

    var showLocationsPanel = function() {
		$('#tagGroupsContent').hide();
		$('#locationContent').show();
		$('#showLocations').addClass("active");
		$('#showTagGroups').removeClass("active");
    };

    var showTagsPanel = function() {
		$('#locationContent').hide();
		$('#tagGroupsContent').show();
		$('#showLocations').removeClass("active");
		$('#showTagGroups').addClass("active");
    };

    // Public API definition
    exports.showContextMenu			= showContextMenu;
	exports.initUI 					= initUI;
	exports.showAlertDialog 		= showAlertDialog;
	exports.showConfirmDialog 		= showConfirmDialog;
	exports.showFileRenameDialog    = showFileRenameDialog;
	exports.showFileCreateDialog    = showFileCreateDialog;
    exports.showTagEditDialog       = showTagEditDialog;
    exports.showLocationsPanel      = showLocationsPanel;
    exports.showTagsPanel       	= showTagsPanel;
	exports.hideAllDropDownMenus	= hideAllDropDownMenus;

});<commit_msg>Dialog html code moved to the inde.html<commit_after>/* Copyright (c) 2012-2013 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
define(function(require, exports, module) {
"use strict";

	console.log("Loading core.ui.js ...");

	var TSCORE = require("tscore");

    var editor = undefined;
	var formatter = undefined;

	var fileContent = undefined;
	var fileType = undefined;

	var showAlertDialog = function(message, title) {
	    if (!title) { title = 'Alert'; }
	    if (!message) { message = 'No Message to Display.'; }

	    var alertModal = $('#alertDialog');
        alertModal.find('h4').text(title);
        alertModal.find('.modal-body').append(message);
	    alertModal.find('#okButton').click(function(event) {
	      alertModal.modal('hide');
	    });

	    alertModal.modal('show');
	};

	var showConfirmDialog = function(title, message, callback) {
	    if (!title) { title = 'Confirm'; }
	    if (!message) { message = 'No Message to Display.'; }

	    var confirmModal = $('#confirmDialog');
        confirmModal.find('h4').text(title);
	    confirmModal.find('.modal-body').text(message);
	    confirmModal.find('#okButton').click(function(event) {
	      callback();
	      confirmModal.modal('hide');
	    });

	    confirmModal.modal('show');
	};

    var showFileCreateDialog = function() {
        fileContent = TSCORE.Config.getNewTextFileContent(); // Default new file in text file
        fileType = "txt";

        $('#newFileNameTags').select2('data', null);
		$("#newFileNameTags").select2({
	        //minimumInputLength: 1,
	        multiple: true,
			tags: TSCORE.Config.getAllTags(),
		});

		$("#newFileName").val("");
		$("#tagWithCurrentDate").prop('checked', false);

        $( '#dialogFileCreate' ).modal({show: true});
        $( '#txtFileTypeButton' ).button('toggle');

		$('#dialogFileCreate').on('shown', function () {
		    $('#newFileName').focus();
		});
    };

    var showFileRenameDialog = function() {
        $( "#renamedFileName" ).val(TSCORE.TagUtils.extractFileName(TSCORE.selectedFiles[0]));
        $( '#dialogFileRename' ).modal({show: true});
    };

    var showTagEditDialog = function() {
        $( "#newTagName" ).val(TSCORE.selectedTag);
        $( '#dialogEditTag' ).modal({show: true});
    };

	var initUI = function() {

	    $( "#toggleLeftPanel" ).click(function() {
			TSCORE.toggleLeftPanel();
	    });

	    $( "#txtFileTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        fileContent = TSCORE.Config.getNewTextFileContent();
	        fileType = "txt";

	    });

	    $( "#htmlFileTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        fileContent = TSCORE.Config.getNewHTMLFileContent();
			fileType = "html";
	    });

	    $( "#mdFileTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        fileContent = TSCORE.Config.getNewMDFileContent();
			fileType = "md";
	    });

	    $( '#fileCreateConfirmButton' ).click(function() {
	    	var fileTags = "";
	    	var rawTags = $( "#newFileNameTags" ).val().split(",");

		    rawTags.forEach(function (value, index) {
	            if(index == 0) {
	                fileTags = value;
	            } else {
	                fileTags = fileTags + TSCORE.TagUtils.tagDelimiter + value;
	            }
	        });

			if($("#tagWithCurrentDate").prop("checked")) {
	            if(fileTags.length < 1) {
	                fileTags = TSCORE.TagUtils.formatDateTime4Tag(new Date());
	            } else {
	                fileTags = fileTags + TSCORE.TagUtils.tagDelimiter + TSCORE.TagUtils.formatDateTime4Tag(new Date());
	            }
			}

			if(fileTags.length > 0) {
				fileTags = TSCORE.TagUtils.beginTagContainer + fileTags + TSCORE.TagUtils.endTagContainer;
			}

			var fileName = TSCORE.currentPath+TSCORE.TagUtils.DIR_SEPARATOR+$( "#newFileName" ).val()+fileTags+"."+fileType;

            TSCORE.IO.saveTextFile(fileName,fileContent);
            TSCORE.IO.listDirectory(TSCORE.currentPath);

        });

        $( '#renameFileButton' ).click(function() {
            var bValid = true;
    //        bValid = bValid && checkLength( $( "#renamedFileName" ).val(), "filename", 3, 200 );
    //        bValid = bValid && checkRegexp( renamedFileName, /^[a-z]([0-9a-z_.])+$/i, "Filename may consist of a-z, 0-9, underscores, begin with a letter." );
            if ( bValid ) {
                var containingDir = TSCORE.TagUtils.extractContainingDirectoryPath(TSCORE.selectedFiles[0]);
                TSCORE.IO.renameFile(
                        TSCORE.selectedFiles[0],
                        containingDir+TSCORE.TagUtils.DIR_SEPARATOR+$( "#renamedFileName" ).val()
                    );
            }
        });

        // Edit Tag Dialog

	    $( "#plainTagTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        TSCORE.selectedTag, $( "#newTagName" ).datepicker( "destroy" ).val("");
	    });

	    $( "#dateTagTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        TSCORE.selectedTag, $( "#newTagName" ).datepicker({
	            showWeek: true,
	            firstDay: 1,
	            dateFormat: "yymmdd"
	        });
	    });

	    $( "#currencyTagTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        TSCORE.selectedTag, $( "#newTagName" ).datepicker( "destroy" ).val("XEUR");
	    });

        $( "#editTagButton" ).click(function() {
            TSCORE.TagUtils.renameTag(TSCORE.selectedFiles[0], TSCORE.selectedTag, $( "#newTagName" ).val());
            TSCORE.startTime = new Date().getTime();
            TSCORE.IO.listDirectory(TSCORE.currentPath);
        });

	    // End Edit Tag Dialog

        $( "#startNewInstanceBack" ).click(function() {
            window.open(window.location.href,'_blank');
        });

	    $( "#aboutDialogBack" ).click(function() {
            $("#aboutIframe").attr("src","about.html");
        });

        // Open About Dialog
        $( "#openAboutBox" ).click(function() {
           $('#dialogAbout').modal('show');
        });

        // Open Options Dialog
        $( "#openOptions" ).click(function() {
            require(['tsoptions'], function () {
                $('#dialogOptions').modal('show');
            });
        });

	    // Advanced Settings
        $( "#advancedSettings" ).click(function() {
            $('#dialogOptions').modal('hide');
            require(['jsoneditor'], function () {
                editor = new JSONEditor(document.getElementById("settingsEditor"));
                formatter = new JSONFormatter(document.getElementById("settingsPlainJSON"));
                $("#settingsPlainJSON").hide();
                editor.set(TSCORE.Config.Settings);
                $('#dialogAdvancedSetting').modal('show');
            });
        });

        $( "#editorButton" ).click(function() {
            if($("#settingsEditor").is(":hidden") ) {
                $("#settingsPlainJSON").hide();
                $("#settingsEditor").show();
                editor.set(formatter.get());
            }
        });

        $( "#importExportButton" ).click(function() {
            if($("#settingsPlainJSON").is(":hidden") ) {
                formatter.set(editor.get());
                $("#settingsPlainJSON").show();
                $("#settingsEditor").hide();
            }
        });

        $( "#defaultSettingsButton" ).click(function() {
            TSCORE.showConfirmDialog(
                "Warning",
                "Are you sure you want to restore the default application settings?\n"+
                "All manually made changes such as tags and taggroups will be lost.",
                function() {
                    TSCORE.Config.loadDefaultSettings();
                }
            );
        });

        $( "#saveSettingsButton" ).click(function() {
            TSCORE.Config.Settings = editor.get();
            TSCORE.Config.saveSettings();
            TSCORE.reloadUI();
        });
        // End Advanced Settings

	    // File Menu
        $( "#fileMenuAddTag" ).click( function() {
            TSCORE.showAddTagsDialog();
        });

        $( "#fileMenuOpenFile" ).click( function() {
            TSCORE.FileOpener.openFile(TSCORE.selectedFiles[0]);
        });

        $( "#fileMenuOpenDirectory" ).click( function() {
            TSCORE.IO.openDirectory(TSCORE.currentPath);
        });

        $( "#fileMenuRenameFile" ).click( function() {
            TSCORE.showFileRenameDialog();
        });

        $( "#fileMenuDeleteFile" ).click( function() {
            console.log("Deleting file...");
            TSCORE.showConfirmDialog(
                "Delete File(s)",
                "These items will be permanently deleted and cannot be recovered. Are you sure?",
                function() {
                    TSCORE.IO.deleteElement(TSCORE.selectedFiles[0]);
                    TSCORE.IO.listDirectory(TSCORE.currentPath);
                }
            );
        });
        // End File Menu

		$('#switchLang').click(function(e) {
			$.i18n.setLng('de', function(t) {
				$('[data-i18n]').i18n();
			});
	    });

		$('#showLocations').click(function(e) {
			showLocationsPanel();
			console.log("Show Directories");
	    });

		$('#showTagGroups').click(function(e) {
			showTagsPanel();
			console.log("Show Tags");
	    });

	    // Hide the taggroups by default
	    $('#tagGroupsContent').hide();

	    // Hide drop downs by click and drag
	    $(document).click(function () {
			TSCORE.hideAllDropDownMenus();
	    });

	};

	var showContextMenu = function(menuId, sourceObject) {
        var leftPos = sourceObject.offset().left;
        var topPos = sourceObject.offset().top+sourceObject.height()+5;
        if (sourceObject.offset().top+sourceObject.height()+$(menuId).height() > window.innerHeight) {
	        topPos = window.innerHeight-$("#tagMenu").height();
	        leftPos = sourceObject.offset().left+15;
        }

        if (sourceObject.offset().left+sourceObject.width()+$(menuId).width() > window.innerWidth) {
	        leftPos = window.innerWidth-$("#tagMenu").width();
        }

        $(menuId).css({
            display: "block",
            left:  leftPos,
            top: topPos
        });
	};

	var hideAllDropDownMenus = function() {
        $('#tagGroupMenu').hide();
        $('#tagTreeMenu').hide();
        $('#directoryMenu').hide();
        $('#tagMenu').hide();
        $('#fileMenu').hide();
	};

    var showLocationsPanel = function() {
		$('#tagGroupsContent').hide();
		$('#locationContent').show();
		$('#showLocations').addClass("active");
		$('#showTagGroups').removeClass("active");
    };

    var showTagsPanel = function() {
		$('#locationContent').hide();
		$('#tagGroupsContent').show();
		$('#showLocations').removeClass("active");
		$('#showTagGroups').addClass("active");
    };

    // Public API definition
    exports.showContextMenu			= showContextMenu;
	exports.initUI 					= initUI;
	exports.showAlertDialog 		= showAlertDialog;
	exports.showConfirmDialog 		= showConfirmDialog;
	exports.showFileRenameDialog    = showFileRenameDialog;
	exports.showFileCreateDialog    = showFileCreateDialog;
    exports.showTagEditDialog       = showTagEditDialog;
    exports.showLocationsPanel      = showLocationsPanel;
    exports.showTagsPanel       	= showTagsPanel;
	exports.hideAllDropDownMenus	= hideAllDropDownMenus;

});<|endoftext|>


<commit_before><commit_msg>nitfixes<commit_after><|endoftext|>


<commit_before><commit_msg>js-beautifier pass<commit_after><|endoftext|>


<commit_before>import 'metabase/services';

describe('metabase.services', function() {
    beforeEach(angular.mock.module('metabase.services'));

    describe('Metabase', function() {
        it('should return empty list of databases', inject(function(Metabase, $httpBackend) {
            $httpBackend.expect('GET', '/api/database/?org=')
                .respond(200, '[]');

            Metabase.db_list().$promise.then(function(data) {
                expect(data.length).toEqual(0);
            });

            $httpBackend.flush();
        }));
    });
});
<commit_msg>Fix frontend test<commit_after>import 'metabase/services';

describe('metabase.services', function() {
    beforeEach(angular.mock.module('metabase.services'));

    describe('Metabase', function() {
        it('should return empty list of databases', inject(function(Metabase, $httpBackend) {
            $httpBackend.expect('GET', '/api/database')
                .respond(200, '[]');

            Metabase.db_list().$promise.then(function(data) {
                expect(data.length).toEqual(0);
            });

            $httpBackend.flush();
        }));
    });
});
<|endoftext|>


<commit_before>exports.make_zblueslip = function () {
    const lib = {};

    const opts = {
        // Silently swallow all debug, log and info calls.
        debug: false,
        log: false,
        info: false,
        // Check against expected error values for the following.
        warn: true,
        error: true,
    };
    const names = Array.from(Object.keys(opts));

    // For fatal messages, we should use assert.throws
    lib.fatal = (msg) => {
        throw Error(msg);
    };

    // Store valid test data for options.
    lib.test_data = {};
    lib.test_logs = {};

    for (const name of names) {
        lib.test_data[name] = [];
        lib.test_logs[name] = [];
    }

    lib.expect = (name, message, count = 1) => {
        if (opts[name] === undefined) {
            throw Error('unexpected arg for expect: ' + name);
        }
        if (count <= 0 && Number.isInteger(count)) {
            throw Error('expected count should be a positive integer');
        }
        const obj = {message, count, expected_count: count};
        lib.test_data[name].push(obj);
    };

    lib.check_seen_messages = () => {
        for (const name of names) {
            for (const obj of lib.test_logs[name]) {
                const message = obj.message;
                const i = lib.test_data[name].findIndex(x => x.message === message);
                if (i === -1) {
                    // Only throw this for message types we want to explicitly track.
                    // For example, we do not want to throw here for debug messages.
                    if (opts[name]) {
                        throw Error (`Unexpected '${name}' message: ${message}`);
                    }
                    continue;
                }
                lib.test_data[name][i].count -= 1;
            }

            for (const obj of lib.test_data[name]) {
                const message = obj.message;
                if (obj.count > 0) {
                    throw Error(`We saw ${obj.count} (expected ${obj.expected_count}) of '${name}': ${message}`);
                } else if (obj.count < 0) {
                    throw Error(`We saw ${obj.expected_count - obj.count} (expected ${obj.expected_count}) of '${name}': ${message}`);
                }
            }
        }
    };

    lib.reset = (skip_checks = false) => {
        if (!skip_checks) {
            lib.check_seen_messages();
        }

        for (const name of names) {
            lib.test_data[name] = [];
            lib.test_logs[name] = [];
        }
    };

    lib.get_test_logs = (name) => {
        return lib.test_logs[name];
    };

    // Create logging functions
    for (const name of names) {
        if (!opts[name]) {
            // should just log the message.
            lib[name] = function (message, more_info, stack) {
                lib.test_logs[name].push({message, more_info, stack});
            };
            continue;
        }
        lib[name] = function (message, more_info, stack) {
            if (typeof message !== 'string') {
                // We may catch exceptions in blueslip, and if
                // so our stub should include that.
                if (message.toString().includes('exception')) {
                    message = message.toString();
                } else {
                    throw Error('message should be string: ' + message);
                }
            }
            lib.test_logs[name].push({message, more_info, stack});
            const matched_error_message = lib.test_data[name].find(x => x.message === message);
            const exact_match_fail = !matched_error_message;
            if (exact_match_fail) {
                const error = Error(`Invalid ${name} message: "${message}".`);
                error.blueslip = true;
                throw error;
            }
        };
    }

    lib.exception_msg = function (ex) {
        return ex.message;
    };

    lib.start_timing = () => {
        return () => {};
    };

    return lib;
};
<commit_msg>zblueslip: Do not expose internal function check_seen_messages.<commit_after>exports.make_zblueslip = function () {
    const lib = {};

    const opts = {
        // Silently swallow all debug, log and info calls.
        debug: false,
        log: false,
        info: false,
        // Check against expected error values for the following.
        warn: true,
        error: true,
    };
    const names = Array.from(Object.keys(opts));

    // For fatal messages, we should use assert.throws
    lib.fatal = (msg) => {
        throw Error(msg);
    };

    // Store valid test data for options.
    lib.test_data = {};
    lib.test_logs = {};

    for (const name of names) {
        lib.test_data[name] = [];
        lib.test_logs[name] = [];
    }

    lib.expect = (name, message, count = 1) => {
        if (opts[name] === undefined) {
            throw Error('unexpected arg for expect: ' + name);
        }
        if (count <= 0 && Number.isInteger(count)) {
            throw Error('expected count should be a positive integer');
        }
        const obj = {message, count, expected_count: count};
        lib.test_data[name].push(obj);
    };

    const check_seen_messages = () => {
        for (const name of names) {
            for (const obj of lib.test_logs[name]) {
                const message = obj.message;
                const i = lib.test_data[name].findIndex(x => x.message === message);
                if (i === -1) {
                    // Only throw this for message types we want to explicitly track.
                    // For example, we do not want to throw here for debug messages.
                    if (opts[name]) {
                        throw Error (`Unexpected '${name}' message: ${message}`);
                    }
                    continue;
                }
                lib.test_data[name][i].count -= 1;
            }

            for (const obj of lib.test_data[name]) {
                const message = obj.message;
                if (obj.count > 0) {
                    throw Error(`We saw ${obj.count} (expected ${obj.expected_count}) of '${name}': ${message}`);
                } else if (obj.count < 0) {
                    throw Error(`We saw ${obj.expected_count - obj.count} (expected ${obj.expected_count}) of '${name}': ${message}`);
                }
            }
        }
    };

    lib.reset = (skip_checks = false) => {
        if (!skip_checks) {
            check_seen_messages();
        }

        for (const name of names) {
            lib.test_data[name] = [];
            lib.test_logs[name] = [];
        }
    };

    lib.get_test_logs = (name) => {
        return lib.test_logs[name];
    };

    // Create logging functions
    for (const name of names) {
        if (!opts[name]) {
            // should just log the message.
            lib[name] = function (message, more_info, stack) {
                lib.test_logs[name].push({message, more_info, stack});
            };
            continue;
        }
        lib[name] = function (message, more_info, stack) {
            if (typeof message !== 'string') {
                // We may catch exceptions in blueslip, and if
                // so our stub should include that.
                if (message.toString().includes('exception')) {
                    message = message.toString();
                } else {
                    throw Error('message should be string: ' + message);
                }
            }
            lib.test_logs[name].push({message, more_info, stack});
            const matched_error_message = lib.test_data[name].find(x => x.message === message);
            const exact_match_fail = !matched_error_message;
            if (exact_match_fail) {
                const error = Error(`Invalid ${name} message: "${message}".`);
                error.blueslip = true;
                throw error;
            }
        };
    }

    lib.exception_msg = function (ex) {
        return ex.message;
    };

    lib.start_timing = () => {
        return () => {};
    };

    return lib;
};
<|endoftext|>


<commit_before>(function($) {
// CMS.$ will be passed for $
$(document).ready(function () {

    CKEDITOR.plugins.add('cmsplugins', {

        // Register the icons. They must match command names.
        icons: 'cmsplugins',

        // The plugin initialization logic goes inside this method.
        init: function(editor) {
            var that = this;

            this.options = CMS.CKEditor.options.settings;
            this.editor = editor;

            /**
             * populated with _fresh_ child plugins
             */
            this.child_plugins = [];
            this.setupCancelCleanupCallback(this.options);

            // don't do anything if there are no plugins defined
            if(this.options === undefined || this.options.plugins === undefined) return false;

            this.setupDialog();

            // add the button
            this.editor.ui.add('cmsplugins', CKEDITOR.UI_PANELBUTTON, {
                'toolbar': 'cms,0',
                'label': this.options.lang.toolbar,
                'title': this.options.lang.toolbar,
                'className' : 'cke_panelbutton__cmsplugins',
                'modes': { wysiwyg:1 },
                'editorFocus': 0,

                'panel': {
                    'css': [CKEDITOR.skin.getPath('editor')].concat(that.editor.config.contentsCss),
                    'attributes': { role: 'cmsplugins', 'aria-label': this.options.lang.aria }
                },

                // this is called when creating the dropdown list
                'onBlock': function (panel, block) {
                    block.element.setHtml(that.editor.plugins.cmsplugins.setupDropdown());

                    var anchors = $(block.element.$).find('.cke_panel_listItem a');
                        anchors.bind('click', function (e) {
                            e.preventDefault();

                            that.addPlugin($(this), panel);
                        });
                }
            });

            // handle edit event via context menu
            if(this.editor.contextMenu) {
                this.setupContextMenu();
                this.editor.addCommand('cmspluginsEdit', {
                    exec: function () {
                        var selection = that.editor.getSelection();
                        var element = selection.getSelectedElement() || selection.getCommonAncestor().getAscendant('a', true);
                        that.editPlugin(element);
                    }
                });
            }

            // handle edit event on double click
            // if event is a jQuery event (touchend), than we mutate
            // event a bit so we make the payload similar to what ckeditor.event produces
            var handleEdit = function(event) {
                if (event.type === 'touchend' || event.type === 'click') {
                    var element = event.currentTarget;
                    event.data = event.data ||  {};
                    that.editor.getSelection().fake(new CKEDITOR.dom.element(element));
                } else {
                    // heavily relies on the fact that double click
                    // also selects an element
                    var selection = that.editor.getSelection();
                    var element = selection.getSelectedElement() || selection.getCommonAncestor().getAscendant('a', true);
                }
                if(element && element.getAttribute('id').indexOf('plugin_obj_') === 0) {
                    event.data.dialog = '';
                    that.editPlugin(element);
                }
            }
            this.editor.on('doubleclick', handleEdit);
            this.editor.on('instanceReady', function () {
                CMS.$('[id*="plugin_obj_"]', CMS.$('iframe.cke_wysiwyg_frame')[0]
                    .contentWindow.document.documentElement).on('click touchend', handleEdit);
            });

            // setup CKEDITOR.htmlDataProcessor
            this.setupDataProcessor();
        },

        setupDialog: function () {
            var that = this;
            var definition = function () { return {
                'title': '',
                'minWidth': 600,
                'minHeight': 200,
                'contents': [{
                    'elements': [{ type: 'html', html: '' }]
                }],
                'onOk': function () {
                    var iframe = $(CKEDITOR.dialog.getCurrent().parts.contents.$).find('iframe').contents();
                        iframe.find('form').submit();

                    // catch the reload event and reattach
                    var reload = CMS.API.Helpers.reloadBrowser;

                    CMS.API.Helpers.reloadBrowser = function() {
                        CKEDITOR.dialog.getCurrent().hide();

                        that.insertPlugin(CMS.API.Helpers.dataBridge);

                        CMS.API.Helpers.reloadBrowser = reload;
                        return false;
                    };
                    return false;
                }
            }};

            // set default definition and open dialog
            CKEDITOR.dialog.add('cmspluginsDialog', definition);
        },

        setupDropdown: function () {
            var tpl = '
';

            // loop through the groups
            $.each(this.options.plugins, function (i, group) {
                // add template
                tpl += '
' + group.group + '
';
                tpl += '
';
                // loop through the plugins
                $.each(group.items, function (ii, item) {
                    tpl += '
' + item.title + '
';
                });
                tpl += '
';
            });

            tpl += '
';

            return tpl;
        },

        setupContextMenu: function () {
            this.editor.addMenuGroup('cmspluginsGroup');
            this.editor.addMenuItem('cmspluginsItem', {
                label: this.options.lang.edit,
                icon: this.path + 'icons/cmsplugins.png',
                command: 'cmspluginsEdit',
                group: 'cmspluginsGroup'
            });

            this.editor.removeMenuItem('image');

            this.editor.contextMenu.addListener(function(element) {
                if (element.$.id.indexOf('plugin_obj_') === 0) {
                    return { cmspluginsItem: CKEDITOR.TRISTATE_OFF };
                }
            });
        },

        editPlugin: function (element) {
            var id = element.getAttribute('id').replace('plugin_obj_', '');
            this.editor.openDialog('cmspluginsDialog');
            var body = CMS.$(document);

            // now tweak in dynamic stuff
            var dialog = CKEDITOR.dialog.getCurrent();
            dialog.resize(body.width() * 0.8, body.height() * 0.7);
            $(dialog.getElement().$).addClass('cms-ckeditor-dialog');
            $(dialog.parts.title.$).text(this.options.lang.edit);
            $(dialog.parts.contents.$).find('iframe').attr('src', '../' + id + '/?_popup=1&no_preview')
                .bind('load', function () {
                    $(this).contents().find('.submit-row').hide().end()
                        .find('#container').css('min-width', 0).css('padding', 0);
                });
        },

        addPlugin: function (item, panel) {
            var that = this;

            // hide the panel
            panel.hide();

            // lets figure out how to write something to the editor
            this.editor.focus();
            this.editor.fire('saveSnapshot');

            // gather data
            var data = {
                'placeholder_id': this.options.placeholder_id,
                'plugin_type': item.attr('rel'),
                'plugin_parent': this.options.plugin_id,
                'plugin_language':  this.options.plugin_language
            };

            that.addPluginDialog(item, data);
        },

        addPluginDialog: function (item, data) {
            var body = CMS.$(document);
            // open the dialog
            var selected_text = this.editor.getSelection().getSelectedText();
            this.editor.openDialog('cmspluginsDialog');

            // now tweak in dynamic stuff
            var dialog = CKEDITOR.dialog.getCurrent();
            dialog.resize(body.width() * 0.8, body.height() * 0.7);
            $(dialog.getElement().$).addClass('cms-ckeditor-dialog');
            $(dialog.parts.title.$).text(this.options.lang.add);
            $(dialog.parts.contents.$).find('iframe').attr('src', this.options.add_plugin_url + '?' + $.param(data))
                .bind('load', function () {
                    $(this).contents().find('.submit-row').hide().end()
                    .find('#container').css('min-width', 0).css('padding', 0)
                    .find('#id_name').val(selected_text);
                });
        },

        // on ajax receivement from server, build  or  tag dependig in the plugin type
        insertPlugin: function (data) {
            var that = this;
            var element, attrs = { id: 'plugin_obj_' + data.plugin_id };
            if (data.plugin_type === this.options.lang.link) {
                element = new CKEDITOR.dom.element('a', this.editor.document);
                $.extend(attrs, {
                    'href': '#',
                    'data-cmsplugin_title': data.plugin_desc,
                    'data-cmsplugin_alt': data.plugin_type,
                    'data-cmsplugin_src': data.plugin_icon
                });
                element.setText(data.plugin_name);
            } else {
                element = new CKEDITOR.dom.element('img', this.editor.document);
                $.extend(attrs, {
                    'title': data.plugin_desc,
                    'alt': data.plugin_type,
                    'src': data.plugin_icon
                });
            }
            element.setAttributes(attrs);

            // in case it's a fresh text plugin children don't have to be
            // deleted separately
            if (!this.options.delete_on_cancel) {
                this.child_plugins.push(data.plugin_id);
            }
            this.editor.insertElement(element);
        },

        /**
         * Sets up cleanup requests. If the plugin itself or child plugin was created and then
         * creation was cancelled - we need to clean up created plugins.
         *
         * @method setupCancelCleanupCallback
         * @public
         * @param {Object} data plugin data
         */
        setupCancelCleanupCallback: function setupCancelCleanupCallback (data) {
            if (!window.parent || !window.parent.CMS || !window.parent.CMS.API || !window.parent.CMS.API.Helpers) {
                return;
            }
            var that = this;
            var CMS = window.parent.CMS;
            var cancelModalCallback = function cancelModalCallback(e, opts) {
                e.preventDefault();
                CMS.API.Toolbar.showLoader();
                var data = {
                    token: that.options.cancel_plugin_token
                };
                if (!that.options.delete_on_cancel ) {
                    data.child_plugins = that.child_plugins;
                }
                $.ajax({
                    method: 'POST',
                    url: that.options.cancel_plugin_url,
                    data: data,
                    // use 'child_plugins' instead of default 'child_plugins[]'
                    traditional: true
                }).done(function (res) {
                    CMS.API.Helpers.removeEventListener('modal-close.text-plugin-' + that.options.plugin_id);
                    opts.instance.close();
                }).fail(function (res) {
                    CMS.API.Messages.open({
                        message: res.responseText + ' | ' + res.status + ' ' + res.statusText,
                        delay: 0,
                        error: true
                    });
                });
            };
            CMS.API.Helpers.addEventListener('modal-close.text-plugin-' + that.options.plugin_id, cancelModalCallback);
        },

        setupDataProcessor: function () {
            var link_name = this.options.lang.link;
            var link_pattern = new RegExp("^"+ link_name +"\\s-\\s(.+)$");

            this.editor.dataProcessor.dataFilter.addRules({
                elements: {
                    // on load from server replace  tag by  in order to display a real link
                    img: function(element) {
                        var new_element, matches;
                        if (element.attributes.id && element.attributes.alt
                          && element.attributes.alt === link_name
                          && element.attributes.id.indexOf('plugin_obj_') === 0) {
                            matches = link_pattern.exec(element.attributes.title);
                            new_element = new CKEDITOR.htmlParser.element('a', {
                                'href': '#',
                                'id': element.attributes.id,
                                'data-cmsplugin_title': element.attributes.title,
                                'data-cmsplugin_src': element.attributes.src,
                                'data-cmsplugin_alt': element.attributes.alt
                            });
                            if (matches) {
                                new_element.add(new CKEDITOR.htmlParser.text(matches[1]));
                            }
                            return new_element;
                        }
                    }
                }
            });

            this.editor.dataProcessor.htmlFilter.addRules({
                elements: {
                    // on post to server replace  tag by  in order keep plugin format consistent
                    a: function(element) {
                        var new_element;
                        if (element.attributes.id && element.attributes.id.indexOf('plugin_obj_') === 0) {
                            new_element = new CKEDITOR.htmlParser.element('img', {
                                id: element.attributes.id,
                                src: element.attributes['data-cmsplugin_src'],
                                title: element.attributes['data-cmsplugin_title'],
                                alt: element.attributes['data-cmsplugin_alt']
                            });
                            return new_element;
                        }
                    }
                }
            });
        }

    });

});
})(CMS.$);
<commit_msg>should not prevent default if canceling plain text edit<commit_after>(function($) {
// CMS.$ will be passed for $
$(document).ready(function () {

    CKEDITOR.plugins.add('cmsplugins', {

        // Register the icons. They must match command names.
        icons: 'cmsplugins',

        // The plugin initialization logic goes inside this method.
        init: function(editor) {
            var that = this;

            this.options = CMS.CKEditor.options.settings;
            this.editor = editor;

            /**
             * populated with _fresh_ child plugins
             */
            this.child_plugins = [];
            this.setupCancelCleanupCallback(this.options);

            // don't do anything if there are no plugins defined
            if(this.options === undefined || this.options.plugins === undefined) return false;

            this.setupDialog();

            // add the button
            this.editor.ui.add('cmsplugins', CKEDITOR.UI_PANELBUTTON, {
                'toolbar': 'cms,0',
                'label': this.options.lang.toolbar,
                'title': this.options.lang.toolbar,
                'className' : 'cke_panelbutton__cmsplugins',
                'modes': { wysiwyg:1 },
                'editorFocus': 0,

                'panel': {
                    'css': [CKEDITOR.skin.getPath('editor')].concat(that.editor.config.contentsCss),
                    'attributes': { role: 'cmsplugins', 'aria-label': this.options.lang.aria }
                },

                // this is called when creating the dropdown list
                'onBlock': function (panel, block) {
                    block.element.setHtml(that.editor.plugins.cmsplugins.setupDropdown());

                    var anchors = $(block.element.$).find('.cke_panel_listItem a');
                        anchors.bind('click', function (e) {
                            e.preventDefault();

                            that.addPlugin($(this), panel);
                        });
                }
            });

            // handle edit event via context menu
            if(this.editor.contextMenu) {
                this.setupContextMenu();
                this.editor.addCommand('cmspluginsEdit', {
                    exec: function () {
                        var selection = that.editor.getSelection();
                        var element = selection.getSelectedElement() || selection.getCommonAncestor().getAscendant('a', true);
                        that.editPlugin(element);
                    }
                });
            }

            // handle edit event on double click
            // if event is a jQuery event (touchend), than we mutate
            // event a bit so we make the payload similar to what ckeditor.event produces
            var handleEdit = function(event) {
                if (event.type === 'touchend' || event.type === 'click') {
                    var element = event.currentTarget;
                    event.data = event.data ||  {};
                    that.editor.getSelection().fake(new CKEDITOR.dom.element(element));
                } else {
                    // heavily relies on the fact that double click
                    // also selects an element
                    var selection = that.editor.getSelection();
                    var element = selection.getSelectedElement() || selection.getCommonAncestor().getAscendant('a', true);
                }
                if(element && element.getAttribute('id').indexOf('plugin_obj_') === 0) {
                    event.data.dialog = '';
                    that.editPlugin(element);
                }
            }
            this.editor.on('doubleclick', handleEdit);
            this.editor.on('instanceReady', function () {
                CMS.$('[id*="plugin_obj_"]', CMS.$('iframe.cke_wysiwyg_frame')[0]
                    .contentWindow.document.documentElement).on('click touchend', handleEdit);
            });

            // setup CKEDITOR.htmlDataProcessor
            this.setupDataProcessor();
        },

        setupDialog: function () {
            var that = this;
            var definition = function () { return {
                'title': '',
                'minWidth': 600,
                'minHeight': 200,
                'contents': [{
                    'elements': [{ type: 'html', html: '' }]
                }],
                'onOk': function () {
                    var iframe = $(CKEDITOR.dialog.getCurrent().parts.contents.$).find('iframe').contents();
                        iframe.find('form').submit();

                    // catch the reload event and reattach
                    var reload = CMS.API.Helpers.reloadBrowser;

                    CMS.API.Helpers.reloadBrowser = function() {
                        CKEDITOR.dialog.getCurrent().hide();

                        that.insertPlugin(CMS.API.Helpers.dataBridge);

                        CMS.API.Helpers.reloadBrowser = reload;
                        return false;
                    };
                    return false;
                }
            }};

            // set default definition and open dialog
            CKEDITOR.dialog.add('cmspluginsDialog', definition);
        },

        setupDropdown: function () {
            var tpl = '
';

            // loop through the groups
            $.each(this.options.plugins, function (i, group) {
                // add template
                tpl += '
' + group.group + '
';
                tpl += '
';
                // loop through the plugins
                $.each(group.items, function (ii, item) {
                    tpl += '
' + item.title + '
';
                });
                tpl += '
';
            });

            tpl += '
';

            return tpl;
        },

        setupContextMenu: function () {
            this.editor.addMenuGroup('cmspluginsGroup');
            this.editor.addMenuItem('cmspluginsItem', {
                label: this.options.lang.edit,
                icon: this.path + 'icons/cmsplugins.png',
                command: 'cmspluginsEdit',
                group: 'cmspluginsGroup'
            });

            this.editor.removeMenuItem('image');

            this.editor.contextMenu.addListener(function(element) {
                if (element.$.id.indexOf('plugin_obj_') === 0) {
                    return { cmspluginsItem: CKEDITOR.TRISTATE_OFF };
                }
            });
        },

        editPlugin: function (element) {
            var id = element.getAttribute('id').replace('plugin_obj_', '');
            this.editor.openDialog('cmspluginsDialog');
            var body = CMS.$(document);

            // now tweak in dynamic stuff
            var dialog = CKEDITOR.dialog.getCurrent();
            dialog.resize(body.width() * 0.8, body.height() * 0.7);
            $(dialog.getElement().$).addClass('cms-ckeditor-dialog');
            $(dialog.parts.title.$).text(this.options.lang.edit);
            $(dialog.parts.contents.$).find('iframe').attr('src', '../' + id + '/?_popup=1&no_preview')
                .bind('load', function () {
                    $(this).contents().find('.submit-row').hide().end()
                        .find('#container').css('min-width', 0).css('padding', 0);
                });
        },

        addPlugin: function (item, panel) {
            var that = this;

            // hide the panel
            panel.hide();

            // lets figure out how to write something to the editor
            this.editor.focus();
            this.editor.fire('saveSnapshot');

            // gather data
            var data = {
                'placeholder_id': this.options.placeholder_id,
                'plugin_type': item.attr('rel'),
                'plugin_parent': this.options.plugin_id,
                'plugin_language':  this.options.plugin_language
            };

            that.addPluginDialog(item, data);
        },

        addPluginDialog: function (item, data) {
            var body = CMS.$(document);
            // open the dialog
            var selected_text = this.editor.getSelection().getSelectedText();
            this.editor.openDialog('cmspluginsDialog');

            // now tweak in dynamic stuff
            var dialog = CKEDITOR.dialog.getCurrent();
            dialog.resize(body.width() * 0.8, body.height() * 0.7);
            $(dialog.getElement().$).addClass('cms-ckeditor-dialog');
            $(dialog.parts.title.$).text(this.options.lang.add);
            $(dialog.parts.contents.$).find('iframe').attr('src', this.options.add_plugin_url + '?' + $.param(data))
                .bind('load', function () {
                    $(this).contents().find('.submit-row').hide().end()
                    .find('#container').css('min-width', 0).css('padding', 0)
                    .find('#id_name').val(selected_text);
                });
        },

        // on ajax receivement from server, build  or  tag dependig in the plugin type
        insertPlugin: function (data) {
            var that = this;
            var element, attrs = { id: 'plugin_obj_' + data.plugin_id };
            if (data.plugin_type === this.options.lang.link) {
                element = new CKEDITOR.dom.element('a', this.editor.document);
                $.extend(attrs, {
                    'href': '#',
                    'data-cmsplugin_title': data.plugin_desc,
                    'data-cmsplugin_alt': data.plugin_type,
                    'data-cmsplugin_src': data.plugin_icon
                });
                element.setText(data.plugin_name);
            } else {
                element = new CKEDITOR.dom.element('img', this.editor.document);
                $.extend(attrs, {
                    'title': data.plugin_desc,
                    'alt': data.plugin_type,
                    'src': data.plugin_icon
                });
            }
            element.setAttributes(attrs);

            // in case it's a fresh text plugin children don't have to be
            // deleted separately
            if (!this.options.delete_on_cancel) {
                this.child_plugins.push(data.plugin_id);
            }
            this.editor.insertElement(element);
        },

        /**
         * Sets up cleanup requests. If the plugin itself or child plugin was created and then
         * creation was cancelled - we need to clean up created plugins.
         *
         * @method setupCancelCleanupCallback
         * @public
         * @param {Object} data plugin data
         */
        setupCancelCleanupCallback: function setupCancelCleanupCallback (data) {
            if (!window.parent || !window.parent.CMS || !window.parent.CMS.API || !window.parent.CMS.API.Helpers) {
                return;
            }
            var that = this;
            var CMS = window.parent.CMS;
            var cancelModalCallback = function cancelModalCallback(e, opts) {
                if (!that.options.delete_on_cancel && !that.child_plugins.length) {
                    return;
                }
                e.preventDefault();
                CMS.API.Toolbar.showLoader();
                var data = {
                    token: that.options.cancel_plugin_token
                };
                if (!that.options.delete_on_cancel) {
                    data.child_plugins = that.child_plugins;
                }
                $.ajax({
                    method: 'POST',
                    url: that.options.cancel_plugin_url,
                    data: data,
                    // use 'child_plugins' instead of default 'child_plugins[]'
                    traditional: true
                }).done(function (res) {
                    CMS.API.Helpers.removeEventListener('modal-close.text-plugin-' + that.options.plugin_id);
                    opts.instance.close();
                }).fail(function (res) {
                    CMS.API.Messages.open({
                        message: res.responseText + ' | ' + res.status + ' ' + res.statusText,
                        delay: 0,
                        error: true
                    });
                });
            };
            CMS.API.Helpers.addEventListener('modal-close.text-plugin-' + that.options.plugin_id, cancelModalCallback);
        },

        setupDataProcessor: function () {
            var link_name = this.options.lang.link;
            var link_pattern = new RegExp("^"+ link_name +"\\s-\\s(.+)$");

            this.editor.dataProcessor.dataFilter.addRules({
                elements: {
                    // on load from server replace  tag by  in order to display a real link
                    img: function(element) {
                        var new_element, matches;
                        if (element.attributes.id && element.attributes.alt
                          && element.attributes.alt === link_name
                          && element.attributes.id.indexOf('plugin_obj_') === 0) {
                            matches = link_pattern.exec(element.attributes.title);
                            new_element = new CKEDITOR.htmlParser.element('a', {
                                'href': '#',
                                'id': element.attributes.id,
                                'data-cmsplugin_title': element.attributes.title,
                                'data-cmsplugin_src': element.attributes.src,
                                'data-cmsplugin_alt': element.attributes.alt
                            });
                            if (matches) {
                                new_element.add(new CKEDITOR.htmlParser.text(matches[1]));
                            }
                            return new_element;
                        }
                    }
                }
            });

            this.editor.dataProcessor.htmlFilter.addRules({
                elements: {
                    // on post to server replace  tag by  in order keep plugin format consistent
                    a: function(element) {
                        var new_element;
                        if (element.attributes.id && element.attributes.id.indexOf('plugin_obj_') === 0) {
                            new_element = new CKEDITOR.htmlParser.element('img', {
                                id: element.attributes.id,
                                src: element.attributes['data-cmsplugin_src'],
                                title: element.attributes['data-cmsplugin_title'],
                                alt: element.attributes['data-cmsplugin_alt']
                            });
                            return new_element;
                        }
                    }
                }
            });
        }

    });

});
})(CMS.$);
<|endoftext|>


<commit_before>var gameModule = angular.module('app', []).
	controller("gameTheoryControl", function gameTheoryControl($scope){

	    	function number(num){
	    		this.name = num;
	    		this.selected = false;
	    		return this;
	    	}

	    	$scope.numbers=[];
	    	$scope.solutions=[];

	    	$scope.getStarter = function(){
	    		var isEven = ($scope.solutions.length % 2) == 0;

	    		if(isEven){
	    			return "Alice";
	    		}
	    		else{
	    			return "Bob";
	    		}
	    	}

	    	function solution(x, parts){
	    		this.number = x;
	    		this.parts = parts;
	    	}

	    	$scope.amount = 5;

	    	$scope.newNumbers = function(){
			$scope.numbers = [];

			intAmount = parseInt($scope.amount);

			for(var i = 1; i < intAmount + 1; i++){
				$scope.numbers.push(new number(i));
			}
		}

		$scope.deleteSelected = function(){
			for(var num in $scope.numbers){
				if($scope.numbers[num].selected){
					$scope.numbers.splice(num, 1);
					num--;
				}
			}
		}

		function sumOf(parts){
			var num = 0;
			for(var i = 0; i < parts.length; i++){
				num += parts[i];
			}
			return num;
		}

		function getSmallerNumbers(number){
			var newArray = [];
			for(var i = 0; i < $scope.numbers.length; i++){
				if($scope.numbers[i].name <= number){
					newArray.push($scope.numbers[i].name);
				}
				else{
					break;
				}
			}
			return newArray;
		}

		var getCombinations2 = function(firstParts, parts, solutions) {
			var results = [];
		    	for (var i = 0; i < parts.length; i++) {
			      solutions.push(firstParts.concat(parts[i]));
			      solutions.concat(getCombinations(firstParts.concat(parts[i]), parts.splice(i + 1)), solutions);
		    	}
		   return solutions;
		}

		var getCombinations = function(startArray, arrayOfNumbers){
			var results = [];
			for(var i = 0; i < arrayOfNumbers.length; i++){
				results.push(startArray.concat(arrayOfNumbers[i]));

				var tempArray = [];
				for(var j = 0; j < arrayOfNumbers.length; j++){
					if(j > i){
						tempArray.push(arrayOfNumbers[j]);
					}
				}

				results = results.concat(getCombinations(startArray.concat(arrayOfNumbers[i]), tempArray));
			}
			return results;
		}

		$scope.getSolutions = function(){
			$scope.solutions = [];
			var calculable = true;
			var currentNumber = 1;

			while(calculable){
				parts = [];

				var solved = false;

				var smallerNums = getSmallerNumbers(currentNumber);

				if(smallerNums.length == 0){
					calculable = false; break;
				}

				for(var i = 0; i < $scope.numbers.length; i++){
					if($scope.numbers[i].name == currentNumber)
					{
						solved = true;
						$scope.solutions.push(new solution(currentNumber, [$scope.numbers[i].name]));
					}
				}

				if(!solved){
					var combinations = getCombinations([], smallerNums);

						for(var i = 0; i < combinations.length; i++){
							if(sumOf(combinations[i]) == currentNumber){
								$scope.solutions.push(new solution(currentNumber, combinations[i]));
								solved = true;
								break;
							}
							if(solved){break;}
						}

					if(!solved){
						calculable = false; break;
					}
				}

				currentNumber++;
			}
		}

		$scope.newNumbers();

	});
<commit_msg>Update gameTheoryController.js<commit_after>var gameModule = angular.module('app', []).
	controller("gameTheoryControl", function gameTheoryControl($scope){

	    	function number(num){
	    		this.name = num;
	    		this.selected = false;
	    		return this;
	    	}

	    	$scope.numbers=[];
	    	$scope.solutions=[];

	    	$scope.getStarter = function(){
	    		var isEven = ($scope.solutions.length % 2) == 0;

	    		if(isEven){
	    			return "Alice";
	    		}
	    		else{
	    			return "Bob";
	    		}
	    	}

	    	function solution(x, parts){
	    		this.number = x;
	    		this.parts = parts;
	    	}

	    	$scope.amount = 5;

	    	$scope.newNumbers = function(){
			$scope.numbers = [];

			intAmount = parseInt($scope.amount);

			for(var i = 1; i < intAmount + 1; i++){
				$scope.numbers.push(new number(i));
			}
		}

		$scope.deleteSelected = function(){
			for(var num in $scope.numbers){
				if($scope.numbers[num].selected){
					$scope.numbers.splice(num, 1);
					num--;
				}
			}
		}

		function sumOf(parts){
			var num = 0;
			for(var i = 0; i < parts.length; i++){
				num += parts[i];
			}
			return num;
		}

		function getSmallerNumbers(number){
			var newArray = [];
			for(var i = 0; i < $scope.numbers.length; i++){
				if($scope.numbers[i].name <= number){
					newArray.push($scope.numbers[i].name);
				}
				else{
					break;
				}
			}
			return newArray;
		}

		var getCombinations2 = function(firstParts, parts, solutions) {
			var results = [];
		    	for (var i = 0; i < parts.length; i++) {
			      solutions.push(firstParts.concat(parts[i]));
			      solutions.concat(getCombinations(firstParts.concat(parts[i]), parts.splice(i + 1)), solutions);
		    	}
		   return solutions;
		}

		var getCombinations = function(startArray, arrayOfNumbers){
			var results = [];
			for(var i = arrayOfNumbers.length; i > -1; i--){
				results.push(startArray.concat(arrayOfNumbers[i]));

				var tempArray = [];
				for(var j = 0; j < i; j++){
					tempArray.push(arrayOfNumbers[j]);
				}

				results = results.concat(getCombinations(startArray.concat(arrayOfNumbers[i]), tempArray));
			}
			return results;
		}

		$scope.getSolutions = function(){
			$scope.solutions = [];
			var calculable = true;
			var currentNumber = 1;

			while(calculable){
				parts = [];

				var solved = false;

				var smallerNums = getSmallerNumbers(currentNumber);

				if(smallerNums.length == 0){
					calculable = false; break;
				}

				for(var i = 0; i < $scope.numbers.length; i++){
					if($scope.numbers[i].name == currentNumber)
					{
						solved = true;
						$scope.solutions.push(new solution(currentNumber, [$scope.numbers[i].name]));
					}
				}

				if(!solved){
					var combinations = getCombinations([], smallerNums);

						for(var i = 0; i < combinations.length; i++){
							if(sumOf(combinations[i]) == currentNumber){
								$scope.solutions.push(new solution(currentNumber, combinations[i]));
								solved = true;
								break;
							}
							if(solved){break;}
						}

					if(!solved){
						calculable = false; break;
					}
				}

				currentNumber++;
			}
		}

		$scope.newNumbers();

	});
<|endoftext|>


<commit_before>require('garnet');

var
	kind = require('enyo/kind'),
	GarnetDatePickerPanel = require('garnet/DatePickerPanel');

var SampleDatePickerPanel = kind({
	name: 'g.sample.DatePickerPanel',
	kind: GarnetDatePickerPanel,
	handlers: {
		onOK: 'tapOK',
		onCancel: 'tapCancel'
	},
	events: {
		onResult: ''
	},
	locale: 'en-US',
	style: 'position: relative;',
	mode: 'year',
	tapOK: function() {
		this.doResult({msg: 'Date is ' + this.getValue()});
	},
	tapCancel: function() {
		this.doResult({msg: 'Cancel!'});
	}
});

module.exports = kind({
	name: 'g.sample.DatePickerPanelSample',
	classes: 'enyo-unselectable garnet g-sample',
	components: [
		{content: '< Date Picker Panel Sample', classes: 'g-sample-header', ontap: 'goBack'},

		{content: 'Date Picker Panel', classes: 'g-sample-subheader'},
		{kind: SampleDatePickerPanel, style: 'position: relative;', onResult: 'result'},

		{style: 'position: fixed; width: 100%; min-height: 160px; bottom: 0; z-index: 9999; background-color: #EDEDED; opacity: 0.8;', classes: 'g-sample-result', components: [
			{content: 'Result', classes: 'g-sample-subheader'},
			{name: 'result', allowHtml: true, content: 'No button pressed yet.', classes: 'g-sample-description'}
		]}
	],
	result: function(inSender, inEvent) {
		this.$.result.setContent(inEvent.msg);
	},
	goBack: function(inSender, inEvent) {
		global.history.go(-1);
		return false;
	}
});
<commit_msg>PLAT-11368: Garnet: removed ok and cancel button<commit_after>require('garnet');

var
	kind = require('enyo/kind'),
	GarnetDatePickerPanel = require('garnet/DatePickerPanel');

var SampleDatePickerPanel = kind({
	name: 'g.sample.DatePickerPanel',
	kind: GarnetDatePickerPanel,
	locale: 'en-US',
	style: 'position: relative;',
	mode: 'year'
});

module.exports = kind({
	name: 'g.sample.DatePickerPanelSample',
	classes: 'enyo-unselectable garnet g-sample',
	components: [
		{content: '< Date Picker Panel Sample', classes: 'g-sample-header', ontap: 'goBack'},

		{content: 'Date Picker Panel', classes: 'g-sample-subheader'},
		{name: 'datepicker', kind: SampleDatePickerPanel, style: 'position: relative;'},

		{style: 'position: fixed; width: 100%; min-height: 160px; bottom: 0; z-index: 9999; background-color: #EDEDED; opacity: 0.8;', classes: 'g-sample-result', components: [
			{content: 'Result', classes: 'g-sample-subheader'},
			{name: 'result', allowHtml: true, content: 'No button pressed yet.', classes: 'g-sample-description'}
		]}
	],
	bindings: [
		{from: '.$.datepicker.value', to: '.$.result.content', transform: function(val) {
			return 'Date is ' + val;
		}}
	],
	goBack: function(inSender, inEvent) {
		global.history.go(-1);
		return false;
	}
});
<|endoftext|>


<commit_before>/*A jQuery plugin which add loading indicators into buttons*/

(function ($) {
    $('.has-spinner').attr("disabled", false);
    $.fn.buttonLoader = function (action) {
        var self = $(this);
        if (action == 'start') {
            if ($(self).attr("disabled") == "disabled") {
                return false;
            }
            $('.has-spinner').attr("disabled", true);
            $(self).attr('data-btn-text', $(self).text());
            $(self).html('Loading');
            $(self).addClass('active');
        }
        if (action == 'stop') {
            $(self).html($(self).attr('data-btn-text'));
            $(self).removeClass('active');
            $('.has-spinner').attr("disabled", false);
        }
    }
})(jQuery);
<commit_msg>Renaming button loaidng text as saving<commit_after>/*A jQuery plugin which add loading indicators into buttons*/

(function ($) {
    $('.has-spinner').attr("disabled", false);
    $.fn.buttonLoader = function (action) {
        var self = $(this);
        if (action == 'start') {
            if ($(self).attr("disabled") == "disabled") {
                return false;
            }
            $('.has-spinner').attr("disabled", true);
            $(self).attr('data-btn-text', $(self).text());
            $(self).html('Saving');
            $(self).addClass('active');
        }
        if (action == 'stop') {
            $(self).html($(self).attr('data-btn-text'));
            $(self).removeClass('active');
            $('.has-spinner').attr("disabled", false);
        }
    }
})(jQuery);
<|endoftext|>


<commit_before>import React, { Component } from "react"
import PropTypes from "prop-types"

class CreatePost extends Component {
  static propTypes = {
  }
  constructor(props) {
    super(props)
    this.state = { content: "" }
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handlePostChange = this.handlePostChange.bind(this)
  }
  handlePostChange(event) {
    // console.log(event) // TODO uncomment to see events fire
    console.log("handling an update to the post body!")
    const content = event.target.value
    this.setState(() => {
      return {
        content
      }
    })
  }
  handleSubmit() {
    console.log("Handling submission")
  }

  render () {
    return (

        <button onClick={this.handleSubmit}>Post</button>
        <textarea
          value={this.state.content}
          onChange={this.handlePostChange}
          placeholder="What's on your mind?"
        />

    )
  }
}

export default CreatePost
<commit_msg>BOOK react-in ch5 some basic length validation<commit_after>import React, { Component } from "react"
import PropTypes from "prop-types"

class CreatePost extends Component {
  static propTypes = {
  }
  constructor(props) {
    super(props)
    this.state = {
      content: "",
      valid: false
    }
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handlePostChange = this.handlePostChange.bind(this)
  }
  handlePostChange(event) {
    // console.log(event) // TODO uncomment to see events fire
    console.log("handling an update to the post body!")
    const content = event.target.value
    this.setState(() => {
      return {
        content,
        valid: content.length <= 280
      }
    })
  }
  handleSubmit() {
    if (!this.state.valid) {
      return
    }
    const newPost = {
      content: this.state.content,
    }
    console.log(this.state)
  }

  render () {
    return (

        <button onClick={this.handleSubmit}>Post</button>
        <textarea
          value={this.state.content}
          onChange={this.handlePostChange}
          placeholder="What's on your mind?"
        />

    )
  }
}

export default CreatePost
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import TextFieldAdapter from '../../../adapters/TextFieldAdapter.js';

export default class TextField extends Component {
  constructor(props) {
    super(props);

    const controlled = this.props.value === undefined ? false : true;

    this.state = {
      value: this.getDefaultValue(),
      controlled
    };
  }

  getDefaultValue() {
    const { defaultValue, value } = this.props;

    if (value !== undefined) {
      return value;
    } else if (defaultValue !== undefined) {
      return defaultValue;
    } else {
      return 'foo-bar';
    }
  }

  getRenderedValue() {
    const { value } = this.props;

    if (value !== undefined) {
      return value;
    } else {
      return this.state.value;
    }
  }

  handleInput = event => {
    if (this.props.onInput) {
      this.props.onInput(event);
    }

    if (this.state.controlled) {
      if (this.textFieldEl) {
        this.textFieldEl.forceNextReset();
        this.setState({ value: this.state.value });
      }
    } else {
      this.setState({ value: event.target.value });
    }
  };

  setTextFieldEl = textFieldEl => {
    this.textFieldEl = textFieldEl;
  };

  render() {
    return (
      <TextFieldAdapter
        ref={this.setTextFieldEl}
        {...this.props}
        value={this.getRenderedValue()}
        onInput={this.handleInput}
      />
    );
  }
}
<commit_msg>Add copyright to TextField component<commit_after>/**
Copyright 2016 Autodesk,Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/
import React, { Component } from 'react';
import TextFieldAdapter from '../../../adapters/TextFieldAdapter.js';

export default class TextField extends Component {
  constructor(props) {
    super(props);

    const controlled = this.props.value === undefined ? false : true;

    this.state = {
      value: this.getDefaultValue(),
      controlled
    };
  }

  getDefaultValue() {
    const { defaultValue, value } = this.props;

    if (value !== undefined) {
      return value;
    } else if (defaultValue !== undefined) {
      return defaultValue;
    } else {
      return 'foo-bar';
    }
  }

  getRenderedValue() {
    const { value } = this.props;

    if (value !== undefined) {
      return value;
    } else {
      return this.state.value;
    }
  }

  handleInput = event => {
    if (this.props.onInput) {
      this.props.onInput(event);
    }

    if (this.state.controlled) {
      if (this.textFieldEl) {
        this.textFieldEl.forceNextReset();
        this.setState({ value: this.state.value });
      }
    } else {
      this.setState({ value: event.target.value });
    }
  };

  setTextFieldEl = textFieldEl => {
    this.textFieldEl = textFieldEl;
  };

  render() {
    return (
      <TextFieldAdapter
        ref={this.setTextFieldEl}
        {...this.props}
        value={this.getRenderedValue()}
        onInput={this.handleInput}
      />
    );
  }
}
<|endoftext|>


<commit_before>/*
 * CodePress - Real Time Syntax Highlighting Editor written in JavaScript - http://codepress.org/
 *
 * Copyright (C) 2006 Fernando M.A.d.S. <fermads@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License as published by the Free Software Foundation.
 *
 * Read the full licence: http://www.opensource.org/licenses/lgpl-license.php
 */

// MOD: All local modifications marked with this comment prefix.

// Copied from http://www.google.com/ig/modules/codepress/codepress.js.  Further modifications to
// decouple the domain of the script and the editor iframe.

CodePress = function(obj) {
  var self = document.createElement('iframe');
  self.textarea = obj;
  self.textarea.disabled = true;
  self.textarea.style.overflow = 'hidden';

  // MOD(daniellee): Set height to match existing textarea element
  self.style.height = self.textarea.offsetHeight + 'px';

  // MOD(wwen): change width to 100%
  //self.style.width = self.textarea.clientWidth+'px';
  self.style.width = "100%";

  self.textarea.style.overflow = 'auto';
  // MOD(daniellee): Remove default border. Stylize editor in gge.xml
  //self.style.border = '1px solid gray';
  self.frameBorder = 0; // remove IE internal iframe border
  self.style.visibility = 'hidden';
  self.style.position = 'absolute';
  self.options = self.textarea.className;

  self.initialize = function() {
    self.editor = self.contentWindow.CodePress;
    self.editor.body = self.contentWindow.document.getElementsByTagName('body')[0];
    self.editor.setCode(self.textarea.value);
    self.setOptions();
    self.editor.syntaxHighlight('init');
    self.textarea.style.display = 'none';
    self.style.position = 'static';
    self.style.visibility = 'visible';
    self.style.display = 'inline';
    // MOD(burdon): Call Wrapper.
    if (CodePress.postInitialize) {
      CodePress.postInitialize();
    }
    // MOD(burdon): Spell check off.
    if (self.editor.body.spellcheck) {
      self.editor.body.spellcheck = false;
    }
  }

  self.edit = function(id,language) {
    if(id) self.textarea.value = document.getElementById(id).value;
    if(!self.textarea.disabled) return;
    self.language = language ? language : self.options.replace(/ ?codepress ?| ?readonly-on ?| ?autocomplete-off ?| ?linenumbers-off ?/g,'');
    if(!CodePress.languages[self.language]) self.language = 'generic';
    self.innerHTML = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' +
        '' +
        '' +
        '	<title>CodePress - Real Time Syntax Highlighting Editor written in JavaScript</title>' +
        '	<meta name="description" content="CodePress - source code editor window" />' +
        '' +
        '	' +
        '' +
        '' +
        '' +
        '' +
        '' +
        '';
    if(self.attachEvent) self.attachEvent('onload',self.initialize);
    else self.addEventListener('load',self.initialize,false);
  }

  self.setOptions = function() {
    if(self.options.match('autocomplete-off')) self.toggleAutoComplete();
    if(self.options.match('readonly-on')) self.toggleReadOnly();
    if(self.options.match('linenumbers-off')) self.toggleLineNumbers();
  }

  self.getCode = function() {
    return self.textarea.disabled ? self.editor.getCode() : self.textarea.value;
  }

  self.setCode = function(code) {
    self.textarea.disabled ? self.editor.setCode(code) : self.textarea.value = code;
  }

  self.toggleAutoComplete = function() {
    self.editor.autocomplete = (self.editor.autocomplete) ? false : true;
  }

  self.toggleReadOnly = function() {
    self.textarea.readOnly = (self.textarea.readOnly) ? false : true;
    if(self.style.display != 'none') // prevent exception on FF + iframe with display:none
      self.editor.readOnly(self.textarea.readOnly ? true : false);
  }

  self.toggleLineNumbers = function() {
    var cn = self.editor.body.className;
    self.editor.body.className = (cn==''||cn=='show-line-numbers') ? 'hide-line-numbers' : 'show-line-numbers';
  }

  self.toggleEditor = function() {
    if(self.textarea.disabled) {
      self.textarea.value = self.getCode();
      self.textarea.disabled = false;
      self.style.display = 'none';
      self.textarea.style.display = 'inline';
    }
    else {
      self.textarea.disabled = true;
      self.setCode(self.textarea.value);
      self.editor.syntaxHighlight('init');
      self.style.display = 'inline';
      self.textarea.style.display = 'none';
    }
  }

  self.edit();
  return self;
}

CodePress.languages = {
  css : 'CSS',
  generic : 'Generic',
  html : 'HTML',
  java : 'Java',
  javascript : 'JavaScript',
  perl : 'Perl',
  ruby : 'Ruby',
  php : 'PHP',
  text : 'Text',
  sql : 'SQL',
  gadget : 'Gadget'
}

// MOD(burdon):
CodePress.getEngine = function() {
  var engine = 'older';
  var ua = navigator.userAgent;
  if(ua.match('MSIE')) engine = 'msie';
  else if(ua.match('KHTML')) engine = 'khtml';
  else if(ua.match('Opera')) engine = 'opera';
  else if(ua.match('Gecko')) engine = 'gecko';
  return engine;
}

CodePress.run = function() {
  CodePress.engine = CodePress.getEngine();
  s = document.getElementsByTagName('script');
  for(var i=0,n=s.length;i<n;i++) {
    if(s[i].src.match(/codepress_wrapper\.js.*/)) {
      CodePress.path = s[i].src.replace(/codepress_wrapper\.js.*/,'');
    }
  }
  t = document.getElementsByTagName('textarea');
  for(var i=0,n=t.length;i<n;i++) {
    if(t[i].className.match('codepress')) {
      id = t[i].id;
      t[i].id = id+'_cp';
      eval(id+' = new CodePress(t[i])');
      t[i].parentNode.insertBefore(eval(id), t[i]);
    }
  }
}

// MOD(burdon): Add our language.
CodePress.languages["gm"] = 'GM';

/*
// MOD(burdon): Now triggered by CodePressEditor:init
if(window.attachEvent) window.attachEvent('onload',CodePress.run);
else window.addEventListener('DOMContentLoaded',CodePress.run,false);
*/
<commit_msg>fixed iframe content creation logic<commit_after>/*
 * CodePress - Real Time Syntax Highlighting Editor written in JavaScript - http://codepress.org/
 *
 * Copyright (C) 2006 Fernando M.A.d.S. <fermads@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License as published by the Free Software Foundation.
 *
 * Read the full licence: http://www.opensource.org/licenses/lgpl-license.php
 */

// MOD: All local modifications marked with this comment prefix.

// Copied from http://www.google.com/ig/modules/codepress/codepress.js.  Further modifications to
// decouple the domain of the script and the editor iframe.

CodePress = function(obj) {
  var self = document.createElement('iframe');
  self.textarea = obj;
  self.textarea.disabled = true;
  self.textarea.style.overflow = 'hidden';

  // MOD(daniellee): Set height to match existing textarea element
  self.style.height = self.textarea.offsetHeight + 'px';

  // MOD(wwen): change width to 100%
  //self.style.width = self.textarea.clientWidth+'px';
  self.style.width = "100%";

  self.textarea.style.overflow = 'auto';
  // MOD(daniellee): Remove default border. Stylize editor in gge.xml
  //self.style.border = '1px solid gray';
  self.frameBorder = 0; // remove IE internal iframe border
  self.style.visibility = 'hidden';
  self.style.position = 'absolute';
  self.options = self.textarea.className;

  self.initialize = function() {
    self.editor = self.contentWindow.CodePress;
    self.editor.body = self.contentWindow.document.getElementsByTagName('body')[0];
    self.editor.setCode(self.textarea.value);
    self.setOptions();
    self.editor.syntaxHighlight('init');
    self.textarea.style.display = 'none';
    self.style.position = 'static';
    self.style.visibility = 'visible';
    self.style.display = 'inline';
    // MOD(burdon): Call Wrapper.
    if (CodePress.postInitialize) {
      CodePress.postInitialize();
    }
    // MOD(burdon): Spell check off.
    if (self.editor.body.spellcheck) {
      self.editor.body.spellcheck = false;
    }
  }

  self.edit = function(id,language) {
    if(id) self.textarea.value = document.getElementById(id).value;
    if(!self.textarea.disabled) return;
    self.language = language ? language : self.options.replace(/ ?codepress ?| ?readonly-on ?| ?autocomplete-off ?| ?linenumbers-off ?/g,'');
    if(!CodePress.languages[self.language]) self.language = 'generic';

    document.body.appendChild(self);
    var contentDoc = self.document || self.contentDocument || self.contentWindow.documnt;
    contentDoc.open();
    contentDoc.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n' +
        '\n' +
        '\n' +
        '	<title>CodePress - Real Time Syntax Highlighting Editor written in JavaScript</title>\n' +
        '	<meta name="description" content="CodePress - source code editor window" />\n' +
        '\n' +
        '	\n' +
        '\n' +
        '\n' +
        '\n' +
        '\n' +
        '\n' +
        '');
    contentDoc.close();

    if(self.attachEvent) self.attachEvent('onload',self.initialize);
    else self.addEventListener('load',self.initialize,false);
  }

  self.setOptions = function() {
    if(self.options.match('autocomplete-off')) self.toggleAutoComplete();
    if(self.options.match('readonly-on')) self.toggleReadOnly();
    if(self.options.match('linenumbers-off')) self.toggleLineNumbers();
  }

  self.getCode = function() {
    return self.textarea.disabled ? self.editor.getCode() : self.textarea.value;
  }

  self.setCode = function(code) {
    self.textarea.disabled ? self.editor.setCode(code) : self.textarea.value = code;
  }

  self.toggleAutoComplete = function() {
    self.editor.autocomplete = (self.editor.autocomplete) ? false : true;
  }

  self.toggleReadOnly = function() {
    self.textarea.readOnly = (self.textarea.readOnly) ? false : true;
    if(self.style.display != 'none') // prevent exception on FF + iframe with display:none
      self.editor.readOnly(self.textarea.readOnly ? true : false);
  }

  self.toggleLineNumbers = function() {
    var cn = self.editor.body.className;
    self.editor.body.className = (cn==''||cn=='show-line-numbers') ? 'hide-line-numbers' : 'show-line-numbers';
  }

  self.toggleEditor = function() {
    if(self.textarea.disabled) {
      self.textarea.value = self.getCode();
      self.textarea.disabled = false;
      self.style.display = 'none';
      self.textarea.style.display = 'inline';
    }
    else {
      self.textarea.disabled = true;
      self.setCode(self.textarea.value);
      self.editor.syntaxHighlight('init');
      self.style.display = 'inline';
      self.textarea.style.display = 'none';
    }
  }

  self.edit();
  return self;
}

CodePress.languages = {
  css : 'CSS',
  generic : 'Generic',
  html : 'HTML',
  java : 'Java',
  javascript : 'JavaScript',
  perl : 'Perl',
  ruby : 'Ruby',
  php : 'PHP',
  text : 'Text',
  sql : 'SQL',
  gadget : 'Gadget'
}

// MOD(burdon):
CodePress.getEngine = function() {
  var engine = 'older';
  var ua = navigator.userAgent;
  if(ua.match('MSIE')) engine = 'msie';
  else if(ua.match('KHTML')) engine = 'khtml';
  else if(ua.match('Opera')) engine = 'opera';
  else if(ua.match('Gecko')) engine = 'gecko';
  return engine;
}

CodePress.run = function() {
  CodePress.engine = CodePress.getEngine();
  s = document.getElementsByTagName('script');
  for(var i=0,n=s.length;i<n;i++) {
    if(s[i].src.match(/codepress_wrapper\.js.*/)) {
      CodePress.path = s[i].src.replace(/codepress_wrapper\.js.*/,'');
    }
  }
  t = document.getElementsByTagName('textarea');
  for(var i=0,n=t.length;i<n;i++) {
    if(t[i].className.match('codepress')) {
      id = t[i].id;
      t[i].id = id+'_cp';
      eval(id+' = new CodePress(t[i])');
      t[i].parentNode.insertBefore(eval(id), t[i]);
    }
  }
}

// MOD(burdon): Add our language.
CodePress.languages["gm"] = 'GM';

/*
// MOD(burdon): Now triggered by CodePressEditor:init
if(window.attachEvent) window.attachEvent('onload',CodePress.run);
else window.addEventListener('DOMContentLoaded',CodePress.run,false);
*/
<|endoftext|>


<commit_before>import reducer from './images';
import {
  ADD_FRAME,
  UPDATE_GIF_PROGRESS,
  UPDATE_GIF_FILENAME,
  ADD_GIF,
  UNDO_BURST,
  UPDATE_IMAGE_SETTING,
  UPDATE_BOUNDS_SETTING,
  UPDATE_STRATEGY,
  UPDATE_TEXT,
  UPDATE_TEXT_COLOR,
  UPDATE_TEXT_POSITION,
  RESET
} from '../constants/action-types';

const initialState = {
  frames: {},
  frameIDs: [],
  gifProgress: 0,
  gifData: '',
  caption: '',
  fontColor: '#000000',
  gifFileName: '',
  textAlign: 'center',
  textBaseline: 'bottom'
};

describe('reducers', () => {
  describe('images', () => {
    it('returns the correct initial state', () => {
      expect(reducer(undefined, {})).toEqual(initialState);
    });

    it('handles ADD_FRAME', () => {
      const imageData = 'URI';
      const newState = reducer(initialState, {
        type: ADD_FRAME,
        payload: {
          id: 1,
          imageData
        }
      });
      expect(newState.frames).toEqual({ 1: imageData });
      expect(newState.frameIDs).toEqual([1]);
    });

    it('handles UPDATE_GIF_PROGRESS', () => {
      const gifProgress = 0.5;
      const newState = reducer(initialState, {
        type: UPDATE_GIF_PROGRESS,
        payload: { progress: gifProgress }
      });
      expect(newState.gifProgress).toEqual(gifProgress);
    });

    it('handles UPDATE_GIF_FILENAME', () => {
      const gifFileName = 'name';
      const newState = reducer(initialState, {
        type: UPDATE_GIF_FILENAME,
        payload: { gifFileName }
      });
      expect(newState.gifFileName).toEqual(gifFileName);
    });

    it('handles ADD_GIF', () => {
      const gifData = 'URI';
      const newState = reducer(initialState, {
        type: ADD_GIF,
        payload: { imageData: gifData }
      });
      expect(newState.gifData).toEqual(gifData);
    });

    it('handles UNDO_BURST', () => {
      const frames = { 0: 'zero' };
      const frameIDs = [0];
      const newState = reducer(initialState, {
        type: UNDO_BURST,
        payload: { frames, frameIDs }
      });
      expect(newState.frames).toEqual(frames);
      expect(newState.frameIDs).toEqual(frameIDs);
    });

    it('handles image setting actions', () => {
      const gifData = 'URI';
      const gifProgress = 1;
      const gifState = reducer(initialState, {
        type: ADD_GIF,
        payload: { imageData: gifData }
      });
      const progressState = reducer(gifState, {
        type: UPDATE_GIF_PROGRESS,
        payload: { progress: gifProgress }
      });
      const finalState = reducer(progressState, {
        type: UPDATE_IMAGE_SETTING,
        payload: { width: 200 }
      });
      expect(finalState.gifData).toEqual('');
      expect(finalState.gifProgress).toEqual(0);
    });

    it('handles UPDATE_GIF_FILENAME', () => {
      const gifFileName = 'name';
      const newState = reducer(initialState, {
        type: UPDATE_GIF_FILENAME,
        payload: { gifFileName }
      });
      expect(newState.gifFileName).toEqual(gifFileName);
    });

    it('handles UPDATE_TEXT', () => {
      const text = 'text';
      const newState = reducer(initialState, {
        type: UPDATE_TEXT,
        payload: { text }
      });
      expect(newState.caption).toEqual(text);
    });

    it('handles UPDATE_TEXT_COLOR', () => {
      const fontColor = '#FFFFFF';
      const newState = reducer(initialState, {
        type: UPDATE_TEXT_COLOR,
        payload: { fontColor }
      });
      expect(newState.fontColor).toEqual(fontColor);
    });

    it('handles UPDATE_TEXT_POSITION', () => {
      const textAlign = 'left';
      const textBaseline = 'top';

      const newState = reducer(initialState, {
        type: UPDATE_TEXT_POSITION,
        payload: { textAlign, textBaseline }
      });
      expect(newState.textAlign).toEqual(textAlign);
      expect(newState.textBaseline).toEqual(textBaseline);
    });

    it('handles RESET', () => {
      const gifData = 'URI';
      const gifProgress = 1;
      const gifState = reducer(initialState, {
        type: ADD_GIF,
        payload: { imageData: gifData }
      });
      const progressState = reducer(gifState, {
        type: UPDATE_GIF_PROGRESS,
        payload: { progress: gifProgress }
      });
      const finalState = reducer(progressState, { type: RESET });
      expect(finalState).toEqual(initialState);
    });
  });
});
<commit_msg>remove duplicate test<commit_after>import reducer from './images';
import {
  ADD_FRAME,
  UPDATE_GIF_PROGRESS,
  UPDATE_GIF_FILENAME,
  ADD_GIF,
  UNDO_BURST,
  UPDATE_IMAGE_SETTING,
  UPDATE_BOUNDS_SETTING,
  UPDATE_STRATEGY,
  UPDATE_TEXT,
  UPDATE_TEXT_COLOR,
  UPDATE_TEXT_POSITION,
  RESET
} from '../constants/action-types';

const initialState = {
  frames: {},
  frameIDs: [],
  gifProgress: 0,
  gifData: '',
  caption: '',
  fontColor: '#000000',
  gifFileName: '',
  textAlign: 'center',
  textBaseline: 'bottom'
};

describe('reducers', () => {
  describe('images', () => {
    it('returns the correct initial state', () => {
      expect(reducer(undefined, {})).toEqual(initialState);
    });

    it('handles ADD_FRAME', () => {
      const imageData = 'URI';
      const newState = reducer(initialState, {
        type: ADD_FRAME,
        payload: {
          id: 1,
          imageData
        }
      });
      expect(newState.frames).toEqual({ 1: imageData });
      expect(newState.frameIDs).toEqual([1]);
    });

    it('handles UPDATE_GIF_PROGRESS', () => {
      const gifProgress = 0.5;
      const newState = reducer(initialState, {
        type: UPDATE_GIF_PROGRESS,
        payload: { progress: gifProgress }
      });
      expect(newState.gifProgress).toEqual(gifProgress);
    });

    it('handles UPDATE_GIF_FILENAME', () => {
      const gifFileName = 'name';
      const newState = reducer(initialState, {
        type: UPDATE_GIF_FILENAME,
        payload: { gifFileName }
      });
      expect(newState.gifFileName).toEqual(gifFileName);
    });

    it('handles ADD_GIF', () => {
      const gifData = 'URI';
      const newState = reducer(initialState, {
        type: ADD_GIF,
        payload: { imageData: gifData }
      });
      expect(newState.gifData).toEqual(gifData);
    });

    it('handles UNDO_BURST', () => {
      const frames = { 0: 'zero' };
      const frameIDs = [0];
      const newState = reducer(initialState, {
        type: UNDO_BURST,
        payload: { frames, frameIDs }
      });
      expect(newState.frames).toEqual(frames);
      expect(newState.frameIDs).toEqual(frameIDs);
    });

    it('handles image setting actions', () => {
      const gifData = 'URI';
      const gifProgress = 1;
      const gifState = reducer(initialState, {
        type: ADD_GIF,
        payload: { imageData: gifData }
      });
      const progressState = reducer(gifState, {
        type: UPDATE_GIF_PROGRESS,
        payload: { progress: gifProgress }
      });
      const finalState = reducer(progressState, {
        type: UPDATE_IMAGE_SETTING,
        payload: { width: 200 }
      });
      expect(finalState.gifData).toEqual('');
      expect(finalState.gifProgress).toEqual(0);
    });

    it('handles UPDATE_TEXT', () => {
      const text = 'text';
      const newState = reducer(initialState, {
        type: UPDATE_TEXT,
        payload: { text }
      });
      expect(newState.caption).toEqual(text);
    });

    it('handles UPDATE_TEXT_COLOR', () => {
      const fontColor = '#FFFFFF';
      const newState = reducer(initialState, {
        type: UPDATE_TEXT_COLOR,
        payload: { fontColor }
      });
      expect(newState.fontColor).toEqual(fontColor);
    });

    it('handles UPDATE_TEXT_POSITION', () => {
      const textAlign = 'left';
      const textBaseline = 'top';

      const newState = reducer(initialState, {
        type: UPDATE_TEXT_POSITION,
        payload: { textAlign, textBaseline }
      });
      expect(newState.textAlign).toEqual(textAlign);
      expect(newState.textBaseline).toEqual(textBaseline);
    });

    it('handles RESET', () => {
      const gifData = 'URI';
      const gifProgress = 1;
      const gifState = reducer(initialState, {
        type: ADD_GIF,
        payload: { imageData: gifData }
      });
      const progressState = reducer(gifState, {
        type: UPDATE_GIF_PROGRESS,
        payload: { progress: gifProgress }
      });
      const finalState = reducer(progressState, { type: RESET });
      expect(finalState).toEqual(initialState);
    });
  });
});
<|endoftext|>