component.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { shallowMergeArray } from '../mol-util/object';
  7. import { RxEventHelper } from '../mol-util/rx-event-helper';
  8. import { Subscription, Observable } from 'rxjs';
  9. import { arraySetRemove } from '../mol-util/array';
  10. export class PluginComponent {
  11. private _ev: RxEventHelper | undefined;
  12. private subs: Subscription[] | undefined = void 0;
  13. protected subscribe<T>(obs: Observable<T>, action: (v: T) => void) {
  14. if (typeof this.subs === 'undefined') this.subs = [];
  15. let sub: Subscription | undefined = obs.subscribe(action);
  16. this.subs.push(sub);
  17. return {
  18. unsubscribe: () => {
  19. if (sub && this.subs && arraySetRemove(this.subs, sub)) {
  20. sub.unsubscribe();
  21. sub = void 0;
  22. }
  23. }
  24. };
  25. }
  26. protected get ev() {
  27. return this._ev || (this._ev = RxEventHelper.create());
  28. }
  29. dispose() {
  30. if (this._ev) this._ev.dispose();
  31. if (this.subs) {
  32. for (const s of this.subs) s.unsubscribe();
  33. this.subs = void 0;
  34. }
  35. }
  36. }
  37. export class StatefulPluginComponent<State> extends PluginComponent {
  38. private _state: State;
  39. protected updateState(...states: Partial<State>[]): boolean {
  40. const latest = this.state;
  41. const s = shallowMergeArray(latest, states);
  42. if (s !== latest) {
  43. this._state = s;
  44. return true;
  45. }
  46. return false;
  47. }
  48. get state() {
  49. return this._state;
  50. }
  51. constructor(initialState: State) {
  52. super();
  53. this._state = initialState;
  54. }
  55. }