<commit_before>/**
 * Editor screen for uploading visualisations
 * @param collectionId
 * @param data
 */

function visualisationEditor(collectionId, data, collectionData) {
    var path = Florence.globalVars.pagePath,
        $indexSelect = $('#filenames'),
        setActiveTab, getActiveTab;

    // Active tab
    $(".edit-accordion").on('accordionactivate', function () {
        setActiveTab = $(".edit-accordion").accordion("option", "active");
        if (setActiveTab !== false) {
            Florence.globalVars.activeTab = setActiveTab;
        }
    });
    getActiveTab = Florence.globalVars.activeTab;
    accordion(getActiveTab);
    getLastPosition();

    // Refresh preview with new URL if index page previously selected (can't use refreshPreview function because it removes "/" from end or path by default)
    function refreshVisPreview(url) {
        var newUrl;
        if (url) {
            newUrl = Florence.tredegarBaseUrl + path + url;
            Florence.globalVars.pagePath = path;
        } else {
            newUrl = Florence.tredegarBaseUrl + path + "/";
        }
        document.getElementById('iframe').contentWindow.location.href = newUrl;
        $('.browser-location').val(newUrl);
    }
    if ($indexSelect.val()) {
        refreshVisPreview();
    }

    // Submit new ZIP file
    bindZipSubmit();

    // Edit existing ZIP file
    $('#edit-vis').on('submit', function (e) {
        e.preventDefault();
        e.stopImmediatePropagation();

        // Refresh visualisations tab but show 'submit ZIP' option
        var tempData = data;
        tempData.zipTitle = "";
        var html = templates.workEditVisualisation(tempData);
        $('.workspace-menu').html(html);
        bindZipSubmit();

        // Set visualisation tab to active
        accordion(1);
    });

    // Listen to change of index page input and refresh preview to show new index page
    $indexSelect.change(function () {
        refreshVisPreview($indexSelect.val());
    });

    // Bind save buttons
    var editNav = $('.edit-nav');
    editNav.off(); // remove any existing event handlers.

    editNav.on('click', '.btn-edit-save', function () {
        var indexPage = $('#filenames').val();
        data['indexPage'] = indexPage;

        save();
    });

    editNav.on('click', '.btn-edit-save-and-submit-for-review', function () {
        saveAndCompleteContent(collectionId, data.uri, JSON.stringify(data), true);
    });

    editNav.on('click', '.btn-edit-save-and-submit-for-approval', function () {
        saveAndReviewContent(collectionId, data.uri, JSON.stringify(data), true);
    });

    /* FUNCTIONS */
    function bindZipSubmit() {
        // Upload ZIP file
        $('#upload-vis').on('submit', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();

            var formdata = new FormData($(this)[0]),
                file = this[0].files[0];

            if (!$('#input-vis')) {
                sweetAlert("Please choose a file before submitting");
                return false;
            }

            if (!file.name.match(/\.zip$/)) {
                sweetAlert("Incorrect file format", "You are only allowed to upload ZIP files", "warning")
            } else {
                var fileNameNoSpace = file.name.replace(/[^a-zA-Z0-9\.]/g, "").toLowerCase();
                var uniqueIdNoSpace = data.uid.replace(/[^a-zA-Z0-9\.]/g, "").toLowerCase();
                var contentUri = "/visualisations/" + uniqueIdNoSpace + "/content";
                var uriUpload = contentUri + "/" + fileNameNoSpace;
                var safeUriUpload = checkPathSlashes(uriUpload);

                path = "/visualisations/" + uniqueIdNoSpace + "/";

                deleteAndUploadFile(
                    safeUriUpload, contentUri, formdata,
                    success = function () {
                        unpackZip(safeUriUpload,
                            success = function () {

                                // On unpack of Zip refresh the reload editor and preview
                                loadPageDataIntoEditor(path, collectionId);
                            }
                        );
                    }
                )
            }

        });
    }

    function deleteAndUploadFile(path, contentUri, formData, success) {
        $.ajax({
            url: "/zebedee/DataVisualisationZip/" + Florence.collection.id + "?zipPath=" + contentUri,
            type: 'DELETE',
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (response) {
                uploadFile(path, formData, success);
            },
            error: function (response) {
                handleApiError(response);
            }
        });
    }

    function uploadFile(path, formData, success) {
        // Send zip file to zebedee
        $.ajax({
            url: "/zebedee/content/" + Florence.collection.id + "?uri=" + path,
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (response) {
                success(response);
            },
            error: function (response) {
                handleApiError(response);
            }
        });
    }

    function unpackZip(zipPath, success, error) {
        // Unpack contents of ZIP
        console.log("Unpack: " + zipPath);
        var url = "/zebedee/DataVisualisationZip/" + Florence.collection.id + "?zipPath=" + zipPath;

        $.ajax({
            url: url,
            contentType: 'application/json',
            type: 'POST',
            success: function (response) {
                success(response);
            },
            error: function (response) {
                if (error) {
                    error(response);
                } else {
                    handleApiError(response);
                }
            }
        });
    }

    function save() {
        putContent(collectionId, data.uri, JSON.stringify(data),
            success = function () {
                Florence.Editor.isDirty = false;
                refreshVisPreview();
                loadPageDataIntoEditor(data.uri, collectionId);
            },
            error = function (response) {
                if (response.status === 409) {
                    sweetAlert("Cannot edit this page", "It is already part of another collection.");
                } else {
                    handleApiError(response);
                }
            },
            true
        );
    }
}
<commit_msg>Use given uri instead of global.<commit_after>/**
 * Editor screen for uploading visualisations
 * @param collectionId
 * @param data
 */

function visualisationEditor(collectionId, data, collectionData) {
    var path = data.uri,
        $indexSelect = $('#filenames'),
        setActiveTab, getActiveTab;

    // Active tab
    $(".edit-accordion").on('accordionactivate', function () {
        setActiveTab = $(".edit-accordion").accordion("option", "active");
        if (setActiveTab !== false) {
            Florence.globalVars.activeTab = setActiveTab;
        }
    });
    getActiveTab = Florence.globalVars.activeTab;
    accordion(getActiveTab);
    getLastPosition();

    // Refresh preview with new URL if index page previously selected (can't use refreshPreview function because it removes "/" from end or path by default)
    function refreshVisPreview(url) {
        var newUrl;
        if (url) {
            newUrl = Florence.tredegarBaseUrl + path + url;
            Florence.globalVars.pagePath = path;
        } else {
            newUrl = Florence.tredegarBaseUrl + path + "/";
        }
        document.getElementById('iframe').contentWindow.location.href = newUrl;
        $('.browser-location').val(newUrl);
    }
    if ($indexSelect.val()) {
        refreshVisPreview();
    }

    // Submit new ZIP file
    bindZipSubmit();

    // Edit existing ZIP file
    $('#edit-vis').on('submit', function (e) {
        e.preventDefault();
        e.stopImmediatePropagation();

        // Refresh visualisations tab but show 'submit ZIP' option
        var tempData = data;
        tempData.zipTitle = "";
        var html = templates.workEditVisualisation(tempData);
        $('.workspace-menu').html(html);
        bindZipSubmit();

        // Set visualisation tab to active
        accordion(1);
    });

    // Listen to change of index page input and refresh preview to show new index page
    $indexSelect.change(function () {
        refreshVisPreview($indexSelect.val());
    });

    // Bind save buttons
    var editNav = $('.edit-nav');
    editNav.off(); // remove any existing event handlers.

    editNav.on('click', '.btn-edit-save', function () {
        var indexPage = $('#filenames').val();
        data['indexPage'] = indexPage;

        save();
    });

    editNav.on('click', '.btn-edit-save-and-submit-for-review', function () {
        saveAndCompleteContent(collectionId, data.uri, JSON.stringify(data), true);
    });

    editNav.on('click', '.btn-edit-save-and-submit-for-approval', function () {
        saveAndReviewContent(collectionId, data.uri, JSON.stringify(data), true);
    });

    /* FUNCTIONS */
    function bindZipSubmit() {
        // Upload ZIP file
        $('#upload-vis').on('submit', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();

            var formdata = new FormData($(this)[0]),
                file = this[0].files[0];

            if (!$('#input-vis')) {
                sweetAlert("Please choose a file before submitting");
                return false;
            }

            if (!file.name.match(/\.zip$/)) {
                sweetAlert("Incorrect file format", "You are only allowed to upload ZIP files", "warning")
            } else {
                var fileNameNoSpace = file.name.replace(/[^a-zA-Z0-9\.]/g, "").toLowerCase();
                var uniqueIdNoSpace = data.uid.replace(/[^a-zA-Z0-9\.]/g, "").toLowerCase();
                var contentUri = "/visualisations/" + uniqueIdNoSpace + "/content";
                var uriUpload = contentUri + "/" + fileNameNoSpace;
                var safeUriUpload = checkPathSlashes(uriUpload);

                path = "/visualisations/" + uniqueIdNoSpace + "/";

                deleteAndUploadFile(
                    safeUriUpload, contentUri, formdata,
                    success = function () {
                        unpackZip(safeUriUpload,
                            success = function () {

                                // On unpack of Zip refresh the reload editor and preview
                                loadPageDataIntoEditor(path, collectionId);
                            }
                        );
                    }
                )
            }

        });
    }

    function deleteAndUploadFile(path, contentUri, formData, success) {
        $.ajax({
            url: "/zebedee/DataVisualisationZip/" + Florence.collection.id + "?zipPath=" + contentUri,
            type: 'DELETE',
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (response) {
                uploadFile(path, formData, success);
            },
            error: function (response) {
                handleApiError(response);
            }
        });
    }

    function uploadFile(path, formData, success) {
        // Send zip file to zebedee
        $.ajax({
            url: "/zebedee/content/" + Florence.collection.id + "?uri=" + path,
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (response) {
                success(response);
            },
            error: function (response) {
                handleApiError(response);
            }
        });
    }

    function unpackZip(zipPath, success, error) {
        // Unpack contents of ZIP
        console.log("Unpack: " + zipPath);
        var url = "/zebedee/DataVisualisationZip/" + Florence.collection.id + "?zipPath=" + zipPath;

        $.ajax({
            url: url,
            contentType: 'application/json',
            type: 'POST',
            success: function (response) {
                success(response);
            },
            error: function (response) {
                if (error) {
                    error(response);
                } else {
                    handleApiError(response);
                }
            }
        });
    }

    function save() {
        putContent(collectionId, data.uri, JSON.stringify(data),
            success = function () {
                Florence.Editor.isDirty = false;
                refreshVisPreview();
                loadPageDataIntoEditor(data.uri, collectionId);
            },
            error = function (response) {
                if (response.status === 409) {
                    sweetAlert("Cannot edit this page", "It is already part of another collection.");
                } else {
                    handleApiError(response);
                }
            },
            true
        );
    }
}
<|endoftext|>


<commit_before>/**
 *  Copyright (C) 2011 Orbeon, Inc.
 *
 *
 *  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; either version
 *  2.1 of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *  See the GNU Lesser General Public License for more details.
 *
 *  The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
 */
(function() {
    var OD = ORBEON.util.Dom;
    var YD = YAHOO.util.Dom;
    var Document = ORBEON.xforms.Document;

    YAHOO.namespace("xbl.fr");
    YAHOO.xbl.fr.Autocomplete = function() {};
    ORBEON.xforms.XBL.declareClass(YAHOO.xbl.fr.Autocomplete, "xbl-fr-autocomplete");
    YAHOO.xbl.fr.Autocomplete.prototype = {

        dynamicItemset: null,       // Do we need to wait for the itemset to change before we update the auto-complete?
        yuiAutoComplete: null,      // YUI object for the auto-complete
        searchControl: null,        // xforms:input control in which users type
        searchField: null,          // Form field in which users type
        valueSelectedTrigger: null,  // Bridge to tell XForms users selected a value
        externalValueInput : null,  // xforms:input containing the external value
        justMadeSelection: false,   // Reset to false when an Ajax response arrives
        suggestionRequested: false, // Whether users requested the suggestion menu to open by clicking on the button

        /**
         * Constructor
         */
        init: function() {
            this.searchControl = YD.getElementsByClassName("fr-autocomplete-search", null, this.container)[0];
            this.searchField = YD.getChildren(this.searchControl)[0];
            this.valueSelectedTrigger = YD.getElementsByClassName("fr-autocomplete-value-selected", null, this.container)[0];
            var yuiDiv = YD.getElementsByClassName("fr-autocomplete-yui-div", null, this.container)[0];
            YD.generateId(yuiDiv); // Generate ID dynamically as our implementation of XBL doesn't rewrite IDs on HTML
            this.externalValueInput = YD.getElementsByClassName("fr-autocomplete-external-value", null, this.container)[0];

            // This is mostly useful for the dynamic and resources cases, but this code is also useful in static mode, allowing us
            // to open the suggestions in static mode when the button is pressed
            ORBEON.xforms.Events.ajaxResponseProcessedEvent.subscribe(_.bind(this.ajaxResponseProcessed, this));

            // Build data source
            var dataSource;
            if (this.isDynamicItemset()) {
                // If the itemset changes dynamically, update list when we have response to an Ajax request
                dataSource = this.buildNullDataSource();
            } else {
                // Simply filters on the values in the hidden dropdown; we could do this on Ajax response, but using a data source
                // allows us to show suggestions faster, without having to wait for the result of the Ajax request
                var autoComplete = this;
                dataSource = new YAHOO.util.FunctionDataSource(function(query) {
                    return autoComplete.getCurrentValues(query);
                });
            }

            // Create YUI auto-complete object
            this.yuiAutoComplete = new YAHOO.widget.AutoComplete(this.searchField.id, yuiDiv.id, dataSource);
            // Use iframe method for IE6/7
            if (YAHOO.env.ua.ie != 0 && YAHOO.env.ua.ie <= 7)
                this.yuiAutoComplete.useIFrame = true;
            this.yuiAutoComplete.animVert = false;

            // Set maximum number of items displayed
            var maxResultsDisplayedOutput = YD.getElementsByClassName("xbl-fr-autocomplete-max-results-displayed", null, this.container)[0];
            var maxResultsDisplayed = Document.getValue(maxResultsDisplayedOutput.id);
            if (maxResultsDisplayed == "") maxResultsDisplayed = 10;
            this.yuiAutoComplete.maxResultsDisplayed = parseInt(maxResultsDisplayed, 10);

            // Listen on user selecting a value
            this.yuiAutoComplete.itemSelectEvent.subscribe(this.itemSelected, this, true);
        },

        /**
         * Called when the user selects a value from the suggestion list
         */
        itemSelected: function(type, args) {
            var itemLabel = args[2][0];
            this.justMadeSelection = true;
            Document.setValue(this.searchControl.id, itemLabel);
            ORBEON.xforms.Document.dispatchEvent(this.container.id, "fr-value-selected");
        },

        /**
         * Called when we received a response for an Ajax request, which means we may have to update the suggestion list
         */
        ajaxResponseProcessed: function() {
            // Get new list of values
            var query = this.searchField.value;
            var newList = this.getCurrentValues(query);

            var doUpdateSuggestionList =
                this.suggestionRequested || (
                // If the user just selected something before which triggered an Ajax query, don't show the suggestion list
                // as users expect the suggestion list to close after making a selection (clicking or pressing enter)
                ! this.justMadeSelection
                // Update the list only of the control has the focus, as updating the list will show the suggestion list
                // and we only want to show the suggestion list if the user happens to be in that field
                && ORBEON.xforms.Globals.currentFocusControlId == this.searchControl.id);
            if (doUpdateSuggestionList) {
                // Tell YUI this control has the focus; we set the focus on the input, but the YUI focus handler is sometimes called too late
                this.yuiAutoComplete._bFocused = true;
                this.yuiAutoComplete._populateList(query, { results: newList }, { query: query });
            }
            this.justMadeSelection = false;
            this.suggestionRequested = false;
        },

        /**
         * Creates a data source that never returns anything
         */
        buildNullDataSource: function() {
            var autoComplete = this;

            var WaitAjaxResponseDataSource = function(oLiveData, oConfigs) {
                this.dataType = YAHOO.util.DataSourceBase.TYPE_JSFUNCTION;
                oLiveData = oLiveData || function() {};
                this.constructor.superclass.constructor.call(this, oLiveData, oConfigs);
            };

            YAHOO.lang.extend(WaitAjaxResponseDataSource, YAHOO.util.DataSourceBase, {
                makeConnection : function(oRequest, oCallback, oCaller) {
                    var dataSource = this;
                    var tId = YAHOO.util.DataSourceBase._nTransactionId++;
                    dataSource.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
                    dataSource.responseType = YAHOO.util.DataSourceBase.TYPE_JSARRAY;
                    return tId;
                }
            });

            return new WaitAjaxResponseDataSource(function(query) { return autoComplete.getCurrentValues(query); }, {});
        },

        /**
         * Returns the list of values currently in the itemset
         */
        isDynamicItemset: function() {
            var autoComplete = this;
            if (autoComplete.dynamicItemset === null) {
                var output = YD.getElementsByClassName("fr-autocomplete-dynamic-itemset", null, autoComplete.container)[0];
                autoComplete.dynamicItemset = Document.getValue(output.id) == "true";
            }
            return autoComplete.dynamicItemset;
        },

        /**
         * Returns the content the values from the select1
         */
        getCurrentValues: function(query) {
            var result = [];

            // YUI autocomplete give us an escaped string
            query = unescape(query);
            // Look again for the element, as on IE the <select> is recreated when the itemset changes, and so can't be cached
            var select1Container = YD.getElementsByClassName("fr-autocomplete-select1", null, this.container)[0];
            var select1Element = OD.getElementByTagName(select1Container, "select");
            var options = select1Element.options;

            if (this.suggestionRequested        // Always build result if asked by users by clicking on button
                    || query != "" ) {          // Don't build result if user deleted everything from the field
                var queryLowerCase = query.toLowerCase();
                var itemsCount = options.length / 2;
                for (var optionIndex = 0; optionIndex < itemsCount; optionIndex++) {
                    var option = options[optionIndex];
                    // We only do filtering for the static itemset mode
                    if (this.isDynamicItemset() || option.value.toLowerCase().indexOf(queryLowerCase) == 0 || query == "")
                        result[result.length] = [ option.value, options[itemsCount + optionIndex].value ];
                }
            }

            // If the result only contains one item, and its label is equal to the current value, don't show suggestions
            // Set the external value to the value of this option
            if (result.length == 1 && result[0][0] == query)
                result = [];

            return result;
        }
    };
})();<commit_msg>Solves issue with selection sometimes having no effect, fixes #436<commit_after>/**
 *  Copyright (C) 2011 Orbeon, Inc.
 *
 *
 *  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; either version
 *  2.1 of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *  See the GNU Lesser General Public License for more details.
 *
 *  The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
 */
(function() {
    var OD = ORBEON.util.Dom;
    var YD = YAHOO.util.Dom;
    var Document = ORBEON.xforms.Document;

    YAHOO.namespace("xbl.fr");
    YAHOO.xbl.fr.Autocomplete = function() {};
    ORBEON.xforms.XBL.declareClass(YAHOO.xbl.fr.Autocomplete, "xbl-fr-autocomplete");
    YAHOO.xbl.fr.Autocomplete.prototype = {

        dynamicItemset: null,       // Do we need to wait for the itemset to change before we update the auto-complete?
        yuiAutoComplete: null,      // YUI object for the auto-complete
        searchControl: null,        // xforms:input control in which users type
        searchField: null,          // Form field in which users type
        valueSelectedTrigger: null,  // Bridge to tell XForms users selected a value
        externalValueInput : null,  // xforms:input containing the external value
        justMadeSelection: false,   // Reset to false when an Ajax response arrives
        suggestionRequested: false, // Whether users requested the suggestion menu to open by clicking on the button

        /**
         * Constructor
         */
        init: function() {
            this.searchControl = YD.getElementsByClassName("fr-autocomplete-search", null, this.container)[0];
            this.searchField = YD.getChildren(this.searchControl)[0];
            this.valueSelectedTrigger = YD.getElementsByClassName("fr-autocomplete-value-selected", null, this.container)[0];
            var yuiDiv = YD.getElementsByClassName("fr-autocomplete-yui-div", null, this.container)[0];
            YD.generateId(yuiDiv); // Generate ID dynamically as our implementation of XBL doesn't rewrite IDs on HTML
            this.externalValueInput = YD.getElementsByClassName("fr-autocomplete-external-value", null, this.container)[0];

            // This is mostly useful for the dynamic and resources cases, but this code is also useful in static mode, allowing us
            // to open the suggestions in static mode when the button is pressed
            ORBEON.xforms.Events.ajaxResponseProcessedEvent.subscribe(_.bind(this.ajaxResponseProcessed, this));

            // Build data source
            var dataSource;
            if (this.isDynamicItemset()) {
                // If the itemset changes dynamically, update list when we have response to an Ajax request
                dataSource = this.buildNullDataSource();
            } else {
                // Simply filters on the values in the hidden dropdown; we could do this on Ajax response, but using a data source
                // allows us to show suggestions faster, without having to wait for the result of the Ajax request
                var autoComplete = this;
                dataSource = new YAHOO.util.FunctionDataSource(function(query) {
                    return autoComplete.getCurrentValues(query);
                });
            }

            // Create YUI auto-complete object
            this.yuiAutoComplete = new YAHOO.widget.AutoComplete(this.searchField.id, yuiDiv.id, dataSource);
            // Use iframe method for IE6/7
            if (YAHOO.env.ua.ie != 0 && YAHOO.env.ua.ie <= 7)
                this.yuiAutoComplete.useIFrame = true;
            this.yuiAutoComplete.animVert = false;

            // Set maximum number of items displayed
            var maxResultsDisplayedOutput = YD.getElementsByClassName("xbl-fr-autocomplete-max-results-displayed", null, this.container)[0];
            var maxResultsDisplayed = Document.getValue(maxResultsDisplayedOutput.id);
            if (maxResultsDisplayed == "") maxResultsDisplayed = 10;
            this.yuiAutoComplete.maxResultsDisplayed = parseInt(maxResultsDisplayed, 10);

            // Listen on user selecting a value
            this.yuiAutoComplete.itemSelectEvent.subscribe(this.itemSelected, this, true);
        },

        /**
         * Called when the user selects a value from the suggestion list
         */
        itemSelected: function(type, args) {
            var itemLabel = args[2][0];
            this.justMadeSelection = true;
            Document.setValue(this.searchControl.id, itemLabel);
            ORBEON.xforms.Document.dispatchEvent(this.container.id, "fr-value-selected");
        },

        /**
         * Called when we received a response for an Ajax request, which means we may have to update the suggestion list
         */
        ajaxResponseProcessed: function() {
            // Get new list of values
            var query = this.searchField.value;
            var newList = this.getCurrentValues(query);

            var doUpdateSuggestionList =
                this.suggestionRequested || (
                // If the user just selected something before which triggered an Ajax query, don't show the suggestion list
                // as users expect the suggestion list to close after making a selection (clicking or pressing enter)
                ! this.justMadeSelection
                // Update the list only of the control has the focus, as updating the list will show the suggestion list
                // and we only want to show the suggestion list if the user happens to be in that field
                && ORBEON.xforms.Globals.currentFocusControlId == this.searchControl.id);
            if (doUpdateSuggestionList) {
                // Tell YUI this control has the focus; we set the focus on the input, but the YUI focus handler is sometimes called too late
                this.yuiAutoComplete._bFocused = true;
                this.yuiAutoComplete._nKeyCode = null;  // See https://github.com/orbeon/orbeon-forms/issues/436
                this.yuiAutoComplete._populateList(query, { results: newList }, { query: query });
            }
            this.justMadeSelection = false;
            this.suggestionRequested = false;
        },

        /**
         * Creates a data source that never returns anything
         */
        buildNullDataSource: function() {
            var autoComplete = this;

            var WaitAjaxResponseDataSource = function(oLiveData, oConfigs) {
                this.dataType = YAHOO.util.DataSourceBase.TYPE_JSFUNCTION;
                oLiveData = oLiveData || function() {};
                this.constructor.superclass.constructor.call(this, oLiveData, oConfigs);
            };

            YAHOO.lang.extend(WaitAjaxResponseDataSource, YAHOO.util.DataSourceBase, {
                makeConnection : function(oRequest, oCallback, oCaller) {
                    var dataSource = this;
                    var tId = YAHOO.util.DataSourceBase._nTransactionId++;
                    dataSource.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
                    dataSource.responseType = YAHOO.util.DataSourceBase.TYPE_JSARRAY;
                    return tId;
                }
            });

            return new WaitAjaxResponseDataSource(function(query) { return autoComplete.getCurrentValues(query); }, {});
        },

        /**
         * Returns the list of values currently in the itemset
         */
        isDynamicItemset: function() {
            var autoComplete = this;
            if (autoComplete.dynamicItemset === null) {
                var output = YD.getElementsByClassName("fr-autocomplete-dynamic-itemset", null, autoComplete.container)[0];
                autoComplete.dynamicItemset = Document.getValue(output.id) == "true";
            }
            return autoComplete.dynamicItemset;
        },

        /**
         * Returns the content the values from the select1
         */
        getCurrentValues: function(query) {
            var result = [];

            // YUI autocomplete give us an escaped string
            query = unescape(query);
            // Look again for the element, as on IE the <select> is recreated when the itemset changes, and so can't be cached
            var select1Container = YD.getElementsByClassName("fr-autocomplete-select1", null, this.container)[0];
            var select1Element = OD.getElementByTagName(select1Container, "select");
            var options = select1Element.options;

            if (this.suggestionRequested        // Always build result if asked by users by clicking on button
                    || query != "" ) {          // Don't build result if user deleted everything from the field
                var queryLowerCase = query.toLowerCase();
                var itemsCount = options.length / 2;
                for (var optionIndex = 0; optionIndex < itemsCount; optionIndex++) {
                    var option = options[optionIndex];
                    // We only do filtering for the static itemset mode
                    if (this.isDynamicItemset() || option.value.toLowerCase().indexOf(queryLowerCase) == 0 || query == "")
                        result[result.length] = [ option.value, options[itemsCount + optionIndex].value ];
                }
            }

            // If the result only contains one item, and its label is equal to the current value, don't show suggestions
            // Set the external value to the value of this option
            if (result.length == 1 && result[0][0] == query)
                result = [];

            return result;
        }
    };
})();<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

// Provides class sap.ui.core.support.plugins.Performance
sap.ui.define(['jquery.sap.global', 'sap/ui/core/RenderManager', 'sap/ui/core/support/Plugin'],
	function(jQuery, RenderManager, Plugin) {
	"use strict";

		/**
		 * Creates an instance of sap.ui.core.support.plugins.Performance.
		 * @class This class represents the plugin for the support tool functionality of UI5. This class is internal and all its functions must not be used by an application.
		 *
		 * With this plugIn the performance measurements are displayed
		 *
		 * @abstract
		 * @extends sap.ui.base.Object
		 * @version ${version}
		 * @constructor
		 * @private
		 * @alias sap.ui.core.support.plugins.Performance
		 */
		var Performance = Plugin.extend("sap.ui.core.support.plugins.Performance", {
			constructor : function(oSupportStub) {
				Plugin.apply(this, ["sapUiSupportPerf", "Performance", oSupportStub]);

				this._oStub = oSupportStub;

				if (this.isToolPlugin()) {

					this._aEventIds = [this.getId() + "SetMeasurements",
									   this.getId() + "SetActive"];
					jQuery.sap.require("sap.ui.core.format.DateFormat");
					this._oDateFormat = sap.ui.core.format.DateFormat.getTimeInstance({pattern: "HH:mm:ss '+' SSS"});

				} else {

					this._aEventIds = [this.getId() + "Refresh",
									   this.getId() + "Clear",
									   this.getId() + "Start",
									   this.getId() + "Stop",
									   this.getId() + "Activate"];

				}

			}
		});

		Performance.prototype.init = function(oSupportStub){
			Plugin.prototype.init.apply(this, arguments);
			if (this.isToolPlugin()) {
				initInTools.call(this, oSupportStub);
			} else {
				initInApps.call(this, oSupportStub);
			}
		};

		Performance.prototype.exit = function(oSupportStub){
			Plugin.prototype.exit.apply(this, arguments);
		};

		function initInTools(oSupportStub) {

			var rm = sap.ui.getCore().createRenderManager();
			rm.write("
");
			rm.write("<button id=\"" + this.getId() + "-refresh\" class=\"sapUiSupportBtn\">Refresh</button>");
			rm.write("<button id=\"" + this.getId() + "-clear\" class=\"sapUiSupportBtn\">Clear</button>");
	//		rm.write("<button id=\"" + this.getId() + "-start\" class=\"sapUiSupportBtn\">Start</button>");
	//		rm.write("<button id=\"" + this.getId() + "-end\" class=\"sapUiSupportBtn\">End</button>");
			rm.write("<input type=\"checkbox\" id=\"" + this.getId() + "-active\" class=\"sapUiSupportChB\">");
			rm.write("Active");
			rm.write("

");
			rm.write("
");
			rm.write("<colgroup><col><col><col><col><col><col></colgroup>");
			rm.write("

");
			rm.write("ID	");
			rm.write("Info	");
			rm.write("Start	");
			rm.write("End	");
			rm.write("Time	");
			rm.write("Duration	");
			rm.write("

");
			rm.write("

");
			rm.write("

");
			rm.flush(this.$().get(0));
			rm.destroy();

			this.$("refresh").click(jQuery.proxy(function(oEvent) {
				this._oStub.sendEvent(this.getId() + "Refresh");
			}, this));
			this.$("clear").click(jQuery.proxy(function(oEvent) {
				this._oStub.sendEvent(this.getId() + "Clear");
			}, this));
	/*		jQuery.sap.byId(this.getId() + "-start").click(jQuery.proxy(function(oEvent) {
				this._oStub.sendEvent(this.getId() + "Start");
			}, this));
			jQuery.sap.byId(this.getId() + "-end").click(jQuery.proxy(function(oEvent) {
				this._oStub.sendEvent(this.getId() + "End");
			}, this));
	*/
			this.$("active").click(jQuery.proxy(function(oEvent) {
				var bActive = false;
				if (this.$("active").attr("checked")) {
					bActive = true;
				}
				this._oStub.sendEvent(this.getId() + "Activate", {"active": bActive});
			}, this));

		}

		function initInApps(oSupportStub) {
			getPerformanceData.call(this);
		}

		function getPerformanceData(oSupportStub) {
			var bActive = jQuery.sap.measure.getActive();
			var aMeasurements = [];

			if (bActive) {
				aMeasurements = jQuery.sap.measure.getAllMeasurements();
			}
			this._oStub.sendEvent(this.getId() + "SetMeasurements", {"measurements": aMeasurements});
			this._oStub.sendEvent(this.getId() + "SetActive", {"active": bActive});
		}

		/**
		 * Handler for sapUiSupportPerfSetMeasurements event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfSetMeasurements = function(oEvent) {

			var aMeasurements = oEvent.getParameter("measurements");
			var oTableBody = this.$("tabBody");
			var rm = sap.ui.getCore().createRenderManager();

			for ( var i = 0; i < aMeasurements.length; i++) {
				var oMeasurement = aMeasurements[i];
				rm.write("
");
				rm.write("" + oMeasurement.id + "	");
				rm.write("" + oMeasurement.info + "	");
				rm.write("" + this._oDateFormat.format(new Date(oMeasurement.start)) + "	");
				rm.write("" + this._oDateFormat.format(new Date(oMeasurement.end)) + "	");
				rm.write("" + oMeasurement.time + "	");
				rm.write("" + oMeasurement.duration + "	");
				rm.write("
");
			}
			rm.flush(oTableBody[0]);
			rm.destroy();

		};

		/**
		 * Handler for sapUiSupportPerfSetActive event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfSetActive = function(oEvent) {

			var bActive = oEvent.getParameter("active");
			var oCheckBox = this.$("active");

			if (bActive) {
				oCheckBox.attr("checked", "checked");
			} else {
				oCheckBox.removeAttr("checked");
			}

		};

		/**
		 * Handler for sapUiSupportPerfRefresh event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfRefresh = function(oEvent) {

			getPerformanceData.call(this);

		};

		/**
		 * Handler for sapUiSupportPerfClear event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfClear = function(oEvent) {

			jQuery.sap.measure.clear();
			this._oStub.sendEvent(this.getId() + "SetMeasurements", {"measurements":[]});

		};

		/**
		 * Handler for sapUiSupportPerfStart event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfStart = function(oEvent) {

			jQuery.sap.measure.start(this.getId() + "-perf","Measurement by support tool");

		};

		/**
		 * Handler for sapUiSupportPerfEnd event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfEnd = function(oEvent) {

			jQuery.sap.measure.end(this.getId() + "-perf");

		};

		/**
		 * Handler for sapUiSupportPerfActivate event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfActivate = function(oEvent) {

			var bActive = oEvent.getParameter("active");

			if (jQuery.sap.measure.getActive() != bActive) {
				jQuery.sap.measure.setActive(bActive);
			}

		};

	return Performance;

}, /* bExport= */ true);
<commit_msg>[INTERNAL][FIX] Diagnosis tool: fix performance tab<commit_after>/*!
 * ${copyright}
 */

// Provides class sap.ui.core.support.plugins.Performance
sap.ui.define(['jquery.sap.global', 'sap/ui/core/RenderManager', 'sap/ui/core/support/Plugin'],
	function(jQuery, RenderManager, Plugin) {
	"use strict";

		/**
		 * Creates an instance of sap.ui.core.support.plugins.Performance.
		 * @class This class represents the plugin for the support tool functionality of UI5. This class is internal and all its functions must not be used by an application.
		 *
		 * With this plugIn the performance measurements are displayed
		 *
		 * @abstract
		 * @extends sap.ui.base.Object
		 * @version ${version}
		 * @constructor
		 * @private
		 * @alias sap.ui.core.support.plugins.Performance
		 */
		var Performance = Plugin.extend("sap.ui.core.support.plugins.Performance", {
			constructor : function(oSupportStub) {
				Plugin.apply(this, ["sapUiSupportPerf", "Performance", oSupportStub]);

				this._oStub = oSupportStub;

				if (this.isToolPlugin()) {

					this._aEventIds = [this.getId() + "SetMeasurements",
									   this.getId() + "SetActive"];
					jQuery.sap.require("sap.ui.core.format.DateFormat");
					this._oDateFormat = sap.ui.core.format.DateFormat.getTimeInstance({pattern: "HH:mm:ss '+' SSS"});

				} else {

					this._aEventIds = [this.getId() + "Refresh",
									   this.getId() + "Clear",
									   this.getId() + "Start",
									   this.getId() + "Stop",
									   this.getId() + "Activate"];

				}

			}
		});

		Performance.prototype.init = function(oSupportStub){
			Plugin.prototype.init.apply(this, arguments);
			if (this.isToolPlugin()) {
				initInTools.call(this, oSupportStub);
			} else {
				initInApps.call(this, oSupportStub);
			}
		};

		Performance.prototype.exit = function(oSupportStub){
			Plugin.prototype.exit.apply(this, arguments);
		};

		function initInTools(oSupportStub) {

			var rm = sap.ui.getCore().createRenderManager();
			rm.write("
");
			rm.write("<button id=\"" + this.getId() + "-refresh\" class=\"sapUiSupportBtn\">Refresh</button>");
			rm.write("<button id=\"" + this.getId() + "-clear\" class=\"sapUiSupportBtn\">Clear</button>");
	//		rm.write("<button id=\"" + this.getId() + "-start\" class=\"sapUiSupportBtn\">Start</button>");
	//		rm.write("<button id=\"" + this.getId() + "-end\" class=\"sapUiSupportBtn\">End</button>");
			rm.write("<input type=\"checkbox\" id=\"" + this.getId() + "-active\" class=\"sapUiSupportChB\">");
			rm.write("Active");
			rm.write("

");
			rm.write("
");
			rm.write("<colgroup><col><col><col><col><col><col></colgroup>");
			rm.write("

");
			rm.write("ID	");
			rm.write("Info	");
			rm.write("Start	");
			rm.write("End	");
			rm.write("Time	");
			rm.write("Duration	");
			rm.write("

");
			rm.write("

");
			rm.write("

");
			rm.flush(this.$().get(0));
			rm.destroy();

			this.$("refresh").click(jQuery.proxy(function(oEvent) {
				this._oStub.sendEvent(this.getId() + "Refresh");
			}, this));
			this.$("clear").click(jQuery.proxy(function(oEvent) {
				this._oStub.sendEvent(this.getId() + "Clear");
			}, this));
	/*		jQuery.sap.byId(this.getId() + "-start").click(jQuery.proxy(function(oEvent) {
				this._oStub.sendEvent(this.getId() + "Start");
			}, this));
			jQuery.sap.byId(this.getId() + "-end").click(jQuery.proxy(function(oEvent) {
				this._oStub.sendEvent(this.getId() + "End");
			}, this));
	*/
			this.$("active").click(jQuery.proxy(function(oEvent) {
				var bActive = false;
				if (this.$("active").prop("checked")) {
					bActive = true;
				}
				this._oStub.sendEvent(this.getId() + "Activate", {"active": bActive});
			}, this));

		}

		function initInApps(oSupportStub) {
			getPerformanceData.call(this);
		}

		function getPerformanceData(oSupportStub) {
			var bActive = jQuery.sap.measure.getActive();
			var aMeasurements = [];

			if (bActive) {
				aMeasurements = jQuery.sap.measure.getAllMeasurements();
			}
			this._oStub.sendEvent(this.getId() + "SetMeasurements", {"measurements": aMeasurements});
			this._oStub.sendEvent(this.getId() + "SetActive", {"active": bActive});
		}

		/**
		 * Handler for sapUiSupportPerfSetMeasurements event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfSetMeasurements = function(oEvent) {

			var aMeasurements = oEvent.getParameter("measurements");
			var oTableBody = this.$("tabBody");
			var rm = sap.ui.getCore().createRenderManager();

			for ( var i = 0; i < aMeasurements.length; i++) {
				var oMeasurement = aMeasurements[i];
				rm.write("
");
				rm.write("" + oMeasurement.id + "	");
				rm.write("" + oMeasurement.info + "	");
				rm.write("" + this._oDateFormat.format(new Date(oMeasurement.start)) + "	");
				rm.write("" + this._oDateFormat.format(new Date(oMeasurement.end)) + "	");
				rm.write("" + oMeasurement.time + "	");
				rm.write("" + oMeasurement.duration + "	");
				rm.write("
");
			}
			rm.flush(oTableBody[0]);
			rm.destroy();

		};

		/**
		 * Handler for sapUiSupportPerfSetActive event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfSetActive = function(oEvent) {

			var bActive = oEvent.getParameter("active");
			var oCheckBox = this.$("active");

			if (bActive) {
				oCheckBox.attr("checked", "checked");
			} else {
				oCheckBox.removeAttr("checked");
			}

		};

		/**
		 * Handler for sapUiSupportPerfRefresh event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfRefresh = function(oEvent) {

			getPerformanceData.call(this);

		};

		/**
		 * Handler for sapUiSupportPerfClear event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfClear = function(oEvent) {

			jQuery.sap.measure.clear();
			this._oStub.sendEvent(this.getId() + "SetMeasurements", {"measurements":[]});

		};

		/**
		 * Handler for sapUiSupportPerfStart event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfStart = function(oEvent) {

			jQuery.sap.measure.start(this.getId() + "-perf","Measurement by support tool");

		};

		/**
		 * Handler for sapUiSupportPerfEnd event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfEnd = function(oEvent) {

			jQuery.sap.measure.end(this.getId() + "-perf");

		};

		/**
		 * Handler for sapUiSupportPerfActivate event
		 *
		 * @param {sap.ui.base.Event} oEvent the event
		 * @private
		 */
		Performance.prototype.onsapUiSupportPerfActivate = function(oEvent) {

			var bActive = oEvent.getParameter("active");

			if (jQuery.sap.measure.getActive() != bActive) {
				jQuery.sap.measure.setActive(bActive);
			}

		};

	return Performance;

}, /* bExport= */ true);
<|endoftext|>


<commit_before>define(
  'tinymce.themes.mobile.touch.view.TapToEditMenuParts',

  [
    'ephox.alloy.api.ui.Menu',
    'tinymce.themes.mobile.style.Styles'
  ],

  function (Menu, Styles) {
    var menu = function () {
      return {
        dom: {
          tag: 'div'
        },
        components: [
          Menu.parts().items()
        ],
        // TODO: Default this to a random value.
        value: 'touch-menu-1',
        markers: {
          item: Styles.resolve('mask-menu-item'),
          selectedItem: Styles.resolve('mask-menu-item-selected')
        },
        members: {
          item: {
            munge: function (itemSpec) {
              return {
                dom: {
                  tag: 'div',
                  attributes: {
                    'data-value': itemSpec.data.value
                  },
                  classes: [ Styles.resolve('mask-menu-item') ]
                },
                components: [
                  {
                    dom: {
                      tag: 'span',
                      innerHtml: itemSpec.data.text
                    }
                  }
                ]
              };
            }
          }
        }
      };
    };

    var view = function () {
      return {
        dom: {
          tag: 'div',
          classes: [ 'tap-button-view' ]
        }
      };
    };

    return {
      menu: menu,
      view: view
    };
  }
);
<commit_msg>TM-34-longpress: updated class<commit_after>define(
  'tinymce.themes.mobile.touch.view.TapToEditMenuParts',

  [
    'ephox.alloy.api.ui.Menu',
    'tinymce.themes.mobile.style.Styles'
  ],

  function (Menu, Styles) {
    var menu = function () {
      return {
        dom: {
          tag: 'div'
        },
        components: [
          Menu.parts().items()
        ],
        // TODO: Default this to a random value.
        value: 'touch-menu-1',
        markers: {
          item: Styles.resolve('mask-menu-item'),
          selectedItem: Styles.resolve('mask-menu-item-selected')
        },
        members: {
          item: {
            munge: function (itemSpec) {
              return {
                dom: {
                  tag: 'div',
                  attributes: {
                    'data-value': itemSpec.data.value
                  },
                  classes: [ Styles.resolve('mask-menu-item') ]
                },
                components: [
                  {
                    dom: {
                      tag: 'span',
                      innerHtml: itemSpec.data.text
                    }
                  }
                ]
              };
            }
          }
        }
      };
    };

    var view = function () {
      return {
        dom: {
          tag: 'div',
          classes: [ Styles.resolve('mask-menu-view') ]
        }
      };
    };

    return {
      menu: menu,
      view: view
    };
  }
);
<|endoftext|>


<commit_before>/* jqBootstrapValidation
 * A plugin for automating validation on Twitter Bootstrap formatted forms.
 *
 * v1.3.6
 *
 * License: MIT <http://opensource.org/licenses/mit-license.php> - see LICENSE file
 *
 * http://ReactiveRaven.github.com/jqBootstrapValidation/
 */

(function( $ ){

	var createdElements = [];

	var defaults = {
		options: {
			prependExistingHelpBlock: false,
			sniffHtml: true, // sniff for 'required', 'maxlength', etc
			preventSubmit: true, // stop the form submit event from firing if validation fails
			submitError: false, // function called if there is an error when trying to submit
			submitSuccess: false, // function called just before a successful submit event is sent to the server
            semanticallyStrict: false, // set to true to tidy up generated HTML output
			autoAdd: {
				helpBlocks: true
			},
            filter: function () {
                // return $(this).is(":visible"); // only validate elements you can see
                return true; // validate everything
            }
		},
    methods: {
      init : function( options ) {

        var settings = $.extend(true, {}, defaults);

        settings.options = $.extend(true, settings.options, options);

        var $siblingElements = this;

        var uniqueForms = $.unique(
          $siblingElements.map( function () {
            return $(this).parents("form")[0];
          }).toArray()
        );

        $(uniqueForms).bind("submit", function (e) {
          var $form = $(this);
          var warningsFound = 0;
          var $inputs = $form.find("input,textarea,select").not("[type=submit],[type=image]").filter(settings.options.filter);
          $inputs.trigger("submit.validation").trigger("validationLostFocus.validation");

          $inputs.each(function (i, el) {
            var $this = $(el),
              $controlGroup = $this.parents(".control-group").first();
            if (
              $controlGroup.hasClass("warning")
            ) {
              $controlGroup.removeClass("warning").addClass("error");
              warningsFound++;
            }
          });

          $inputs.trigger("validationLostFocus.validation");

          if (warningsFound) {
            if (settings.options.preventSubmit) {
              e.preventDefault();
            }
            $form.addClass("error");
            if ($.isFunction(settings.options.submitError)) {
              settings.options.submitError($form, e, $inputs.jqBootstrapValidation("collectErrors", true));
            }
          } else {
            $form.removeClass("error");
            if ($.isFunction(settings.options.submitSuccess)) {
              settings.options.submitSuccess($form, e);
            }
          }
        });

        return this.each(function(){

          // Get references to everything we're interested in
          var $this = $(this),
            $controlGroup = $this.parents(".control-group").first(),
            $helpBlock = $controlGroup.find(".help-block").first(),
            $form = $this.parents("form").first(),
            validatorNames = [];

          // create message container if not exists
          if (!$helpBlock.length && settings.options.autoAdd && settings.options.autoAdd.helpBlocks) {
              $helpBlock = $('<div class="help-block" />');
              $controlGroup.find('.controls').append($helpBlock);
							createdElements.push($helpBlock[0]);
          }

          // =============================================================
          //                                     SNIFF HTML FOR VALIDATORS
          // =============================================================

          // *snort sniff snuffle*

          if (settings.options.sniffHtml) {
            var message = "";
            // ---------------------------------------------------------
            //                                                   PATTERN
            // ---------------------------------------------------------
            if ($this.attr("pattern") !== undefined) {
              message = "Not in the expected format<!-- data-validation-pattern-message to override -->";
              if ($this.data("validationPatternMessage")) {
                message = $this.data("validationPatternMessage");
              }
              $this.data("validationPatternMessage", message);
              $this.data("validationPatternRegex", $this.attr("pattern"));
            }
            // ---------------------------------------------------------
            //                                                       MAX
            // ---------------------------------------------------------
            if ($this.attr("max") !== undefined || $this.attr("aria-valuemax") !== undefined) {
              var max = ($this.attr("max") !== undefined ? $this.attr("max") : $this.attr("aria-valuemax"));
              message = "Too high: Maximum of '" + max + "'<!-- data-validation-max-message to override -->";
              if ($this.data("validationMaxMessage")) {
                message = $this.data("validationMaxMessage");
              }
              $this.data("validationMaxMessage", message);
              $this.data("validationMaxMax", max);
            }
            // ---------------------------------------------------------
            //                                                       MIN
            // ---------------------------------------------------------
            if ($this.attr("min") !== undefined || $this.attr("aria-valuemin") !== undefined) {
              var min = ($this.attr("min") !== undefined ? $this.attr("min") : $this.attr("aria-valuemin"));
              message = "Too low: Minimum of '" + min + "'<!-- data-validation-min-message to override -->";
              if ($this.data("validationMinMessage")) {
                message = $this.data("validationMinMessage");
              }
              $this.data("validationMinMessage", message);
              $this.data("validationMinMin", min);
            }
            // ---------------------------------------------------------
            //                                                 MAXLENGTH
            // ---------------------------------------------------------
            if ($this.attr("maxlength") !== undefined) {
              message = "Too long: Maximum of '" + $this.attr("maxlength") + "' characters<!-- data-validation-maxlength-message to override -->";
              if ($this.data("validationMaxlengthMessage")) {
                message = $this.data("validationMaxlengthMessage");
              }
              $this.data("validationMaxlengthMessage", message);
              $this.data("validationMaxlengthMaxlength", $this.attr("maxlength"));
            }
            // ---------------------------------------------------------
            //                                                 MINLENGTH
            // ---------------------------------------------------------
            if ($this.attr("minlength") !== undefined) {
              message = "Too short: Minimum of '" + $this.attr("minlength") + "' characters<!-- data-validation-minlength-message to override -->";
              if ($this.data("validationMinlengthMessage")) {
                message = $this.data("validationMinlengthMessage");
              }
              $this.data("validationMinlengthMessage", message);
              $this.data("validationMinlengthMinlength", $this.attr("minlength"));
            }
            // ---------------------------------------------------------
            //                                                  REQUIRED
            // ---------------------------------------------------------
            if ($this.attr("required") !== undefined || $this.attr("aria-required") !== undefined) {
              message = settings.builtInValidators.required.message;
              if ($this.data("validationRequiredMessage")) {
                message = $this.data("validationRequiredMessage");
              }
              $this.data("validationRequiredMessage", message);
            }
            // ---------------------------------------------------------
            //                                                    NUMBER
            // ---------------------------------------------------------
            if ($this.attr("type") !== undefined && $this.attr("type").toLowerCase() === "number") {
              message = settings.builtInValidators.number.message;
              if ($this.data("validationNumberMessage")) {
                message = $this.data("validationNumberMessage");
              }
              $this.data("validationNumberMessage", message);
            }
            // ---------------------------------------------------------
            //                                                     EMAIL
            // ---------------------------------------------------------
            if ($this.attr("type") !== undefined && $this.attr("type").toLowerCase() === "email") {
              message = "Not a valid email address<!-- data-validator-validemail-message to override -->";
              if ($this.data("validationValidemailMessage")) {
                message = $this.data("validationValidemailMessage");
              } else if ($this.data("validationEmailMessage")) {
                message = $this.data("validationEmailMessage");
              }
              $this.data("validationValidemailMessage", message);
            }
            // ---------------------------------------------------------
            //                                                MINCHECKED
            // ---------------------------------------------------------
            if ($this.attr("minchecked") !== undefined) {
              message = "Not enough options checked; Minimum of '" + $this.attr("minchecked") + "' required<!-- data-validation-minchecked-message to override -->";
              if ($this.data("validationMincheckedMessage")) {
                message = $this.data("validationMincheckedMessage");
              }
              $this.data("validationMincheckedMessage", message);
              $this.data("validationMincheckedMinchecked", $this.attr("minchecked"));
            }
            // ---------------------------------------------------------
            //                                                MAXCHECKED
            // ---------------------------------------------------------
            if ($this.attr("maxchecked") !== undefined) {
              message = "Too many options checked; Maximum of '" + $this.attr("maxchecked") + "' required<!-- data-validation-maxchecked-message to override -->";
              if ($this.data("validationMaxcheckedMessage")) {
                message = $this.data("validationMaxcheckedMessage");
              }
              $this.data("validationMaxcheckedMessage", message);
              $this.data("validationMaxcheckedMaxchecked", $this.attr("maxchecked"));
            }
          }

          // =============================================================
          //                                       COLLECT VALIDATOR NAMES
          // =============================================================

          // Get named validators
          if ($this.data("validation") !== undefined) {
            validatorNames = $this.data("validation").split(",");
          }

          // Get extra ones defined on the element's data attributes
          $.each($this.data(), function (i, el) {
            var parts = i.replace(/([A-Z])/g, ",$1").split(",");
            if (parts[0] === "validation" && parts[1]) {
              validatorNames.push(parts[1]);
            }
          });

          // =============================================================
          //                                     NORMALISE VALIDATOR NAMES
          // =============================================================

          var validatorNamesToInspect = validatorNames;
          var newValidatorNamesToInspect = [];

          do // repeatedly expand 'shortcut' validators into their real validators
          {
            // Uppercase only the first letter of each name
            $.each(validatorNames, function (i, el) {
              validatorNames[i] = formatValidatorName(el);
            });

            // Remove duplicate validator names
            validatorNames = $.unique(validatorNames);

            // Pull out the new validator names from each shortcut
            newValidatorNamesToInspect = [];
            $.each(validatorNamesToInspect, function(i, el) {
              if ($this.data("validation" + el + "Shortcut") !== undefined) {
                // Are these custom validators?
                // Pull them out!
                $.each($this.data("validation" + el + "Shortcut").split(","), function(i2, el2) {
                  newValidatorNamesToInspect.push(el2);
                });
              } else if (settings.builtInValidators[el.toLowerCase()]) {
                // Is this a recognised built-in?
                // Pull it out!
                var validator = settings.builtInValidators[el.toLowerCase()];
                if (validator.type.toLowerCase() === "shortcut") {
                  $.each(validator.shortcut.split(","), function (i, el) {
                    el = formatValidatorName(el);
                    newValidatorNamesToInspect.push(el);
                    validatorNames.push(el);
                  });
                }
              }
            });

            validatorNamesToInspect = newValidatorNamesToInspect;

          } while (validatorNamesToInspect.length > 0)

          // =============================================================
          //                                       SET UP VALIDATOR ARRAYS
          // =============================================================

          var validators = {};

          $.each(validatorNames, function (i, el) {
            // Set up the 'override' message
            var message = $this.data("validation" + el + "Message");
            var hasOverrideMessage = (message !== undefined);
            var foundValidator = false;
            message =
              (
                message
                  ? message
                  : "'" + el + "' validation failed <!-- Add attribute 'data-validation-" + el.toLowerCase() + "-message' to input to change this message -->"
              )
            ;

            $.each(
              settings.validatorTypes,
              function (validatorType, validatorTemplate) {
                if (validators[validatorType] === undefined) {
                  validators[validatorType] = [];
                }
                if (!foundValidator && $this.data("validation" + el + formatValidatorName(validatorTemplate.name)) !== undefined) {
                  validators[validatorType].push(
                    $.extend(
                      true,
                      {
                        name: formatValidatorName(validatorTemplate.name),
                        message: message
                      },
                      validatorTemplate.init($this, el)
                    )
                  );
                  foundValidator = true;
                }
              }
            );

            if (!foundValidator && settings.builtInValidators[el.toLowerCase()]) {

              var validator = $.extend(true, {}, settings.builtInValidators[el.toLowerCase()]);
              if (hasOverrideMessage) {
                validator.message = message;
              }
              var validatorType = validator.type.toLowerCase();

              if (validatorType === "shortcut") {
                foundValidator = true;
              } else {
                $.each(
                  settings.validatorTypes,
                  function (validatorTemplateType, validatorTemplate) {
                    if (validators[validatorTemplateType] === undefined) {
                      validators[validatorTemplateType] = [];
                    }
                    if (!foundValidator && validatorType === validatorTemplateType.toLowerCase()) {
                      $this.data("validation" + el + formatValidatorName(validatorTemplate.name), validator[validatorTemplate.name.toLowerCase()]);
                      validators[validatorType].push(
                        $.extend(
                          validator,
                          validatorTemplate.init($this, el)
                        )
                      );
                      foundValidator = true;
                    }
                  }
                );
              }
            }

            if (! foundValidator) {
              $.error("Cannot find validation info for '" + el + "'");
            }
          });

          // =============================================================
          //                                         STORE FALLBACK VALUES
          // =============================================================

          $helpBlock.data(
            "original-contents",
            (
              $helpBlock.data("original-contents")
                ? $helpBlock.data("original-contents")
                : $helpBlock.html()
            )
          );

          $helpBlock.data(
            "original-role",
            (
              $helpBlock.data("original-role")
                ? $helpBlock.data("original-role")
                : $helpBlock.attr("role")
            )
          );

          $controlGroup.data(
            "original-classes",
            (
              $controlGroup.data("original-clases")
                ? $controlGroup.data("original-classes")
                : $controlGroup.attr("class")
            )
          );

          $this.data(
            "original-aria-invalid",
            (
              $this.data("original-aria-invalid")
                ? $this.data("original-aria-invalid")
                : $this.attr("aria-invalid")
            )
          );

          // =============================================================
          //                                                    VALIDATION
          // =============================================================

          $this.bind(
            "validation.validation",
            function (event, params) {

              var value = getValue($this);

              // Get a list of the errors to apply
              var errorsFound = [];

              $.each(validators, function (validatorType, validatorTypeArray) {
                if (value || value.length || (params && params.includeEmpty) || (!!settings.validatorTypes[validatorType].blockSubmit && params && !!params.submitting)) {
                  $.each(validatorTypeArray, function (i, validator) {
                    if (settings.validatorTypes[validatorType].validate($this, value, validator)) {
                      errorsFound.push(validator.message);
                    }
                  });
                }
              });

              return errorsFound;
            }
          );

          $this.bind(
            "getValidators.validation",
            function () {
              return validators;
            }
          );

          // =============================================================
          //                                             WATCH FOR CHANGES
          // =============================================================
          $this.bind(
            "submit.validation",
            function () {
              return $this.triggerHandler("change.validation", {submitting: true});
            }
          );
          $this.bind(
            [
              "keyup",
              "focus",
              "blur",
              "click",
              "keydown",
              "keypress",
              "change"
            ].join(".validation ") + ".validation",
            function (e, params) {

              var value = getValue($this);

              var errorsFound = [];

              $controlGroup.find("input,textarea,select").each(function (i, el) {
                var oldCount = errorsFound.length;
                $.each($(el).triggerHandler("validation.validation", params), function (j, message) {
                  errorsFound.push(message);
                });
                if (errorsFound.length > oldCount) {
                  $(el).attr("aria-invalid", "true");
                } else {
                  var original = $this.data("original-aria-invalid");
                  $(el).attr("aria-invalid", (original !== undefined ? original : false));
                }
              });

              $form.find("input,select,textarea").not($this).not("[name=\"" + $this.attr("name") + "\"]").trigger("validationLostFocus.validation");

              errorsFound = $.unique(errorsFound.sort());

              // Were there any errors?
              if (errorsFound.length) {
                // Better flag it up as a warning.
                $controlGroup.removeClass("success error").addClass("warning");

                // How many errors did we find?
                if (settings.options.semanticallyStrict && errorsFound.length === 1) {
                  // Only one? Being strict? Just output it.
                  $helpBlock.html(errorsFound[0] +
                    ( settings.options.prependExistingHelpBlock ? $helpBlock.data("original-contents") : "" ));
                } else {
                  // Multiple? Being sloppy? Glue them together into an UL.
                  $helpBlock.html("<ul role=\"alert\"><li>" + errorsFound.join("</li><li>") + "</li></ul>" +
                    ( settings.options.prependExistingHelpBlock ? $helpBlock.data("original-contents") : "" ));
                }
              } else {
                $controlGroup.removeClass("warning error success");
                if (value.length > 0) {
                  $controlGroup.addClass("success");
                }
                $helpBlock.html($helpBlock.data("original-contents"));
              }

              if (e.type === "blur") {
                $controlGroup.removeClass("success");
              }
            }
          );
          $this.bind("validationLostFocus.validation", function () {
            $controlGroup.removeClass("success");
          });
        });
      },
      destroy : function( ) {

        return this.each(
          function() {

            var
              $this = $(this),
              $controlGroup = $this.parents(".control-group").first(),
              $helpBlock = $controlGroup.find(".help-block").first();

            // remove our events
            $this.unbind('.validation'); // events are namespaced.
            // reset help text
            $helpBlock.html($helpBlock.data("original-contents"));
            // reset classes
            $controlGroup.attr("class", $controlGroup.data("original-classes"));
            // reset aria
            $this.attr("aria-invalid", $this.data("original-aria-invalid"));
            // reset role
            $helpBlock.attr("role", $this.data("original-role"));
						// remove all elements we created
						if (createdElements.indexOf($helpBlock[0]) > -1) {
							$helpBlock.remove();
						}

          }
        );

      },
      collectErrors : function(includeEmpty) {

        var errorMessages = {};
        this.each(function (i, el) {
          var $el = $(el);
          var name = $el.attr("name");
          var errors = $el.triggerHandler("validation.validation", {includeEmpty: true});
          errorMessages[name] = $.extend(true, errors, errorMessages[name]);
        });

        $.each(errorMessages, function (i, el) {
          if (el.length === 0) {
            delete errorMessages[i];
          }
        });

        return errorMessages;

      },
      hasErrors: function() {

        var errorMessages = [];

        this.each(function (i, el) {
          errorMessages = errorMessages.concat(
            $(el).triggerHandler("getValidators.validation") ? $(el).triggerHandler("validation.validation", {submitting: true}) : []
          );
        });

        return (errorMessages.length > 0);
      },
      override : function (newDefaults) {
        defaults = $.extend(true, defaults, newDefaults);
      }
    },
		validatorTypes: {
      callback: {
        name: "callback",
        init: function ($this, name) {
          return {
            validatorName: name,
            callback: $this.data("validation" + name + "Callback"),
            lastValue: $this.val(),
            lastValid: true,
            lastFinished: true
          };
        },
        validate: function ($this, value, validator) {
          if (validator.lastValue === value && validator.lastFinished) {
            return !validator.lastValid;
          }

          if (validator.lastFinished === true)
          {
            validator.lastValue = value;
            validator.lastValid = true;
            validator.lastFinished = false;

            var rrjqbvValidator = validator;
            var rrjqbvThis = $this;
            executeFunctionByName(
              validator.callback,
              window,
              $this,
              value,
              function (data) {
                if (rrjqbvValidator.lastValue === data.value) {
                  rrjqbvValidator.lastValid = data.valid;
                  if (data.message) {
                    rrjqbvValidator.message = data.message;
                  }
                  rrjqbvValidator.lastFinished = true;
                  rrjqbvThis.data("validation" + rrjqbvValidator.validatorName + "Message", rrjqbvValidator.message);
                  // Timeout is set to avoid problems with the events being considered 'already fired'
                  setTimeout(function () {
                    rrjqbvThis.trigger("change.validation");
                  }, 1); // doesn't need a long timeout, just long enough for the event bubble to burst
                }
              }
            );
          }

          return false;

        }
      },
      ajax: {
        name: "ajax",
        init: function ($this, name) {
          return {
            validatorName: name,
            url: $this.data("validation" + name + "Ajax"),
            lastValue: $this.val(),
            lastValid: true,
            lastFinished: true
          };
        },
        validate: function ($this, value, validator) {
          if (""+validator.lastValue === ""+value && validator.lastFinished === true) {
            return validator.lastValid === false;
          }

          if (validator.lastFinished === true)
          {
            validator.lastValue = value;
            validator.lastValid = true;
            validator.lastFinished = false;
            $.ajax({
              url: validator.url,
              data: "value=" + value + "&field=" + $this.attr("name"),
              dataType: "json",
              success: function (data) {
                if (""+validator.lastValue === ""+data.value) {
                  validator.lastValid = !!(data.valid);
                  if (data.message) {
                    validator.message = data.message;
                  }
                  validator.lastFinished = true;
                  $this.data("validation" + validator.validatorName + "Message", validator.message);
                  // Timeout is set to avoid problems with the events being considered 'already fired'
                  setTimeout(function () {
                    $this.trigger("change.validation");
                  }, 1); // doesn't need a long timeout, just long enough for the event bubble to burst
                }
              },
              failure: function () {
                validator.lastValid = true;
                validator.message = "ajax call failed";
                validator.lastFinished = true;
                $this.data("validation" + validator.validatorName + "Message", validator.message);
                // Timeout is set to avoid problems with the events being considered 'already fired'
                setTimeout(function () {
                  $this.trigger("change.validation");
                }, 1); // doesn't need a long timeout, just long enough for the event bubble to burst
              }
            });
          }

          return false;

        }
      },
			regex: {
				name: "regex",
				init: function ($this, name) {
					return {regex: regexFromString($this.data("validation" + name + "Regex"))};
				},
				validate: function ($this, value, validator) {
					return (!validator.regex.test(value) && ! validator.negative)
						|| (validator.regex.test(value) && validator.negative);
				}
			},
			required: {
				name: "required",
				init: function ($this, name) {
					return {};
				},
				validate: function ($this, value, validator) {
					return !!(value.length === 0  && ! validator.negative)
						|| !!(value.length > 0 && validator.negative);
				},
        blockSubmit: true
			},
			match: {
				name: "match",
				init: function ($this, name) {
					var element = $this.parents("form").first().find("[name=\"" + $this.data("validation" + name + "Match") + "\"]").first();
					element.bind("validation.validation", function () {
						$this.trigger("change.validation", {submitting: true});
					});
					return {"element": element};
				},
				validate: function ($this, value, validator) {
					return (value !== validator.element.val() && ! validator.negative)
						|| (value === validator.element.val() && validator.negative);
				},
        blockSubmit: true
			},
			max: {
				name: "max",
				init: function ($this, name) {
					return {max: $this.data("validation" + name + "Max")};
				},
				validate: function ($this, value, validator) {
					return (parseFloat(value, 10) > parseFloat(validator.max, 10) && ! validator.negative)
						|| (parseFloat(value, 10) <= parseFloat(validator.max, 10) && validator.negative);
				}
			},
			min: {
				name: "min",
				init: function ($this, name) {
					return {min: $this.data("validation" + name + "Min")};
				},
				validate: function ($this, value, validator) {
					return (parseFloat(value) < parseFloat(validator.min) && ! validator.negative)
						|| (parseFloat(value) >= parseFloat(validator.min) && validator.negative);
				}
			},
			maxlength: {
				name: "maxlength",
				init: function ($this, name) {
					return {maxlength: $this.data("validation" + name + "Maxlength")};
				},
				validate: function ($this, value, validator) {
					return ((value.length > validator.maxlength) && ! validator.negative)
						|| ((value.length <= validator.maxlength) && validator.negative);
				}
			},
			minlength: {
				name: "minlength",
				init: function ($this, name) {
					return {minlength: $this.data("validation" + name + "Minlength")};
				},
				validate: function ($this, value, validator) {
					return ((value.length < validator.minlength) && ! validator.negative)
						|| ((value.length >= validator.minlength) && validator.negative);
				}
			},
			maxchecked: {
				name: "maxchecked",
				init: function ($this, name) {
					var elements = $this.parents("form").first().find("[name=\"" + $this.attr("name") + "\"]");
					elements.bind("click.validation", function () {
						$this.trigger("change.validation", {includeEmpty: true});
					});
					return {maxchecked: $this.data("validation" + name + "Maxchecked"), elements: elements};
				},
				validate: function ($this, value, validator) {
					return (validator.elements.filter(":checked").length > validator.maxchecked && ! validator.negative)
						|| (validator.elements.filter(":checked").length <= validator.maxchecked && validator.negative);
				},
        blockSubmit: true
			},
			minchecked: {
				name: "minchecked",
				init: function ($this, name) {
					var elements = $this.parents("form").first().find("[name=\"" + $this.attr("name") + "\"]");
					elements.bind("click.validation", function () {
						$this.trigger("change.validation", {includeEmpty: true});
					});
					return {minchecked: $this.data("validation" + name + "Minchecked"), elements: elements};
				},
				validate: function ($this, value, validator) {
					return (validator.elements.filter(":checked").length < validator.minchecked && ! validator.negative)
						|| (validator.elements.filter(":checked").length >= validator.minchecked && validator.negative);
				},
        blockSubmit: true
			}
		},
		builtInValidators: {
			email: {
				name: "Email",
				type: "shortcut",
				shortcut: "validemail"
			},
			validemail: {
				name: "Validemail",
				type: "regex",
				regex: "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\.[A-Za-z]{2,4}",
				message: "Not a valid email address<!-- data-validator-validemail-message to override -->"
			},
			passwordagain: {
				name: "Passwordagain",
				type: "match",
				match: "password",
				message: "Does not match the given password<!-- data-validator-paswordagain-message to override -->"
			},
			positive: {
				name: "Positive",
				type: "shortcut",
				shortcut: "number,positivenumber"
			},
			negative: {
				name: "Negative",
				type: "shortcut",
				shortcut: "number,negativenumber"
			},
			number: {
				name: "Number",
				type: "regex",
				regex: "([+-]?\\\d+(\\\.\\\d*)?([eE][+-]?[0-9]+)?)?",
				message: "Must be a number<!-- data-validator-number-message to override -->"
			},
			integer: {
				name: "Integer",
				type: "regex",
				regex: "[+-]?\\\d+",
				message: "No decimal places allowed<!-- data-validator-integer-message to override -->"
			},
			positivenumber: {
				name: "Positivenumber",
				type: "min",
				min: 0,
				message: "Must be a positive number<!-- data-validator-positivenumber-message to override -->"
			},
			negativenumber: {
				name: "Negativenumber",
				type: "max",
				max: 0,
				message: "Must be a negative number<!-- data-validator-negativenumber-message to override -->"
			},
			required: {
				name: "Required",
				type: "required",
				message: "This is required<!-- data-validator-required-message to override -->"
			},
			checkone: {
				name: "Checkone",
				type: "minchecked",
				minchecked: 1,
				message: "Check at least one option<!-- data-validation-checkone-message to override -->"
			}
		}
	};

	var formatValidatorName = function (name) {
		return name
			.toLowerCase()
			.replace(
				/(^|\s)([a-z])/g ,
				function(m,p1,p2) {
					return p1+p2.toUpperCase();
				}
			)
		;
	};

	var getValue = function ($this) {
		// Extract the value we're talking about
		var value = $this.val();
		var type = $this.attr("type");
		if (type === "checkbox") {
			value = ($this.is(":checked") ? value : "");
		}
		if (type === "radio") {
			value = ($('input[name="' + $this.attr("name") + '"]:checked').length > 0 ? value : "");
		}
		return value;
	};

  function regexFromString(inputstring) {
		return new RegExp("^" + inputstring + "$");
	}

  /**
   * Thanks to Jason Bunting via StackOverflow.com
   *
   * http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string#answer-359910
   * Short link: http://tinyurl.com/executeFunctionByName
  **/
  function executeFunctionByName(functionName, context /*, args*/) {
    var args = Array.prototype.slice.call(arguments).splice(2);
    var namespaces = functionName.split(".");
    var func = namespaces.pop();
    for(var i = 0; i < namespaces.length; i++) {
      context = context[namespaces[i]];
    }
    return context[func].apply(this, args);
  }

	$.fn.jqBootstrapValidation = function( method ) {

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

	};

  $.jqBootstrapValidation = function (options) {
    $(":input").not("[type=image],[type=submit]").jqBootstrapValidation.apply(this,arguments);
  };

})( jQuery );
<commit_msg>Delete jqBootstrapValidation.js<commit_after><|endoftext|>


<commit_before>import { create } from '@storybook/theming';

export default create({
  base: 'light',
  colorPrimary: 'rgb(51, 51, 51)',
  colorSecondary: 'rgb(51, 51, 51)',
  appBg: '#f3f3f3',
  appBorderColor: 'rgb(51, 51, 51)',
  appBorderRadius: 4,
  fontBase: '"urw-din", sans-serif',
  fontCode: 'monospace',
  barTextColor: 'rgb(51, 51, 51)',
  barSelectedColor: 'rgb(51, 51, 51)',
  // barBg: '#302e2e',
  inputBorderRadius: 4,
  brandTitle: 'Spark Design System',
  brandUrl: 'https://sparkdesignsystem.com',
  brandImage: 'https://spark-assets.netlify.com/spark-placeholder.jpg',
});
<commit_msg>add check in spark theme for different logo by SB instance<commit_after>import { create } from '@storybook/theming';
import { getStorybookInstance } from '../getStorybookInstance';

const storybookInstance = getStorybookInstance();
let sparkLogo;

switch (storybookInstance) {
  case 'react':
    sparkLogo = 'https://spark-assets.netlify.com/spark-logo-black-text.svg';
    break;
  case 'angular':
    sparkLogo = 'https://spark-assets.netlify.com/spark-logo-black-text.svg';
    break;
  case 'html':
    sparkLogo = 'https://spark-assets.netlify.com/spark-logo-black-text.svg';
    break;
  default:
    sparkLogo = 'https://spark-assets.netlify.com/spark-logo-black-text.svg';
}

export default create({
  base: 'light',
  colorPrimary: 'rgb(51, 51, 51)',
  colorSecondary: 'rgb(51, 51, 51)',
  appBg: '#f3f3f3',
  appBorderColor: 'rgb(51, 51, 51)',
  appBorderRadius: 4,
  fontBase: '"urw-din", sans-serif',
  fontCode: 'monospace',
  barTextColor: 'rgb(51, 51, 51)',
  barSelectedColor: 'rgb(51, 51, 51)',
  // barBg: '#302e2e',
  inputBorderRadius: 4,
  brandTitle: 'Spark Design System',
  brandUrl: 'https://sparkdesignsystem.com',
  brandImage: sparkLogo,
});
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you 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.
 */

var javaPolicyArray = new Array(); //contains Java Polices list
var javaPolicyIndexArray = []; //used to maintain the selected Java Policy ID's list

/**
 * Load all the available Java Policies List and the Mapping for given Application Id
 * @param applicationUUID
 * @param isGlobalPolicy - if application level policy : true else if resource level policy : false
 */
function loadAvailableJavaPolicies(applicationUUID, isGlobalPolicy, action) {
    $.ajax({
        url: caramel.context + '/api/entitlement/get/all/available/java/policy/handlers/details/list/' + applicationUUID + '/' + isGlobalPolicy,
        type: 'GET',
        contentType: 'application/json',
        dataType: 'json',
        async: false,
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                var obj = {
                    javaPolicyId: data[i].javaPolicyId,
                    displayName: data[i].displayName,
                    fullQualifiedName: data[i].fullQualifiedName,
                    description: data[i].description,
                    displayOrder: data[i].displayOrder,
                    isMandatory: data[i].isMandatory,
                    policyProperties: data[i].policyProperties,
                    applicationId: data[i].applicationId
                };
                javaPolicyArray.push(obj);
            }
            updateJavaPolicyPartial(action);

        },
        error: function () {
        }
    });
}

/**
 * draw java policies list
 */
function updateJavaPolicyPartial(action) {
    var checkedStatus = "";
    $.each(javaPolicyArray, function (index, obj) {
        if (obj != null) {

            if (javaPolicyIndexArray.indexOf(obj.javaPolicyId) == -1) {
                //if policy is saved, tick the java policy checkbox
                if (obj.applicationId != null) {
                    checkedStatus = "checked";
                    //push the id's of saved policies to array
                    javaPolicyIndexArray.push(obj.javaPolicyId);
                } else {
                    if (action == "add" && obj.displayName == "Publish Statistics:") {
                        checkedStatus = "checked";
                        javaPolicyIndexArray.push(obj.javaPolicyId);
                    }
                }

                //draw div's to each policy
                $('#divJavaPolicies').empty().append(
                    "
 " +
                    " " + obj.displayName + " " +
                    "
" +
                    "<input  class='javaPolicy-opt-val' data-javaPolicy-id='" + obj.javaPolicyId + "'  type='checkbox' "
                    + checkedStatus + ">" +
                    "
" +
                    "
");
            }
        }
    });

    //store the list of Java Policy id's (used in save operation to map the application wise assigned java policies)
    $('#uritemplate_javaPolicyIds').val(JSON.stringify(javaPolicyIndexArray));

    //draw java policy items
    $("#javaPolicy_tbody").trigger("draw");

}

function uniq(a) {
    var seen = {};
    return a.filter(function(item) {
        return seen.hasOwnProperty(item) ? false : (seen[item] = true);
    });
}

//this event triggers when an dynamic optional java policy get clicked. Need to maintain the selected policy id list
$(document).on("click", ".javaPolicy-opt-val", function () {
    var javaPolicyId = parseInt($(this).attr("data-javaPolicy-id"));
    var itemIndex = javaPolicyIndexArray.indexOf(javaPolicyId); //index of clicked (current) item

    if ($(this).prop("checked")) {
        //add item if checked and if not exists in the array
        if (itemIndex == -1) {
            javaPolicyIndexArray.push(javaPolicyId);
        }
    }
    else {
        //remove item if unchecked and if exists in the array
        if (itemIndex > -1) {
            javaPolicyIndexArray.splice(itemIndex, 1);
        }
    }

    //update hidden field which used in save operation to get the mapped java policies
    $('#uritemplate_javaPolicyIds').val(JSON.stringify(javaPolicyIndexArray));

});<commit_msg>Revert "APPM-1461:App creation fail"<commit_after>/*
 *  Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you 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.
 */

var javaPolicyArray = new Array(); //contains Java Polices list
var javaPolicyIndexArray = []; //used to maintain the selected Java Policy ID's list

/**
 * Load all the available Java Policies List and the Mapping for given Application Id
 * @param applicationUUID
 * @param isGlobalPolicy - if application level policy : true else if resource level policy : false
 */
function loadAvailableJavaPolicies(applicationUUID, isGlobalPolicy, action) {
    $.ajax({
        url: caramel.context + '/api/entitlement/get/all/available/java/policy/handlers/details/list/' + applicationUUID + '/' + isGlobalPolicy,
        type: 'GET',
        contentType: 'application/json',
        dataType: 'json',
        async: false,
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                var obj = {
                    javaPolicyId: data[i].javaPolicyId,
                    displayName: data[i].displayName,
                    fullQualifiedName: data[i].fullQualifiedName,
                    description: data[i].description,
                    displayOrder: data[i].displayOrder,
                    isMandatory: data[i].isMandatory,
                    policyProperties: data[i].policyProperties,
                    applicationId: data[i].applicationId
                };
                javaPolicyArray.push(obj);
            }
            updateJavaPolicyPartial(action);

        },
        error: function () {
        }
    });
}

/**
 * draw java policies list
 */
function updateJavaPolicyPartial(action) {
    var checkedStatus = "";
    $.each(javaPolicyArray, function (index, obj) {
        if (obj != null) {

            if(action == "add" && obj.displayName == "Publish Statistics:"){
                checkedStatus = "checked";
                javaPolicyIndexArray.push(obj.javaPolicyId);
            }

            //if policy is saved, tick the java policy checkbox
            if (obj.applicationId != null) {
                checkedStatus = "checked";
                //push the id's of saved policies to array
                javaPolicyIndexArray.push(obj.javaPolicyId);
            }

            //draw div's to each policy
            $('#divJavaPolicies').empty().append(
                "
 " +
                " " + obj.displayName + " " +
                "
" +
                "<input  class='javaPolicy-opt-val' data-javaPolicy-id='" + obj.javaPolicyId + "'  type='checkbox' "
                + checkedStatus + ">" +
                "
" +
                "
");
        }
    });

    //store the list of Java Policy id's (used in save operation to map the application wise assigned java policies)
    $('#uritemplate_javaPolicyIds').val(JSON.stringify(javaPolicyIndexArray));

    //draw java policy items
    $("#javaPolicy_tbody").trigger("draw");

}

//this event triggers when an dynamic optional java policy get clicked. Need to maintain the selected policy id list
$(document).on("click", ".javaPolicy-opt-val", function () {
    var javaPolicyId = parseInt($(this).attr("data-javaPolicy-id"));
    var itemIndex = javaPolicyIndexArray.indexOf(javaPolicyId); //index of clicked (current) item

    if ($(this).prop("checked")) {
        //add item if checked and if not exists in the array
        if (itemIndex == -1) {
            javaPolicyIndexArray.push(javaPolicyId);
        }
    }
    else {
        //remove item if unchecked and if exists in the array
        if (itemIndex > -1) {
            javaPolicyIndexArray.splice(itemIndex, 1);
        }
    }

    //update hidden field which used in save operation to get the mapped java policies
    $('#uritemplate_javaPolicyIds').val(JSON.stringify(javaPolicyIndexArray));

});<|endoftext|>