Completed
Push — master ( 651c35...c2f34b )
by greg
03:07
created

?!?.?!?   F

Complexity

Conditions 21
Paths 4096

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
c 2
b 2
f 0
nc 4096
nop 2
dl 0
loc 36
cc 21
rs 2.6757

How to fix   Complexity   

Complexity

Complex classes like ?!?.?!? often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1 View Code Duplication
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
0 ignored issues
show
Comprehensibility introduced by
Usage of the sequence operator is discouraged, since it may lead to obfuscated code.

The sequence or comma operator allows the inclusion of multiple expressions where only is permitted. The result of the sequence is the value of the last expression.

This operator is most often used in for statements.

Used in another places it can make code hard to read, especially when people do not realize it even exists as a seperate operator.

This check looks for usage of the sequence operator in locations where it is not necessary and could be replaced by a series of expressions or statements.

var a,b,c;

a = 1, b = 1,  c= 3;

could just as well be written as:

var a,b,c;

a = 1;
b = 1;
c = 3;

To learn more about the sequence operator, please refer to the MDN.

Loading history...
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2
(function (global){
3
// Best place to find information on XHR features is:
4
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
5
6
var reqfields = [
7
  'responseType', 'withCredentials', 'timeout', 'onprogress'
8
]
9
10
// Simple and small ajax function
11
// Takes a parameters object and a callback function
12
// Parameters:
13
//  - url: string, required
14
//  - headers: object of `{header_name: header_value, ...}`
15
//  - body:
16
//      + string (sets content type to 'application/x-www-form-urlencoded' if not set in headers)
17
//      + FormData (doesn't set content type so that browser will set as appropriate)
18
//  - method: 'GET', 'POST', etc. Defaults to 'GET' or 'POST' based on body
19
//  - cors: If your using cross-origin, you will need this true for IE8-9
20
//
21
// The following parameters are passed onto the xhr object.
22
// IMPORTANT NOTE: The caller is responsible for compatibility checking.
23
//  - responseType: string, various compatability, see xhr docs for enum options
24
//  - withCredentials: boolean, IE10+, CORS only
25
//  - timeout: long, ms timeout, IE8+
26
//  - onprogress: callback, IE10+
27
//
28
// Callback function prototype:
29
//  - statusCode from request
30
//  - response
31
//    + if responseType set and supported by browser, this is an object of some type (see docs)
32
//    + otherwise if request completed, this is the string text of the response
33
//    + if request is aborted, this is "Abort"
34
//    + if request times out, this is "Timeout"
35
//    + if request errors before completing (probably a CORS issue), this is "Error"
36
//  - request object
37
//
38
// Returns the request object. So you can call .abort() or other methods
39
//
40
// DEPRECATIONS:
41
//  - Passing a string instead of the params object has been removed!
42
//
43
exports.ajax = function (params, callback) {
44
  // Any variable used more than once is var'd here because
45
  // minification will munge the variables whereas it can't munge
46
  // the object access.
47
  var headers = params.headers || {}
48
    , body = params.body
49
    , method = params.method || (body ? 'POST' : 'GET')
50
    , called = false
51
52
  var req = getRequest(params.cors)
53
54
  function cb(statusCode, responseText) {
55
    return function () {
56
      if (!called) {
57
        callback(req.status === undefined ? statusCode : req.status,
58
                 req.status === 0 ? "Error" : (req.response || req.responseText || responseText),
59
                 req)
60
        called = true
61
      }
62
    }
63
  }
64
65
  req.open(method, params.url, true)
66
67
  var success = req.onload = cb(200)
68
  req.onreadystatechange = function () {
69
    if (req.readyState === 4) success()
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
70
  }
71
  req.onerror = cb(null, 'Error')
72
  req.ontimeout = cb(null, 'Timeout')
73
  req.onabort = cb(null, 'Abort')
74
75
  if (body) {
76
    setDefault(headers, 'X-Requested-With', 'XMLHttpRequest')
77
78
    if (!global.FormData || !(body instanceof global.FormData)) {
79
      setDefault(headers, 'Content-Type', 'application/x-www-form-urlencoded')
80
    }
81
  }
82
83
  for (var i = 0, len = reqfields.length, field; i < len; i++) {
84
    field = reqfields[i]
85
    if (params[field] !== undefined)
86
      req[field] = params[field]
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
87
  }
88
89
  for (var field in headers)
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
Comprehensibility Naming Best Practice introduced by
The variable field already seems to be declared on line 83. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
90
    req.setRequestHeader(field, headers[field])
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
91
92
  req.send(body)
93
94
  return req
95
}
96
97
function getRequest(cors) {
98
  // XDomainRequest is only way to do CORS in IE 8 and 9
99
  // But XDomainRequest isn't standards-compatible
100
  // Notably, it doesn't allow cookies to be sent or set by servers
101
  // IE 10+ is standards-compatible in its XMLHttpRequest
102
  // but IE 10 can still have an XDomainRequest object, so we don't want to use it
103
  if (cors && global.XDomainRequest && !/MSIE 1/.test(navigator.userAgent))
0 ignored issues
show
Bug introduced by
The variable navigator seems to be never declared. If this is a global, consider adding a /** global: navigator */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
104
    return new XDomainRequest
0 ignored issues
show
Bug introduced by
The variable XDomainRequest seems to be never declared. If this is a global, consider adding a /** global: XDomainRequest */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
105
  if (global.XMLHttpRequest)
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if global.XMLHttpRequest is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
106
    return new XMLHttpRequest
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
107
}
108
109
function setDefault(obj, key, value) {
110
  obj[key] = obj[key] || value
111
}
112
113
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
0 ignored issues
show
Bug introduced by
The variable self seems to be never declared. If this is a global, consider adding a /** global: self */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
114
},{}],2:[function(require,module,exports){
115
'use strict';
116
117
var replace = String.prototype.replace;
118
var percentTwenties = /%20/g;
119
120
module.exports = {
121
    'default': 'RFC3986',
122
    formatters: {
123
        RFC1738: function (value) {
124
            return replace.call(value, percentTwenties, '+');
125
        },
126
        RFC3986: function (value) {
127
            return value;
128
        }
129
    },
130
    RFC1738: 'RFC1738',
131
    RFC3986: 'RFC3986'
132
};
133
134
},{}],3:[function(require,module,exports){
135
'use strict';
136
137
var stringify = require('./stringify');
138
var parse = require('./parse');
139
var formats = require('./formats');
140
141
module.exports = {
142
    formats: formats,
143
    parse: parse,
144
    stringify: stringify
145
};
146
147
},{"./formats":2,"./parse":4,"./stringify":5}],4:[function(require,module,exports){
148
'use strict';
149
150
var utils = require('./utils');
151
152
var has = Object.prototype.hasOwnProperty;
153
154
var defaults = {
155
    allowDots: false,
156
    allowPrototypes: false,
157
    arrayLimit: 20,
158
    decoder: utils.decode,
159
    delimiter: '&',
160
    depth: 5,
161
    parameterLimit: 1000,
162
    plainObjects: false,
163
    strictNullHandling: false
164
};
165
166
var parseValues = function parseValues(str, options) {
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable parseValues already seems to be declared on line 166. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
167
    var obj = {};
168
    var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
169
170
    for (var i = 0; i < parts.length; ++i) {
171
        var part = parts[i];
172
        var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
173
174
        var key, val;
175
        if (pos === -1) {
176
            key = options.decoder(part);
177
            val = options.strictNullHandling ? null : '';
178
        } else {
179
            key = options.decoder(part.slice(0, pos));
180
            val = options.decoder(part.slice(pos + 1));
181
        }
182
        if (has.call(obj, key)) {
183
            obj[key] = [].concat(obj[key]).concat(val);
184
        } else {
185
            obj[key] = val;
186
        }
187
    }
188
189
    return obj;
190
};
191
192
var parseObject = function parseObject(chain, val, options) {
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable parseObject already seems to be declared on line 192. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
193
    if (!chain.length) {
194
        return val;
195
    }
196
197
    var root = chain.shift();
198
199
    var obj;
200
    if (root === '[]') {
201
        obj = [];
202
        obj = obj.concat(parseObject(chain, val, options));
203
    } else {
204
        obj = options.plainObjects ? Object.create(null) : {};
205
        var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root;
206
        var index = parseInt(cleanRoot, 10);
207
        if (
208
            !isNaN(index) &&
209
            root !== cleanRoot &&
210
            String(index) === cleanRoot &&
211
            index >= 0 &&
212
            (options.parseArrays && index <= options.arrayLimit)
213
        ) {
214
            obj = [];
215
            obj[index] = parseObject(chain, val, options);
216
        } else {
217
            obj[cleanRoot] = parseObject(chain, val, options);
218
        }
219
    }
220
221
    return obj;
222
};
223
224
var parseKeys = function parseKeys(givenKey, val, options) {
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable parseKeys already seems to be declared on line 224. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
225
    if (!givenKey) {
226
        return;
227
    }
228
229
    // Transform dot notation to bracket notation
230
    var key = options.allowDots ? givenKey.replace(/\.([^\.\[]+)/g, '[$1]') : givenKey;
231
232
    // The regex chunks
233
234
    var parent = /^([^\[\]]*)/;
235
    var child = /(\[[^\[\]]*\])/g;
236
237
    // Get the parent
238
239
    var segment = parent.exec(key);
240
241
    // Stash the parent if it exists
242
243
    var keys = [];
244
    if (segment[1]) {
245
        // If we aren't using plain objects, optionally prefix keys
246
        // that would overwrite object prototype properties
247
        if (!options.plainObjects && has.call(Object.prototype, segment[1])) {
248
            if (!options.allowPrototypes) {
249
                return;
250
            }
251
        }
252
253
        keys.push(segment[1]);
254
    }
255
256
    // Loop through children appending to the array until we hit depth
257
258
    var i = 0;
259
    while ((segment = child.exec(key)) !== null && i < options.depth) {
260
        i += 1;
261
        if (!options.plainObjects && has.call(Object.prototype, segment[1].replace(/\[|\]/g, ''))) {
262
            if (!options.allowPrototypes) {
263
                continue;
264
            }
265
        }
266
        keys.push(segment[1]);
267
    }
268
269
    // If there's a remainder, just add whatever is left
270
271
    if (segment) {
272
        keys.push('[' + key.slice(segment.index) + ']');
273
    }
274
275
    return parseObject(keys, val, options);
276
};
277
278
module.exports = function (str, opts) {
279
    var options = opts || {};
280
281
    if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
282
        throw new TypeError('Decoder has to be a function.');
283
    }
284
285
    options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
286
    options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
287
    options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
288
    options.parseArrays = options.parseArrays !== false;
289
    options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
290
    options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
291
    options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
292
    options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
293
    options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
294
    options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
295
296
    if (str === '' || str === null || typeof str === 'undefined') {
297
        return options.plainObjects ? Object.create(null) : {};
298
    }
299
300
    var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
301
    var obj = options.plainObjects ? Object.create(null) : {};
302
303
    // Iterate over the keys and setup the new object
304
305
    var keys = Object.keys(tempObj);
306
    for (var i = 0; i < keys.length; ++i) {
307
        var key = keys[i];
308
        var newObj = parseKeys(key, tempObj[key], options);
309
        obj = utils.merge(obj, newObj, options);
310
    }
311
312
    return utils.compact(obj);
313
};
314
315 View Code Duplication
},{"./utils":6}],5:[function(require,module,exports){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
316
'use strict';
317
318
var utils = require('./utils');
319
var formats = require('./formats');
320
321
var arrayPrefixGenerators = {
322
    brackets: function brackets(prefix) {
323
        return prefix + '[]';
324
    },
325
    indices: function indices(prefix, key) {
326
        return prefix + '[' + key + ']';
327
    },
328
    repeat: function repeat(prefix) {
329
        return prefix;
330
    }
331
};
332
333
var toISO = Date.prototype.toISOString;
334
335
var defaults = {
336
    delimiter: '&',
337
    encode: true,
338
    encoder: utils.encode,
339
    serializeDate: function serializeDate(date) {
340
        return toISO.call(date);
341
    },
342
    skipNulls: false,
343
    strictNullHandling: false
344
};
345
346
var stringify = function stringify(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter) {
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable stringify already seems to be declared on line 346. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
347
    var obj = object;
348
    if (typeof filter === 'function') {
349
        obj = filter(prefix, obj);
350
    } else if (obj instanceof Date) {
351
        obj = serializeDate(obj);
352
    } else if (obj === null) {
353
        if (strictNullHandling) {
354
            return encoder ? encoder(prefix) : prefix;
355
        }
356
357
        obj = '';
358
    }
359
360
    if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
361
        if (encoder) {
362
            return [formatter(encoder(prefix)) + '=' + formatter(encoder(obj))];
363
        }
364
        return [formatter(prefix) + '=' + formatter(String(obj))];
365
    }
366
367
    var values = [];
368
369
    if (typeof obj === 'undefined') {
370
        return values;
371
    }
372
373
    var objKeys;
374
    if (Array.isArray(filter)) {
375
        objKeys = filter;
376
    } else {
377
        var keys = Object.keys(obj);
378
        objKeys = sort ? keys.sort(sort) : keys;
379
    }
380
381
    for (var i = 0; i < objKeys.length; ++i) {
382
        var key = objKeys[i];
383
384
        if (skipNulls && obj[key] === null) {
385
            continue;
386
        }
387
388
        if (Array.isArray(obj)) {
389
            values = values.concat(stringify(
390
                obj[key],
391
                generateArrayPrefix(prefix, key),
392
                generateArrayPrefix,
393
                strictNullHandling,
394
                skipNulls,
395
                encoder,
396
                filter,
397
                sort,
398
                allowDots,
399
                serializeDate,
400
                formatter
401
            ));
402
        } else {
403
            values = values.concat(stringify(
404
                obj[key],
405
                prefix + (allowDots ? '.' + key : '[' + key + ']'),
406
                generateArrayPrefix,
407
                strictNullHandling,
408
                skipNulls,
409
                encoder,
410
                filter,
411
                sort,
412
                allowDots,
413
                serializeDate,
414
                formatter
415
            ));
416
        }
417
    }
418
419
    return values;
420
};
421
422
module.exports = function (object, opts) {
423
    var obj = object;
424
    var options = opts || {};
425
    var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
426
    var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
427
    var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
428
    var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
429
    var encoder = encode ? (typeof options.encoder === 'function' ? options.encoder : defaults.encoder) : null;
430
    var sort = typeof options.sort === 'function' ? options.sort : null;
431
    var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
432
    var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
433
    if (typeof options.format === 'undefined') {
434
        options.format = formats.default;
435
    } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
436
        throw new TypeError('Unknown format option provided.');
437
    }
438
    var formatter = formats.formatters[options.format];
439
    var objKeys;
440
    var filter;
441
442
    if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
443
        throw new TypeError('Encoder has to be a function.');
444
    }
445
446
    if (typeof options.filter === 'function') {
447
        filter = options.filter;
448
        obj = filter('', obj);
449
    } else if (Array.isArray(options.filter)) {
450
        filter = options.filter;
451
        objKeys = filter;
452
    }
453
454
    var keys = [];
455
456
    if (typeof obj !== 'object' || obj === null) {
457
        return '';
458
    }
459
460
    var arrayFormat;
461
    if (options.arrayFormat in arrayPrefixGenerators) {
462
        arrayFormat = options.arrayFormat;
463
    } else if ('indices' in options) {
464
        arrayFormat = options.indices ? 'indices' : 'repeat';
465
    } else {
466
        arrayFormat = 'indices';
467
    }
468
469
    var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
470
471
    if (!objKeys) {
472
        objKeys = Object.keys(obj);
473
    }
474
475
    if (sort) {
476
        objKeys.sort(sort);
477
    }
478
479
    for (var i = 0; i < objKeys.length; ++i) {
480
        var key = objKeys[i];
481
482
        if (skipNulls && obj[key] === null) {
483
            continue;
484
        }
485
486
        keys = keys.concat(stringify(
487
            obj[key],
488
            key,
489
            generateArrayPrefix,
490
            strictNullHandling,
491
            skipNulls,
492
            encoder,
493
            filter,
0 ignored issues
show
Bug introduced by
The variable filter does not seem to be initialized in case Array.isArray(options.filter) on line 449 is false. Are you sure the function stringify handles undefined variables?
Loading history...
494
            sort,
495
            allowDots,
496
            serializeDate,
497
            formatter
498
        ));
499
    }
500
501
    return keys.join(delimiter);
502
};
503
504
},{"./formats":2,"./utils":6}],6:[function(require,module,exports){
505
'use strict';
506
507
var has = Object.prototype.hasOwnProperty;
508
509
var hexTable = (function () {
510
    var array = [];
511
    for (var i = 0; i < 256; ++i) {
512
        array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
513
    }
514
515
    return array;
516
}());
517
518
exports.arrayToObject = function (source, options) {
519
    var obj = options && options.plainObjects ? Object.create(null) : {};
520
    for (var i = 0; i < source.length; ++i) {
521
        if (typeof source[i] !== 'undefined') {
522
            obj[i] = source[i];
523
        }
524
    }
525
526
    return obj;
527
};
528
529
exports.merge = function (target, source, options) {
530
    if (!source) {
531
        return target;
532
    }
533
534
    if (typeof source !== 'object') {
535
        if (Array.isArray(target)) {
536
            target.push(source);
537
        } else if (typeof target === 'object') {
538
            target[source] = true;
539
        } else {
540
            return [target, source];
541
        }
542
543
        return target;
544
    }
545
546
    if (typeof target !== 'object') {
547
        return [target].concat(source);
548
    }
549
550
    var mergeTarget = target;
551
    if (Array.isArray(target) && !Array.isArray(source)) {
552
        mergeTarget = exports.arrayToObject(target, options);
553
    }
554
555
    if (Array.isArray(target) && Array.isArray(source)) {
556
        source.forEach(function (item, i) {
557
            if (has.call(target, i)) {
558
                if (target[i] && typeof target[i] === 'object') {
559
                    target[i] = exports.merge(target[i], item, options);
560
                } else {
561
                    target.push(item);
562
                }
563
            } else {
564
                target[i] = item;
565
            }
566
        });
567
        return target;
568
    }
569
570
    return Object.keys(source).reduce(function (acc, key) {
571
        var value = source[key];
572
573
        if (Object.prototype.hasOwnProperty.call(acc, key)) {
574
            acc[key] = exports.merge(acc[key], value, options);
575
        } else {
576
            acc[key] = value;
577
        }
578
        return acc;
579
    }, mergeTarget);
580
};
581
582
exports.decode = function (str) {
583
    try {
584
        return decodeURIComponent(str.replace(/\+/g, ' '));
585
    } catch (e) {
586
        return str;
587
    }
588
};
589
590
exports.encode = function (str) {
591
    // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
592
    // It has been adapted here for stricter adherence to RFC 3986
593
    if (str.length === 0) {
594
        return str;
595
    }
596
597
    var string = typeof str === 'string' ? str : String(str);
598
599
    var out = '';
600
    for (var i = 0; i < string.length; ++i) {
601
        var c = string.charCodeAt(i);
602
603
        if (
604
            c === 0x2D || // -
605
            c === 0x2E || // .
606
            c === 0x5F || // _
607
            c === 0x7E || // ~
608
            (c >= 0x30 && c <= 0x39) || // 0-9
609
            (c >= 0x41 && c <= 0x5A) || // a-z
610
            (c >= 0x61 && c <= 0x7A) // A-Z
611
        ) {
612
            out += string.charAt(i);
613
            continue;
614
        }
615
616
        if (c < 0x80) {
617
            out = out + hexTable[c];
618
            continue;
619
        }
620
621
        if (c < 0x800) {
622
            out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
623
            continue;
624
        }
625
626
        if (c < 0xD800 || c >= 0xE000) {
627
            out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
628
            continue;
629
        }
630
631
        i += 1;
632
        c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
633
        out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)];
634
    }
635
636
    return out;
637
};
638
639
exports.compact = function (obj, references) {
640
    if (typeof obj !== 'object' || obj === null) {
641
        return obj;
642
    }
643
644
    var refs = references || [];
645
    var lookup = refs.indexOf(obj);
646
    if (lookup !== -1) {
647
        return refs[lookup];
648
    }
649
650
    refs.push(obj);
651
652
    if (Array.isArray(obj)) {
653
        var compacted = [];
654
655
        for (var i = 0; i < obj.length; ++i) {
656
            if (obj[i] && typeof obj[i] === 'object') {
657
                compacted.push(exports.compact(obj[i], refs));
658
            } else if (typeof obj[i] !== 'undefined') {
659
                compacted.push(obj[i]);
660
            }
661
        }
662
663
        return compacted;
664
    }
665
666
    var keys = Object.keys(obj);
667
    keys.forEach(function (key) {
668
        obj[key] = exports.compact(obj[key], refs);
669
    });
670
671
    return obj;
672
};
673
674
exports.isRegExp = function (obj) {
675
    return Object.prototype.toString.call(obj) === '[object RegExp]';
676
};
677
678
exports.isBuffer = function (obj) {
679
    if (obj === null || typeof obj === 'undefined') {
680
        return false;
681
    }
682
683
    return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
684
};
685
686
},{}],7:[function(require,module,exports){
687
'use strict';
688
689
Object.defineProperty(exports, "__esModule", {
690
  value: true
691
});
692
693
var _nanoajax = require('nanoajax');
694
695
var _nanoajax2 = _interopRequireDefault(_nanoajax);
696
697
var _qs = require('qs');
698
699
var _qs2 = _interopRequireDefault(_qs);
700
701
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
702
703
/*global document, confirm, $ */
704
705
var usersList = {
706
  init: function init() {
707
    var scope = document.querySelector('.user-list');
708
    if (scope != null) {
709
      this._ajax = _nanoajax2.default.ajax;
710
711
      this._scope = scope;
712
      this._table = this._scope.querySelector('#filtered-list tbody');
713
      this._alert = document.querySelector('.alert');
714
      this._handleActivate = this._activate.bind(this);
715
      this._handleDeactivate = this._deactivate.bind(this);
716
      this._handleRemove = this._remove.bind(this);
717
      this._handleEdit = this._edit.bind(this);
718
      this._handleUpdate = this._update.bind(this);
719
      this._handleCloseUpdate = this._closeUpdate.bind(this);
720
      this._handleAdd = this._add.bind(this);
721
722
      this._bindEvents();
723
    }
724
725
    if (document.querySelectorAll('#filtered-list').length > 0) {
726
      var orderables = document.querySelectorAll('#filtered-list thead th');
727
      var columns = [];
728
      Array.prototype.forEach.call(orderables, function (orderable) {
729
        var order = orderable.getAttribute('data-orderable');
730
        if (order != null) {
731
          columns.push({ 'orderable': order == 'true' ? true : false });
732
        } else {
733
          columns.push(null);
734
        }
735
      });
736
      this.table = $('#filtered-list').DataTable({
737
        paging: false,
738
        'info': false,
739
        'columns': columns
740
      });
741
    }
742
743
    if (document.querySelectorAll('#filtered-list-url').length > 0) {
744
      this._handleFormUserRoleSubmit = this._formUserRoleSubmit.bind(this);
745
746
      this._formUserRole = document.querySelector('[data-user-role]');
747
      this._formUserRoleSave = document.querySelector('[data-save-user-role]');
748
749
      if (typeof this._formUserRole !== 'undefined' && this._formUserRole !== null) {
750
        this._formUserRole.addEventListener('submit', this._handleFormUserRoleSubmit);
751
      }
752
    }
753
  },
754
  _bindEvents: function _bindEvents() {
755
    var _this = this;
756
757
    this._activateBtn = this._scope.querySelectorAll('[data-activate]');
758
    this._deactivateBtn = this._scope.querySelectorAll('[data-deactivate]');
759
    this._removeBtn = this._scope.querySelectorAll('[data-remove]');
760
    this._editBtn = this._scope.querySelectorAll('[data-edit]');
761
    this._updateBtn = this._scope.querySelectorAll('[data-update]');
762
    this._addBtn = this._scope.querySelector('[data-add-user]');
763
764
    Array.prototype.forEach.call(this._activateBtn, function (btn) {
765
      btn.removeEventListener('click', _this._handleActivate);
766
      btn.addEventListener('click', _this._handleActivate);
767
    });
768
769
    Array.prototype.forEach.call(this._deactivateBtn, function (btn) {
770
      btn.removeEventListener('click', _this._handleDeactivate);
771
      btn.addEventListener('click', _this._handleDeactivate);
772
    });
773
774
    Array.prototype.forEach.call(this._removeBtn, function (btn) {
775
      btn.removeEventListener('click', _this._handleRemove);
776
      btn.addEventListener('click', _this._handleRemove);
777
    });
778
779
    Array.prototype.forEach.call(this._editBtn, function (btn) {
780
      btn.removeEventListener('click', _this._handleEdit, true);
781
      btn.addEventListener('click', _this._handleEdit, true);
782
    });
783
784
    Array.prototype.forEach.call(this._updateBtn, function (btn) {
785
      btn.removeEventListener('click', _this._handleUpdate, true);
786
      btn.addEventListener('click', _this._handleUpdate, true);
787
    });
788
789
    if (typeof this._addBtn !== 'undefined' && this._addBtn !== null) {
790
      this._addBtn.addEventListener('click', this._handleAdd);
791
    }
792
  },
793
  _formUserRoleSubmit: function _formUserRoleSubmit(e) {
794
    e.preventDefault();
795
796
    var inputs = this._formUserRole.querySelectorAll('input[type=checkbox]');
797
    var data = {};
798
    Array.prototype.forEach.call(inputs, function (input) {
799
      if (!input.disabled) {
800
        var name = input.getAttribute('name');
801
        if (data[name] == null) {
802
          data[name] = [];
803
        }
804
        if (input.checked) {
805
          data[name].push(input.getAttribute('value'));
806
        }
807
      }
808
    });
809
810
    var toSave = _qs2.default.stringify(data);
811
812
    this._ajax({
813
      url: '/abe/list-url/save',
814
      body: toSave,
815
      method: 'post'
816
    }, function () {});
817
  },
818
  _activate: function _activate(e) {
819
    var _this2 = this;
820
821
    var target = e.currentTarget;
822
    var id = target.getAttribute('data-user-id');
823
824
    var toSave = _qs2.default.stringify({
825
      id: id
826
    });
827
828
    this._ajax({
829
      url: '/abe/users/activate',
830
      body: toSave,
831
      method: 'post'
832
    }, function () {
833
      var childGlyph = target.querySelector('.glyphicon');
834
      childGlyph.classList.remove('glyphicon-eye-open', 'text-info');
835
      childGlyph.classList.add('glyphicon-eye-close', 'text-danger');
836
      target.classList.remove('glyphicon-eye-close', 'text-danger');
837
      target.classList.add('glyphicon-eye-open', 'text-info');
838
      target.removeEventListener('click', _this2._handleActivate);
839
      target.addEventListener('click', _this2._handleDeactivate);
840
    });
841
  },
842
  _deactivate: function _deactivate(e) {
843
    var _this3 = this;
844
845
    var target = e.currentTarget;
846
    var id = target.getAttribute('data-user-id');
847
848
    var toSave = _qs2.default.stringify({
849
      id: id
850
    });
851
852
    this._ajax({
853
      url: '/abe/users/deactivate',
854
      body: toSave,
855
      method: 'post'
856
    }, function () {
857
      var childGlyph = target.querySelector('.glyphicon');
858
      childGlyph.classList.remove('glyphicon-eye-close', 'text-danger');
859
      childGlyph.classList.add('glyphicon-eye-open', 'text-info');
860
      target.classList.remove('glyphicon-eye-open', 'text-info');
861
      target.classList.add('glyphicon-eye-close', 'text-danger');
862
      target.removeEventListener('click', _this3._handleDeactivate);
863
      target.addEventListener('click', _this3._handleActivate);
864
    });
865
  },
866
  _edit: function _edit(e) {
867
    var parent = e.currentTarget.parentNode.parentNode;
868
    e.currentTarget.removeEventListener('click', this._handleEdit, true);
869
870
    parent.classList.add('editing');
871
    var closeUpdateBtn = parent.querySelector('[data-close-update]');
872
    closeUpdateBtn.removeEventListener('click', this._handleCloseUpdate);
873
    closeUpdateBtn.addEventListener('click', this._handleCloseUpdate);
874
  },
875
  _closeFormUpdate: function _closeFormUpdate(target) {
876
    var parent = target.parentNode.parentNode.parentNode;
877
    var edit = parent.querySelector('[data-edit]');
878
    parent.classList.remove('editing');
879
    edit.addEventListener('click', this._handleEdit, true);
880
    target.removeEventListener('click', this._handleCloseUpdate);
881
  },
882
883
  _closeUpdate: function _closeUpdate(e) {
884
    this._closeFormUpdate(e.currentTarget);
885
  },
886
  _update: function _update(e) {
887
    var _this4 = this;
888
889
    var parent = e.currentTarget.parentNode.parentNode.parentNode;
890
    var target = e.currentTarget;
891
    var data = {
892
      id: target.getAttribute('data-user-id')
893
    };
894
895
    var inputs = parent.querySelectorAll('.form-control');
896
    var msg = '';
897
    var hasError = false;
898
    Array.prototype.forEach.call(inputs, function (input) {
899
      data[input.name] = input.value;
900
901
      if (input.name === 'email' && !this._validateEmail(input.value)) {
902
        hasError = true;
903
        input.parentNode.classList.add('has-error');
904
        this._alert.classList.remove('hidden');
905
        msg += 'email is invalid<br />';
906
        return;
0 ignored issues
show
Unused Code introduced by
This return has no effect and can be removed.
Loading history...
907
      } else if (input.value.trim() === '') {
908
        hasError = true;
909
        input.parentNode.classList.add('has-error');
910
        this._alert.classList.remove('hidden');
911
        msg += input.name + ' is invalid<br />';
912
        return;
0 ignored issues
show
Unused Code introduced by
This return has no effect and can be removed.
Loading history...
913
      } else {
914
        input.parentNode.classList.remove('has-error');
915
      }
916
    }.bind(this));
917
918
    if (hasError) {
919
      this._alert.innerHTML = msg;
920
      return;
921
    } else {
922
      this._alert.classList.add('hidden');
923
      this._alert.innerHTML = '';
924
    }
925
    var toSave = _qs2.default.stringify(data);
926
927
    this._ajax({
928
      url: '/abe/users/update',
929
      body: toSave,
930
      method: 'post'
931
    }, function (code, responseText) {
932
      var response = JSON.parse(responseText);
933
      if (response.success === 1) {
934
        Array.prototype.forEach.call(inputs, function (input) {
935
          input.parentNode.parentNode.querySelector('.value').innerHTML = input.value;
936
        });
937
        _this4._closeFormUpdate(target);
938
      } else {
939
        _this4._alert.classList.remove('hidden');
940
        _this4._alert.innerHTML = response.message;
941
      }
942
    });
943
  },
944
  _remove: function _remove(e) {
945
    var confirmDelete = confirm(e.currentTarget.getAttribute('data-text'));
946
    if (!confirmDelete) return;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
947
948
    var target = e.currentTarget;
949
    var id = target.getAttribute('data-user-id');
950
    var toSave = _qs2.default.stringify({
951
      id: id
952
    });
953
954
    this._ajax({
955
      url: '/abe/users/remove',
956
      body: toSave,
957
      method: 'post'
958
    }, function () {
959
      target.parentNode.parentNode.remove();
960
    });
961
  },
962
  _validateEmail: function _validateEmail(email) {
963
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
964
    return re.test(email);
965
  },
966
  _add: function _add() {
967
    var _this5 = this;
968
969
    this._alert.classList.add('hidden');
970
    var username = document.querySelector('[data-add-user-username]');
971
    if (typeof username.value === 'undefined' || username.value === null || username.value === '') {
972
      username.parentNode.classList.add('has-error');
973
      return;
974
    }
975
    username.parentNode.classList.remove('has-error');
976
977
    var name = document.querySelector('[data-add-user-name]');
978
    if (typeof name.value === 'undefined' || name.value === null || name.value === '') {
979
      name.parentNode.classList.add('has-error');
980
      return;
981
    }
982
    name.parentNode.classList.remove('has-error');
983
984
    var email = document.querySelector('[data-add-user-email]');
985
    if (typeof email.value === 'undefined' || email.value === null || email.value === '') {
986
      email.parentNode.classList.add('has-error');
987
      return;
988
    }
989
    if (!this._validateEmail(email.value)) {
990
      email.parentNode.classList.add('has-error');
991
      this._alert.classList.remove('hidden');
992
      this._alert.innerHTML = 'email is invalid';
993
      return;
994
    }
995
    email.parentNode.classList.remove('has-error');
996
997
    var password = document.querySelector('[data-add-user-password]');
998
    if (typeof password.value === 'undefined' || password.value === null || password.value === '') {
999
      password.parentNode.classList.add('has-error');
1000
      return;
1001
    }
1002
1003
    password.parentNode.classList.remove('has-error');
1004
1005
    var role = document.querySelector('[data-add-user-role]');
1006
    var toSave = _qs2.default.stringify({
1007
      username: username.value,
1008
      name: name.value,
1009
      email: email.value,
1010
      password: password.value,
1011
      role: role.value
1012
    });
1013
1014
    this._ajax({
1015
      url: '/abe/users/add',
1016
      body: toSave,
1017
      method: 'post'
1018
    }, function (code, responseText) {
1019
      var data = JSON.parse(responseText);
1020
      if (data.success === 1) {
1021
        var tr = document.createElement('tr');
1022
        var oldTr = document.querySelector('[data-user-base]');
1023
        if (typeof oldTr !== 'undefined' && oldTr !== null) {
1024
          tr.innerHTML = oldTr.innerHTML;
1025
1026
          var tdUsername = tr.querySelector('.td-username');
1027
          tdUsername.querySelector('.value').innerHTML = data.user.username;
1028
          tdUsername.querySelector('input').value = data.user.username;
1029
1030
          var tdName = tr.querySelector('.td-name');
1031
          tdName.querySelector('.value').innerHTML = data.user.name;
1032
          tdName.querySelector('input').value = data.user.name;
1033
1034
          var tdEmail = tr.querySelector('.td-email');
1035
          tdEmail.querySelector('.value').innerHTML = data.user.email;
1036
          tdEmail.querySelector('input').value = data.user.email;
1037
1038
          var tdRole = tr.querySelector('.td-role');
1039
          tdRole.querySelector('.value').innerHTML = data.user.role.name;
1040
          var tdRoleOptions = tdRole.querySelectorAll('select option');
1041
          Array.prototype.forEach.call(tdRoleOptions, function (option) {
1042
            if (option.value === data.user.role.name) {
1043
              option.selected = 'selected';
1044
            }
1045
          });
1046
1047
          var tdActive = tr.querySelector('.td-active');
1048
          var glypEyeClose = tdActive.querySelector('.glyphicon-eye-close');
1049
          glypEyeClose.addEventListener('click', _this5._handleActivate, true);
1050
          glypEyeClose.setAttribute('data-user-id', data.user.id);
1051
1052
          var tdActions = tr.querySelector('.td-actions');
1053
          var glypEdit = tdActions.querySelector('.glyphicon-pencil');
1054
          glypEdit.addEventListener('click', _this5._handleEdit, true);
1055
          glypEdit.setAttribute('data-user-id', data.user.id);
1056
1057
          var glypOk = tdActions.querySelector('.glyphicon-ok');
1058
          glypOk.addEventListener('click', _this5._handleUpdate, true);
1059
          glypOk.setAttribute('data-user-id', data.user.id);
1060
1061
          var glypCloseUpdate = tdActions.querySelector('.glyphicon-remove');
1062
          glypCloseUpdate.setAttribute('data-user-id', data.user.id);
1063
          // glypCloseUpdate.addEventListener('click', this._handleCloseUpdate, true)
1064
1065
          var glypRemove = tdActions.querySelector('.glyphicon-trash');
1066
          glypRemove.setAttribute('data-user-id', data.user.id);
1067
          glypRemove.addEventListener('click', _this5._handleRemove, true);
1068
        }
1069
1070
        _this5._table.appendChild(tr);
1071
1072
        username.value = '';
1073
        name.value = '';
1074
        email.value = '';
1075
        password.value = '';
1076
      } else {
1077
        _this5._alert.classList.remove('hidden');
1078
        _this5._alert.innerHTML = data.message;
1079
      }
1080
    });
1081
  }
1082
};
1083
1084
exports.default = usersList;
1085
1086
// var userListEle = document.querySelector('.user-list');
1087
// if(typeof userListEle !== 'undefined' && userListEle !== null) {
1088
//   usersList.init(userListEle)
1089
// }
1090
1091
},{"nanoajax":1,"qs":3}],8:[function(require,module,exports){
1092
'use strict';
1093
1094
Object.defineProperty(exports, "__esModule", {
1095
  value: true
1096
});
1097
1098
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1099
1100
var _UserList = require('./modules/UserList');
1101
1102
var _UserList2 = _interopRequireDefault(_UserList);
1103
1104
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1105
1106
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1107
1108
/*global document, window, json, XMLHttpRequest */
1109
var singleton = Symbol();
1110
var singletonEnforcer = Symbol();
1111
1112
var UserLogin = function () {
1113
  function UserLogin(enforcer) {
1114
    _classCallCheck(this, UserLogin);
1115
1116
    this.init();
1117
    if (enforcer != singletonEnforcer) throw 'Cannot construct UserLogin singleton';
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1118
  }
1119
1120
  _createClass(UserLogin, [{
1121
    key: 'init',
1122
    value: function init() {
1123
      _UserList2.default.init();
1124
1125
      this.isInit = true;
1126
      // const
1127
      this._btnActions = [].slice.call(document.querySelectorAll('.form-wrapper .btns [data-workflow]'));
1128
      this._formWrapper = document.querySelector('.abeform-wrapper');
1129
      if (this._btnActions.length > 0) {
1130
        this._btnHidden = document.querySelector('.form-wrapper .btns [data-action="draft"]');
1131
        this._btnReject = document.querySelector('.form-wrapper .btns [data-extra-btn="reject"]');
1132
        this._btnEdit = document.querySelector('.form-wrapper .btns [data-extra-btn="edit"]');
1133
1134
        this._inputs = [].slice.call(this._formWrapper.querySelectorAll('.tab-pane:not([id=slug]) input.form-abe'));
1135
        this._inputs = this._inputs.concat([].slice.call(this._formWrapper.querySelectorAll('.tab-pane:not([id=slug]) textarea.form-abe')));
1136
        this._inputsFile = [].slice.call(this._formWrapper.querySelectorAll('.tab-pane:not([id=slug]) .upload-wrapper input[type="file"]'));
1137
        this._selects = [].slice.call(this._formWrapper.querySelectorAll('.tab-pane:not([id=slug]) select'));
1138
        this._inputHasChanged = false;
1139
        this._checkInputChanged = typeof this._btnHidden !== 'undefined' && this._btnHidden !== null ? true : false;
1140
1141
        // bind this
1142
        this._handleInputChange = this._inputChange.bind(this);
1143
        this._handleOnSaved = this._onSaved.bind(this);
1144
        // this._handleWillSave = this._willSaved.bind(this);
1145
1146
        this._bindEvent();
1147
        this._showHideBtn();
1148
      }
1149
    }
1150
  }, {
1151
    key: '_csrfToken',
1152
    value: function _csrfToken() {
1153
      var csrfToken = document.querySelector('#globalCsrfToken').value;
1154
1155
      (function (open) {
1156
        XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
1157
          // extracting domain of the query
1158
          var domain = url.indexOf('://') > -1 ? url.split('/')[2] : window.location.hostname;
1159
          this._domain = domain.split(':')[0];
1160
          this._port = domain.split(':').length == 2 ? domain.split(':')[1] : window.location.port;
1161
          open.call(this, method, url, async, user, password);
1162
        };
1163
      })(XMLHttpRequest.prototype.open);
1164
1165
      (function (send) {
1166
        XMLHttpRequest.prototype.send = function (data) {
1167
          // if query domain == abe domain => CSRF token
1168
          if (window.location.hostname == this._domain && window.location.port == this._port) this.setRequestHeader('X-CSRF-Token', csrfToken);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1169
          send.call(this, data);
1170
        };
1171
      })(XMLHttpRequest.prototype.send);
1172
    }
1173
  }, {
1174
    key: '_showHideBtn',
1175
    value: function _showHideBtn() {
1176
      this._changeCurrentBtn(document.querySelector('.form-wrapper .btns [data-action="' + json.abe_meta.status + '"]'));
1177
1178
      var isCurrent = false;
1179
      Array.prototype.forEach.call(this._btnActions, function (btn) {
1180
1181
        if (btn.classList.contains('current')) {
1182
          btn.classList.add('btn-hidden');
1183
          // btn.classList.remove('btn-hidden')
1184
          isCurrent = true;
1185
        } else {
1186
          if (isCurrent) {
1187
            btn.classList.remove('btn-hidden');
1188
            isCurrent = false;
1189
          } else {
1190
            btn.classList.add('btn-hidden');
1191
          }
1192
        }
1193
      }.bind(this));
0 ignored issues
show
unused-code introduced by
The call to bind does not seem necessary since the function does not use this. Consider calling it directly.
Loading history...
1194
1195
      if (json.abe_meta.status !== 'draft' && json.abe_meta.status !== 'publish') {
1196
        this._btnReject.classList.remove('btn-hidden');
1197
      } else {
1198
        this._btnReject.classList.add('btn-hidden');
1199
      }
1200
      if (json.abe_meta.status === 'publish') {
1201
        this._btnEdit.classList.remove('btn-hidden');
1202
      } else {
1203
        this._btnEdit.classList.add('btn-hidden');
1204
      }
1205
      if (json.abe_meta.status === 'draft') {
1206
        this._enableInput();
1207
        this._btnActions[0].classList.remove('btn-hidden');
1208
        this._btnActions[1].classList.remove('btn-hidden');
1209
      } else {
1210
        this._disableInput();
1211
      }
1212
    }
1213
  }, {
1214
    key: '_changeCurrentBtn',
1215
    value: function _changeCurrentBtn(currentBtn) {
1216
      Array.prototype.forEach.call(this._btnActions, function (btn) {
1217
        btn.classList.remove('current');
1218
      }.bind(this));
0 ignored issues
show
unused-code introduced by
The call to bind does not seem necessary since the function does not use this. Consider calling it directly.
Loading history...
1219
      currentBtn.classList.add('current');
1220
    }
1221
  }, {
1222
    key: '_disableInput',
1223
    value: function _disableInput() {
1224
      Array.prototype.forEach.call(this._inputsFile, function (input) {
1225
        input.setAttribute('disabled', '');
1226
      }.bind(this));
0 ignored issues
show
unused-code introduced by
The call to bind does not seem necessary since the function does not use this. Consider calling it directly.
Loading history...
1227
      Array.prototype.forEach.call(this._inputs, function (input) {
1228
        input.setAttribute('disabled', '');
1229
      }.bind(this));
0 ignored issues
show
unused-code introduced by
The call to bind does not seem necessary since the function does not use this. Consider calling it directly.
Loading history...
1230
      Array.prototype.forEach.call(this._selects, function (input) {
1231
        input.setAttribute('disabled', '');
1232
      }.bind(this));
0 ignored issues
show
unused-code introduced by
The call to bind does not seem necessary since the function does not use this. Consider calling it directly.
Loading history...
1233
    }
1234
  }, {
1235
    key: '_enableInput',
1236
    value: function _enableInput() {
1237
      Array.prototype.forEach.call(this._inputsFile, function (input) {
1238
        input.removeAttribute('disabled');
1239
      }.bind(this));
0 ignored issues
show
unused-code introduced by
The call to bind does not seem necessary since the function does not use this. Consider calling it directly.
Loading history...
1240
      Array.prototype.forEach.call(this._inputs, function (input) {
1241
        input.removeAttribute('disabled');
1242
      }.bind(this));
0 ignored issues
show
unused-code introduced by
The call to bind does not seem necessary since the function does not use this. Consider calling it directly.
Loading history...
1243
      Array.prototype.forEach.call(this._selects, function (input) {
1244
        input.removeAttribute('disabled');
1245
      }.bind(this));
0 ignored issues
show
unused-code introduced by
The call to bind does not seem necessary since the function does not use this. Consider calling it directly.
Loading history...
1246
    }
1247
  }, {
1248
    key: '_bindEvent',
1249
    value: function _bindEvent() {
1250
      window.abe.save.onFileSaved(this._handleOnSaved);
1251
1252
      Array.prototype.forEach.call(this._btnActions, function (btn) {
1253
        btn.addEventListener('click', this._handleWillSave);
1254
      }.bind(this));
1255
1256
      Array.prototype.forEach.call(this._inputsFile, function (input) {
1257
        if (!this._checkInputChanged) {
1258
          input.setAttribute('disabled', '');
1259
        }
1260
      }.bind(this));
1261
      Array.prototype.forEach.call(this._inputs, function (input) {
1262
        if (!this._checkInputChanged) {
1263
          input.setAttribute('disabled', '');
1264
        }
1265
        input.addEventListener('keyup', this._handleInputChange);
1266
      }.bind(this));
1267
      Array.prototype.forEach.call(this._selects, function (input) {
1268
        if (!this._checkInputChanged) {
1269
          input.setAttribute('disabled', '');
1270
        }
1271
        input.addEventListener('change', this._handleInputChange);
1272
      }.bind(this));
1273
    }
1274
  }, {
1275
    key: '_onSaved',
1276
    value: function _onSaved() {
1277
      this._showHideBtn();
1278
    }
1279
  }, {
1280
    key: '_inputChange',
1281
    value: function _inputChange() {
1282
      if (json.abe_meta.status !== 'draft') {
1283
        if (!this._checkInputChanged || this._inputHasChanged) return;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1284
        this._inputHasChanged = true;
1285
        Array.prototype.forEach.call(document.querySelectorAll('.btn-save'), function (btn) {
1286
          if (!btn.classList.contains('btn-hidden')) btn.classList.add('btn-hidden');
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1287
        }.bind(this));
0 ignored issues
show
unused-code introduced by
The call to bind does not seem necessary since the function does not use this. Consider calling it directly.
Loading history...
1288
        this._btnHidden.classList.remove('btn-hidden');
1289
      }
1290
    }
1291
  }], [{
1292
    key: 'instance',
1293
    get: function get() {
1294
      if (!this[singleton]) {
1295
        this[singleton] = new UserLogin(singletonEnforcer);
1296
      }
1297
      return this[singleton];
1298
    }
1299
  }]);
1300
1301
  return UserLogin;
1302
}();
1303
1304
exports.default = UserLogin;
1305
1306
1307
document.addEventListener('DOMContentLoaded', function () {
1308
  UserLogin.instance;
0 ignored issues
show
introduced by
The result of the property access to UserLogin.instance is not used.
Loading history...
1309
  UserLogin.instance._csrfToken();
1310
});
1311
1312
},{"./modules/UserList":7}]},{},[8]);
1313