Skip to content

Commit 3dd8fc8

Browse files
committed
create NodeComponent class
1 parent 0a5917f commit 3dd8fc8

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

src/NodeComponent.ts

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* Copyright © 2024 Cloudnode OÜ
3+
*
4+
* This file is part of @cldn/components.
5+
*
6+
* \@cldn/components is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser
7+
* General Public License as published by the Free Software Foundation, either version 3 of the License,
8+
* or (at your option) any later version.
9+
*
10+
* \@cldn/components is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
11+
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12+
* for more details.
13+
*
14+
* You should have received a copy of the GNU Lesser General Public License along with @cldn/components.
15+
* If not, see <https://www.gnu.org/licenses/>.
16+
*/
17+
18+
/**
19+
* A {@link !Node} component
20+
* @typeParam T Node type
21+
*/
22+
export abstract class NodeComponent<T extends Node> {
23+
/**
24+
* This component's node
25+
*/
26+
public readonly node: T;
27+
28+
/**
29+
* @param node Initial node for this component
30+
* @protected
31+
*/
32+
protected constructor(node: T) {
33+
this.node = node;
34+
}
35+
36+
/**
37+
* Insert component after the last child
38+
*/
39+
public append(...components: NodeComponent<any>[]) {
40+
components.forEach((component) => this.node.appendChild(component.node))
41+
return this;
42+
}
43+
44+
/**
45+
* Set text content
46+
*/
47+
public text(text: string) {
48+
this.node.textContent = text;
49+
return this;
50+
}
51+
52+
/**
53+
* Add event listener
54+
* @param type
55+
* @param listener
56+
* @param options
57+
*/
58+
public on(type: string, listener: (ev: Event, component: this) => any, options?: boolean | AddEventListenerOptions) {
59+
this.node.addEventListener(type, e => listener(e, this), options);
60+
return this;
61+
}
62+
}

0 commit comments

Comments
 (0)