<commit_before>/**
 *    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.
 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 */

/**
 * wrapper around bootgrid component to use our defaults (including scaling footer)
 * @param id
 * @param sourceUrl
 * @param options associative array containing extra bootgrid options or overwrites
 */
function stdBootgridUI(obj, sourceUrl, options) {
    // set defaults our defaults
    var gridopt = {
        ajax: true,
        selection: true,
        multiSelect: true,
        rowCount:[7,14,20,-1],
        url: sourceUrl,
        formatters: {
            "commands": function (column, row) {
                return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.uuid + "\"></button> " +
                    "<button type=\"button\" class=\"btn btn-xs btn-default command-copy\" data-row-id=\"" + row.uuid + "\"></button>" +
                    "<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.uuid + "\"></button>";
            },
            "rowtoggle": function (column, row) {
                if (parseInt(row[column.id], 2) == 1) {
                    return "";
                } else {
                    return "";
                }
            },
            "boolean": function (column, row) {
                if (parseInt(row[column.id], 2) == 1) {
                    return "";
                } else {
                    return "";
                }
            },
        }
    };

    // merge additional options (if any)
    if (options != undefined) {
        $.each(options,  function(key, value) {
            gridopt[key] = value;
        });
    }

    // construct a new grid
    var grid = obj.bootgrid(gridopt).on("loaded.rs.jquery.bootgrid", function (e)
    {
        // scale footer on resize
        $(this).find("tfoot td:first-child").attr('colspan',$(this).find("th").length - 1);
        // invert colors if needed (check if there is a disabled field instead of an enabled field
        var inverted = $(this).find("thead th[data-column-id=disabled]").length > 0;
        $(this).find('tr[data-row-id]').each(function(index, entry){
            ['[class*="command-toggle"]', '[class*="command-boolean"]'].forEach(function (selector) {
                var selected_element = $(entry).find(selector).first();
                if (selected_element.length > 0) {
                    if ((selected_element.data("value") == "0") != inverted ) {
                        $(entry).addClass("text-muted");
                    }
                }
            });
        });

    })

    return grid;
}

/**
 * reload bootgrid, return to current selected page
 */
function std_bootgrid_reload(gridId) {
    var currentpage = $("#"+gridId).bootgrid("getCurrentPage");
    $("#"+gridId).bootgrid("reload");
    // absolutely not perfect, bootgrid.reload doesn't seem to support when().done()
    setTimeout(function(){
        $('#'+gridId+'-footer  a[data-page="'+currentpage+'"]').click();
    }, 400);
}

/**
 * creates new bootgrid object and links actions to our standard templates
 * uses the following data properties to define functionality:
 *      data-editDialog : id of the edit dialog to use (  see base_dialog.volt template for details )
 *      data-action [add] : set data-action "add" to create a new record
 *      data-action [deleteSelected]: set data-action "deleteSelected" to delete selected items
 *
 * and uses the following properties (params array):
 *  search  : url to search action (GET)
 *  get     : url to get data action (GET) will be suffixed by uuid
 *  set     : url to set data action (POST) will be suffixed by uuid
 *  add     : url to create a new data record (POST)
 *  del     : url to del item action (POST) will be suffixed by uuid
 *
 * @param params
 * @returns {*}
 * @constructor
 */
$.fn.UIBootgrid = function (params) {
    return this.each((function(){
        var gridId = $(this).attr('id');
        var gridParams = params;
        if (gridParams != undefined) {
            if (gridParams['search'] != undefined) {
                // create new bootgrid component and link source
                var grid = stdBootgridUI($(this), gridParams['search'],gridParams['options']);

                // edit dialog id to use ( see base_dialog.volt template for details)
                var editDlg = $(this).attr('data-editDialog');

                // link edit and delete event buttons
                grid.on("loaded.rs.jquery.bootgrid", function(){
                    // edit item
                    grid.find(".command-edit").on("click", function(e)
                    {
                        if (editDlg != undefined && gridParams['get'] != undefined) {
                            var uuid = $(this).data("row-id");
                            var urlMap = {};
                            urlMap['frm_' + editDlg] = gridParams['get'] + uuid;
                            mapDataToFormUI(urlMap).done(function () {
                                // update selectors
                                formatTokenizersUI();
                                $('.selectpicker').selectpicker('refresh');
                                // clear validation errors (if any)
                                clearFormValidation('frm_' + editDlg);

                                // show dialog for pipe edit
                                $('#'+editDlg).modal({backdrop: 'static', keyboard: false});
                                // define save action
                                $("#btn_"+editDlg+"_save").unbind('click').click(function(){
                                    if (gridParams['set'] != undefined) {
                                        saveFormToEndpoint(url=gridParams['set']+uuid,
                                            formid='frm_' + editDlg, callback_ok=function(){
                                                $("#"+editDlg).modal('hide');
                                                std_bootgrid_reload(gridId);
                                            }, true);
                                    } else {
                                        console.log("[grid] action set missing")
                                    }
                                });
                            });
                        } else {
                            console.log("[grid] action get or data-editDialog missing")
                        }
                    }).end();

                    // copy item, save as new
                    grid.find(".command-copy").on("click", function(e)
                    {
                        if (editDlg != undefined && gridParams['get'] != undefined) {
                            var uuid = $(this).data("row-id");
                            var urlMap = {};
                            urlMap['frm_' + editDlg] = gridParams['get'] + uuid;
                            mapDataToFormUI(urlMap).done(function () {
                                // update selectors
                                formatTokenizersUI();
                                $('.selectpicker').selectpicker('refresh');
                                // clear validation errors (if any)
                                clearFormValidation('frm_' + editDlg);

                                // show dialog for pipe edit
                                $('#'+editDlg).modal({backdrop: 'static', keyboard: false});
                                // define save action
                                $("#btn_"+editDlg+"_save").unbind('click').click(function(){
                                    if (gridParams['add'] != undefined) {
                                        saveFormToEndpoint(url=gridParams['add'],
                                            formid='frm_' + editDlg, callback_ok=function(){
                                                $("#"+editDlg).modal('hide');
                                                std_bootgrid_reload(gridId);
                                            }, true);
                                    } else {
                                        console.log("[grid] action add missing")
                                    }
                                });
                            });
                        } else {
                            console.log("[grid] action get or data-editDialog missing")
                        }
                    }).end();

                    // delete item
                    grid.find(".command-delete").on("click", function(e)
                    {
                        if (gridParams['del'] != undefined) {
                            var uuid=$(this).data("row-id");
                            // XXX must be replaced, cannot translate
                            stdDialogRemoveItem('Remove selected item?',function() {
                                ajaxCall(url=gridParams['del'] + uuid,
                                    sendData={},callback=function(data,status){
                                        // reload grid after delete
                                        $("#"+gridId).bootgrid("reload");
                                    });
                            });
                        } else {
                            console.log("[grid] action del missing")
                        }
                    }).end();

                    // toggle item
                    grid.find(".command-toggle").on("click", function(e)
                    {
                        if (gridParams['toggle'] != undefined) {
                            var uuid=$(this).data("row-id");
                            $(this).addClass("fa-spinner fa-pulse");
                            ajaxCall(url=gridParams['toggle'] + uuid,
                                sendData={},callback=function(data,status){
                                    // reload grid after delete
                                    std_bootgrid_reload(gridId);
                                });
                        } else {
                            console.log("[grid] action toggle missing")
                        }
                    }).end();
                });

                // link Add new to child button with data-action = add
                $(this).find("*[data-action=add]").click(function(){
                    if ( gridParams['get'] != undefined && gridParams['add'] != undefined) {
                        var urlMap = {};
                        urlMap['frm_' + editDlg] = gridParams['get'];
                        mapDataToFormUI(urlMap).done(function(){
                            // update selectors
                            formatTokenizersUI();
                            $('.selectpicker').selectpicker('refresh');
                            // clear validation errors (if any)
                            clearFormValidation('frm_' + editDlg);
                        });

                        // show dialog for edit
                        $('#'+editDlg).modal({backdrop: 'static', keyboard: false});
                        //
                        $("#btn_"+editDlg+"_save").unbind('click').click(function(){
                            saveFormToEndpoint(url=gridParams['add'],
                                formid='frm_' + editDlg, callback_ok=function(){
                                    $("#"+editDlg).modal('hide');
                                    $("#"+gridId).bootgrid("reload");
                                }, true);
                        });
                    }  else {
                        console.log("[grid] action add missing")
                    }
                });

                // link delete selected items action
                $(this).find("*[data-action=deleteSelected]").click(function(){
                    if ( gridParams['del'] != undefined) {
                        // XXX must be replaced, cannot translate
                        stdDialogRemoveItem("Remove selected items?",function(){
                            var rows =$("#"+gridId).bootgrid('getSelectedRows');
                            if (rows != undefined){
                                var deferreds = [];
                                $.each(rows, function(key,uuid){
                                    deferreds.push(ajaxCall(url=gridParams['del'] + uuid, sendData={},null));
                                });
                                // refresh after load
                                $.when.apply(null, deferreds).done(function(){
                                    std_bootgrid_reload(gridId);
                                });
                            }
                        });
                    } else {
                        console.log("[grid] action del missing")
                    }
                });

                return grid;
            }
        }
    }));
};
<commit_msg>Include an "info" action variant for bootgrid.<commit_after>/**
 *    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.
 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 */

/**
 * wrapper around bootgrid component to use our defaults (including scaling footer)
 * @param id
 * @param sourceUrl
 * @param options associative array containing extra bootgrid options or overwrites
 */
function stdBootgridUI(obj, sourceUrl, options) {
    // set defaults our defaults
    var gridopt = {
        ajax: true,
        selection: true,
        multiSelect: true,
        rowCount:[7,14,20,-1],
        url: sourceUrl,
        formatters: {
            "commands": function (column, row) {
                return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.uuid + "\"></button> " +
                    "<button type=\"button\" class=\"btn btn-xs btn-default command-copy\" data-row-id=\"" + row.uuid + "\"></button>" +
                    "<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.uuid + "\"></button>";
            },
            "commandsWithInfo": function(column, row) {
                return "<button type=\"button\" class=\"btn btn-xs btn-default command-info\" data-row-id=\"" + row.uuid + "\"></button> " +
                    "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.uuid + "\"></button>" +
                    "<button type=\"button\" class=\"btn btn-xs btn-default command-copy\" data-row-id=\"" + row.uuid + "\"></button>" +
                    "<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.uuid + "\"></button>";
            },
            "rowtoggle": function (column, row) {
                if (parseInt(row[column.id], 2) == 1) {
                    return "";
                } else {
                    return "";
                }
            },
            "boolean": function (column, row) {
                if (parseInt(row[column.id], 2) == 1) {
                    return "";
                } else {
                    return "";
                }
            },
        }
    };

    // merge additional options (if any)
    if (options != undefined) {
        $.each(options,  function(key, value) {
            gridopt[key] = value;
        });
    }

    // construct a new grid
    var grid = obj.bootgrid(gridopt).on("loaded.rs.jquery.bootgrid", function (e)
    {
        // scale footer on resize
        $(this).find("tfoot td:first-child").attr('colspan',$(this).find("th").length - 1);
        // invert colors if needed (check if there is a disabled field instead of an enabled field
        var inverted = $(this).find("thead th[data-column-id=disabled]").length > 0;
        $(this).find('tr[data-row-id]').each(function(index, entry){
            ['[class*="command-toggle"]', '[class*="command-boolean"]'].forEach(function (selector) {
                var selected_element = $(entry).find(selector).first();
                if (selected_element.length > 0) {
                    if ((selected_element.data("value") == "0") != inverted ) {
                        $(entry).addClass("text-muted");
                    }
                }
            });
        });

    })

    return grid;
}

/**
 * reload bootgrid, return to current selected page
 */
function std_bootgrid_reload(gridId) {
    var currentpage = $("#"+gridId).bootgrid("getCurrentPage");
    $("#"+gridId).bootgrid("reload");
    // absolutely not perfect, bootgrid.reload doesn't seem to support when().done()
    setTimeout(function(){
        $('#'+gridId+'-footer  a[data-page="'+currentpage+'"]').click();
    }, 400);
}

/**
 * creates new bootgrid object and links actions to our standard templates
 * uses the following data properties to define functionality:
 *      data-editDialog : id of the edit dialog to use (  see base_dialog.volt template for details )
 *      data-action [add] : set data-action "add" to create a new record
 *      data-action [deleteSelected]: set data-action "deleteSelected" to delete selected items
 *
 * and uses the following properties (params array):
 *  search  : url to search action (GET)
 *  get     : url to get data action (GET) will be suffixed by uuid
 *  set     : url to set data action (POST) will be suffixed by uuid
 *  add     : url to create a new data record (POST)
 *  del     : url to del item action (POST) will be suffixed by uuid
 *  info    : url to get data action that will be displayed informationally suffixed by the uuid
 *
 * @param params
 * @returns {*}
 * @constructor
 */
$.fn.UIBootgrid = function (params) {
    return this.each((function(){
        var gridId = $(this).attr('id');
        var gridParams = params;
        if (gridParams != undefined) {
            if (gridParams['search'] != undefined) {
                // create new bootgrid component and link source
                var grid = stdBootgridUI($(this), gridParams['search'],gridParams['options']);

                // edit dialog id to use ( see base_dialog.volt template for details)
                var editDlg = $(this).attr('data-editDialog');

                // link edit and delete event buttons
                grid.on("loaded.rs.jquery.bootgrid", function(){

                    // info item
                    grid.find(".command-info").on("click", function(e) {
                        if(gridParams['info'] != undefined) {
                            var uuid=$(this).data("row-id");
                            ajaxGet(url=gridParams['info'] + uuid,
                                sendData={}, callback=function(data, status) {
                                    if(status == 'success') {
                                        var title = data['title'] || "Information";
                                        var message = data['message'] || "A Message";
                                        var close = data['close'] || "Close";
                                        stdDialogInform(title, message, close, undefined, "info");
                                    }
                                });
                        } else {
                            console.log("[grid] action info missing");
                        }
                    }).end();

                    // edit item
                    grid.find(".command-edit").on("click", function(e)
                    {
                        if (editDlg != undefined && gridParams['get'] != undefined) {
                            var uuid = $(this).data("row-id");
                            var urlMap = {};
                            urlMap['frm_' + editDlg] = gridParams['get'] + uuid;
                            mapDataToFormUI(urlMap).done(function () {
                                // update selectors
                                formatTokenizersUI();
                                $('.selectpicker').selectpicker('refresh');
                                // clear validation errors (if any)
                                clearFormValidation('frm_' + editDlg);

                                // show dialog for pipe edit
                                $('#'+editDlg).modal({backdrop: 'static', keyboard: false});
                                // define save action
                                $("#btn_"+editDlg+"_save").unbind('click').click(function(){
                                    if (gridParams['set'] != undefined) {
                                        saveFormToEndpoint(url=gridParams['set']+uuid,
                                            formid='frm_' + editDlg, callback_ok=function(){
                                                $("#"+editDlg).modal('hide');
                                                std_bootgrid_reload(gridId);
                                            }, true);
                                    } else {
                                        console.log("[grid] action set missing")
                                    }
                                });
                            });
                        } else {
                            console.log("[grid] action get or data-editDialog missing")
                        }
                    }).end();

                    // copy item, save as new
                    grid.find(".command-copy").on("click", function(e)
                    {
                        if (editDlg != undefined && gridParams['get'] != undefined) {
                            var uuid = $(this).data("row-id");
                            var urlMap = {};
                            urlMap['frm_' + editDlg] = gridParams['get'] + uuid;
                            mapDataToFormUI(urlMap).done(function () {
                                // update selectors
                                formatTokenizersUI();
                                $('.selectpicker').selectpicker('refresh');
                                // clear validation errors (if any)
                                clearFormValidation('frm_' + editDlg);

                                // show dialog for pipe edit
                                $('#'+editDlg).modal({backdrop: 'static', keyboard: false});
                                // define save action
                                $("#btn_"+editDlg+"_save").unbind('click').click(function(){
                                    if (gridParams['add'] != undefined) {
                                        saveFormToEndpoint(url=gridParams['add'],
                                            formid='frm_' + editDlg, callback_ok=function(){
                                                $("#"+editDlg).modal('hide');
                                                std_bootgrid_reload(gridId);
                                            }, true);
                                    } else {
                                        console.log("[grid] action add missing")
                                    }
                                });
                            });
                        } else {
                            console.log("[grid] action get or data-editDialog missing")
                        }
                    }).end();

                    // delete item
                    grid.find(".command-delete").on("click", function(e)
                    {
                        if (gridParams['del'] != undefined) {
                            var uuid=$(this).data("row-id");
                            // XXX must be replaced, cannot translate
                            stdDialogRemoveItem('Remove selected item?',function() {
                                ajaxCall(url=gridParams['del'] + uuid,
                                    sendData={},callback=function(data,status){
                                        // reload grid after delete
                                        $("#"+gridId).bootgrid("reload");
                                    });
                            });
                        } else {
                            console.log("[grid] action del missing")
                        }
                    }).end();

                    // toggle item
                    grid.find(".command-toggle").on("click", function(e)
                    {
                        if (gridParams['toggle'] != undefined) {
                            var uuid=$(this).data("row-id");
                            $(this).addClass("fa-spinner fa-pulse");
                            ajaxCall(url=gridParams['toggle'] + uuid,
                                sendData={},callback=function(data,status){
                                    // reload grid after delete
                                    std_bootgrid_reload(gridId);
                                });
                        } else {
                            console.log("[grid] action toggle missing")
                        }
                    }).end();
                });

                // link Add new to child button with data-action = add
                $(this).find("*[data-action=add]").click(function(){
                    if ( gridParams['get'] != undefined && gridParams['add'] != undefined) {
                        var urlMap = {};
                        urlMap['frm_' + editDlg] = gridParams['get'];
                        mapDataToFormUI(urlMap).done(function(){
                            // update selectors
                            formatTokenizersUI();
                            $('.selectpicker').selectpicker('refresh');
                            // clear validation errors (if any)
                            clearFormValidation('frm_' + editDlg);
                        });

                        // show dialog for edit
                        $('#'+editDlg).modal({backdrop: 'static', keyboard: false});
                        //
                        $("#btn_"+editDlg+"_save").unbind('click').click(function(){
                            saveFormToEndpoint(url=gridParams['add'],
                                formid='frm_' + editDlg, callback_ok=function(){
                                    $("#"+editDlg).modal('hide');
                                    $("#"+gridId).bootgrid("reload");
                                }, true);
                        });
                    }  else {
                        console.log("[grid] action add missing")
                    }
                });

                // link delete selected items action
                $(this).find("*[data-action=deleteSelected]").click(function(){
                    if ( gridParams['del'] != undefined) {
                        // XXX must be replaced, cannot translate
                        stdDialogRemoveItem("Remove selected items?",function(){
                            var rows =$("#"+gridId).bootgrid('getSelectedRows');
                            if (rows != undefined){
                                var deferreds = [];
                                $.each(rows, function(key,uuid){
                                    deferreds.push(ajaxCall(url=gridParams['del'] + uuid, sendData={},null));
                                });
                                // refresh after load
                                $.when.apply(null, deferreds).done(function(){
                                    std_bootgrid_reload(gridId);
                                });
                            }
                        });
                    } else {
                        console.log("[grid] action del missing")
                    }
                });

                return grid;
            }
        }
    }));
};
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF 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.
 */

// @ts-check
// Note: type annotations allow type checking and IDEs autocompletion

const lightCodeTheme = require('prism-react-renderer/themes/github');
const darkCodeTheme = require('prism-react-renderer/themes/dracula');

/** @type {import('@docusaurus/types').Config} */
const config = {
  title: 'Superset',
  tagline:
    'Apache Superset is a modern data exploration and visualization platform',
  url: 'https://superset.apache.org',
  baseUrl: '/',
  onBrokenLinks: 'throw',
  onBrokenMarkdownLinks: 'throw',
  favicon: 'img/favicon.ico',
  organizationName: 'apache', // Usually your GitHub org/user name.
  projectName: 'superset', // Usually your repo name.
    themes: [
        '@saucelabs/theme-github-codeblock'
    ],
   plugins: [
    [
      '@docusaurus/plugin-client-redirects',
      {
        fromExtensions: ['html', 'htm'],
        toExtensions: ['exe', 'zip'],
        redirects: [
          {
            to: '/docs/installation/installing-superset-using-docker-compose',
            from: '/installation.html',
          },
          {
            to: '/docs/intro',
            from: '/tutorials.html',
          },
          {
            to: '/docs/Creating Charts and Dashboards/creating-your-first-dashboard',
            from: '/admintutorial.html',
          },
          {
            to: '/docs/Creating Charts and Dashboards/creating-your-first-dashboard',
            from: '/usertutorial.html',
          },
          {
            to: '/docs/security',
            from: '/security.html',
          },
          {
            to: '/docs/installation/sql-templating',
            from: '/sqllab.html',
          },
          {
            to: '/docs/intro',
            from: '/gallery.html',
          },
          {
            to: '/docs/connecting-to-databases/druid',
            from: '/druid.html',
          },
          {
            to: '/docs/miscellaneous/country-map-tools',
            from: '/misc.html',
          },
          {
            to: '/docs/miscellaneous/country-map-tools',
            from: '/visualization.html',
          },
          {
            to: '/docs/frequently-asked-questions',
            from: '/videos.html',
          },
          {
            to: '/docs/frequently-asked-questions',
            from: '/faq.html',
          },
          {
            to: '/docs/Creating Charts and Dashboards/creating-your-first-dashboard',
            from: '/tutorial.html',
          },
          {
            to: '/docs/installation/alerts-reports',
            from: '/docs/installation/email-reports',
          },
          {
            to: '/docs/intro',
            from: '/docs/roadmap',
          },
        ],
      },
    ],
  ],

  presets: [
    [
      '@docusaurus/preset-classic',
      /** @type {import('@docusaurus/preset-classic').Options} */
      ({
        docs: {
          sidebarPath: require.resolve('./sidebars.js'),
          editUrl: 'https://github.com/apache/superset/tree/master/docs-v2',
        },
        blog: {
          showReadingTime: true,
          // Please change this to your repo.
          editUrl:
            'https://github.com/facebook/docusaurus/edit/main/website/blog/',
        },
        theme: {
          customCss: require.resolve('./src/css/custom.css'),
        },
      }),
    ],
  ],

  themeConfig:
    /** @type {import('@docusaurus/preset-classic').ThemeConfig} */
    ({
      colorMode: {
        defaultMode: 'light',
        disableSwitch: true,
      },
      navbar: {
        logo: {
          alt: 'Superset Logo',
          src: 'img/superset-logo-horiz.svg',
          srcDark: 'img/superset-logo-horiz-dark.svg',
        },
        items: [
          {
            type: 'doc',
            docId: 'intro',
            position: 'left',
            label: 'Documentation',
          },
          { to: '/community', label: 'Community', position: 'left' },
          {
            href: 'https://github.com/apache/superset',
            label: 'GitHub',
            position: 'right',
          },
        ],
      },
      footer: {
        style: 'dark',
        links: [
          {
            title: 'Docs',
            items: [
              {
                label: 'Tutorial',
                to: '/docs/intro',
              },
            ],
          },
          {
            title: 'Community',
            items: [
              {
                label: 'Stack Overflow',
                href: 'https://stackoverflow.com/questions/tagged/superset+apache-superset',
              },
              {
                label: 'Slack',
                href: 'https://join.slack.com/t/apache-superset/shared_invite/zt-uxbh5g36-AISUtHbzOXcu0BIj7kgUaw',
              },
              {
                label: 'Mailing List',
                href: 'https://lists.apache.org/list.html?dev@superset.apache.org',
              },
            ],
          },
          {
            title: 'More',
            items: [
              {
                label: 'GitHub',
                href: 'https://github.com/apache/superset',
              },
            ],
          },
        ],
        copyright: `Copyright © ${new Date().getFullYear()},
        The Apache Software Foundation,
        Licensed under the Apache License.

        Apache Superset, Apache, Superset, the Superset logo, and the Apache feather logo are either registered trademarks or trademarks of The Apache Software Foundation. All other products or name brands are trademarks of their respective holders, including The Apache Software Foundation.
        Apache Software Foundation resources

        Security |
        Donate |
        Thanks |
        Events |
        License
        `,
      },
      prism: {
        theme: lightCodeTheme,
        darkTheme: darkCodeTheme,
      },
    }),

};

module.exports = config;
<commit_msg>Update docusaurus.config.js (#18577)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF 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.
 */

// @ts-check
// Note: type annotations allow type checking and IDEs autocompletion

const lightCodeTheme = require('prism-react-renderer/themes/github');
const darkCodeTheme = require('prism-react-renderer/themes/dracula');

/** @type {import('@docusaurus/types').Config} */
const config = {
  title: 'Superset',
  tagline:
    'Apache Superset is a modern data exploration and visualization platform',
  url: 'https://superset.apache.org',
  baseUrl: '/',
  onBrokenLinks: 'throw',
  onBrokenMarkdownLinks: 'throw',
  favicon: 'img/favicon.ico',
  organizationName: 'apache', // Usually your GitHub org/user name.
  projectName: 'superset', // Usually your repo name.
    themes: [
        '@saucelabs/theme-github-codeblock'
    ],
   plugins: [
    [
      '@docusaurus/plugin-client-redirects',
      {
        fromExtensions: ['html', 'htm'],
        toExtensions: ['exe', 'zip'],
        redirects: [
          {
            to: '/docs/installation/installing-superset-using-docker-compose',
            from: '/installation.html',
          },
          {
            to: '/docs/intro',
            from: '/tutorials.html',
          },
          {
            to: '/docs/Creating Charts and Dashboards/creating-your-first-dashboard',
            from: '/admintutorial.html',
          },
          {
            to: '/docs/Creating Charts and Dashboards/creating-your-first-dashboard',
            from: '/usertutorial.html',
          },
          {
            to: '/docs/security',
            from: '/security.html',
          },
          {
            to: '/docs/installation/sql-templating',
            from: '/sqllab.html',
          },
          {
            to: '/docs/intro',
            from: '/gallery.html',
          },
          {
            to: '/docs/connecting-to-databases/druid',
            from: '/druid.html',
          },
          {
            to: '/docs/miscellaneous/country-map-tools',
            from: '/misc.html',
          },
          {
            to: '/docs/miscellaneous/country-map-tools',
            from: '/visualization.html',
          },
          {
            to: '/docs/frequently-asked-questions',
            from: '/videos.html',
          },
          {
            to: '/docs/frequently-asked-questions',
            from: '/faq.html',
          },
          {
            to: '/docs/Creating Charts and Dashboards/creating-your-first-dashboard',
            from: '/tutorial.html',
          },
          {
            to: '/docs/installation/alerts-reports',
            from: '/docs/installation/email-reports',
          },
          {
            to: '/docs/intro',
            from: '/docs/roadmap',
          },
        ],
      },
    ],
  ],

  presets: [
    [
      '@docusaurus/preset-classic',
      /** @type {import('@docusaurus/preset-classic').Options} */
      ({
        docs: {
          sidebarPath: require.resolve('./sidebars.js'),
          editUrl: 'https://github.com/apache/superset/tree/master/docs',
        },
        blog: {
          showReadingTime: true,
          // Please change this to your repo.
          editUrl:
            'https://github.com/facebook/docusaurus/edit/main/website/blog/',
        },
        theme: {
          customCss: require.resolve('./src/css/custom.css'),
        },
      }),
    ],
  ],

  themeConfig:
    /** @type {import('@docusaurus/preset-classic').ThemeConfig} */
    ({
      colorMode: {
        defaultMode: 'light',
        disableSwitch: true,
      },
      navbar: {
        logo: {
          alt: 'Superset Logo',
          src: 'img/superset-logo-horiz.svg',
          srcDark: 'img/superset-logo-horiz-dark.svg',
        },
        items: [
          {
            type: 'doc',
            docId: 'intro',
            position: 'left',
            label: 'Documentation',
          },
          { to: '/community', label: 'Community', position: 'left' },
          {
            href: 'https://github.com/apache/superset',
            label: 'GitHub',
            position: 'right',
          },
        ],
      },
      footer: {
        style: 'dark',
        links: [
          {
            title: 'Docs',
            items: [
              {
                label: 'Tutorial',
                to: '/docs/intro',
              },
            ],
          },
          {
            title: 'Community',
            items: [
              {
                label: 'Stack Overflow',
                href: 'https://stackoverflow.com/questions/tagged/superset+apache-superset',
              },
              {
                label: 'Slack',
                href: 'https://join.slack.com/t/apache-superset/shared_invite/zt-uxbh5g36-AISUtHbzOXcu0BIj7kgUaw',
              },
              {
                label: 'Mailing List',
                href: 'https://lists.apache.org/list.html?dev@superset.apache.org',
              },
            ],
          },
          {
            title: 'More',
            items: [
              {
                label: 'GitHub',
                href: 'https://github.com/apache/superset',
              },
            ],
          },
        ],
        copyright: `Copyright © ${new Date().getFullYear()},
        The Apache Software Foundation,
        Licensed under the Apache License.

        Apache Superset, Apache, Superset, the Superset logo, and the Apache feather logo are either registered trademarks or trademarks of The Apache Software Foundation. All other products or name brands are trademarks of their respective holders, including The Apache Software Foundation.
        Apache Software Foundation resources

        Security |
        Donate |
        Thanks |
        Events |
        License
        `,
      },
      prism: {
        theme: lightCodeTheme,
        darkTheme: darkCodeTheme,
      },
    }),

};

module.exports = config;
<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var mysql = require('mysql');
var stringify = require('json-stringify-safe');
var dateTimeFormat = 'YYYY-MM-DD HH:mm:ss';

/**
 * @param {Object} criteria
 * @param {Object} orderBy
 * @param {Number} limit
 * @param {Number} offset
 * @param {String} table
 * @returns {String}
 */
module.exports.buildSelectQuery = function (criteria, orderBy, limit, offset, table)
{
    return util.format(
        'SELECT * FROM %s%s%s%s',
        this.escapeField(table),
        this.buildWherePart(criteria),
        this.buildOrderByPart(orderBy),
        this.buildPaginationPart(limit, offset)
    );
};

/**
 * @param {Object} object
 * @param {String} table
 * @returns {String}
 */
module.exports.buildInsertQuery = function (object, table)
{
    var values = [];

    for (var key in object) {
        if (!object.hasOwnProperty(key)) continue;

        values.push(this.sanitizeValue(object[key]));
    }

    return util.format(
        'INSERT INTO %s (`%s`) VALUES (%s)',
        this.escapeField(table),
        Object.keys(object).join('`, `'),
        values.join(', ')
    );
};

/**
 * @param {Object} criteria
 * @param {Object} object
 * @param {String} table
 */
module.exports.buildUpdateQuery = function (criteria, object, table)
{
    var sql = 'UPDATE ' + this.escapeField(table) + ' SET ';
    var valueCount = 0;

    for (var key in object) {
        if (object.hasOwnProperty(key)) {
            if (valueCount > 0) {
                sql += ', ';
            }

            sql += this.escapeField(key) + ' = ' + this.sanitizeValue(object[key]);
        }

        valueCount++;
    }

    sql += this.buildWherePart(criteria);

    return sql;
};

/**
 * @param {Object} criteria
 * @param {String} table
 */
module.exports.buildDeleteQuery = function (criteria, table)
{
    return util.format(
        'DELETE FROM %s%s',
        this.escapeField(table),
        this.buildWherePart(criteria)
    );
};

/**
 * @param {Object} criteria
 * @returns {String}
 */
module.exports.buildWherePart = function (criteria)
{
    var sql = '';

    if (Object.keys(criteria).length !== 0) {
        var n = 0;

        sql += ' WHERE ';

        for (var key in criteria) {
            if (!criteria.hasOwnProperty(key)) {
                continue;
            }

            if (n !== 0) {
                sql += ' AND ';
            }

            sql += this.escapeField(key);

            var value = criteria[key];
            if (value === null) {
                sql += ' IS NULL';
            } else if (typeof value === 'number') {
                sql += ' = ' + value;
            } else if (value instanceof Array) {
                sql += ' IN (' + this.stringifyArray(value) + ')';
            } else {
                sql += ' LIKE ' + this.sanitizeValue(value);
            }

            n += 1;
        }
    }

    return sql;
};

/**
 *
 * @param {Number} limit
 * @param {Number} offset
 * @returns {String}
 */
module.exports.buildPaginationPart = function (limit, offset)
{
    var sql = '';

    if (limit !== null && offset !== null) {
        limit = Number(limit);
        offset = Number(offset);

        sql += ' LIMIT ' + limit + ' OFFSET ' + offset;
    }

    return sql;
};

/**
 * @param {Object} orderBy
 * @returns {String}
 */
module.exports.buildOrderByPart = function (orderBy)
{
    var sql = '';

    if (Object.keys(orderBy).length !== 0) {
        var i = 0;

        sql += ' ORDER BY ';

        for (var field in orderBy) {
            if (!orderBy.hasOwnProperty(field)) {
                continue;
            }

            if (i !== 0) {
                sql += ', ';
            }

            sql += this.escapeField(field);

            var order = orderBy[field];
            var orderAdded = false;
            if (order === 'desc' || order === 'DESC') {
                sql += ' DESC';
                orderAdded = true;
            }

            if (order === 'asc' || order === 'ASC') {
                sql += ' ASC';
                orderAdded = true;
            }

            if (!orderAdded) {
                throw new Error('Order must be ASC or DESC');
            }

            i++;
        }
    }

    return sql;
};

/**
 * @param {Array} array
 * @returns {String}
 */
module.exports.stringifyArray = function (array)
{
    var arrayString = '';

    for (var i in array) {
        if (!array.hasOwnProperty(i)) {
            continue;
        }

        arrayString += this.sanitizeValue(array[i]);

        if (i != array.length - 1) arrayString += ', ';
    }

    return arrayString;
};

/**
 * @param value
 * @return {String}
 */
module.exports.sanitizeValue = function (value)
{
    if (value !== null && typeof value === 'object' && value._isAMomentObject) {
        value = value.format(dateTimeFormat);
    }

    if (value !== null && typeof value === 'object') {
        value = stringify(value);
    }

    return mysql.escape(value);
};

/**
 * @param {String} name
 * @returns {string}
 */
module.exports.escapeField = function (name)
{
    return '`' + name + '`';
};
<commit_msg>One line own property checks<commit_after>'use strict';

var util = require('util');
var mysql = require('mysql');
var stringify = require('json-stringify-safe');
var dateTimeFormat = 'YYYY-MM-DD HH:mm:ss';

/**
 * @param {Object} criteria
 * @param {Object} orderBy
 * @param {Number} limit
 * @param {Number} offset
 * @param {String} table
 * @returns {String}
 */
module.exports.buildSelectQuery = function (criteria, orderBy, limit, offset, table)
{
    return util.format(
        'SELECT * FROM %s%s%s%s',
        this.escapeField(table),
        this.buildWherePart(criteria),
        this.buildOrderByPart(orderBy),
        this.buildPaginationPart(limit, offset)
    );
};

/**
 * @param {Object} object
 * @param {String} table
 * @returns {String}
 */
module.exports.buildInsertQuery = function (object, table)
{
    var values = [];

    for (var key in object) {
        if (!object.hasOwnProperty(key)) continue;

        values.push(this.sanitizeValue(object[key]));
    }

    return util.format(
        'INSERT INTO %s (`%s`) VALUES (%s)',
        this.escapeField(table),
        Object.keys(object).join('`, `'),
        values.join(', ')
    );
};

/**
 * @param {Object} criteria
 * @param {Object} object
 * @param {String} table
 */
module.exports.buildUpdateQuery = function (criteria, object, table)
{
    var sql = 'UPDATE ' + this.escapeField(table) + ' SET ';
    var valueCount = 0;

    for (var key in object) {
        if (object.hasOwnProperty(key)) {
            if (valueCount > 0) {
                sql += ', ';
            }

            sql += this.escapeField(key) + ' = ' + this.sanitizeValue(object[key]);
        }

        valueCount++;
    }

    sql += this.buildWherePart(criteria);

    return sql;
};

/**
 * @param {Object} criteria
 * @param {String} table
 */
module.exports.buildDeleteQuery = function (criteria, table)
{
    return util.format(
        'DELETE FROM %s%s',
        this.escapeField(table),
        this.buildWherePart(criteria)
    );
};

/**
 * @param {Object} criteria
 * @returns {String}
 */
module.exports.buildWherePart = function (criteria)
{
    var sql = '';

    if (Object.keys(criteria).length !== 0) {
        var n = 0;

        sql += ' WHERE ';

        for (var key in criteria) {
            if (!criteria.hasOwnProperty(key)) continue;

            if (n !== 0) {
                sql += ' AND ';
            }

            sql += this.escapeField(key);

            var value = criteria[key];
            if (value === null) {
                sql += ' IS NULL';
            } else if (typeof value === 'number') {
                sql += ' = ' + value;
            } else if (value instanceof Array) {
                sql += ' IN (' + this.stringifyArray(value) + ')';
            } else {
                sql += ' LIKE ' + this.sanitizeValue(value);
            }

            n += 1;
        }
    }

    return sql;
};

/**
 *
 * @param {Number} limit
 * @param {Number} offset
 * @returns {String}
 */
module.exports.buildPaginationPart = function (limit, offset)
{
    var sql = '';

    if (limit !== null && offset !== null) {
        limit = Number(limit);
        offset = Number(offset);

        sql += ' LIMIT ' + limit + ' OFFSET ' + offset;
    }

    return sql;
};

/**
 * @param {Object} orderBy
 * @returns {String}
 */
module.exports.buildOrderByPart = function (orderBy)
{
    var sql = '';

    if (Object.keys(orderBy).length !== 0) {
        var i = 0;

        sql += ' ORDER BY ';

        for (var field in orderBy) {
            if (!orderBy.hasOwnProperty(field)) continue;

            if (i !== 0) {
                sql += ', ';
            }

            sql += this.escapeField(field);

            var order = orderBy[field];
            var orderAdded = false;
            if (order === 'desc' || order === 'DESC') {
                sql += ' DESC';
                orderAdded = true;
            }

            if (order === 'asc' || order === 'ASC') {
                sql += ' ASC';
                orderAdded = true;
            }

            if (!orderAdded) {
                throw new Error('Order must be ASC or DESC');
            }

            i++;
        }
    }

    return sql;
};

/**
 * @param {Array} array
 * @returns {String}
 */
module.exports.stringifyArray = function (array)
{
    var arrayString = '';

    for (var i in array) {
        if (!array.hasOwnProperty(i)) continue;

        arrayString += this.sanitizeValue(array[i]);

        if (i != array.length - 1) arrayString += ', ';
    }

    return arrayString;
};

/**
 * @param value
 * @return {String}
 */
module.exports.sanitizeValue = function (value)
{
    if (value !== null && typeof value === 'object' && value._isAMomentObject) {
        value = value.format(dateTimeFormat);
    }

    if (value !== null && typeof value === 'object') {
        value = stringify(value);
    }

    return mysql.escape(value);
};

/**
 * @param {String} name
 * @returns {string}
 */
module.exports.escapeField = function (name)
{
    return '`' + name + '`';
};
<|endoftext|>


<commit_before>define(['../../../js/common'], function() {

    document.title = '挂件列表 - CMS内容管理系统';

    require(['template', 'moment', 'select2', 'form', 'paging', 'MDialog'], function(template, moment) {

        template.helper('format_date', function(date) {
            return moment(date).format('YYYY-MM-DD');
        });

        var form = $('#post_form'),
            nav = $('#nav_tools'),
            siteId = util.get_query('siteId');

        $('select', form).select2({
            minimumResultsForSearch: -1,
            allowClear: true
        });

        if (form.find('input[name=siteId]').length == 0) {
            form.append('<input type="hidden" name="siteId" value="' + siteId + '" />');
        }

        // 添加新挂件
        $('.add-widgets', nav).on('click', function() {

            var add_form = $(template('widget_add_form', { site_id: siteId })),
                dlg = $M({
                    title: '添加新挂件',
                    content: add_form[0],
                    width: '450px',
                    lock: true,
                    position: '50 % 50 %',
                    ok: function() {
                        add_form.submit();
                    },
                    okVal: '保存',
                    cancel: false,
                    cancelVal: '取消'
                });

            add_form.gform({
                url: config.host + 'widget/save',
                beforeSubmit: function() {
                    var name = $('[name=name]', add_form).val();

                    if (name.length == 0) {

                        $('[name=name]', add_form).parent().addClass('has-error');
                        alert('名称不能为空');

                        return false;
                    }

                },
                onSuccess: function(r) {

                    if (!r || r.code < 0) {

                        alert(r.msg || '发生未知错误，请刷新后尝试');
                        return false;
                    }

                    dlg.close();

                    alert('已成功添加站点信息');
                    form.submit(); //重新刷新站点列表
                }
            });

        });

        // TODO  绑定表单
        form.gform({
            url: config.host + 'widget/list',
            onSuccess: function(r) {

                if (!r || r.code < 0) {

                    alert(r.msg || '发生未知错误，请刷新后尝试')
                    return false;
                }

                //更新总数
                $('#total_count').html(r.paging.total_count);
                $('#table_container', form).html(template('widgets_table', r));

                //绑定表格
                var table = $('table', form).gtable();

                // 编辑站点
                $('.edit', table).on('click', function() {
                    debugger;
                    var siteId = util.get_query('siteId'),
                        id = $(this).data('id');

                    $.post(config.host + 'widget/detail', { id: $(this).data('id'), siteId: siteId }, function(r) {

                        r = handleException(r);

                        if (!r || r.code < 0) {
                            alert(r.msg || '发生未知错误，请刷新页面后尝试');
                            return false;
                        }

                        var edit_form = $(template('widget_add_form', r.widget)),
                            dlg = $M({
                                title: '编辑站点',
                                content: edit_form[0],
                                width: '450px',
                                lock: true,
                                position: '50% 50%',
                                ok: function() {
                                    edit_form.submit();
                                },
                                okVal: '保存',
                                cancel: false,
                                cancelVal: '取消'
                            });

                        edit_form.gform({

                            url: config.host + 'widget/save',

                            beforeSubmit: function() {

                                var name = $('[name=name]', edit_form).val();

                                if (name.length == 0) {

                                    $('[name=name]', edit_form).parent().addClass('has-error');
                                    alert('名称不能为空');

                                    return false;
                                }

                            },
                            onSuccess: function(r) {

                                if (!r || r.code < 0) {

                                    alert(r.msg || '发生未知错误，请刷新后尝试');
                                    return false;
                                }

                                dlg.close();

                                alert('已修改添加站点信息');
                                form.submit(); //重新刷新站点列表
                            }
                        });

                    }, 'json');
                });

                // 删除站点
                $('.delete', table).on('click', function() {

                    var siteId = util.get_query('siteId'),
                        id = $(this).data('id');

                    if (!confirm('是否确定彻底删除此挂件')) return false;

                    var delete_site = function(confirmed) {

                        $.post(config.host + 'widget/delete', {
                            id: id,
                            siteId: siteId,
                            confirmed: confirmed || false
                        }, function(r) {

                            if (!r || r.code < 0) {
                                alert(r.msg || '发生未知错误，请刷新页面后尝试');
                                return false;
                            }

                            alert('已彻底删除该站点');
                            form.submit();

                        }, 'json');
                    };

                    delete_site(false);
                });
                //绑定分页信息
                $('.x-paging-container', form).paging(r.paging);
            },
            callback: function(form) {
                form.submit();
            }
        });

    });
});<commit_msg>样式优化<commit_after>define(['../../../js/common'], function () {

    document.title = '挂件列表 - CMS内容管理系统';

    require(['template', 'moment', 'select2', 'form', 'paging', 'MDialog'], function (template, moment) {

        template.helper('format_date', function (date) {
            return moment(date).format('YYYY-MM-DD');
        });

        var form = $('#post_form'),
            nav = $('#nav_tools'),
            siteId = util.get_query('siteId');

        $('select', form).select2({
            minimumResultsForSearch: -1,
            allowClear: true
        });

        if (form.find('input[name=siteId]').length == 0) {
            form.append('<input type="hidden" name="siteId" value="' + siteId + '" />');
        }

        // 添加新挂件
        $('.add-widgets', nav).on('click', function () {

            var add_form = $(template('widget_add_form', { site_id: siteId })),
                dlg = $M({
                    title: '添加新挂件',
                    content: add_form[0],
                    width: '450px',
                    lock: true,
                    position: '50 % 50 %',
                    ok: function () {
                        add_form.submit();
                    },
                    okVal: '保存',
                    cancel: false,
                    cancelVal: '取消'
                });

            add_form.gform({
                url: config.host + 'widget/save',
                beforeSubmit: function () {
                    var name = $('[name=name]', add_form).val();

                    if (name.length == 0) {

                        $('[name=name]', add_form).parent().addClass('has-error');
                        alert('名称不能为空');

                        return false;
                    }

                },
                onSuccess: function (r) {

                    if (!r || r.code < 0) {

                        alert(r.msg || '发生未知错误，请刷新后尝试');
                        return false;
                    }

                    dlg.close();

                    alert('已成功添加站点信息');
                    form.submit(); //重新刷新站点列表
                }
            });

        });

        // 绑定表单
        form.gform({
            url: config.host + 'widget/list',
            onSuccess: function (r) {

                if (!r || r.code < 0) {

                    alert(r.msg || '发生未知错误，请刷新后尝试')
                    return false;
                }

                //更新总数
                $('#total_count').html(r.paging.total_count);
                $('#table_container', form).html(template('widgets_table', r));

                //绑定表格
                var table = $('table', form).gtable();

                // 编辑站点
                $('.edit', table).on('click', function () {
                    var siteId = util.get_query('siteId'),
                        id = $(this).data('id');

                    $.post(config.host + 'widget/detail', { id: $(this).data('id'), siteId: siteId }, function (r) {

                        r = handleException(r);

                        if (!r || r.code < 0) {
                            alert(r.msg || '发生未知错误，请刷新页面后尝试');
                            return false;
                        }

                        var edit_form = $(template('widget_add_form', r.widget)),
                            dlg = $M({
                                title: '编辑站点',
                                content: edit_form[0],
                                width: '450px',
                                lock: true,
                                position: '50% 50%',
                                ok: function () {
                                    edit_form.submit();
                                },
                                okVal: '保存',
                                cancel: false,
                                cancelVal: '取消'
                            });

                        edit_form.gform({

                            url: config.host + 'widget/save',

                            beforeSubmit: function () {

                                var name = $('[name=name]', edit_form).val();

                                if (name.length == 0) {

                                    $('[name=name]', edit_form).parent().addClass('has-error');
                                    alert('名称不能为空');

                                    return false;
                                }

                            },
                            onSuccess: function (r) {

                                if (!r || r.code < 0) {

                                    alert(r.msg || '发生未知错误，请刷新后尝试');
                                    return false;
                                }

                                dlg.close();

                                alert('已修改添加站点信息');
                                form.submit(); //重新刷新站点列表
                            }
                        });

                    }, 'json');
                });

                // 删除站点
                $('.delete', table).on('click', function () {

                    var siteId = util.get_query('siteId'),
                        id = $(this).data('id');

                    if (!confirm('是否确定彻底删除此挂件')) return false;

                    var delete_site = function (confirmed) {

                        $.post(config.host + 'widget/delete', {
                            id: id,
                            siteId: siteId,
                            confirmed: confirmed || false
                        }, function (r) {

                            if (!r || r.code < 0) {
                                alert(r.msg || '发生未知错误，请刷新页面后尝试');
                                return false;
                            }

                            alert('已彻底删除该站点');
                            form.submit();

                        }, 'json');
                    };

                    delete_site(false);
                });
                //绑定分页信息
                $('.x-paging-container', form).paging(r.paging);
            },
            callback: function (form) {
                form.submit();
            }
        });

    });
});<|endoftext|>


<commit_before>(function (window) {
	//latter overwrite former
	var Spai =  window.Spai || {};
	var isFunction = function (value) {
		return typeof value === "function";
	};

	Spai.promise = function(fn) {
		var promise = {};
		promise.state = "pending";
		promise.then = function (onFulfilled, onRejected) {
		};

		var resolve = function (value) {
			if (promise.state === "pending") {
				promise.state = "fulfilled";
			}
			else {
				return;
			}

			if (promise.onFulfilled) {
				promise.onFulfilled(value);
			}
		};
		var reject = function  (reason) {
			if (promise.state === "pending") {
				promise.state = "rejected";
			}
			else {
				return;
			}

			if (promise.onRejected) {
				promise.onRejected(reason);
			}
		};

		if (isFunction(fn)) {
			fn.call(promise, resolve, reject);
		}
		return promise;
	};

	Spai.defer = function() {
		var deferred = {};
		deferred.promise = Spai.promise(function (resolve, reject) {
			deferred.resolve = resolve;
			deferred.reject = reject;
		});
		return deferred;
	};

	if (typeof module === "object" && module && typeof module.exports === "object") {
		//node env
		module.exports = Spai;
	}
	else {
		//browser env
		window.Spai = Spai;
	}
})(this);<commit_msg>pass 80 tests<commit_after>(function (window) {
	//latter overwrite former
	var Spai =  window.Spai || {};

	var isFunction = function (value) {
		return typeof value === "function";
	};
	var allStates = {
		pending: 0,
		fulfilled: 1,
		rejected: 2
	};
	var mutationObserver = window.MutationObserver || window.WebKitMutationObserver;
	var callbackQueue = [];
	var invoke = function () {
		for (var i = 0; i < callbackQueue.length; i++) {
			var tuple = callbackQueue[i],
				fn = tuple[0],
				arg = tuple[1];

			try {
				fn(arg);
			}
			catch (e) {

			}
		}
		callbackQueue = [];
	};
	//steal form rsvp.js
	var flush = (function () {
		//node env
		if (typeof process !== 'undefined' && toString.call(process) === '[object process]') {
			return function() {
				process.nextTick(invoke);
			};
		//modern browser
		} else if (mutationObserver) {
			//todo
		//old browser
		} else {
			//todo
		}
	})();
	var asycnInvoke = function (fn, arg) {
		callbackQueue.push([fn, arg]);
		flush();
	};

	Spai.promise = function (fn) {
		var promise = {};
		//private properties
		var _state = allStates.pending,
			_onFulfilledQueue = [],
			_onRejectedQueue = [],
			_resolveValue,
			_rejectedReason;
		promise.then = function (onFulfilled, onRejected) {
			var returnValue;
			if (_state === allStates.fulfilled && isFunction(onFulfilled)) {
				asycnInvoke(onFulfilled, _resolveValue);
			}
			else if (_state === allStates.rejected && isFunction(onRejected)) {
				asycnInvoke(onRejected, _rejectedReason);
			}
			else {
				_onFulfilledQueue.push(onFulfilled);
				_onRejectedQueue.push(onRejected);
			}

			//THIS LINE is A BUG!
			return promise;
		};

		var resolve = function (value) {
			if (_state === allStates.pending) {
				_state = allStates.fulfilled;
				_resolveValue = value;
			}
			else {
				return;
			}

			for (var i = 0; i < _onFulfilledQueue.length; i++) {
				asycnInvoke(_onFulfilledQueue[i], _resolveValue);
			}
		};
		var reject = function (reason) {
			if (_state === allStates.pending) {
				_state = allStates.rejected;
				_rejectedReason = reason;
			}
			else {
				return;
			}

			for (var i = 0; i < _onRejectedQueue.length; i++) {
				asycnInvoke(_onRejectedQueue[i], _rejectedReason);
			}
		};

		if (isFunction(fn)) {
			fn.call(this, resolve, reject);
		}
		return promise;
	};

	//meets test suite's need
	Spai.defer = function () {
		var deferred = {};
		deferred.promise = Spai.promise(function (resolve, reject) {
			deferred.resolve = resolve;
			deferred.reject = reject;
		});
		return deferred;
	};

	if (typeof module === "object" && module && typeof module.exports === "object") {
		//node env
		module.exports = Spai;
	}
	else {
		//browser env
		window.Spai = Spai;
	}
})(this);<|endoftext|>


<commit_before>// require esphinx/support/jquery
// require esphinx_ui

"use strict";

var
    jQuery,
    esPhinx;

(function ($module) {

    $module.extend({

        navigators: {

            tabs: {

                new: function (selector, container, options) {
                    var
                        $ = esPhinx,
                        ConstructorReference = $module.navigators.tabs.new,
                        args,
                        navs,
                        containers,

                        Tab = function (handler, container) {
                            this.select = function () {
                                selectNav(handler);
                                showContent(handler, container);
                            };
                        },

                       showContentOnload = function (navs, containers) {
                            var
                                id = navs.parent().findHasNotAttr("a", "href")
                                    .attr("id"),
                                container = containers.parent()
                                    .find(".container#" + id);
                            containers.hide();
                            container.show();
                        },

                        selectNav = function (target, onload) {
                            var
                                navs,
                                selected,
                                selectOnload;
                            navs = $(target).parent("ul").find("li");

                            selected = navs
                                .findHasNotAttr("a.selector", "href");

                            if (selected.length) {
                                selected.attr("href", "#");
                            }

                            selected.removeClass("selected");
                            $(target).addClass("selected");
                            $(target).removeAttr("href");

                            selectOnload = navs.parent("ul.select-onload");
                            if (!onload && selectOnload.length) {
                                location
                                    .queryParam('tab', $(target).attr("id"));
                            }
                        },

                        selectNavOnload = function (selectors) {
                            var
                                tabParam = location.queryParam("tab"),
                                parent = selectors.parent(),
                                href,
                                anchor;

                            if (tabParam) {
                                selectNav(parent.find("a#" + tabParam));
                            } else {
                                href = location.pathname
                                    .match(/[a-z\/\_\-]+[a-z]+/);

                                anchor = parent.findHasNotAttr("a", "href");

                                if (anchor.length) {
                                    selectNav(anchor);
                                } else {
                                    selectNav(selectors.first(), true);
                                }
                            }
                        },

                        resolveNavs = function (navs, options) {
                            var
                                tagName = navs.tagName().toLowerCase(),
                                anchor,
                                selectors;

                            if (tagName !== "li" && tagName !== "a") {
                                navs = navs.find("li");
                            } else if (tagName === "a") {
                                navs = navs.parent();
                            }

                            navs.each(function (nav, i) {
                                nav = $(nav);
                                anchor = nav.find("a");

                                if (!anchor.count()) {
                                    anchor = $("");
                                    anchor.append(nav.text());

                                    nav.text("");
                                    nav.prepend(anchor);
                                }

                                anchor.attr("id", "tab-" + (i + 1));
                                anchor.attr("class", "selector");
                                anchor.attr("href", "#");
                            });

                            selectors = navs.find("a.selector");

                            if (options) {
                                if (options.selectOnload) {
                                    navs.parent("ul").addClass("select-onload");
                                }
                            } else {
                                $(selectors.first()).removeAttr("href");
                            }

                            return selectors;
                        },

                        resolveContainers = function (containers, navs) {
                            var
                                containerTagName = containers.tagName()
                                    .toLowerCase();

                            if (containerTagName !== "li") {
                                containers = containers.find("li");
                            }

                            containers.each(function (container, i) {
                                container.id = "tab-" + (i + 1);
                                container.classList.add("container");
                            });

                            showContentOnload(navs, containers);
                        },

                        init = function (navs, containers, options) {
                            if (containers) {
                                if (options) {
                                    if (options.selectOnload) {
                                        selectNavOnload(navs);
                                    }
                                }
                                resolveContainers(containers, navs);
                            } else {
                                selectNavOnload(navs);
                            }
                        },

                        showContent = function (target, container) {
                            var
                                containers = $(container).parent("ul")
                                    .find(".container");
                            containers.hide();
                            $(container).show();
                        },

                        map = function (navs, containers, options) {
                            var
                                tabs = [];

                            navs = resolveNavs(navs, options);
                            init(navs, containers, options);
                            navs.each(function (a, i) {
                                tabs.push({
                                    // to set event
                                    handler: a,
                                    tab: new Tab(a, containers.parent().first()
                                        .querySelector(".container#" + a.id))
                                });
                            });

                            return tabs;
                        };

                    if (!(this instanceof ConstructorReference)) {
                        return new ConstructorReference(selector, container, options);
                    }

                    navs = selector;
                    containers = container;

                    return map(navs, containers, options);
                }

            }

        }

    });

}(esPhinx.ui));
<commit_msg>improves tabs<commit_after>// require esphinx/support/jquery
// require esphinx_ui

"use strict";

var
    jQuery,
    esPhinx;

(function ($module) {

    $module.extend({

        navigators: {

            tabs: {

                new: function (selector, container, options) {
                    var
                        $ = esPhinx,
                        ConstructorReference = $module.navigators.tabs.new,
                        args,
                        navs,
                        containers,

                        Tab = function (handler, container) {
                            this.select = function () {
                                selectNav(handler);
                                showContent(handler, container);
                            };
                        },

                       showContentOnload = function (navs, containers) {
                            var
                                id = navs.parent().findHasNotAttr("a", "href")
                                    .attr("id"),
                                container = containers.parent()
                                    .find(".container#" + id);
                            containers.hide();
                            container.show();
                        },

                        selectNav = function (target, onload) {
                            var
                                navs,
                                selected,
                                selectOnload;
                            navs = $(target).parent("ul").find("li");

                            selected = navs
                                .findHasNotAttr("a.selector", "href");

                            if (selected.length) {
                                selected.attr("href", "#");
                            }

                            selected.removeClass("selected");
                            $(target).addClass("selected");
                            $(target).removeAttr("href");

                            selectOnload = navs.parent("ul.select-onload");
                            if (!onload && selectOnload.length) {
                                location
                                    .queryParam('tab', $(target).attr("id"));
                            }
                        },

                        selectNavOnload = function (selectors) {
                            var
                                tabParam = location.queryParam("tab"),
                                parent = selectors.parent(),
                                href,
                                anchor;

                            if (tabParam) {
                                selectNav(parent.find("a#" + tabParam));
                            } else {
                                href = location.pathname
                                    .match(/[a-z\/\_\-]+[a-z]+/);

                                anchor = parent.findHasNotAttr("a", "href");

                                if (anchor.length) {
                                    selectNav(anchor);
                                } else {
                                    selectNav(selectors.first(), true);
                                }
                            }
                        },

                        resolveNavs = function (navs, options) {
                            var
                                tagName = navs.tagName().toLowerCase(),
                                anchor,
                                selectors;

                            if (tagName !== "li" && tagName !== "a") {
                                navs = navs.find("li");
                            } else if (tagName === "a") {
                                navs = navs.parent();
                            }

                            navs.each(function (nav, i) {
                                nav = $(nav);
                                anchor = nav.find("a");

                                if (!anchor.count()) {
                                    anchor = $("");
                                    anchor.append(nav.text());

                                    nav.text("");
                                    nav.prepend(anchor);
                                }

                                anchor.attr("id", "tab-" + (i + 1));
                                anchor.attr("class", "selector");
                                anchor.attr("href", "#");
                            });

                            selectors = navs.find("a.selector");

                            if (options) {
                                if (options.selectOnload) {
                                    navs.parent("ul").addClass("select-onload");
                                }
                            } else {
                                $(selectors.first()).removeAttr("href");
                            }

                            return selectors;
                        },

                        resolveContainers = function (containers, navs) {
                            var
                                containerTagName = containers.tagName()
                                    .toLowerCase();

                            if (containerTagName !== "li") {
                                containers = containers.find("li");
                            }

                            containers.each(function (container, i) {
                                container.id = "tab-" + (i + 1);
                                container.classList.add("container");
                            });

                            showContentOnload(navs, containers);
                        },

                        init = function (navs, containers, options) {
                            if (containers) {
                                if (options) {
                                    if (options.selectOnload) {
                                        selectNavOnload(navs);
                                    }
                                }
                                resolveContainers(containers, navs);
                            } else {
                                selectNavOnload(navs);
                            }
                        },

                        showContent = function (target, container) {
                            var
                                containers = $(container).parent("ul")
                                    .find(".container");
                            containers.hide();
                            $(container).show();
                        },

                        map = function (navs, containers, options) {
                            var
                                tabs = [];

                            navs = resolveNavs(navs, options);
                            init(navs, containers, options);
                            navs.each(function (a, i) {
                                tabs.push({
                                    // to set event
                                    handler: a,
                                    tab: new Tab(a, containers.parent()
                                        .find(".container#" + a.id))
                                });
                            });

                            return tabs;
                        };

                    if (!(this instanceof ConstructorReference)) {
                        return new ConstructorReference(selector, container, options);
                    }

                    navs = selector;
                    containers = container;

                    return map(navs, containers, options);
                }

            }

        }

    });

}(esPhinx.ui));
<|endoftext|>