svelte-ux
Version:
- Increment version in `package.json` and commit as `Version bump to x.y.z` - `npm run publish`
62 lines (61 loc) • 1.97 kB
JavaScript
/**
* Apply changes to an HTMLElement with the ability to reverse.
* Useful with Svelte actions when being destroyed
*/
export default class DomTracker {
constructor(node) {
this.node = node;
this.changes = {
classes: [],
styles: [],
attributes: [],
eventListeners: [],
actions: [],
};
}
addClass(className) {
this.node.classList.add(className);
this.changes.classes.push(className);
}
addStyle(property, value) {
this.node.style.setProperty(property, value);
this.changes.styles.push({ property, value });
}
addAttribute(qualifiedName, value) {
this.node.setAttribute(qualifiedName, value);
this.changes.attributes.push({ qualifiedName, value });
}
addEventListener(type, listener) {
this.node.addEventListener(type, listener);
this.changes.eventListeners.push({ type, listener });
}
addAction(action) {
// Action added in creation
this.changes.actions.push(action);
}
reset() {
this.changes.classes.forEach((className) => {
this.node.classList.remove(className);
});
this.changes.styles.forEach(({ property, value }) => {
this.node.style.removeProperty(property);
});
this.changes.attributes.forEach(({ qualifiedName, value }) => {
this.node.removeAttribute(qualifiedName);
});
this.changes.eventListeners.forEach(({ type, listener }) => {
this.node.removeEventListener(type, listener);
});
this.changes.actions.forEach((action) => {
var _a;
(_a = action.destroy) === null || _a === void 0 ? void 0 : _a.call(action);
});
this.changes = {
classes: [],
styles: [],
attributes: [],
eventListeners: [],
actions: [],
};
}
}