ActivatableMixin.ts
82 lines
| 2.5 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r13 | import { IActivationController, IActivatable, ICancellation } from '../interfaces'; | |
|
|
r9 | import { AsyncComponent } from './AsyncComponent'; | |
|
|
r13 | import { Cancellation } from '../Cancellation'; | |
|
|
r22 | import { TraceSource } from '../log/TraceSource'; | |
|
|
r9 | ||
| type Constructor<T = {}> = new (...args: any[]) => T; | |||
|
|
r11 | const log = TraceSource.get('@implab/core/components/ActivatableMixin'); | |
|
|
r22 | export function ActivatableMixin<TBase extends Constructor<AsyncComponent>>(Base: TBase) { | |
|
|
r9 | return class extends Base implements IActivatable { | |
| _controller: IActivationController; | |||
| _active: boolean; | |||
| isActive() { | |||
| return this._active; | |||
| } | |||
| getActivationController() { | |||
| return this._controller; | |||
| } | |||
| setActivationController(controller: IActivationController) { | |||
| this._controller = controller; | |||
| } | |||
| async onActivating(ct: ICancellation) { | |||
| if (this._controller) | |||
| await this._controller.activating(this, ct); | |||
| } | |||
| async onActivated(ct: ICancellation) { | |||
| if (this._controller) | |||
| await this._controller.activated(this, ct); | |||
| } | |||
|
|
r13 | activate(ct: ICancellation = Cancellation.none) { | |
| return this.runOperation(this._activateAsync.bind(this), ct); | |||
| } | |||
| async _activateAsync(ct: ICancellation) { | |||
|
|
r9 | if (this.isActive()) | |
| return; | |||
|
|
r13 | ||
| await this.onActivating(ct); | |||
| this._active = true; | |||
|
|
r9 | try { | |
|
|
r13 | await this.onActivated(ct); | |
|
|
r9 | } catch (e) { | |
|
|
r13 | log.error("Suppressed onActivated error: {0}", e); | |
|
|
r9 | } | |
| } | |||
| async onDeactivating(ct: ICancellation) { | |||
| if (this._controller) | |||
| await this._controller.deactivating(this, ct); | |||
| } | |||
| async onDeactivated(ct: ICancellation) { | |||
| if (this._controller) | |||
| await this._controller.deactivated(this, ct); | |||
| } | |||
|
|
r13 | deactivate(ct: ICancellation = Cancellation.none) { | |
| return this.runOperation(this._deactivateAsync.bind(this), ct); | |||
| } | |||
| async _deactivateAsync(ct: ICancellation) { | |||
|
|
r9 | if (!this.isActive()) | |
| return; | |||
|
|
r13 | await this.onDeactivating(ct); | |
| this._active = false; | |||
|
|
r9 | try { | |
|
|
r13 | await this.onDeactivated(ct); | |
|
|
r9 | } catch (e) { | |
|
|
r13 | log.error("Suppressed onDeactivated error: {0}", e); | |
|
|
r9 | } | |
| } | |||
| } | |||
| } | |||
|
|
r22 | export const traceSource = log; |
