]> git.proxmox.com Git - proxmox-widget-toolkit.git/blobdiff - src/api-viewer/APIViewer.js
api-viewer: eslint fixes, code cleanups
[proxmox-widget-toolkit.git] / src / api-viewer / APIViewer.js
index c2864ed1f3d29eaa8f29c27e54e59cf874598357..61a160099c7a546a0e6606902b4cd23e92b0fed4 100644 (file)
@@ -1,45 +1,38 @@
-// avoid errors when running without development tools
-if (!Ext.isDefined(Ext.global.console)) {
-    var console = {
-        dir: function() {},
-        log: function() {}
-    };
-}
+/*global apiSchema*/
 
 Ext.onReady(function() {
-
     Ext.define('pmx-param-schema', {
         extend: 'Ext.data.Model',
-        fields:  [
+        fields: [
            'name', 'type', 'typetext', 'description', 'verbose_description',
            'enum', 'minimum', 'maximum', 'minLength', 'maxLength',
            'pattern', 'title', 'requires', 'format', 'default',
            'disallow', 'extends', 'links',
            {
                name: 'optional',
-               type: 'boolean'
-           }
-       ]
+               type: 'boolean',
+           },
+       ],
     });
 
-    var store = Ext.define('pmx-updated-treestore', {
+    let store = Ext.define('pmx-updated-treestore', {
        extend: 'Ext.data.TreeStore',
        model: Ext.define('pmx-api-doc', {
             extend: 'Ext.data.Model',
-            fields:  [
+            fields: [
                'path', 'info', 'text',
-           ]
+           ],
        }),
-        proxy: {
-            type: 'memory',
-            data: pmxapi
-        },
-        sorters: [{
-            property: 'leaf',
-            direction: 'ASC'
-        }, {
-            property: 'text',
-            direction: 'ASC'
+       proxy: {
+           type: 'memory',
+           data: apiSchema,
+       },
+       sorters: [{
+           property: 'leaf',
+           direction: 'ASC',
+       }, {
+           property: 'text',
+           direction: 'ASC',
        }],
        filterer: 'bottomup',
        doFilter: function(node) {
@@ -47,18 +40,18 @@ Ext.onReady(function() {
        },
 
        filterNodes: function(node, filterFn, parentVisible) {
-           var me = this,
-               bottomUpFiltering = me.filterer === 'bottomup',
-               match = filterFn(node) && parentVisible || (node.isRoot() && !me.getRootVisible()),
-               childNodes = node.childNodes,
-               len = childNodes && childNodes.length, i, matchingChildren;
-
-           if (len) {
-               for (i = 0; i < len; ++i) {
-                   matchingChildren = me.filterNodes(childNodes[i], filterFn, match || bottomUpFiltering) || matchingChildren;
+           let me = this;
+
+           let match = filterFn(node) && (parentVisible || (node.isRoot() && !me.getRootVisible()));
+
+           if (node.childNodes && node.childNodes.length) {
+               let bottomUpFiltering = me.filterer === 'bottomup';
+               let childMatch;
+               for (const child of node.childNodes) {
+                   childMatch = me.filterNodes(child, filterFn, match || bottomUpFiltering) || childMatch;
                }
                if (bottomUpFiltering) {
-                   match = matchingChildren || match;
+                   match = childMatch || match;
                }
            }
 
@@ -68,64 +61,64 @@ Ext.onReady(function() {
 
     }).create();
 
-    var render_description = function(value, metaData, record) {
-       var pdef = record.data;
+    let render_description = function(value, metaData, record) {
+       let pdef = record.data;
 
        value = pdef.verbose_description || value;
 
        // TODO: try to render asciidoc correctly
 
-       metaData.style = 'white-space:pre-wrap;'
+       metaData.style = 'white-space:pre-wrap;';
 
        return Ext.htmlEncode(value);
     };
 
-    var render_type = function(value, metaData, record) {
-       var pdef = record.data;
+    let render_type = function(value, metaData, record) {
+       let pdef = record.data;
 
-       return pdef['enum'] ? 'enum' : (pdef.type || 'string');
+       return pdef.enum ? 'enum' : pdef.type || 'string';
     };
 
     let render_simple_format = function(pdef, type_fallback) {
-       if (pdef.typetext)
+       if (pdef.typetext) {
            return pdef.typetext;
-
-       if (pdef['enum'])
-           return pdef['enum'].join(' | ');
-
-       if (pdef.format)
+       }
+       if (pdef.enum) {
+           return pdef.enum.join(' | ');
+       }
+       if (pdef.format) {
            return pdef.format;
-
-       if (pdef.pattern)
+       }
+       if (pdef.pattern) {
            return pdef.pattern;
-
-       if (pdef.type === 'boolean')
+       }
+       if (pdef.type === 'boolean') {
            return `<true|false>`;
-
-       if (type_fallback && pdef.type)
+       }
+       if (type_fallback && pdef.type) {
            return `<${pdef.type}>`;
-
-       return;
+       }
+       return '';
     };
 
     let render_format = function(value, metaData, record) {
        let pdef = record.data;
 
-       metaData.style = 'white-space:normal;'
+       metaData.style = 'white-space:normal;';
 
        if (pdef.type === 'array' && pdef.items) {
            let format = render_simple_format(pdef.items, true);
            return `[${Ext.htmlEncode(format)}, ...]`;
        }
 
-       return Ext.htmlEncode(render_simple_format(pdef) || '');
+       return Ext.htmlEncode(render_simple_format(pdef));
     };
 
-    var real_path = function(path) {
+    let real_path = function(path) {
        return path.replace(/^.*\/_upgrade_(\/)?/, "/");
     };
 
-    var permission_text = function(permission) {
+    let permission_text = function(permission) {
        let permhtml = "";
 
        if (permission.user) {
@@ -135,89 +128,70 @@ Ext.onReady(function() {
                } else if (permission.user === 'all') {
                    permhtml += "Accessible by all authenticated users.";
                } else {
-                   permhtml += 'Onyl accessible by user "' +
-                       permission.user + '"';
+                   permhtml += `Only accessible by user "${permission.user}"`;
                }
            }
        } else if (permission.check) {
-           permhtml += "<pre>Check: " +
-               Ext.htmlEncode(Ext.JSON.encode(permission.check))  + "</pre>";
+           permhtml += `<pre>Check: ${Ext.htmlEncode(JSON.stringify(permission.check))}</pre>`;
        } else if (permission.userParam) {
            permhtml += `<div>Check if user matches parameter '${permission.userParam}'`;
        } else if (permission.or) {
            permhtml += "<div>Or<div style='padding-left: 10px;'>";
-           Ext.Array.each(permission.or, function(sub_permission) {
-               permhtml += permission_text(sub_permission);
-           })
+           permhtml += permission.or.map(v => permission_text(v)).join('');
            permhtml += "</div></div>";
        } else if (permission.and) {
            permhtml += "<div>And<div style='padding-left: 10px;'>";
-           Ext.Array.each(permission.and, function(sub_permission) {
-               permhtml += permission_text(sub_permission);
-           })
+           permhtml += permission.and.map(v => permission_text(v)).join('');
            permhtml += "</div></div>";
        } else {
-           //console.log(permission);
            permhtml += "Unknown syntax!";
        }
 
        return permhtml;
     };
 
-    var render_docu = function(data) {
-       var md = data.info;
+    let render_docu = function(data) {
+       let md = data.info;
 
-       // console.dir(data);
-
-       var items = [];
-
-       var clicmdhash = {
-           GET: 'get',
-           POST: 'create',
-           PUT: 'set',
-           DELETE: 'delete'
-       };
+       let items = [];
 
        Ext.Array.each(['GET', 'POST', 'PUT', 'DELETE'], function(method) {
-           var info = md[method];
+           let info = md[method];
            if (info) {
+               let endpoint = real_path(data.path);
+               let usage = `<table><tr><td>HTTP:&nbsp;&nbsp;&nbsp;</td><td>`;
+               usage += `${method} /api2/json/${endpoint}</td></tr>`;
 
-               var usage = "";
-
-               usage += "<table><tr><td>HTTP:&nbsp;&nbsp;&nbsp;</td><td>"
-                   + method + " " + real_path("/api2/json" + data.path) + "</td></tr>";
-
-               if (typeof cliusage === 'function') {
-                   usage += cliusage(method, real_path(data.path));
+               if (typeof cliUsageRenderer === 'function') {
+                   usage += cliUsageRenderer(method, endpoint); // eslint-disable-line no-undef
                }
 
-               var sections = [
+               let sections = [
                    {
                        title: 'Description',
                        html: Ext.htmlEncode(info.description),
-                       bodyPadding: 10
+                       bodyPadding: 10,
                    },
                    {
                        title: 'Usage',
                        html: usage,
-                       bodyPadding: 10
-                   }
+                       bodyPadding: 10,
+                   },
                ];
 
                if (info.parameters && info.parameters.properties) {
-
-                   var pstore = Ext.create('Ext.data.Store', {
+                   let pstore = Ext.create('Ext.data.Store', {
                        model: 'pmx-param-schema',
                        proxy: {
-                           type: 'memory'
+                           type: 'memory',
                        },
                        groupField: 'optional',
                        sorters: [
                            {
                                property: 'name',
-                               direction: 'ASC'
-                           }
-                       ]
+                               direction: 'ASC',
+                           },
+                       ],
                    });
 
                    Ext.Object.each(info.parameters.properties, function(name, pdef) {
@@ -227,9 +201,9 @@ Ext.onReady(function() {
 
                    pstore.sort();
 
-                   var groupingFeature = Ext.create('Ext.grid.feature.Grouping',{
+                   let groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
                        enableGroupingMenu: false,
-                       groupHeaderTpl: '<tpl if="groupValue">Optional</tpl><tpl if="!groupValue">Required</tpl>'
+                       groupHeaderTpl: '<tpl if="groupValue">Optional</tpl><tpl if="!groupValue">Required</tpl>',
                    });
 
                    sections.push({
@@ -239,66 +213,62 @@ Ext.onReady(function() {
                        store: pstore,
                        viewConfig: {
                            trackOver: false,
-                           stripeRows: true
+                           stripeRows: true,
                        },
                        columns: [
                            {
                                header: 'Name',
                                dataIndex: 'name',
-                               flex: 1
+                               flex: 1,
                            },
                            {
                                header: 'Type',
                                dataIndex: 'type',
                                renderer: render_type,
-                               flex: 1
+                               flex: 1,
                            },
                            {
                                header: 'Default',
                                dataIndex: 'default',
-                               flex: 1
+                               flex: 1,
                            },
                            {
                                header: 'Format',
                                dataIndex: 'type',
                                renderer: render_format,
-                               flex: 2
+                               flex: 2,
                            },
                            {
                                header: 'Description',
                                dataIndex: 'description',
                                renderer: render_description,
-                               flex: 6
-                           }
-                       ]
+                               flex: 6,
+                           },
+                       ],
                    });
-
                }
 
                if (info.returns) {
+                   let retinf = info.returns;
+                   let rtype = retinf.type;
+                   if (!rtype && retinf.items) {rtype = 'array';}
+                   if (!rtype) {rtype = 'object';}
 
-                   var retinf = info.returns;
-                   var rtype = retinf.type;
-                   if (!rtype && retinf.items)
-                       rtype = 'array';
-                   if (!rtype)
-                       rtype = 'object';
-
-                   var rpstore = Ext.create('Ext.data.Store', {
+                   let rpstore = Ext.create('Ext.data.Store', {
                        model: 'pmx-param-schema',
                        proxy: {
-                           type: 'memory'
+                           type: 'memory',
                        },
                        groupField: 'optional',
                        sorters: [
                            {
                                property: 'name',
-                               direction: 'ASC'
-                          }
-                       ]
+                               direction: 'ASC',
+                          },
+                       ],
                    });
 
-                   var properties;
+                   let properties;
                    if (rtype === 'array' && retinf.items.properties) {
                        properties = retinf.items.properties;
                    }
@@ -314,11 +284,11 @@ Ext.onReady(function() {
 
                    rpstore.sort();
 
-                   var groupingFeature = Ext.create('Ext.grid.feature.Grouping',{
+                   let groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
                        enableGroupingMenu: false,
-                       groupHeaderTpl: '<tpl if="groupValue">Optional</tpl><tpl if="!groupValue">Obligatory</tpl>'
+                       groupHeaderTpl: '<tpl if="groupValue">Optional</tpl><tpl if="!groupValue">Obligatory</tpl>',
                    });
-                   var returnhtml;
+                   let returnhtml;
                    if (retinf.items) {
                        returnhtml = '<pre>items: ' + Ext.htmlEncode(JSON.stringify(retinf.items, null, 4)) + '</pre>';
                    }
@@ -328,10 +298,10 @@ Ext.onReady(function() {
                        returnhtml += '<pre>properties:' + Ext.htmlEncode(JSON.stringify(retinf.properties, null, 4)) + '</pre>';
                    }
 
-                   var rawSection = Ext.create('Ext.panel.Panel', {
+                   let rawSection = Ext.create('Ext.panel.Panel', {
                        bodyPadding: '0px 10px 10px 10px',
                        html: returnhtml,
-                       hidden: true
+                       hidden: true,
                    });
 
                    sections.push({
@@ -341,56 +311,55 @@ Ext.onReady(function() {
                        store: rpstore,
                        viewConfig: {
                            trackOver: false,
-                           stripeRows: true
-                       },
-                   columns: [
-                       {
-                           header: 'Name',
-                           dataIndex: 'name',
-                           flex: 1
-                       },
-                       {
-                           header: 'Type',
-                           dataIndex: 'type',
-                           renderer: render_type,
-                           flex: 1
-                       },
-                       {
-                           header: 'Default',
-                           dataIndex: 'default',
-                           flex: 1
+                           stripeRows: true,
                        },
-                       {
-                           header: 'Format',
-                           dataIndex: 'type',
-                           renderer: render_format,
-                           flex: 2
-                       },
-                       {
-                           header: 'Description',
-                           dataIndex: 'description',
-                           renderer: render_description,
-                           flex: 6
-                       }
-                   ],
-                   bbar: [
-                       {
-                           xtype: 'button',
-                           text: 'Show RAW',
-                           handler: function(btn) {
-                               rawSection.setVisible(!rawSection.isVisible());
-                               btn.setText(rawSection.isVisible() ? 'Hide RAW' : 'Show RAW');
-                           }}
-                   ]
-               });
-
-               sections.push(rawSection);
-
+                       columns: [
+                           {
+                               header: 'Name',
+                               dataIndex: 'name',
+                               flex: 1,
+                           },
+                           {
+                               header: 'Type',
+                               dataIndex: 'type',
+                               renderer: render_type,
+                               flex: 1,
+                           },
+                           {
+                               header: 'Default',
+                               dataIndex: 'default',
+                               flex: 1,
+                           },
+                           {
+                               header: 'Format',
+                               dataIndex: 'type',
+                               renderer: render_format,
+                               flex: 2,
+                           },
+                           {
+                               header: 'Description',
+                               dataIndex: 'description',
+                               renderer: render_description,
+                               flex: 6,
+                           },
+                       ],
+                       bbar: [
+                           {
+                               xtype: 'button',
+                               text: 'Show RAW',
+                               handler: function(btn) {
+                                   rawSection.setVisible(!rawSection.isVisible());
+                                   btn.setText(rawSection.isVisible() ? 'Hide RAW' : 'Show RAW');
+                               },
+                           },
+                       ],
+                   });
 
+                   sections.push(rawSection);
                }
 
                if (!data.path.match(/\/_upgrade_/)) {
-                   var permhtml = '';
+                   let permhtml = '';
 
                    if (!info.permissions) {
                        permhtml = "Root only.";
@@ -403,13 +372,13 @@ Ext.onReady(function() {
                    }
 
                    if (info.allowtoken !== undefined && !info.allowtoken) {
-                       permhtml += "<br />This API endpoint is not available for API tokens."
+                       permhtml += "<br />This API endpoint is not available for API tokens.";
                    }
 
                    sections.push({
                        title: 'Required permissions',
                        bodyPadding: 10,
-                       html: permhtml
+                       html: permhtml,
                    });
                }
 
@@ -417,15 +386,15 @@ Ext.onReady(function() {
                    title: method,
                    autoScroll: true,
                    defaults: {
-                       border: false
+                       border: false,
                    },
-                   items: sections
+                   items: sections,
                });
            }
        });
 
-       var ct = Ext.getCmp('docview');
-       ct.setTitle("Path: " +  real_path(data.path));
+       let ct = Ext.getCmp('docview');
+       ct.setTitle("Path: " + real_path(data.path));
        ct.removeAll(true);
        ct.add(items);
        ct.setActiveTab(0);
@@ -441,41 +410,40 @@ Ext.onReady(function() {
 
        inputType: 'search',
        listeners: {
-           'change': function(){
-
-               var value = this.getValue();
+           'change': function() {
+               let value = this.getValue();
                if (!Ext.isEmpty(value)) {
                    store.filter({
                        property: 'path',
                        value: value,
-                       anyMatch: true
+                       anyMatch: true,
                    });
                } else {
                    store.clearFilter();
                }
-           }
-       }
+           },
+       },
     });
 
-    var tree = Ext.create('Ext.tree.Panel', {
+    let treePanel = Ext.create('Ext.tree.Panel', {
        title: 'Resource Tree',
        tbar: [
            {
                xtype: 'searchfield',
-           }
+           },
        ],
        tools: [
            {
                type: 'expand',
                tooltip: 'Expand all',
                tooltipType: 'title',
-               callback: (tree) => tree.expandAll(),
+               callback: tree => tree.expandAll(),
            },
            {
                type: 'collapse',
                tooltip: 'Collapse all',
                tooltipType: 'title',
-               callback: (tree) => tree.collapseAll(),
+               callback: tree => tree.collapseAll(),
            },
        ],
         store: store,
@@ -486,20 +454,19 @@ Ext.onReady(function() {
         rootVisible: false,
        listeners: {
            selectionchange: function(v, selections) {
-               if (!selections[0])
-                   return;
-               var rec = selections[0];
+               if (!selections[0]) {return;}
+               let rec = selections[0];
                render_docu(rec.data);
                location.hash = '#' + rec.data.path;
-           }
-       }
+           },
+       },
     });
 
     Ext.create('Ext.container.Viewport', {
        layout: 'border',
        renderTo: Ext.getBody(),
        items: [
-           tree,
+           treePanel,
            {
                xtype: 'tabpanel',
                title: 'Documentation',
@@ -507,23 +474,22 @@ Ext.onReady(function() {
                region: 'center',
                margins: '5 5 5 0',
                layout: 'fit',
-               items: []
-           }
-       ]
+               items: [],
+           },
+       ],
     });
 
-    var deepLink = function() {
-       var path = window.location.hash.substring(1).replace(/\/\s*$/, '')
-       var endpoint = store.findNode('path', path);
+    let deepLink = function() {
+       let path = window.location.hash.substring(1).replace(/\/\s*$/, '');
+       let endpoint = store.findNode('path', path);
 
        if (endpoint) {
-           tree.getSelectionModel().select(endpoint);
-           tree.expandPath(endpoint.getPath());
+           treePanel.getSelectionModel().select(endpoint);
+           treePanel.expandPath(endpoint.getPath());
            render_docu(endpoint.data);
        }
-    }
+    };
     window.onhashchange = deepLink;
 
     deepLink();
-
 });