-
Notifications
You must be signed in to change notification settings - Fork 556
Expand file tree
/
Copy pathutils.js
More file actions
276 lines (252 loc) · 7.55 KB
/
utils.js
File metadata and controls
276 lines (252 loc) · 7.55 KB
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
* @namespace
*/
var Utils = {};
/**
* @member {object}
* @memberof QueryBuilder
* @see Utils
*/
QueryBuilder.utils = Utils;
/**
* @callback Utils#OptionsIteratee
* @param {string} key
* @param {string} value
* @param {string} [optgroup]
*/
/**
* Iterates over radio/checkbox/selection options, it accept four formats
*
* @example
* // array of values
* options = ['one', 'two', 'three']
* @example
* // simple key-value map
* options = {1: 'one', 2: 'two', 3: 'three'}
* @example
* // array of 1-element maps
* options = [{1: 'one'}, {2: 'two'}, {3: 'three'}]
* @example
* // array of elements
* options = [{value: 1, label: 'one', optgroup: 'group'}, {value: 2, label: 'two'}]
*
* @param {object|array} options
* @param {Utils#OptionsIteratee} tpl
*/
Utils.iterateOptions = function(options, tpl) {
if (options) {
if ($.isArray(options)) {
options.forEach(function(entry) {
if ($.isPlainObject(entry)) {
// array of elements
if ('value' in entry) {
tpl(entry.value, entry.label || entry.value, entry.optgroup);
}
// array of one-element maps
else {
$.each(entry, function(key, val) {
tpl(key, val);
return false; // break after first entry
});
}
}
// array of values
else {
tpl(entry, entry);
}
});
}
// unordered map
else {
$.each(options, function(key, val) {
tpl(key, val);
});
}
}
};
/**
* Replaces {0}, {1}, ... in a string
* @param {string} str
* @param {...*} args
* @returns {string}
*/
Utils.fmt = function(str, args) {
if (!Array.isArray(args)) {
args = Array.prototype.slice.call(arguments, 1);
}
return str.replace(/{([0-9]+)}/g, function(m, i) {
return args[parseInt(i)];
});
};
/**
* Throws an Error object with custom name or logs an error
* @param {boolean} [doThrow=true]
* @param {string} type
* @param {string} message
* @param {...*} args
*/
Utils.error = function() {
var i = 0;
var doThrow = typeof arguments[i] === 'boolean' ? arguments[i++] : true;
var type = arguments[i++];
var message = arguments[i++];
var args = Array.isArray(arguments[i]) ? arguments[i] : Array.prototype.slice.call(arguments, i);
if (doThrow) {
var err = new Error(Utils.fmt(message, args));
err.name = type + 'Error';
err.args = args;
throw err;
}
else {
console.error(type + 'Error: ' + Utils.fmt(message, args));
}
};
/**
* Changes the type of a value to int, float or bool
* @param {*} value
* @param {string} type - 'integer', 'double', 'boolean' or anything else (passthrough)
* @returns {*}
*/
Utils.changeType = function(value, type) {
if (value === '' || value === undefined) {
return undefined;
}
switch (type) {
// @formatter:off
case 'integer':
if (typeof value === 'string' && !/^-?\d+$/.test(value)) {
return value;
}
return parseInt(value);
case 'double':
if (typeof value === 'string' && !/^-?\d+\.?\d*$/.test(value)) {
return value;
}
return parseFloat(value);
case 'boolean':
if (typeof value === 'string' && !/^(0|1|true|false){1}$/i.test(value)) {
return value;
}
return value === true || value === 1 || value.toLowerCase() === 'true' || value === '1';
default: return value;
// @formatter:on
}
};
/**
* Escapes a string like PHP's mysql_real_escape_string does
* @param {string} value
* @param {string} [additionalEscape] additionnal chars to escape
* @returns {string}
*/
Utils.escapeString = function(value, additionalEscape) {
if (typeof value != 'string') {
return value;
}
var escaped = value
.replace(/[\0\n\r\b\\\'\"]/g, function(s) {
switch (s) {
// @formatter:off
case '\0': return '\\0';
case '\n': return '\\n';
case '\r': return '\\r';
case '\b': return '\\b';
case '\'': return '\'\'';
default: return '\\' + s;
// @formatter:off
}
})
// uglify compliant
.replace(/\t/g, '\\t')
.replace(/\x1a/g, '\\Z');
if (additionalEscape) {
escaped = escaped
.replace(new RegExp('[' + additionalEscape + ']', 'g'), function(s) {
return '\\' + s;
});
}
return escaped;
};
/**
* Escapes a string for use in regex
* @param {string} str
* @returns {string}
*/
Utils.escapeRegExp = function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
};
/**
* Escapes a string for use in HTML element id
* @param {string} str
* @returns {string}
*/
Utils.escapeElementId = function(str) {
// Regex based on that suggested by:
// https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/
// - escapes : . [ ] ,
// - avoids escaping already escaped values
return (str) ? str.replace(/(\\)?([:.\[\],])/g,
function( $0, $1, $2 ) { return $1 ? $0 : '\\' + $2; }) : str;
};
/**
* Sorts objects by grouping them by `key`, preserving initial order when possible
* @param {object[]} items
* @param {string} key
* @returns {object[]}
*/
Utils.groupSort = function(items, key) {
var optgroups = [];
var newItems = [];
items.forEach(function(item) {
var idx;
if (item[key]) {
idx = optgroups.lastIndexOf(item[key]);
if (idx == -1) {
idx = optgroups.length;
}
else {
idx++;
}
}
else {
idx = optgroups.length;
}
optgroups.splice(idx, 0, item[key]);
newItems.splice(idx, 0, item);
});
return newItems;
};
/**
* Defines properties on an Node prototype with getter and setter.<br>
* Update events are emitted in the setter through root Model (if any).<br>
* The object must have a `__` object, non enumerable property to store values.
* @param {function} obj
* @param {string[]} fields
*/
Utils.defineModelProperties = function(obj, fields) {
fields.forEach(function(field) {
Object.defineProperty(obj.prototype, field, {
enumerable: true,
get: function() {
return this.__[field];
},
set: function(value) {
var previousValue = (this.__[field] !== null && typeof this.__[field] == 'object') ?
$.extend({}, this.__[field]) :
this.__[field];
this.__[field] = value;
if (this.model !== null) {
/**
* After a value of the model changed
* @event model:update
* @memberof Model
* @param {Node} node
* @param {string} field
* @param {*} value
* @param {*} previousValue
*/
this.model.trigger('update', this, field, value, previousValue);
}
}
});
});
};