From 592fc8dd586255e719a31785d3989a348f63cce8 Mon Sep 17 00:00:00 2001
From: Ali Mihandoost <ali.mihandoost@gmail.com>
Date: Thu, 9 Mar 2023 00:51:12 +0330
Subject: [PATCH] feat(element/fsm): rewrite state machine for lit

---
 .../finite-state-machine.ts                   | 36 +++++++------------
 1 file changed, 13 insertions(+), 23 deletions(-)

diff --git a/ui/element/src/reactive-controllers/finite-state-machine.ts b/ui/element/src/reactive-controllers/finite-state-machine.ts
index ed6d44eda..1fc9389f2 100644
--- a/ui/element/src/reactive-controllers/finite-state-machine.ts
+++ b/ui/element/src/reactive-controllers/finite-state-machine.ts
@@ -1,41 +1,26 @@
-import {FiniteStateMachine, type StateContext, type MachineConfig} from '@alwatr/fsm';
+import {FiniteStateMachine, type FsmConfig} from '@alwatr/fsm';
 
-import {nothing, ReactiveController} from '../lit.js';
+import {nothing, type ReactiveController} from '../lit.js';
 
 import type {LoggerMixinInterface} from '../mixins/logging.js';
 import type {StringifyableRecord} from '@alwatr/type';
 
-export declare class AlwatrElementHostController<
-  TState extends string,
-  TEventId extends string
-> extends LoggerMixinInterface {
-  stateUpdate(state: StateContext<TState, TEventId>): void;
-}
-
 export class FiniteStateMachineController<
     TState extends string,
     TEventId extends string,
     TContext extends StringifyableRecord
-  >
-  extends FiniteStateMachine<TState, TEventId, TContext>
-  implements ReactiveController {
+  > extends FiniteStateMachine<TState, TEventId, TContext> implements ReactiveController {
   constructor(
-    private _host: AlwatrElementHostController<TState, TEventId>,
-    config: Readonly<MachineConfig<TState, TEventId, TContext>>,
+    private _host: LoggerMixinInterface,
+    config: Readonly<FsmConfig<TState, TEventId, TContext>>,
   ) {
     super(config);
-    this._logger.logMethodArgs('constructor', config);
     this._host.addController(this);
   }
 
-  protected override setState(to: TState, by: TEventId | 'INIT' ): void {
-    super.setState(to, by);
-    this._host.stateUpdate.call(this._host, this.state);
-  }
-
   render(states: {[P in TState]?: (() => unknown) | TState}): unknown {
-    this._logger.logMethodArgs('render', this.state.to);
-    let renderFn = states[this.state.to];
+    this._logger.logMethodArgs('render', this.state.target);
+    let renderFn = states[this.state.target];
     if (typeof renderFn === 'string') {
       renderFn = states[<TState>renderFn];
     }
@@ -47,6 +32,11 @@ export class FiniteStateMachineController<
   }
 
   hostUpdate(): void {
-    this._host.setAttribute('state', this.state.to);
+    this._host.setAttribute('state', this.state.target);
+  }
+
+  protected override callFunction<T>(fn?: () => T): T | void {
+    if (typeof fn !== 'function') return;
+    return fn.call(this._host);
   }
 }