aboutsummaryrefslogtreecommitdiff
path: root/js/Utils.js
blob: e031c78a59d7fb8393b93115d11f06af7e2e9fcf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/**
 * Formats a date.
 * @param {date} date - toggle decorations
 * @param {params} params - 
 */
function formatDate( date, params ) {
    var options = {
        weekday: "short",
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
        timeZone: "UTC",
        timeZoneName: "short",
    };

    options = [options, params].reduce(function (r, o) {
        Object.keys(o).forEach(function (k) { r[k] = o[k]; });
        return r;
    }, {});

    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
    return new Date( date ).toLocaleString( 'en-US', options );
}

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function showSeedPage() {
    // Shows `Settings->Seed & keys`. Prompts a password dialog.
    passwordDialog.onAcceptedCallback = function() {
        if(walletPassword === passwordDialog.password){
            if(currentWallet.seedLanguage == "") {
                console.log("No seed language set. Using English as default");
                currentWallet.setSeedLanguage("English");
            }
            // Load keys page
            appWindow.showPageRequest("Keys");
        } else {
            passwordDialog.showError(qsTr("Wrong password"));
        }
    }
    passwordDialog.onRejectedCallback = function() {
        leftPanel.selectItem(middlePanel.state);
    }
    passwordDialog.open();
    updateBalance();
}

function ago(epoch) {
    // Returns '<delta> [seconds|minutes|hours|days] ago' string given an epoch

    var now = new Date().getTime() / 1000;
    var delta = Math.max(now - epoch, 0);

    if(delta < 60)
        return qsTr("%n second(s) ago", "0", Math.floor(delta))
    else if (delta < 3600)
        return qsTr("%n minute(s) ago", "0", Math.floor(delta / 60))
    else if (delta < 86400)
        return qsTr("%n hour(s) ago", "0", Math.floor(delta / 3600))
    else
        return qsTr("%n day(s) ago", "0", Math.floor(delta / 86400))
}

function netTypeToString(){
    // 0: mainnet, 1: testnet, 2: stagenet
    var nettype = appWindow.persistentSettings.nettype;
    return nettype == 1 ? qsTr("Testnet") : nettype == 2 ? qsTr("Stagenet") : qsTr("Mainnet");
}

function epoch(){
    return Math.floor((new Date).getTime()/1000);
}

function roundDownToNearestThousand(_num){
    return Math.floor(_num/1000.0)*1000
}

function qmlEach(item, properties, ignoredObjectNames, arr){
    // Traverse QML object tree and return components that match
    // via property names. Similar to jQuery("myclass").each(...
    // item: root QML object
    // properties: list of strings
    // ignoredObjectNames: list of strings
    if(typeof(arr) == 'undefined') arr = [];
    if(item.hasOwnProperty('data') && item['data'].length > 0){
        for(var i = 0; i < item['data'].length; i += 1){
            arr = qmlEach(item['data'][i], properties, ignoredObjectNames, arr);
        }
    }

    // ignore QML objects on .objectName
    for(var a = 0; a < ignoredObjectNames.length; a += 1){
        if(item.objectName === ignoredObjectNames[a]){
            return arr;
        }
    }

    for(var u = 0; u < properties.length; u += 1){
        if(item.hasOwnProperty(properties[u])) arr.push(item);
        else break;
    }

    return arr;
}

function capitalize(s){
    if (typeof s !== 'string') return ''
    return s.charAt(0).toUpperCase() + s.slice(1)
}

function removeTrailingZeros(value) {
    return (value + '').replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
}

function parseDateStringOrRestoreHeightAsInteger(value) {
    // Parse date string or restore height as integer
    var restoreHeight = 0;
    if (value.indexOf('-') === 4 && value.length === 10) {
        restoreHeight = Wizard.getApproximateBlockchainHeight(value, Utils.netTypeToString());
    } else if (parseInt(value.substring(0, 4)) >= 2014 && parseInt(value.substring(0, 4)) <= 2025 && value.length === 8) {
        // Correct date typed in a wrong format (20201225 instead of 2020-12-25)
        var restoreHeightHyphenated = value.substring(0, 4) + "-" + value.substring(4, 6) + "-" + value.substring(6, 8);
        restoreHeight = Wizard.getApproximateBlockchainHeight(restoreHeightHyphenated, Utils.netTypeToString());
    } else {
        restoreHeight = parseInt(value);
    }
    return restoreHeight;
}

function htmlEscape(s) {
    if (s === null || s === undefined)
        return "";
    return String(s)
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;");
}