1 namespace("kivi", function(ns) {
21 ns.setup_formats = function(params) {
22 var res = (params.dates || "").match(/^([ymd]+)([^a-z])([ymd]+)[^a-z]([ymd]+)$/);
24 ns._date_format = { sep: res[2] };
25 ns._date_format[res[1].substr(0, 1)] = 0;
26 ns._date_format[res[3].substr(0, 1)] = 1;
27 ns._date_format[res[4].substr(0, 1)] = 2;
30 res = (params.times || "").match(/^([hm]+)([^a-z])([hm]+)$/);
32 ns._time_format = { sep: res[2] };
33 ns._time_format[res[1].substr(0, 1)] = 0;
34 ns._time_format[res[3].substr(0, 1)] = 1;
37 res = (params.numbers || "").match(/^\d*([^\d]?)\d+([^\d])\d+$/);
45 ns.parse_date = function(date) {
46 if (date === undefined)
52 if (date === '0' || date === '00')
55 var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
56 var today = new Date();
59 // assume fixed pattern, and extract parts again
60 if (parts.length == 1) {
62 parts = date.match(/../g);
63 if (date.length == 8) {
64 parts[ns._date_format.y] += parts.splice(ns._date_format.y + 1, 1)
67 if (date.length == 6 || date.length == 4) {
70 if (date.length == 1 || date.length == 2) {
72 parts[ ns._date_format.y ] = today.getFullYear();
73 parts[ ns._date_format.m ] = today.getMonth() + 1;
74 parts[ ns._date_format.d ] = date;
81 if (parts.length == 3) {
82 var year = +parts[ ns._date_format.y ] || 0 * 1 || (new Date()).getFullYear();
86 year += year > 70 ? 1900 : 2000;
90 (parts[ ns._date_format.m ] || (today.getMonth() + 1)) * 1 - 1, // Months are 0-based.
91 (parts[ ns._date_format.d ] || today.getDate()) * 1
93 } else if (parts.length == 2) {
95 (new Date()).getFullYear(),
96 (parts[ (ns._date_format.m > ns._date_format.d) * 1 ] || (today.getMonth() + 1)) * 1 - 1, // Months are 0-based.
97 (parts[ (ns._date_format.d > ns._date_format.m) * 1 ] || today.getDate()) * 1
102 return isNaN(date.getTime()) ? undefined : date;
105 ns.format_date = function(date) {
106 if (isNaN(date.getTime()))
109 var parts = [ "", "", "" ]
110 parts[ ns._date_format.y ] = date.getFullYear();
111 parts[ ns._date_format.m ] = (date.getMonth() < 9 ? "0" : "") + (date.getMonth() + 1); // Months are 0-based, but days are 1-based.
112 parts[ ns._date_format.d ] = (date.getDate() < 10 ? "0" : "") + date.getDate();
113 return parts.join(ns._date_format.sep);
116 ns.parse_time = function(time) {
117 var now = new Date();
119 if (time === undefined)
128 // special case 1: military time in fixed "hhmm" format
129 if (time.length == 4) {
130 var res = time.match(/(\d\d)(\d\d)/);
132 now.setHours(res[1], res[2]);
139 var parts = time.replace(/\s+/g, "").split(ns._time_format.sep);
140 if (parts.length == 2) {
141 for (var idx in parts) {
142 if (Number.isNaN(Number.parseInt(parts[idx])))
145 now.setHours(parts[ns._time_format.h], parts[ns._time_format.m]);
151 ns.format_time = function(date) {
152 if (isNaN(date.getTime()))
155 var parts = [ "", "" ]
156 parts[ ns._time_format.h ] = date.getHours().toString().padStart(2, '0');
157 parts[ ns._time_format.m ] = date.getMinutes().toString().padStart(2, '0');
158 return parts.join(ns._time_format.sep);
161 ns.parse_amount = function(amount) {
162 if (amount === undefined)
168 if (ns._number_format.decimalSep == ',')
169 amount = amount.replace(/\./g, "").replace(/,/g, ".");
171 amount = amount.replace(/[\',]/g, "");
173 // Make sure no code wich is not a math expression ends up in eval().
174 if (!amount.match(/^[0-9 ()\-+*/.]*$/))
177 amount = amount.replace(/^0+(\d+)/, '$1');
187 ns.round_amount = function(amount, places) {
188 var neg = amount >= 0 ? 1 : -1;
189 var mult = Math.pow(10, places + 1);
190 var temp = Math.abs(amount) * mult;
191 var diff = Math.abs(1 - temp + Math.floor(temp));
192 temp = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
194 temp += dec >= 5 ? 10 - dec: dec * -1;
196 return neg * temp / mult;
199 ns.format_amount = function(amount, places) {
200 amount = amount || 0;
202 if ((places !== undefined) && (places >= 0))
203 amount = ns.round_amount(amount, Math.abs(places));
205 var parts = ("" + Math.abs(amount)).split(/\./);
207 var dec = parts.length > 1 ? parts[1] : "";
208 var sign = amount < 0 ? "-" : "";
210 if (places !== undefined) {
211 while (dec.length < Math.abs(places))
214 if ((places > 0) && (dec.length > Math.abs(places)))
215 dec = d.substr(0, places);
218 if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
219 var len = ((intg.length + 2) % 3) + 1,
221 res = intg.substr(0, len);
222 while (start < intg.length) {
223 res += ns._number_format.thousandSep + intg.substr(start, 3);
230 var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
232 return sign + intg + sep + dec;
235 ns.t8 = function(text, params) {
236 text = ns._locale[text] || text;
239 if( Object.prototype.toString.call( params ) === '[object Array]' ) {
240 var len = params.length;
242 for(var i=0; i<len; ++i) {
245 text = text.split("#"+ key).join(value);
248 else if( typeof params == 'object' ) {
251 text = text.split("#{"+ key +"}").join(value);
258 ns.setupLocale = function(locale) {
262 ns.set_focus = function(element) {
263 var $e = $(element).eq(0);
264 if ($e.data('ckeditorInstance'))
265 ns.focus_ckeditor_when_ready($e);
270 ns.focus_ckeditor_when_ready = function(element) {
271 $(element).data('ckeditorInstance').on('instanceReady', function() { ns.focus_ckeditor(element); });
274 ns.focus_ckeditor = function(element) {
275 $(element).data('ckeditorInstance').focus();
278 ns.selectall_ckeditor = function(element) {
279 var editor = $(element).ckeditorGet();
280 var editable = editor.editable();
281 if (editable.is('textarea')) {
282 var textarea = editable.$;
285 textarea.createTextRange().execCommand('SelectAll');
287 textarea.selectionStart = 0;
288 textarea.selectionEnd = textarea.value.length;
291 if (editable.is('body'))
292 editor.document.$.execCommand('SelectAll', false, null);
295 var range = editor.createRange();
296 range.selectNodeContents(editable);
300 editor.forceNextSelectionCheck();
301 editor.selectionChange();
305 ns.init_tabwidget = function(element) {
306 var $element = $(element);
308 var elementId = $element.attr('id');
311 var cookieName = 'jquery_ui_tab_'+ elementId;
312 if (!window.location.hash) {
313 // only activate if there's no hash to overwrite it
314 tabsParams.active = $.cookie(cookieName);
316 tabsParams.activate = function(event, ui) {
317 var i = ui.newTab.parent().children().index(ui.newTab);
318 $.cookie(cookieName, i);
322 $element.tabs(tabsParams);
325 ns.init_text_editor = function(element) {
327 all: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
328 default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
332 var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
336 removePlugins: 'resize',
337 extraPlugins: 'inline_resize',
339 disableAutoInline: true,
341 disableNativeSpellChecker: false
344 config.height = $e.height();
345 config.width = $e.width();
347 var editor = CKEDITOR.inline($e.get(0), config);
348 $e.data('ckeditorInstance', editor);
350 if ($e.hasClass('texteditor-autofocus'))
351 editor.on('instanceReady', function() { ns.focus_ckeditor($e); });
354 ns.filter_select = function() {
355 var $input = $(this);
356 var $select = $('#' + $input.data('select-id'));
357 var filter = $input.val().toLocaleLowerCase();
359 $select.find('option').each(function() {
360 if ($(this).text().toLocaleLowerCase().indexOf(filter) != -1)
367 ns.reinit_widgets = function() {
368 ns.run_once_for('.datepicker', 'datepicker', function(elt) {
372 if (ns.Part) ns.Part.reinit_widgets();
373 if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
374 if (ns.Validator) ns.Validator.reinit_widgets();
375 if (ns.Materialize) ns.Materialize.reinit_widgets();
377 if (ns.ProjectPicker)
378 ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
379 kivi.ProjectPicker($(elt));
383 ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
384 kivi.ChartPicker($(elt));
387 ns.run_once_for('div.filtered_select input', 'filtered_select', function(elt) {
388 $(elt).bind('change keyup', ns.filter_select);
391 var func = kivi.get_function_by_name('local_reinit_widgets');
395 ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
397 contentAsHTML: false,
398 theme: 'tooltipster-light'
402 ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
405 theme: 'tooltipster-light'
409 ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
410 ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
413 ns.submit_ajax_form = function(url, form_selector, additional_data) {
414 $(form_selector).ajaxSubmit({
416 data: additional_data,
417 success: ns.eval_json_result
423 // This function submits an existing form given by "form_selector"
424 // and sets the "action" input to "action_to_call" before submitting
425 // it. Any existing input named "action" will be removed prior to
427 ns.submit_form_with_action = function(form_selector, action_to_call) {
428 $('[name=action]').remove();
430 var $form = $(form_selector);
431 var $hidden = $('<input type=hidden>');
433 $hidden.attr('name', 'action');
434 $hidden.attr('value', action_to_call);
435 $form.append($hidden);
440 // This function exists solely so that it can be found with
441 // kivi.get_functions_by_name() and called later on. Using something
442 // like "var func = history["back"]" works, but calling it later
443 // with "func.apply()" doesn't.
444 ns.history_back = function() {
448 // Return a function object by its name (a string). Works both with
449 // global functions (e.g. "focus_by_name") and those in namespaces (e.g.
451 // Returns null if the object is not found.
452 ns.get_function_by_name = function(name) {
453 var parts = name.match("(.+)\\.([^\\.]+)$");
456 return namespace(parts[1])[ parts[2] ];
459 // Open a modal jQuery UI popup dialog. The content can be either
460 // loaded via AJAX (if the parameter 'url' is given) or simply
461 // displayed if it exists in the DOM already (referenced via
462 // 'id') or given via param.html. If an existing DOM div should be used then
463 // the element won't be removed upon closing the dialog which allows
464 // re-opening it later on.
467 // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
468 // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
469 // - dialog: an optional object of options passed to the $.dialog() call
470 // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
471 ns.popup_dialog = function(params) {
472 if (kivi.Materialize)
473 return kivi.Materialize.popup_dialog(params);
477 params = params || { };
478 var id = params.id || 'jqueryui_popup_dialog';
479 var custom_close = params.dialog ? params.dialog.close : undefined;
480 var dialog_params = $.extend(
481 { // kivitendo default parameters:
486 // User supplied options:
487 params.dialog || { },
488 { // Options that must not be changed:
489 close: function(event, ui) {
490 dialog.dialog('close');
495 if (params.url || params.html)
500 if (!params.url && !params.html) {
501 // Use existing DOM element and show it. No AJAX call.
504 .bind('dialogopen', function() {
505 ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
507 .dialog(dialog_params);
511 $('#' + id).remove();
513 dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
514 dialog.dialog(dialog_params);
517 dialog.html(params.html);
519 // no html? get it via ajax
524 success: function(new_html) {
525 dialog.html(new_html);
526 dialog.removeClass('loading');
536 // Run code only once for each matched element
538 // This allows running the function 'code' exactly once for each
539 // element that matches 'selector'. This is achieved by storing the
540 // state with jQuery's 'data' function. The 'identification' is
541 // required for differentiating unambiguously so that different code
542 // functions can still be run on the same elements.
544 // 'code' can be either a function or the name of one. It must
545 // resolve to a function that receives the jQueryfied element as its
549 ns.run_once_for = function(selector, identification, code) {
550 var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
551 var fn = typeof code === 'function' ? code : ns.get_function_by_name(code);
553 console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
557 $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
559 $elt.data(attr_name, true);
564 // Run a function by its name passing it some arguments
566 // This is a function useful mainly for the ClientJS functionality.
567 // It finds a function by its name and then executes it on an empty
568 // object passing the elements in 'args' (an array) as the function
569 // parameters retuning its result.
571 // Logs an error to the console and returns 'undefined' if the
572 // function cannot be found.
573 ns.run = function(function_name, args) {
574 var fn = ns.get_function_by_name(function_name);
576 return fn.apply({}, args || []);
578 console.error('kivi.run("' + function_name + '"): No function by that name found');
582 ns.save_file = function(base64_data, content_type, size, attachment_name) {
583 // atob returns a unicode string with one codepoint per octet. revert this
584 const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
585 const byteCharacters = atob(b64Data);
586 const byteArrays = [];
588 for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
589 const slice = byteCharacters.slice(offset, offset + sliceSize);
591 const byteNumbers = new Array(slice.length);
592 for (let i = 0; i < slice.length; i++) {
593 byteNumbers[i] = slice.charCodeAt(i);
596 const byteArray = new Uint8Array(byteNumbers);
597 byteArrays.push(byteArray);
600 const blob = new Blob(byteArrays, {type: contentType});
604 var blob = b64toBlob(base64_data, content_type);
605 var a = $("<a style='display: none;'/>");
606 var url = window.URL.createObjectURL(blob);
608 a.attr("download", attachment_name);
611 window.URL.revokeObjectURL(url);
615 ns.detect_duplicate_ids_in_dom = function() {
619 $('[id]').each(function() {
620 if (this.id && ids[this.id]) {
622 console.warn('Duplicate ID #' + this.id);
628 console.log('No duplicate IDs found :)');
631 ns.validate_form = function(selector) {
632 if (!kivi.Validator) {
633 console.log('kivi.Validator is not loaded');
635 return kivi.Validator.validate_all(selector);
639 // Verifies that at least one checkbox matching the
640 // "checkbox_selector" is actually checked. If not, an error message
641 // is shown, and false is returned. Otherwise (at least one of them
642 // is checked) nothing is shown and true returned.
644 // Can be used in checks when clicking buttons.
645 ns.check_if_entries_selected = function(checkbox_selector) {
646 if ($(checkbox_selector + ':checked').length > 0)
649 alert(kivi.t8('No entries have been selected.'));
654 ns.switch_areainput_to_textarea = function(id) {
655 var $input = $('#' + id);
659 var $area = $('<textarea></textarea>');
661 $area.prop('rows', 3);
662 $area.prop('cols', $input.prop('size') || 40);
663 $area.prop('name', $input.prop('name'));
664 $area.prop('id', $input.prop('id'));
665 $area.val($input.val());
667 $input.parent().replaceWith($area);
671 ns.set_cursor_position = function(selector, position) {
672 var $input = $(selector);
673 if (position === 'end')
674 position = $input.val().length;
676 $input.prop('selectionStart', position);
677 $input.prop('selectionEnd', position);
680 ns._shell_escape = function(str) {
681 if (str.match(/^[a-zA-Z0-9.,_=+/-]+$/))
684 return "'" + str.replace(/'/, "'\\''") + "'";
687 ns.call_as_curl = function(params) {
688 params = params || {};
689 var uri = document.documentURI.replace(/\?.*/, '');
690 var command = ['curl', '--user', kivi.myconfig.login + ':SECRET', '--request', params.method || 'POST']
692 $(params.data || []).each(function(idx, elt) {
693 command = command.concat([ '--form-string', elt.name + '=' + (elt.value || '') ]);
698 return $.map(command, function(elt, idx) {
699 return kivi._shell_escape(elt);
704 kivi = namespace('kivi');