@stimulus-library/controllers
Version:
A library of useful controllers for Stimulus
42 lines (41 loc) • 1.47 kB
JavaScript
import { installClassMethods, useMutationObserver } from "@stimulus-library/mixins";
import { BaseController } from "@stimulus-library/utilities";
export class EmptyDomController extends BaseController {
get _container() {
return this.hasContainerTarget ? this.containerTarget : this.el;
}
get _children() {
const element = this._container;
if (this.hasScopeSelectorValue) {
return Array.from(element.querySelectorAll(this.scopeSelectorValue));
}
else {
return Array.from(element.children);
}
}
connect() {
installClassMethods(this);
useMutationObserver(this, this._container, this.mutate, { childList: true });
this.checkEmpty();
}
mutate(_entries) {
this.checkEmpty();
}
checkEmpty() {
const element = this._container;
const children = this._children;
if (children.length === 0) {
this.removeNotEmptyClasses();
this.addEmptyClasses();
this.dispatchEvent(element, this.eventName("empty"));
}
else {
this.addNotEmptyClasses();
this.removeEmptyClasses();
this.dispatchEvent(element, this.eventName("not-empty"), { detail: { count: children.length } });
}
}
}
EmptyDomController.targets = ["container"];
EmptyDomController.classes = ["empty", "notEmpty"];
EmptyDomController.values = { scopeSelector: String };