forked from frappe/frappe
/
dom.js
348 lines (318 loc) · 8.73 KB
/
dom.js
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
// add a new dom element
frappe.provide('frappe.dom');
frappe.dom = {
id_count: 0,
freeze_count: 0,
by_id: function(id) {
return document.getElementById(id);
},
get_unique_id: function() {
const id = 'unique-' + frappe.dom.id_count;
frappe.dom.id_count++;
return id;
},
set_unique_id: function(ele) {
var $ele = $(ele);
if($ele.attr('id')) {
return $ele.attr('id');
}
var id = 'unique-' + frappe.dom.id_count;
$ele.attr('id', id);
frappe.dom.id_count++;
return id;
},
eval: function(txt) {
if(!txt) return;
var el = document.createElement('script');
el.appendChild(document.createTextNode(txt));
// execute the script globally
document.getElementsByTagName('head')[0].appendChild(el);
},
remove_script_and_style: function(txt) {
const evil_tags = ["script", "style", "noscript", "title", "meta", "base", "head"];
const regex = new RegExp(evil_tags.map(tag => `<${tag}>.*<\\/${tag}>`).join('|'), 's');
if (!regex.test(txt)) {
// no evil tags found, skip the DOM method entirely!
return txt;
}
var div = document.createElement('div');
div.innerHTML = txt;
var found = false;
evil_tags.forEach(function(e) {
var elements = div.getElementsByTagName(e);
i = elements.length;
while (i--) {
found = true;
elements[i].parentNode.removeChild(elements[i]);
}
});
// remove links with rel="stylesheet"
var elements = div.getElementsByTagName('link');
var i = elements.length;
while (i--) {
if (elements[i].getAttribute("rel")=="stylesheet"){
found = true;
elements[i].parentNode.removeChild(elements[i]);
}
}
if(found) {
return div.innerHTML;
} else {
// don't disturb
return txt;
}
},
is_element_in_viewport: function (el, tolerance=0) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top + tolerance >= 0
&& rect.left + tolerance >= 0
&& rect.bottom - tolerance <= $(window).height()
&& rect.right - tolerance <= $(window).width()
);
},
is_element_in_modal(element) {
return Boolean($(element).parents('.modal').length);
},
set_style: function(txt, id) {
if(!txt) return;
var se = document.createElement('style');
se.type = "text/css";
if (id) {
var element = document.getElementById(id);
if (element) {
element.parentNode.removeChild(element);
}
se.id = id;
}
if (se.styleSheet) {
se.styleSheet.cssText = txt;
} else {
se.appendChild(document.createTextNode(txt));
}
document.getElementsByTagName('head')[0].appendChild(se);
return se;
},
add: function(parent, newtag, className, cs, innerHTML, onclick) {
if(parent && parent.substr)parent = frappe.dom.by_id(parent);
var c = document.createElement(newtag);
if(parent)
parent.appendChild(c);
// if image, 3rd parameter is source
if(className) {
if(newtag.toLowerCase()=='img')
c.src = className
else
c.className = className;
}
if(cs) frappe.dom.css(c,cs);
if(innerHTML) c.innerHTML = innerHTML;
if(onclick) c.onclick = onclick;
return c;
},
css: function(ele, s) {
if(ele && s) {
$.extend(ele.style, s);
}
return ele;
},
activate: function($parent, $child, common_class, active_class='active') {
$parent.find(`.${common_class}.${active_class}`)
.removeClass(active_class);
$child.addClass(active_class);
},
freeze: function(msg, css_class) {
// blur
if(!$('#freeze').length) {
var freeze = $('<div id="freeze" class="modal-backdrop fade"></div>')
.on("click", function() {
if (cur_frm && cur_frm.cur_grid) {
cur_frm.cur_grid.toggle_view();
return false;
}
})
.appendTo("#body_div");
freeze.html(repl('<div class="freeze-message-container"><div class="freeze-message"><p class="lead">%(msg)s</p></div></div>',
{msg: msg || ""}));
setTimeout(function() { freeze.addClass("in") }, 1);
} else {
$("#freeze").addClass("in");
}
if (css_class) {
$("#freeze").addClass(css_class);
}
frappe.dom.freeze_count++;
},
unfreeze: function() {
if(!frappe.dom.freeze_count) return; // anything open?
frappe.dom.freeze_count--;
if(!frappe.dom.freeze_count) {
var freeze = $('#freeze').removeClass("in").remove();
}
},
save_selection: function() {
// via http://stackoverflow.com/questions/5605401/insert-link-in-contenteditable-element
if (window.getSelection) {
var sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
var ranges = [];
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
ranges.push(sel.getRangeAt(i));
}
return ranges;
}
} else if (document.selection && document.selection.createRange) {
return document.selection.createRange();
}
return null;
},
restore_selection: function(savedSel) {
if (savedSel) {
if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
for (var i = 0, len = savedSel.length; i < len; ++i) {
sel.addRange(savedSel[i]);
}
} else if (document.selection && savedSel.select) {
savedSel.select();
}
}
},
is_touchscreen: function() {
return ('ontouchstart' in window)
},
handle_broken_images(container) {
$(container).find('img').on('error', (e) => {
const $img = $(e.currentTarget);
$img.addClass('no-image');
});
},
scroll_to_bottom(container) {
const $container = $(container);
$container.scrollTop($container[0].scrollHeight);
},
file_to_base64(file_obj) {
return new Promise(resolve => {
const reader = new FileReader();
reader.onload = function() {
resolve(reader.result);
};
reader.readAsDataURL(file_obj);
});
},
scroll_to_section(section_name) {
setTimeout(() => {
const section = $(`a:contains("${section_name}")`);
if (section.length) {
if(section.parent().hasClass('collapsed')) {
// opens the section
section.click();
}
frappe.ui.scroll(section.parent().parent());
}
}, 200);
},
pixel_to_inches(pixels) {
const div = $('<div id="dpi" style="height: 1in; width: 1in; left: 100%; position: fixed; top: 100%;"></div>');
div.appendTo(document.body);
const dpi_x = document.getElementById('dpi').offsetWidth;
const inches = pixels / dpi_x;
div.remove();
return inches;
}
};
frappe.ellipsis = function(text, max) {
if(!max) max = 20;
text = cstr(text);
if(text.length > max) {
text = text.substr(0, max) + '...';
}
return text;
};
frappe.run_serially = function(tasks) {
var result = Promise.resolve();
tasks.forEach(task => {
if(task) {
result = result.then ? result.then(task) : Promise.resolve();
}
});
return result;
};
frappe.load_image = (src, onload, onerror, preprocess = () => {}) => {
var tester = new Image();
tester.onload = function() {
onload(this);
};
tester.onerror = onerror;
preprocess(tester);
tester.src = src;
}
frappe.timeout = seconds => {
return new Promise((resolve) => {
setTimeout(() => resolve(), seconds * 1000);
});
};
frappe.scrub = function(text, spacer='_') {
return text.replace(/ /g, spacer).toLowerCase();
};
frappe.get_modal = function(title, content) {
return $(`<div class="modal fade" style="overflow: auto;" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div class="flex justify-between">
<div class="fill-width flex">
<span class="indicator hidden"></span>
<h4 class="modal-title" style="font-weight: bold;">${title}</h4>
</div>
<div>
<div class="text-right buttons">
<button type="button" class="btn btn-default btn-sm btn-modal-minimize hide">
<i class="octicon octicon-chevron-down" style="padding: 1px 0px;"></i>
</button>
<button type="button" class="btn btn-default btn-sm btn-modal-close" data-dismiss="modal">
<i class="octicon octicon-x visible-xs" style="padding: 1px 0px;"></i>
<span class="hidden-xs">${__("Close")}</span>
</button>
<button type="button" class="btn btn-primary btn-sm hide">
${__("Confirm")}
</button>
</div>
</div>
</div>
</div>
<div class="modal-body ui-front">${content}</div>
</div>
</div>
</div>`);
};
frappe.is_online = function() {
if (frappe.boot.developer_mode == 1) {
// always online in developer_mode
return true;
}
if ('onLine' in navigator) {
return navigator.onLine;
}
return true;
};
// bind online/offline events
$(window).on('online', function() {
frappe.show_alert({
indicator: 'green',
message: __('You are connected to internet.')
});
});
$(window).on('offline', function() {
frappe.show_alert({
indicator: 'orange',
message: __('Connection lost. Some features might not work.')
});
});