-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathlight-dom-controller.ts
64 lines (55 loc) · 1.55 KB
/
light-dom-controller.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
import { isServer, type ReactiveController, type ReactiveElement } from 'lit';
import { Logger } from './logger.js';
export interface Options {
observe?: boolean | MutationObserverInit;
emptyWarning?: string;
}
export class LightDOMController implements ReactiveController {
private mo: MutationObserver;
private logger: Logger;
private initializer: () => void;
constructor(
private host: ReactiveElement,
initializer: () => void,
private options?: Options | undefined,
) {
this.initializer = initializer.bind(host);
this.mo = new MutationObserver(this.initializer);
this.logger = new Logger(this.host);
host.addController(this);
}
hostConnected(): void {
if (this.hasLightDOM()) {
this.initializer();
} else if (this.options?.emptyWarning) {
this.logger.warn(this.options?.emptyWarning);
}
this.initObserver();
}
hostDisconnected(): void {
this.mo.disconnect();
}
private initObserver() {
if (this.options?.observe ?? true) {
// Use the provided options, or their defaults
this.mo.observe(
this.host,
typeof this.options?.observe !== 'object' ? { childList: true }
: this.options?.observe as MutationObserverInit
);
}
}
/**
* Returns a boolean statement of whether or not this component contains any light DOM.
*/
hasLightDOM(): boolean {
if (isServer) {
return false;
} else {
return !!(
this.host.children.length > 0
|| (this.host.textContent ?? '').trim().length > 0
);
}
}
}