]> git.proxmox.com Git - proxmox-widget-toolkit.git/blobdiff - src/Utils.js
edit: fix comment typos
[proxmox-widget-toolkit.git] / src / Utils.js
index b617c4bb31d4b7e6350ba57210561b3f20facf17..d325644a429b3394ad99738b2977ad41f70aa04e 100644 (file)
@@ -90,7 +90,7 @@ utilities: {
     },
 
     render_language: function(value) {
-       if (!value) {
+       if (!value || value === '__default__') {
            return Proxmox.Utils.defaultText + ' (English)';
        }
        let text = Proxmox.Utils.language_map[value];
@@ -155,7 +155,7 @@ utilities: {
     // somewhat like a human would tell durations, omit zero values and do not
     // give seconds precision if we talk days already
     format_duration_human: function(ut) {
-       let seconds = 0, minutes = 0, hours = 0, days = 0;
+       let seconds = 0, minutes = 0, hours = 0, days = 0, years = 0;
 
        if (ut <= 0.1) {
            return '<0.1s';
@@ -171,7 +171,11 @@ utilities: {
                hours = remaining % 24;
                remaining = Math.trunc(remaining / 24);
                if (remaining > 0) {
-                   days = remaining;
+                   days = remaining % 365;
+                   remaining = Math.trunc(remaining / 365); // yea, just lets ignore leap years...
+                   if (remaining > 0) {
+                       years = remaining;
+                   }
                }
            }
        }
@@ -182,11 +186,14 @@ utilities: {
            return t > 0;
        };
 
+       let addMinutes = !add(years, 'y');
        let addSeconds = !add(days, 'd');
        add(hours, 'h');
-       add(minutes, 'm');
-       if (addSeconds) {
-           add(seconds, 's');
+       if (addMinutes) {
+           add(minutes, 'm');
+           if (addSeconds) {
+               add(seconds, 's');
+           }
        }
        return res.join(' ');
     },
@@ -544,7 +551,7 @@ utilities: {
        });
     },
 
-    updateColumnWidth: function(container) {
+    updateColumnWidth: function(container, thresholdWidth) {
        let mode = Ext.state.Manager.get('summarycolumns') || 'auto';
        let factor;
        if (mode !== 'auto') {
@@ -553,7 +560,8 @@ utilities: {
                factor = 1;
            }
        } else {
-           factor = container.getSize().width < 1600 ? 1 : 2;
+           thresholdWidth = (thresholdWidth || 1400) + 1;
+           factor = Math.ceil(container.getSize().width / thresholdWidth);
        }
 
        if (container.oldFactor === factor) {
@@ -574,6 +582,9 @@ utilities: {
        container.updateLayout();
     },
 
+    // NOTE: depreacated, use updateColumnWidth
+    updateColumns: container => Proxmox.Utils.updateColumnWidth(container),
+
     dialog_title: function(subject, create, isAdd) {
        if (create) {
            if (isAdd) {
@@ -660,6 +671,53 @@ utilities: {
        return `${size.toFixed(commaDigits)} ${unit}B`;
     },
 
+    SizeUnits: {
+       'B': 1,
+
+       'KiB': 1024,
+       'MiB': 1024*1024,
+       'GiB': 1024*1024*1024,
+       'TiB': 1024*1024*1024*1024,
+       'PiB': 1024*1024*1024*1024*1024,
+
+       'KB': 1000,
+       'MB': 1000*1000,
+       'GB': 1000*1000*1000,
+       'TB': 1000*1000*1000*1000,
+       'PB': 1000*1000*1000*1000*1000,
+    },
+
+    parse_size_unit: function(val) {
+       //let m = val.match(/([.\d])+\s?([KMGTP]?)(i?)B?\s*$/i);
+       let m = val.match(/(\d+(?:\.\d+)?)\s?([KMGTP]?)(i?)B?\s*$/i);
+       let size = parseFloat(m[1]);
+       let scale = m[2].toUpperCase();
+       let binary = m[3].toLowerCase();
+
+       let unit = `${scale}${binary}B`;
+       let factor = Proxmox.Utils.SizeUnits[unit];
+
+       return { size, factor, unit, binary }; // for convenience return all we got
+    },
+
+    size_unit_to_bytes: function(val) {
+       let { size, factor } = Proxmox.Utils.parse_size_unit(val);
+       return size * factor;
+    },
+
+    autoscale_size_unit: function(val) {
+       let { size, factor, binary } = Proxmox.Utils.parse_size_unit(val);
+       return Proxmox.Utils.format_size(size * factor, binary !== "i");
+    },
+
+    size_unit_ratios: function(a, b) {
+       a = typeof a !== "undefined" ? a : 0;
+       b = typeof b !== "undefined" ? b : Infinity;
+       let aBytes = typeof a === "number" ? a : Proxmox.Utils.size_unit_to_bytes(a);
+       let bBytes = typeof b === "number" ? b : Proxmox.Utils.size_unit_to_bytes(b);
+       return aBytes / (bBytes || Infinity); // avoid division by zero
+    },
+
     render_upid: function(value, metaData, record) {
        let task = record.data;
        let type = task.type || task.worker_type;
@@ -1111,34 +1169,107 @@ utilities: {
        return acme;
     },
 
-    updateColumns: function(container) {
-       let mode = Ext.state.Manager.get('summarycolumns') || 'auto';
-       let factor;
-       if (mode !== 'auto') {
-           factor = parseInt(mode, 10);
-           if (Number.isNaN(factor)) {
-               factor = 1;
-           }
-       } else {
-           factor = container.getSize().width < 1400 ? 1 : 2;
+    get_health_icon: function(state, circle) {
+       if (circle === undefined) {
+           circle = false;
        }
 
-       if (container.oldFactor === factor) {
-           return;
+       if (state === undefined) {
+           state = 'uknown';
        }
 
-       let items = container.query('>'); // direct childs
-       factor = Math.min(factor, items.length);
-       container.oldFactor = factor;
+       var icon = 'faded fa-question';
+       switch (state) {
+           case 'good':
+               icon = 'good fa-check';
+               break;
+           case 'upgrade':
+               icon = 'warning fa-upload';
+               break;
+           case 'old':
+               icon = 'warning fa-refresh';
+               break;
+           case 'warning':
+               icon = 'warning fa-exclamation';
+               break;
+           case 'critical':
+               icon = 'critical fa-times';
+               break;
+           default: break;
+       }
 
-       items.forEach((item) => {
-           item.columnWidth = 1 / factor;
-       });
+       if (circle) {
+           icon += '-circle';
+       }
 
-       // we have to update the layout twice, since the first layout change
-       // can trigger the scrollbar which reduces the amount of space left
-       container.updateLayout();
-       container.updateLayout();
+       return icon;
+    },
+
+    formatNodeRepoStatus: function(status, product) {
+       let fmt = (txt, cls) => `<i class="fa fa-fw fa-lg fa-${cls}"></i>${txt}`;
+
+       let getUpdates = Ext.String.format(gettext('{0} updates'), product);
+       let noRepo = Ext.String.format(gettext('No {0} repository enabled!'), product);
+
+       if (status === 'ok') {
+           return fmt(getUpdates, 'check-circle good') + ' ' +
+               fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good');
+       } else if (status === 'no-sub') {
+           return fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good') + ' ' +
+                   fmt(gettext('Enterprise repository needs valid subscription'), 'exclamation-circle warning');
+       } else if (status === 'non-production') {
+           return fmt(getUpdates, 'check-circle good') + ' ' +
+                  fmt(gettext('Non production-ready repository enabled!'), 'exclamation-circle warning');
+       } else if (status === 'no-repo') {
+           return fmt(noRepo, 'exclamation-circle critical');
+       }
+
+       return Proxmox.Utils.unknownText;
+    },
+
+    render_u2f_error: function(error) {
+       var ErrorNames = {
+           '1': gettext('Other Error'),
+           '2': gettext('Bad Request'),
+           '3': gettext('Configuration Unsupported'),
+           '4': gettext('Device Ineligible'),
+           '5': gettext('Timeout'),
+       };
+       return "U2F Error: " + ErrorNames[error] || Proxmox.Utils.unknownText;
+    },
+
+    // Convert an ArrayBuffer to a base64url encoded string.
+    // A `null` value will be preserved for convenience.
+    bytes_to_base64url: function(bytes) {
+       if (bytes === null) {
+           return null;
+       }
+
+       return btoa(Array
+           .from(new Uint8Array(bytes))
+           .map(val => String.fromCharCode(val))
+           .join(''),
+       )
+       .replace(/\+/g, '-')
+       .replace(/\//g, '_')
+       .replace(/[=]/g, '');
+    },
+
+    // Convert an a base64url string to an ArrayBuffer.
+    // A `null` value will be preserved for convenience.
+    base64url_to_bytes: function(b64u) {
+       if (b64u === null) {
+           return null;
+       }
+
+       return new Uint8Array(
+           atob(b64u
+               .replace(/-/g, '+')
+               .replace(/_/g, '/'),
+           )
+           .split('')
+           .map(val => val.charCodeAt(0)),
+       );
     },
 },
 
@@ -1181,6 +1312,7 @@ utilities: {
 
        let DnsName_REGEXP = "(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?)\\.)*(?:[A-Za-z0-9](?:[A-Za-z0-9\\-]*[A-Za-z0-9])?))";
        me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
+       me.DnsName_or_Wildcard_match = new RegExp("^(?:\\*\\.)?" + DnsName_REGEXP + "$");
 
        me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$");
        me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$");