-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcblib.js
More file actions
696 lines (641 loc) · 28.4 KB
/
cblib.js
File metadata and controls
696 lines (641 loc) · 28.4 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
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// @namespace https://github.com/cbaoth/userscripts
// @author cbaoth235
//
// @name My user script JS library
// @version 2020-09-09
// @description Some common functions used in user scripts
// @downloadURL https://github.com/cbaoth/userscripts/raw/master/lib/cblib.js
//
// @require http://code.jquery.com/jquery-latest.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @require https://raw.githubusercontent.com/jashkenas/underscore/master/underscore.js
/**
* Important:
* - The above mentioned @required dependencies must be available for
* most functions to work.
* - They must be loaded BEFORE this lib (add this lib as last requirement)
*/
(function (cb, $, _, undefined) {
//import $, { each } from "jquery";
/* {{{ = GENERAL ========================================================== */
/**
* Return either the given value or the default in case the value is `undefined` or `null`.
*
* @param {any} val - Any value.
* @param {any} def - The default value in case `val` is `undefined` or `null`.
* @returns `val` if non-null else `dev`.
*/
cb.nvl = function (val, def) {
return val === undefined || val === null ? def : val;
};
/* }}} = GENERAL ========================================================== */
/* {{{ = STRINGS ========================================================== */
/**
* Capitalize the first char of the given string.
*
* @param {string} str - A string.
* @param {boolean} [lowerRest=false] - Convert the remaining string to lowercase?
* @returns {string} The capitalized string.
*/
cb.stringCapitalize = function (str, lowerRest = false) {
return str && str.charAt(0).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
};
/**
* Calculate a hash code for the given string.
*
* @param {string} str - A string.
* @returns {string} The string's hash value.
*
* @see https://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
*/
cb.stringHash = function (str) {
let hash = 0;
let i;
let chr;
if (str.length === 0) return hash;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
/**
* Escape HTML code in given string.
*
* @param {string} str - A string.
* @returns {string} The string with escaped HTML code.
*/
cb.stringEscape = function (str) {
return $('<p>').text(str).html();
};
/**
* Shorten a string, considering spaces.
*
* @param {string} str - A string.
* @param {number} maxLength - Maximum length of the resulting string, considering spaces.
* @param {string} [suffix=...] - The suffix to append to the result (not considered when calculating max length).
* @returns {string} The shortened string.
*
* @example
* cb.stringShorten('This is a long string.', 12)
* -> 'This is a ...'
* cb.stringShorten('This is a long string.', 12, '')
* -> 'This is a'
* cb.stringShorten('This is a long string.', 100)
* -> 'This is a long string.'
*/
cb.stringShorten = function (str, maxLength, suffix = ' ...') {
if (str === undefined) {
return str;
}
if (maxLength === undefined || maxLength <= 0) {
throw 'maxLength must be > 0, invalid value: ' + maxLength;
}
const trimStr = str.trim();
if (trimStr.length > maxLength) {
const maxStr = trimStr.substr(0, maxLength);
const newStr = trimStr.substr(0, maxStr.lastIndexOf(' '));
return newStr.trim() === '' ? maxStr : newStr + suffix;
}
return trimStr;
};
/**
* Covert a given name to it's initials / shortened form.
*
* @param {string} name - A name.
* @param {Object} obj - An object.
* @param {string} [obj.separator=.] - Separator string, separating first and last lame.
* @param {number} [obj.firstLength=1] - First name max length (initials only).
* @param {number} [obj.lastLength=1] - Last name max length (initials only).
* @param {boolean} [obj.toUpper=false] - First char of first and last name to upper case and rest to lower?
* @param {boolean} [obj.reverse=false] - Reverse initials?
* @returns The name's initials.
*
* Notes:
* * Comma and period `[,.]` will be stripped from the name
* * Email domains `@{domain}` will be stripped from the name
* * Function always assumes first name first, if input is "Last, First" or similar, consider using option { reverse: true }
*
* @example
* cb.nameToInitials("John Doe")
* -> "J.D"
* cb.nameToInitials("john.doe@bar.com", { toUpper:true })
* -> "J.D"
* cb.nameToInitials("John Doe", { separator:", ", firstLength:1, lastLength:15 })
* -> "Doe, J"
* cb.nameToInitials("Doe, John", { firstLength:1, lastLength:10, reverse:true})
* -> "J.Doe"
*/
cb.nameToInitials = function (
name,
{ separator = '.', firstLength = 1, lastLength = 1, toUpper = false, reverse = false } = {}
) {
// process name
const nameClean = name
.trim()
.replace(/@.*/, '')
.replace(/[,. ]+/, ' ');
const nameParts = nameClean.split(' ');
const nameFirst = toUpper ? cb.stringCapitalize(nameParts[0], true) : nameParts[0];
let nameLast = nameParts.length > 1 ? nameParts[nameParts.length - 1] : '';
if (toUpper) {
nameLast = cb.stringCapitalize(nameLast, true);
}
// return result
if (reverse) {
return (
(nameLast !== '' ? nameLast.substr(0, lastLength) + separator : '') + nameFirst.substr(0, firstLength)
);
}
return nameFirst.substr(0, firstLength) + (nameLast !== '' ? separator + nameLast.substr(0, lastLength) : '');
};
/* }}} = STRINGS ========================================================== */
/* {{{ = CSS STYLES ======================================================= */
/**
* Convert an assoc list of CSS styles to CSS style code.
*
* @param {Object} cssAssoc - An assoc list containing the CSS styles.
* @param {string} selector - A CSS selector.
* @retuns {string} The CSS code.
*
* @example
* cb.assocToCSS({ 'color': 'red', 'background': 'black' }, 'div.foo, span.bar')
* -> 'div.foo, span.bar { color: red; background: black; }'
*/
cb.assocToCSS = function (cssAssoc, selector) {
let result = '';
for (const key in cssAssoc) {
result += key + ': ' + cssAssoc[key] + '; ';
}
return selector === undefined || selector == '' ? result : selector + ' { ' + result + ' } ';
};
const CB_STYLE_TAG_ID = 'cb_css_styles';
/**
* Inject CSS style(s) into the page.
*
* @param {string} styles - Either a string in form of `selector { style(s); }` (one or many) or style(s) only with a single selector provided as second argument.
* @param {string} selector - A CSS selector.
*
* @example
* cb.addCSS('color: red; background: black;', 'div.foo, span.bar');
* cb.addCSS('div.foo, span.bar { color: red; background: black; }');
*/
cb.addCSS = function (cssStyles, selector) {
let styleTag = $('style#' + CB_STYLE_TAG_ID);
if (styleTag.length <= 0) {
styleTag = $('<style type="text/css" id="' + CB_STYLE_TAG_ID + '"></style>').appendTo('html > head');
}
let styles;
if (selector === undefined || selector == '') {
styles = cssStyles;
} else {
styles = selector + ' { ' + cssStyles + ' } ';
}
styleTag.text(styleTag.text() + ' ' + styles + '\n');
};
/**
* Inject a selector + CSS style(s) into the page.
*
* @param {Object} cssAssoc - An assoc list containing the CSS styles.
* @param {string} selector - A CSS selector.
*
* Example:
* cb.addCSSAssoc('div.foo, span.bar', {'color': 'red', 'background': 'black'});
*/
cb.addCSSAssoc = function (cssAssoc, selector) {
addCSS(cb.assocToCSS(cssAssoc, selector));
};
/* }}} = CSS STYLES ======================================================= */
/* {{{ = JQUERY =========================================================== */
/**
* Find all inner text-nodes.
*
* @param {$|string} jQuery - A jquery or jquery selector string.
* @returns {$} The jQuery search result.
*
* @see https://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery
*/
cb.findTextNodes = function (jQuery) {
return $(jQuery)
.find(':not(iframe)')
.addBack()
.contents()
.filter(function () {
return this.nodeType == 3;
});
};
const _findTextAddCSSClasses = []; // keep global state (don't inject repeatedly)
/**
* Adds CSS styles to all selected elements containing the given text (regex match).
*
* arrays:
* [<selector>, [i,0] - match elements
* [ [i,1] - multiple patterns per selector are supported
* [<pattern>, [i,1,j,0] - match regex pattern within the selected element's inner text
* {css}], ...j+1 [i,1,j,2] - css styles applied to all elements matching selector + pattern
* ], ...i+1
* ]
*
* @example
* # make (complete) div elements with class=foo containing text "foo bar" red
* ["div.foo"
* [[ /foo bar/i, { "color": "red" } ]]]
* -> <div class="foo">Foo <b>bar</b> baz</div>
* => <div class="foo" style="color: red;">Foo <b>bar</b> baz</div>
*/
cb.findTextAddCSS = function (arrays) {
if (arrays === undefined) return;
let cssStyleCode = '';
$.each(arrays, (i1, selectorArray) => {
if (!(Array.isArray(selectorArray) && selectorArray.length)) return;
// loop: selectors
const selector = selectorArray[0];
const patternArrays = selectorArray[1];
$.each(patternArrays, (i2, patternArray) => {
// loop: patterns
const regex = patternArray[0];
const cssStyle = patternArray[1];
const cssClass = 'findTextAddCSS_' + cb.stringHash(selector + regex);
// add css class to all elements with a matching text
$(selector)
.filter(function () {
return regex.test($(this).text());
})
.addClass(cssClass);
// append css to global css style if not yet added
if (!_findTextAddCSSClasses.includes(cssClass)) {
cssStyleCode += cb.assocToCSS(cssStyle, '.' + cssClass);
_findTextAddCSSClasses.push(cssClass);
}
});
});
// inject global css style(s) if non-empty
if (cssStyleCode != '') {
$('html > head').append('<style type="text/css">' + cssStyleCode + '</style>');
}
};
const _substituteTextWithCSSClasses = []; // keep global state (don't inject repeatedly)
/**
* Substitute texts and inject CSS styles by wrapping text in spans.
*
* arrays: a multi dimensional array in the following format
* [<selector>, [i,0] - match elements
* [ [i,1] - multiple patterns per selector are supported
* [<regexPattern>, [i,1,j,0] - match regex pattern within the selected element's inner text
* <regexSubst>, [i,1,j,1] - substitution text
* {css}], ...j+1 [i,1,j,2] - css styles applied to the substituted text
* ], ...i+1
* ]
* options: {
* fullTextMustMatch: match selected elements inner text first, default: false
* if true the processing might be more efficient (no search for individual
* text elements if inner text doesn't match) but ^ and $ may not work as
* expected since inner text could contain html.
* }
*
* Notes:
* * Any sub-element of the `<selector>` will be searched for the given regex <pattern>
* * To simplify things the regex `<pattern>` must match a single text-only node meaning html content is omitted, e.g. `/foo bar/` would not match `foo <b>bar</b>` due to it's html content, but /foo/ and /bar/ would match individually.
*
* @example
* # make all text fragments starting with "b", including all following non-space characters, red and add a "!" at the end
* ["div.foo"
* [[ /(b[^ ]+)/, "$1!", { "color": "red" } ]]]
* -> <div class="foo">Foo bar baz</div>
* => <div class="foo">Foo <span style="color: red;">bar!</span> <span style="color: red;">baz!</span></div>
* # and
* -> <div class="foo">Foo ra<b>b</b>az</div></div>
* => <div class="foo">Foo ra<b><span style="color: red;">b</span></b>az</div></div>
* # only "b" matches, not "baz" due to the intermitted "b" tags
* # text of <b> is matched, not inner text of selected div
*/
cb.substituteTextWithCSS = function (arrays, { fullTextMustMatch = false } = {}) {
if (arrays === undefined) return;
let cssStyleCode = '';
$.each(arrays, (i1, selectorArray) => {
if (!(Array.isArray(selectorArray) && selectorArray.length)) return;
// loop: selector
const selector = selectorArray[0];
const patternArrays = selectorArray[1];
$(selector).each((i2, element) => {
// loop: matching elements
$.each(patternArrays, (i3, patternArray) => {
// loop: substitutions for current selector
const regex = patternArray[0];
// check if the inner text of the whole selection matches
if (fullTextMustMatch && !regex.test($(element).text())) {
return; // no match, skip this iteration
}
// text content does match
const regexSubst = patternArray[1];
const cssStyle = patternArray[2];
const cssClass = 'substituteTextWithCSS_' + cb.stringHash(selector + regex);
const spanHTML = '<span class="' + cssClass + '">' + regexSubst + '</span>';
// replace text node with substitution wrapped in span
cb.findTextNodes($(element)).each((i4, e) => {
// replace only if parent is not already span with same class
// (from earlier execution), we don't want to add additional
// spans with every repeated execution
if (!$(e).parent().hasClass(cssClass)) {
$(e).replaceWith($(e).text().replace(regex, spanHTML));
}
});
// append css to global css style if not yet added
if (!_substituteTextWithCSSClasses.includes(cssClass)) {
cssStyleCode += cb.assocToCSS(cssStyle, 'span.' + cssClass);
_substituteTextWithCSSClasses.push(cssClass);
}
});
});
});
// inject global css style(s) if non-empty
if (cssStyleCode != '') {
$('html > head').append('<style type="text/css">' + cssStyleCode + '</style>');
}
};
/* }}} = JQUERY =========================================================== */
/* {{{ = EVENTS =========================================================== */
/* {{{ - KEY EVENTS ------------------------------------------------------- */
/**
* Check if key event would affect focused input field / editable content.
*
* Should be tested at least for key bindings that use no mod / shift only.
*
* @param {Event} e - A key event.
* @returns {boolean} Are we in an input context?
*/
function _isKeyEventEditableContent(e) {
return $(e.target).is(':input, [contenteditable]');
}
/**
* Create a new key binding.
*
* @example $(document).keydown(e => _bindKey(e, (70, myFind, { mods: { ctrl:true }, preventDefault:true }))
* @example $(document).keydown(e => _bindKey(e, (70, myFind, { skipEditable:true }))
*
* @param { number } keyCode - A key code.
* @param { Function } f - The function to call when key binding is pressed.
* @param { Object } obj - An object.
* @param { Object } obj.mods - Mod keys state wrapper object.
* @param { boolean } [obj.mods.shift=false] - Must the`shift` key be pressed?
* @param { boolean } [obj.mods.alt=false] - Must the`alt` key be pressed?
* @param { boolean } [obj.mods.meta=false] - Must the`meta` key be pressed?
* @param { boolean } [obj.mods.ctrl=false] - Must the`control` key be pressed?
* @param { boolean } [preventDefault=false] - Prevent`key` binding default action?
* @param { boolean } [skipEditable=false] - Skip key event in editable context?
* @returns { any } Result of`f` function call.
*/
function _bindKey(
e,
keyCode,
f,
{
mods: { shift = false, alt = false, meta = false, ctrl = false } = {},
skipEditable = false,
preventDefault = false,
} = {}
) {
const event = e || window.event;
if (skipEditable && _isKeyEventEditableContent(event)) {
return; // skip, we seem to be in an input field / editable content
}
function _required(m) {
return m !== undefined && m;
}
function _notRequired(m) {
return m === undefined || !m;
}
// keyCode pressed?
if ((event.keyCode || event.which) != keyCode) return;
// any meta key expected but not pressed OR not expected but pressed? -> return
if ((_required(shift) && !event.shiftKey) || (_notRequired(shift) && event.shiftKey)) return;
if ((_required(ctrl) && !event.ctrlKey) || (_notRequired(ctrl) && event.ctrlKey)) return;
if ((_required(alt) && !event.altKey) || (_notRequired(alt) && event.altKey)) return;
if ((_required(meta) && !event.metaKey) || (_notRequired(meta) && event.metaKey)) return;
// prevent key binding default action
if (preventDefault) {
// still here? skip subsequent events (normally triggerd by the page)
event.cancelBubble = true;
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
}
// call the function
return f(event);
}
/**
* Register a new `keyDown` key binding.
*
* @example cb.bindKeyDown(70, myFind, { mods: { ctrl:true }, preventDefault:true })
* @example cb.bindKeyDown(70, myFind, { skipEditable:true })
*
* @param { number } keyCode - A key code.
* @param { Function } f - The function to call when key binding is pressed.
* @param { Object } obj - An object.
* @param { Object } obj.mods - Mod keys state wrapper object.
* @param { boolean } [obj.mods.shift=false] - Must the`shift` key be pressed?
* @param { boolean } [obj.mods.alt=false] - Must the`alt` key be pressed?
* @param { boolean } [obj.mods.meta=false] - Must the`meta` key be pressed?
* @param { boolean } [obj.mods.ctrl=false] - Must the`control` key be pressed?
* @param { boolean } [preventDefault=false] - Prevent`key` binding default action?
* @param { boolean } [skipEditable=false] - Skip key event in editable context?
* @returns { any } Result of`f` function call.
*/
cb.bindKeyDown = function (
keyCode,
f,
{
mods: { shift = false, alt = false, meta = false, ctrl = false } = {},
skipEditable = false,
preventDefault = false,
} = {}
) {
$(document).keydown((e) =>
_bindKey(e, keyCode, f, { mods: { shift, alt, meta, ctrl }, skipEditable, preventDefault })
);
};
/**
* Register a new `keyUp` key binding.
*
* @example cb.bindKeyUp(70, myFind, { mods: { ctrl:true }, preventDefault:true })
* @example cb.bindKeyUp(70, myFind, { skipEditable:true })
*
* @param { number } keyCode - A key code.
* @param { Function } f - The function to call when key binding is pressed.
* @param { Object } obj - An object.
* @param { Object } obj.mods - Mod keys state wrapper object.
* @param { boolean } [obj.mods.shift=false] - Must the`shift` key be pressed?
* @param { boolean } [obj.mods.alt=false] - Must the`alt` key be pressed?
* @param { boolean } [obj.mods.meta=false] - Must the`meta` key be pressed?
* @param { boolean } [obj.mods.ctrl=false] - Must the`control` key be pressed?
* @param { boolean } [preventDefault=false] - Prevent`key` binding default action?
* @param { boolean } [skipEditable=false] - Skip key event in editable context?
* @returns { any } Result of`f` function call.
*/
//{foo = 'Foo', bar: {quux = 'Quux', corge = 'Corge'} = {}}
cb.bindKeyUp = function (
keyCode,
f,
{
mods: { shift = false, alt = false, meta = false, ctrl = false } = {},
skipEditable = false,
preventDefault = false,
} = {}
) {
$(document).keyup((e) =>
_bindKey(e, keyCode, f, { mods: { shift, alt, meta, ctrl }, skipEditable, preventDefault })
);
};
/* }}} - KEY EVENTS ------------------------------------------------------- */
/* {{{ - MOUSE EVENTS ----------------------------------------------------- */
let cbMouseX = 0;
let cbMouseY = 0;
/**
* Constantly track the mouse poiter position (private).
*/
$('body').mousemove((event) => {
cbMouseX = event.pageX - document.body.scrollLeft;
cbMouseY = event.pageY - document.body.scrollTop;
});
// click element(s) n-times (default: 1)
cb.clickElement = function (query, times = 1) {
// recursive click function
function _clickItRec(e, i) {
e.click();
if (i === undefined || i <= 1) {
return; // stop it
} else {
_clickItRec(e, i - 1); // recursive call
}
}
// click element(s) n-times
$(query).each((i, e) => _clickItRec($(e), times)); // click
};
/* }}} - MOUSE EVENTS ----------------------------------------------------- */
/* {{{ - WAIT FOR ELEMENT ------------------------------------------------- */
/**
* Wait for element(s) to appear then call `f` using `_.throttle`.
*
* @param {$} jQuery - A JQuery.
* @param {Function} f - The function to call in case the element appears.
* @param {number} wait - Throttle time interval in ms.
* @param {Object} options - An Object.
* @param {boolean} [options.leading=false] - Disable execution on the leading edge.
* @param {boolean} [options.trailing=false] - Disable execution on the trailing edge.
*/
cb.waitAndThrottle = function (jQuery, f, wait = 200, options = {}) {
waitForKeyElements(jQuery, _.throttle(f, wait, options));
};
/**
* Wait for element(s) to appear then call `f` using `_.debounce`.
*
* @param {$} jQuery - A JQuery.
* @param {Function} f - The function to call in case the element appears.
* @param {number} wait - Throttle time interval in ms.
* @param {Object} options - An Object.
*/
cb.waitAndDebounce = function (jQuery, f, wait = 200, immediate = false) {
waitForKeyElements(jQuery, _.debounce(f, wait, immediate));
};
/* }}} - WAIT FOR ELEMENT ------------------------------------------------- */
/* }}} = EVENTS =========================================================== */
/* {{{ = COMPONENTS ======================================================= */
/* {{{ - TOOL-TIP --------------------------------------------------------- */
let _cbcreateTTStyleInjected = false;
let _cbcreateTTLastTT;
/**
* Create a tooltip at the given absolution or relative mouse pointer position.
*
* @param {string} html - Tooltip html / text.
* @param {number} timeout - Timeout in ms after which the tootlip should vanish. A value <= 0 disables the timeout (stays indefinitely).
* @param {Object} obj - An Object.
* @param {number} [offsetX=10] - The tooltip's `x` absolute position or mouse pointer position offset in pixels.
* @param {number} [offsetY=10] - The tooltip's `y` absolute position or mouse pointer position offset in pixels.
* @param {number} [offsetMouse=true] - If enabled the tooltip's `x`/`y` offset is relative to the mouse pointer, else it is treated as absolution position.
* @param {number} [fadeoutTime=1000] - Fade out time in ms. A value <= 0 disables the fade out effect.
* @param {Object} css - Set additional css styles within the tooltip div element.
* @param {string} [cssClass=cb_createTT] - Set a css class for the tooltip `<div>`. Changing the class will remove the default style, except for element styles like positioning, click-through and cursor style.
* @returns {$} The tooltip's `<div>` (jQuery object)
*
* When a tooltip is created, a potentially existing predecessor is removed.
*
* @example cb.createTT('TEST', 3000, { offsetX: 50, offsetY: 50 }});
* @example cb.createTT('TEST', { offsetMouse: true });
*/
cb.createTT = function (
html,
timeout,
{ offsetX = 10, offsetY = 10, offsetMouse = true, fadeoutTime = 1000, css = {}, cssClass = 'cb_createTT' } = {}
) {
// parse arguments
const timeout_ms = cb.nvl(timeout, -1);
// inject default style, if not already done and no custom class is set
if (cssClass == 'cb_createTT' && !_cbcreateTTStyleInjected) {
createTTAddDefaultStyle();
_cbcreateTTStyleInjected = true;
}
const posLeft = (offsetMouse ? cbMouseX : 0) + offsetX;
const posTop = (offsetMouse ? cbMouseY : 0) + offsetY;
// create tt div
const div = $('<div class="cb_createTT">' + html + '</div>');
div.css({
position: 'absolute',
display: 'block',
'z-index': 9999,
left: posLeft,
top: posTop,
cursor: 'default',
pointer_events: 'none',
});
div.css(css);
// show tt and keep it locked to mouse pointer position
if (offsetMouse) {
function _tomouse() {
div.css({ left: posLeft, top: posTop });
}
$('body').mousemove(_tomouse);
}
// delete previous tooltip (if still existing)
if (_cbcreateTTLastTT !== undefined && _cbcreateTTLastTT.length > 0) {
_cbcreateTTLastTT.remove();
}
div.appendTo('body'); // show it
_cbcreateTTLastTT = div;
// create auto hide time (if timeout > 0)
if (timeout_ms > 0) {
setTimeout(() => div.fadeOut(fadeoutTime, () => div.remove()), timeout_ms);
}
return div;
};
/**
* @depreacted Use cb.createTT with mouse=true instead
* @see cb.createTT
*/
cb.createMouseTT = function (
html,
timeout,
{ offsetX = 10, offsetY = 10, fadeoutTime = 1000, cssClass = 'cb_createTT' } = {}
) {
return cb.createTT(html, timeout, { offsetX, offsetY, offsetMouse: true, fadeoutTime, cssClass });
};
/**
* Inject the default tooltip style.
*/
function createTTAddDefaultStyle() {
cb.addCSS(`div.cb_createTT {
font-family: Arial, Helvetica, sans-serif;
font-size: 11px; /* 0.85em; */
font-weight: bold;
background-color: black;
color: #fff;
text-align: center;
padding: 4px 8px; /* 0.2em 0.4em; */
border-radius: 6px;
/* always on top */
z-index: 999999;
}`);
}
/* }}} - TOOL-TIP --------------------------------------------------------- */
/* }}} = COMPONENTS ======================================================= */
})((window.cb = window.cb || {}), jQuery, _);