Merge pull request #244 from JsSucks/builtin-base

Builtin base
This commit is contained in:
Alexei Stukov 2018-08-23 22:57:55 +03:00 committed by GitHub
commit 22ea3ff2ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 68 additions and 5 deletions

View File

@ -9,6 +9,8 @@
*/
import { Settings } from 'modules';
import { Patcher, MonkeyPatch as Patch, Cache } from 'modules';
import { ClientLogger as Logger } from 'common';
export default class BuiltinModule {
@ -16,21 +18,82 @@ export default class BuiltinModule {
this._settingUpdated = this._settingUpdated.bind(this);
if (this.enabled) this.enabled = this.enabled.bind(this);
if (this.disabled) this.disabled = this.disabled.bind(this);
if (this.applyPatches) this.applyPatches = this.applyPatches.bind(this);
this.patch = this.patch.bind(this);
}
init() {
this.setting.on('setting-updated', this._settingUpdated);
if (this.setting.value && this.enabled) this.enabled();
if (this.setting.value) {
if (this.enabled) this.enabled();
if (this.applyPatches) this.applyPatches();
}
}
get setting() {
return Settings.getSetting(...this.settingPath);
}
_settingUpdated(e) {
const { value } = e;
if (value === true && this.enabled) this.enabled(e);
if (value === false && this.disabled) this.disabled(e);
get patches() {
return Patcher.getPatchesByCaller(`BD:${this.moduleName}`);
}
_settingUpdated(e) {
const { value } = e;
if (value === true) {
if (this.enabled) this.enabled(e);
if (this.applyPatches) this.applyPatches();
return;
}
if (value === false) {
if (this.disabled) this.disabled(e);
this.unpatch();
}
}
get cache() {
return {
push: data => Cache.push(this.moduleName, data),
find: filter => Cache.find(this.moduleName, filter)
}
}
/**
* By default unpatch everything.
* Override to do something else.
*/
unpatch() {
Patcher.unpatchAll(`BD:${this.moduleName}`);
}
/**
* Patch a function in a module
* @param {any} module Module to patch
* @param {String} fnName Name of the function to patch
* @param {Function} cb Callback
* @param {String} [when=after] before|after|instead
*/
patch(module, fnName, cb, when = 'after') {
if (!['before', 'after', 'instead'].includes(when)) when = 'after';
Patch(`BD:${this.moduleName}`, module)[when](fnName, cb.bind(this));
}
/**
* Logger wraps
*/
log(message) {
Logger.log(this.moduleName, message);
}
warn(message) {
Logger.warn(this.moduleName, message);
}
info(message) {
Logger.warn(this.moduleName, message);
}
debug(message) {
Logger.dbg(this.moduleName, message);
}
}