opnsense_ui.js 10.7 KB
Newer Older
1
/**
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
 *    Copyright (C) 2015 Deciso B.V.
 *
 *    All rights reserved.
 *
 *    Redistribution and use in source and binary forms, with or without
 *    modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 *    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 *    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 *    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *    POSSIBILITY OF SUCH DAMAGE.
 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *
 *    User interface shared components, requires opnsense.js for supporting functions.
30 31
 */

32 33 34 35 36 37
 /**
  * format bytes
  * @param bytes number of bytes to format
  * @param decimals decimal places
  * @return string
  */
38
 function byteFormat(bytes, decimals)
39
 {
40 41 42
     if (decimals == undefined) {
        decimals = 0;
     }
43 44 45 46 47 48
     var kb = 1024;
     var ndx = Math.floor( Math.log(bytes) / Math.log(kb) );
     var fileSizeTypes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
     return (bytes / Math.pow(kb, ndx)).toFixed(decimals) + ' ' + fileSizeTypes[ndx];
 }

49 50 51 52
/**
 * save form to server
 * @param url endpoint url
 * @param formid parent id to grep input data from
53
 * @param disable_dialog don't show input validation message box on failure
54
 */
55 56
function saveFormToEndpoint(url,formid,callback_ok, disable_dialog) {
    disable_dialog = disable_dialog || false;
57
    var data = getFormData(formid);
58 59
    ajaxCall(url=url,sendData=data,callback=function(data,status){
        if ( status == "success") {
60 61 62
            // update field validation
            handleFormValidation(formid,data['validations']);

63 64
            // if there are validation issues, update our screen and show a dialog.
            if (data['validations'] != undefined) {
65 66 67 68 69 70 71 72 73 74 75 76
                if (!disable_dialog) {
                    // validation message box is optional, form is already updated using handleFormValidation
                    BootstrapDialog.show({
                        type:BootstrapDialog.TYPE_WARNING,
                        title: 'Input validation',
                        message: 'Please correct validation errors in form',
                        buttons: [{
                            label: 'Dismiss',
                            action: function(dialogRef){
                                dialogRef.close();
                            }
                        }]
77

78 79
                    });
                }
80 81 82
            } else if ( callback_ok != undefined ) {
                // execute callback function
                callback_ok();
83
            }
84

85 86 87 88 89 90 91 92 93 94 95 96
        } else {
            // error handling, show internal errors
            // Normally the form should only return validation issues, if other things go wrong throw an error.
            BootstrapDialog.show({
                type: BootstrapDialog.TYPE_ERROR,
                title: 'save',
                message: 'Unable to save data, an internal error occurred.<br> ' +
                'Response from server was: <br> <small>'+JSON.stringify(data)+'</small>'
            });
        }

    });
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
}

/**
 * standard data mapper to map json request data to forms on this page
 * @param data_get_map named array containing form names and source url's to get data from {'frm_example':"/api/example/settings/get"};
 * @return promise object, resolves when all are loaded
 */
function mapDataToFormUI(data_get_map) {
    var dfObj = new $.Deferred();

    // calculate number of items for deferred object to resolve
    var data_map_seq = 1;
    var data_map_count = 0;
    $.each(data_get_map, function(){
        data_map_count += 1;
    });

114
    var collected_data = {};
115 116 117 118
    $.each(data_get_map, function(data_index, data_url) {
        ajaxGet(url=data_url,sendData={}, callback=function(data, status) {
            if (status == "success") {
                $("form").each(function( index ) {
119
                    if ( $(this).attr('id') && $(this).attr('id').split('-')[0] == data_index) {
120 121
                        // related form found, load data
                        setFormData($(this).attr('id'), data);
122
                        collected_data[$(this).attr('id')] = data;
123 124 125 126
                    }
                });
            }
            if (data_map_seq == data_map_count) {
127
                dfObj.resolve(collected_data);
128 129 130 131 132 133 134 135 136 137 138
            }
            data_map_seq += 1;
        });
    });

    return dfObj;
}

/**
 * update service status buttons in user interface
 */
Ad Schellevis's avatar
Ad Schellevis committed
139
function updateServiceStatusUI(status) {
140

141
    var status_html = '<span class="glyphicon glyphicon-play btn ';
142 143

    if (status == "running") {
144
        status_html += 'btn-success' ;
145
    } else if (status == "stopped") {
146
        status_html += 'btn-danger' ;
147 148
    }

149
    status_html += '"></span>';
150 151 152 153 154 155 156 157

    $('#service_status_container').html(status_html);
}

/**
 * reformat all tokenizers on this document
 */
function formatTokenizersUI(){
158 159 160 161
    // remove old tokenizers (if any)
    $('div[class="tokenize Tokenize"]').each(function(){
        $(this).remove();
    });
162 163 164 165 166 167 168 169 170 171 172
    $('select[class="tokenize"]').each(function(){
        if ($(this).prop("size")==0) {
            maxDropdownHeight=String(36*5)+"px"; // default number of items

        } else {
            number_of_items = $(this).prop("size");
            maxDropdownHeight=String(36*number_of_items)+"px";
        }
        hint=$(this).data("hint");
        width=$(this).data("width");
        allownew=$(this).data("allownew");
173
        nbDropdownElements=$(this).data("nbdropdownelements");
174 175 176 177 178
        maxTokenContainerHeight=$(this).data("maxheight");

        $(this).tokenize({
            displayDropdownOnFocus: true,
            newElements: allownew,
179
            nbDropdownElements: nbDropdownElements,
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
            placeholder:hint
        });
        $(this).parent().find('ul[class="TokensContainer"]').parent().css("width",width);
        $(this).parent().find('ul[class="Dropdown"]').css("max-height", maxDropdownHeight);
        if ( maxDropdownHeight != undefined ) {
            $(this).parent().find('ul[class="TokensContainer"]').css("max-height", maxTokenContainerHeight);
        }
    });
}

/**
 * clear multiselect boxes on click event, works on standard and tokenized versions
 */
function addMultiSelectClearUI() {
    $('[id*="clear-options"]').each(function() {
        $(this).click(function() {
            var id = $(this).attr("for");
            BootstrapDialog.confirm({
                title: 'Deselect or remove all items ?',
                message: 'Deselect or remove all items ?',
                type: BootstrapDialog.TYPE_DANGER,
                closable: true,
                draggable: true,
                btnCancelLabel: 'Cancel',
                btnOKLabel: 'Yes',
                btnOKClass: 'btn-primary',
                callback: function(result) {
                    if(result) {
                        if ($('select[id="' + id + '"]').hasClass("tokenize")) {
                            // trigger close on all Tokens
                            $('select[id="' + id + '"]').parent().find('ul[class="TokensContainer"]').find('li[class="Token"]').find('a').trigger("click");
                        } else {
                            // remove options from selection
                            $('select[id="' + id + '"]').find('option').prop('selected',false);
                        }
                    }
216 217 218 219 220 221 222
                    // In case this modal was triggered from another modal, fix focus issues
                    $('.modal').on("hidden.bs.modal", function (e) {
                        if($('.modal:visible').length)
                        {
                            $('body').addClass('modal-open');
                        }
                    });
223 224 225 226 227 228 229 230 231 232 233
                }
            });
        });
    });
}

/**
 * setup form help buttons
 */
function initFormHelpUI() {
    // handle help messages show/hide
234
    $("a[class='showhelp']").click(function (event) {
235
        $("*[for='" + $(this).attr('id') + "']").toggleClass("hidden show");
236
        event.preventDefault();
237 238 239
    });

    // handle all help messages show/hide
240
    $('[id*="show_all_help"]').click(function(event) {
241 242 243 244 245 246 247 248 249
        $('[id*="show_all_help"]').toggleClass("fa-toggle-on fa-toggle-off");
        $('[id*="show_all_help"]').toggleClass("text-success text-danger");
        if ($('[id*="show_all_help"]').hasClass("fa-toggle-on")) {
            $('[for*="help_for"]').addClass("show");
            $('[for*="help_for"]').removeClass("hidden");
        } else {
            $('[for*="help_for"]').addClass("hidden");
            $('[for*="help_for"]').removeClass("show");
        }
250
        event.preventDefault();
251 252
    });
}
253

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
/**
 * handle advanced show/hide
 */
function initFormAdvancedUI() {
    $('[data-advanced*="true"]').hide(function(){
        $('[data-advanced*="true"]').after("<tr data-advanced='hidden_row'></tr>"); // the table row is added to keep correct table striping
    });
    $('[id*="show_advanced"]').click(function() {
        $('[id*="show_advanced"]').toggleClass("fa-toggle-on fa-toggle-off");
        $('[id*="show_advanced"]').toggleClass("text-success text-danger");
        if ($('[id*="show_advanced"]').hasClass("fa-toggle-on")) {
            $('[data-advanced*="true"]').show();
            $('[data-advanced*="hidden_row"]').remove(); // the table row is deleted to keep correct table striping
        } else {
            $('[data-advanced*="true"]').after("<tr data-advanced='hidden_row'></tr>").hide(); // the table row is added to keep correct table striping
        }
    });
271
}
272 273 274 275 276 277 278 279

/**
 * standard remove items dialog, wrapper around BootstrapDialog
 */
function stdDialogRemoveItem(message, callback) {
    BootstrapDialog.confirm({
        title: 'Remove',
        message: message,
280
        type:BootstrapDialog.TYPE_DANGER,
281 282 283 284 285 286 287 288 289
        btnCancelLabel: 'Cancel',
        btnOKLabel: 'Yes',
        btnOKClass: 'btn-primary',
        callback: function(result) {
            if(result) {
                callback();
            }
        }
    });
290
}