From 76730d38d4f839f47c5adc4d3b4852070251aab1 Mon Sep 17 00:00:00 2001 From: Jiiks Date: Wed, 31 Jan 2018 15:35:22 +0200 Subject: [PATCH] add dom observer --- client/src/index.js | 2 +- client/src/ui/dom.js | 55 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/client/src/index.js b/client/src/index.js index d43150ea..060eb804 100644 --- a/client/src/index.js +++ b/client/src/index.js @@ -14,8 +14,8 @@ import { Events, CssEditor, Globals, PluginManager, ThemeManager } from 'modules import { ClientLogger as Logger } from 'common'; class BetterDiscord { + constructor() { - window.pom = PluginManager; DOM.injectStyle(BdCss, 'bdmain'); Events.on('global-ready', this.globalReady.bind(this)); } diff --git a/client/src/ui/dom.js b/client/src/ui/dom.js index f7e09916..330ca962 100644 --- a/client/src/ui/dom.js +++ b/client/src/ui/dom.js @@ -30,8 +30,63 @@ class BdNode { } } +class DOMObserver { + + constructor() { + this.observe = this.observe.bind(this); + this.subscribe = this.subscribe.bind(this); + this.observerCallback = this.observerCallback.bind(this); + this.observer = new MutationObserver(this.observerCallback); + } + + observerCallback(mutations) { + this.subscriptions.forEach(sub => { + try { + const f = mutations.find(sub.filter); + if (f) sub.callback(f); + } catch (err) { } + }); + } + + observe() { + this.observer.observe(this.root, this.options); + } + + get root() { + return document.getElementById('app-mount'); + } + + get options() { + return { attributes: true, childList: true, subtree: true }; + } + + get subscriptions() { + return this._subscriptions || (this._subscriptions = []); + } + + subscribe(id, filter, callback) { + if (this.subscriptions.find(sub => sub.id === id)) return; + this.subscriptions.push({ + id, + filter, + callback + }); + } + + unsubscribe(id) { + const index = this.subscriptions.find(sub => sub.id === id); + if (index < 0) return; + this.subscriptions.splice(index, 1); + } + +} + class DOM { + static get observer() { + return this._observer || (this._observer = new DOMObserver()); + } + static get bdHead() { return this.getElement('bd-head') || this.createElement('bd-head').appendTo('head'); }