-
Notifications
You must be signed in to change notification settings - Fork 0
/
Component.ts
82 lines (55 loc) · 2.17 KB
/
Component.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
80
81
82
import DOMElement from "./DOMElement.js";
export default class Component extends DOMElement {
public readonly children: Array<DOMElement> = [];
constructor ( element?: Element, attributes: { [ name: string ]: string } = {} ) {
super( element, attributes );
for ( let i = 0; i < this.element.children.length; i++ )
this.children.push( DOMElement.wrap( this.element.children[ i ] ) );
}
get firstChild () {
return this.children[ 0 ];
}
add<T extends DOMElement> ( child: T ) {
this.children.push( child );
this.element.appendChild( child.element );
}
contains<T extends DOMElement> ( child: T ): boolean {
return this.element.contains( child.element );
}
remove<T extends DOMElement> ( oldChild?: T ) {
if ( arguments.length === 0 ) {
if ( this.element.parentElement != null && this.element.parentElement.contains( this.element ) )
this.element.parentElement.removeChild( this.element );
} else {
if ( this.element.contains( oldChild.element ) ) {
this.element.removeChild( oldChild.element );
let index = this.children.indexOf( oldChild );
if ( index != -1 )
this.children.splice( index, 1 );
}
}
}
setAttribute ( qualifiedName: string, value: string ): void {
this.element.setAttribute( qualifiedName, value );
}
replaceChild<T extends Component> ( newChild: T, oldChild: T ) {
this.element.replaceChild( newChild.element, oldChild.element );
}
find ( filter: ( component: Component ) => boolean, deep: boolean | number ) {
let results = [];
if ( filter( this ) )
results.push( this );
if ( deep == false || deep == 0 )
return results;
( <number>deep )--;
this.children.forEach( child => {
if ( child instanceof Component )
results = results.concat( child.find( filter, deep ) );
} );
return results;
}
clear () {
while ( this.firstChild )
this.remove( this.firstChild );
}
}