forked from ng-bootstrap/ng-bootstrap
/
util.ts
79 lines (64 loc) · 2.05 KB
/
util.ts
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
export function toInteger(value: any): number {
return parseInt(`${value}`, 10);
}
export function toString(value: any): string {
return (value !== undefined && value !== null) ? `${value}` : '';
}
export function getValueInRange(value: number, max: number, min = 0): number {
return Math.max(Math.min(value, max), min);
}
export function isString(value: any): value is string {
return typeof value === 'string';
}
export function isNumber(value: any): value is number {
return !isNaN(toInteger(value));
}
export function isInteger(value: any): value is number {
return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
}
export function isDefined(value: any): boolean {
return value !== undefined && value !== null;
}
export function padNumber(value: number) {
if (isNumber(value)) {
return `0${value}`.slice(-2);
} else {
return '';
}
}
export function isFocusable(element: any) {
return element instanceof HTMLElement && element['focus'];
}
export function regExpEscape(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
export function hasClassName(element: any, className: string): boolean {
return element && element.className && element.className.split &&
element.className.split(/\s+/).indexOf(className) >= 0;
}
if (typeof Element !== 'undefined' && !Element.prototype.closest) {
// Polyfill for ie10+
if (!Element.prototype.matches) {
// IE uses the non-standard name: msMatchesSelector
Element.prototype.matches = (Element.prototype as any).msMatchesSelector || Element.prototype.webkitMatchesSelector;
}
Element.prototype.closest = function(s: string) {
let el = this;
if (!document.documentElement.contains(el)) {
return null;
}
do {
if (el.matches(s)) {
return el;
}
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
};
}
export function closest(element: HTMLElement, selector): HTMLElement {
if (!selector) {
return null;
}
return element.closest(selector);
}