### Install Dependencies Source: https://github.com/tfcp68/yantrix/blob/main/docs/examples/100_redux.md After navigating to the example folder, run this command to install all necessary project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Run Development Mode Source: https://github.com/tfcp68/yantrix/blob/main/examples/01-traffic-light/README.md Start the development server to view the example locally. ```bash pnpm dev // Check out the example at http://localhost:5173 ``` -------------------------------- ### Project Installation and Execution Commands Source: https://github.com/tfcp68/yantrix/blob/main/docs/examples/110_react.md Commands to clone, install, generate code, and run the traffic light example project. ```bash git clone https://github.com/tfcp68/yantrix.git ``` ```bash cd yantrix cd examples cd 02-traffic-light-react ``` ```bash pnpm install ``` ```bash yantrix codegen ./src/diagrams/traffic-light.mermaid -l TypeScript -o src/generated/TrafficLightAutomata.ts -c TrafficLightAutomata ``` ```bash pnpm dev ``` ```bash pnpm build ``` -------------------------------- ### Navigate to Traffic Light Example Source: https://github.com/tfcp68/yantrix/blob/main/examples/02-traffic-light-react/README.md Navigate into the cloned Yantrix repository and specifically into the traffic light React example directory. This prepares the environment for dependency installation. ```bash cd yantrix cd examples cd 02-traffic-light-react ``` -------------------------------- ### Navigate to Example Directory Source: https://github.com/tfcp68/yantrix/blob/main/examples/01-traffic-light/README.md Commands to access the specific traffic light example folder. ```bash cd yantrix cd examples cd 01-traffic-light ``` -------------------------------- ### Install @yantrix/codegen Package Source: https://github.com/tfcp68/yantrix/blob/main/packages/codegen/README.md Install the primary package using npm, Yarn, or pnpm. All secondary dependencies will be installed automatically. pnpm is suggested. ```bash # Via NPM $ npm install @yantrix/codegen # Via Yarn $ yarn add @yantrix/codegen # Via PNPM $ pnpm install @yantrix/codegen # ✨ Auto-detection $ npx nypm install @yantrix/codegen ``` -------------------------------- ### Install dependencies Source: https://github.com/tfcp68/yantrix/blob/main/docs/contributing/index.md Installs project dependencies using a frozen lockfile to ensure consistency. ```bash pnpm install --frozen-lockfile ``` -------------------------------- ### Install @yantrix/core Source: https://github.com/tfcp68/yantrix/blob/main/packages/core/README.md Use these commands to install the core package via your preferred package manager. ```bash # Via NPM $ npm install @yantrix/core # Via Yarn $ yarn add @yantrix/core # Via PNPM $ pnpm install @yantrix/core # ✨ Auto-detection $ npx nypm install @yantrix/core ``` -------------------------------- ### Install @yantrix/automata via NPM Source: https://github.com/tfcp68/yantrix/blob/main/packages/automata/README.md Install the primary package using NPM. Secondary dependencies will be installed automatically. ```bash npm install @yantrix/automata ``` -------------------------------- ### Install Yantrix CLI and Codegen Source: https://github.com/tfcp68/yantrix/blob/main/packages/cli/README.md Install @yantrix/codegen and @yantrix/cli using your preferred package manager. Secondary dependencies are installed automatically. ```bash # Via NPM $ npm install @yantrix/codegen @yantrix/cli ``` ```bash # Via Yarn $ yarn add @yantrix/codegen @yantrix/cli ``` ```bash # Via PNPM $ pnpm install @yantrix/codegen @yantrix/cli ``` ```bash # ✨ Auto-detection $ npx nypm install @yantrix/codegen @yantrix/cli ``` -------------------------------- ### Install @yantrix/automata via PNPM Source: https://github.com/tfcp68/yantrix/blob/main/packages/automata/README.md Install the primary package using PNPM. Secondary dependencies will be installed automatically. PNPM is the recommended package manager. ```bash pnpm install @yantrix/automata ``` -------------------------------- ### Install @yantrix/automata via Yarn Source: https://github.com/tfcp68/yantrix/blob/main/packages/automata/README.md Install the primary package using Yarn. Secondary dependencies will be installed automatically. ```bash yarn add @yantrix/automata ``` -------------------------------- ### Initialize Context with Default Values Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/120_values_and_constants.md Demonstrates setting starting values for Context properties during initialization. ```text #{value1, value2} <= #value1 = 1, #value2 = 1 ''' same as #{value1 = 1, value2 = 1} <= #value1, #value2 ''' same as shortcut #{value1 = 1, value2 = 1 } ``` -------------------------------- ### Install @yantrix/automata via Auto-detection Source: https://github.com/tfcp68/yantrix/blob/main/packages/automata/README.md Install the primary package using the npx nypm command for auto-detection of the package manager. Secondary dependencies will be installed automatically. ```bash npx nypm install @yantrix/automata ``` -------------------------------- ### Run Project in Development Mode Source: https://github.com/tfcp68/yantrix/blob/main/docs/examples/100_redux.md Command to start the project in development mode. Access the application at http://localhost:5173. ```bash pnpm dev ``` -------------------------------- ### Install Yantrix CLI and Codegen Packages Source: https://context7.com/tfcp68/yantrix/llms.txt Install the necessary packages for using the Yantrix CLI and code generation features. ```bash npm install @yantrix/cli @yantrix/codegen ``` -------------------------------- ### Install Yantrix APIs Source: https://github.com/tfcp68/yantrix/blob/main/README.md Commands to install specific Yantrix packages for TypeScript development. ```bash # Via NPM $ npm install @yantrix/automata @yantrix/utils @yantrix/yantrix-parser # Via Yarn $ yarn add @yantrix/automata @yantrix/utils @yantrix/yantrix-parser # Via PNPM $ pnpm install @yantrix/automata @yantrix/utils @yantrix/yantrix-parser # ✨ Auto-detection $ npx nypm install @yantrix/automata @yantrix/utils @yantrix/yantrix-parser ``` -------------------------------- ### Install Yantrix CLI Source: https://github.com/tfcp68/yantrix/blob/main/README.md Commands to install the Yantrix command line tool using various package managers. ```bash # Via NPM $ npm install @yantrix/cli # Via Yarn $ yarn add @yantrix/cli # Via PNPM $ pnpm install @yantrix/cli # ✨ Auto-detection $ npx nypm install @yantrix/cli ``` -------------------------------- ### Commit message examples Source: https://github.com/tfcp68/yantrix/blob/main/docs/contributing/02_git_commit_naming_convention.md Various examples of commit messages following the conventional format. ```text feat(Automata): add 'tag' method ``` ```text fix(Automata): handle events correctly close #999 ``` ```text perf(core): improve patching by removing 'bar' option BREAKING CHANGE: The 'bar' option has been removed. ``` ```text revert: feat(EventDictionary): add EventType This reverts commit 123abc4654a317a13331b17617d973392f415f02. ``` -------------------------------- ### Install Yantrix React Packages Source: https://github.com/tfcp68/yantrix/blob/main/packages/react/README.md Install the primary `@yantrix/react` package along with `@yantrix/automata` for types and `@yantrix/cli` for code generation. Supports NPM, Yarn, and PNPM. ```bash # Via NPM $ npm install @yantrix/react @yantrix/automata @yantrix/cli # Via Yarn $ yarn add @yantrix/react @yantrix/automata @yantrix/cli # Via PNPM $ pnpm install @yantrix/react @yantrix/automata @yantrix/cli # ✨ Auto-detection $ npx nypm install @yantrix/react @yantrix/automata @yantrix/cli ``` -------------------------------- ### Clone Yantrix Repository Source: https://github.com/tfcp68/yantrix/blob/main/docs/examples/100_redux.md Use this command to clone the Yantrix repository to your local machine. This is the first step to setting up the examples locally. ```bash git clone https://github.com/tfcp68/yantrix.git ``` -------------------------------- ### Example output for reducer-based context Source: https://github.com/tfcp68/yantrix/blob/main/docs/concepts/500_codegen.md Sample array of strings generated when a context block includes an explicit reducer. ```ts [ "foo: (function(){ const boundValue = ...; return boundValue; }())", "bar: (function(){ const boundValue = ...; if(boundValue !== null) return boundValue; else return ; }())", ] ``` -------------------------------- ### Mermaid State Diagram Example Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/index.md This example demonstrates a Mermaid State Diagram implementing an 'until' loop. It visualizes the flow of a counter variable and conditional iteration. ```mermaid direction LR [*] --> LOOP_BEGIN: START_LOOP(counter) LOOP_BEGIN --> LOOP_REPEAT: ITERATE state loop_ends <> LOOP_REPEAT --> loop_ends: [-] loop_ends --> LOOP_REPEAT: isGreater($counter,0) loop_ends --> LOOP_END note right of LOOP_BEGIN #{ counter } <= $counter = 1 end note note left of LOOP_REPEAT +ByPass #{ counter } <= add(#counter, -1) end note ``` ```mermaid stateDiagram-v2 direction LR [*] --> LOOP_BEGIN: START_LOOP(counter) LOOP_BEGIN --> LOOP_REPEAT: ITERATE state loop_ends <> LOOP_REPEAT --> loop_ends: [-] loop_ends --> LOOP_REPEAT: isGreater($counter,0) loop_ends --> LOOP_END note right of LOOP_BEGIN #{ counter } <= $counter = 1 end note note left of LOOP_REPEAT +ByPass #{ counter } <= add(#counter, -1) end note ``` -------------------------------- ### Get Help for Yantrix Codegen Source: https://github.com/tfcp68/yantrix/blob/main/packages/cli/README.md Run 'yantrix codegen -h' to display help information for the codegen command, including available options and their descriptions. ```bash yantrix codegen -h ``` -------------------------------- ### Install @yantrix/redux dependencies Source: https://github.com/tfcp68/yantrix/blob/main/packages/redux/README.md Commands to install the necessary Yantrix packages using various package managers. ```bash # Via NPM $ npm install @yantrix/redux @yantrix/automata @yantrix/cli # Via Yarn $ yarn add @yantrix/redux @yantrix/automata @yantrix/cli # Via PNPM $ pnpm install @yantrix/redux @yantrix/automata @yantrix/cli # ✨ Auto-detection $ npx nypm install @yantrix/redux @yantrix/automata @yantrix/cli ``` -------------------------------- ### Event Bus Setup and FSM Communication Source: https://context7.com/tfcp68/yantrix/llms.txt This TypeScript code demonstrates how to create an event bus to connect multiple Finite State Machines (FSMs). It shows how to initialize the bus with specific automata and access individual FSM instances for context retrieval. ```typescript import { createEventBus } from './generated/TrafficLightAutomata'; import PedestrianAutomata from './generated/PedestrianAutomata'; // Create an event bus connecting multiple FSMs const [eventBus, automatas] = createEventBus('intersection', { trafficLight: TrafficLightAutomata, pedestrian: PedestrianAutomata, }); // FSMs can now communicate via events // Events emitted by one FSM can trigger actions in another // Access individual automata instances const { trafficLight, pedestrian } = automatas; // Get current states console.log('Traffic:', trafficLight.getContext()); console.log('Pedestrian:', pedestrian.getContext()); // Event bus handles cross-FSM communication automatically // when diagrams include emit/subscribe statements ``` -------------------------------- ### Import and Use Generated Slider Controller Source: https://github.com/tfcp68/yantrix/blob/main/docs/index.md Example of importing a generated Yantrix controller into a JavaScript project and dispatching actions to control the slider's state. Includes handlers for UI interactions and methods to get the current value and check disabled status. ```javascript import Slider from './slider_controller.js'; const SLIDER_MAX = 1000; const SLIDER_MIN = -1000; const SliderController = new Slider(); SliderController.dispatch( Slider.createAction('RESET', { min: SLIDER_MIN, max: SLIDER_MAX, }), ); // adjusted to local needs /* * ...somewhere later on at UI ... */ // bind these to buttons and/or keys const rightHandler = () => SliderController.dispatch(Slider.createAction('INCREASE', { by: 50 })); const leftHandler = () => SliderController.dispatch(Slider.createAction('DECREASE', { by: 50 })); // bind this to a click handler, using relative coordinate const setHandler = percentage => SliderController.dispatch( Slider.createAction('SET', { value: SLIDER_MIN + percentage * (SLIDER_MAX - SLIDER_MIN), }), ); // use this to display value in the GUI const getSliderValue = () => SliderController.getContext().value; // and this - to prevent UI from changing the slider value const isDisabled = () => Slider.hasState(SliderConroller, 'DISABLED'); ``` -------------------------------- ### Reference Payload Properties Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/120_values_and_constants.md Examples of invoking functions on Payload properties and subscribing to events. ```text ''' Expression that invokes a Function upon a Payload property func($payloadValue) ''' assign three Payload properties to respective Context properties #{a,b,c} <= $payloadA, $payloadB, $payloadC ''' Translate an Event with its Meta to Action with Payload subscribe/someEvent SomeAction ( payloadValue ) <= ( eventMetaValue ) ``` -------------------------------- ### Action Helpers Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/150_JSAPI.md Details how to get action IDs and create payloads for dispatching actions using the FSM. ```APIDOC ## Action Helpers To invoke an `Action`, a [dispatch](../API/automata/interfaces/IAutomata.html#dispatch) method should be used. Since it accepts numeric ids, they also have to be mapped. ### Get Action ID ```javascript Slider.getAction('DISABLE'); Slider.getAction('ENABLE'); ``` Since most of the time you need to pass a `Payload` object into `dispatch`, there's a helper to create a `Payload`: ### Create Action Payload ```javascript const payload = Slider.createAction('RESET', { min: 0, max: 50, }); Slider.dispatch(payload); ``` ``` -------------------------------- ### Define FSM with Payload and Transitions Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/100_data_objects.md Example of a state machine diagram using payloads and state transitions. ```mermaid stateDiagram-v2 direction TB [*] --> INIT: START (counter) INIT --> WORKING: [-] state isFinished <> WORKING --> isFinished: REDUCE (value) isFinished --> END: isGreater($value, #counter) isFinished --> WORKING note right of INIT +ByPass +Init #{counter} <= $counter = 10 end note note left of WORKING #{counter} <= add(#counter, neg($value = 1)) end note note right of END #{counter} <= 0 end note ``` -------------------------------- ### Install Yantrix Redux dependencies Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/200_redux.md Install the necessary packages for Redux integration and code generation. ```shell $ npm install @yantrix/redux @yantrix-codegen ``` -------------------------------- ### Lifelike Context Transformation Examples Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/120_values_and_constants.md Common patterns for copying, trimming, concatenating, and incrementing context fields. ```Yantrix #{id, name} ``` ```Yantrix #{id, name} <= #id, trim(#name) ``` ```Yantrix #{id, name} <= #id, concat(trim(#name),' ',trim(#lastname)) ``` ```Yantrix #{counter} <= add(#counter, $increment) ``` -------------------------------- ### Property Assignment and Error Handling Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/110_reducers.md Examples of property mapping between source and target objects, including error conditions for mismatched property counts. ```text ''' assigns Null to the latter property, and copieis the rest #{ property1, property2, property 3 } <= #property2, #property3 ''' copies values in order of reference # { property1, property2, property 3 } <= $payloadA, $payloadB, $payloadC ''' throws an error due to excessive properties on the right side # { property1, property 2} <= $payloadA, $payloadB, $payloadC ``` -------------------------------- ### Reference Context Properties Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/120_values_and_constants.md Examples of referencing Context members and using them in expressions or event emissions. ```text ''' declare a Context with three members #{a,b,c} ''' Declare a Context with three more members, that copy value from previous ones #{oldA, oldB, oldC} <= #a,#b,#c ''' fire an Event with a numeric property, derived from a function applied to those emit/someEvent (eventCode) <= #{encode(oldA, oldB, oldC)} ``` -------------------------------- ### Configure Redux Store with Custom FSM Middleware Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/200_redux.md Shows how to configure a Redux store using `configureStore` and integrate custom middleware created with `createMiddleware`. This example demonstrates mapping Redux actions to FSM payloads and FSM context back to Redux actions. ```typescript import { combineReducers, configureStore } from '@reduxjs/toolkit'; import { createMiddleware } from '@yantrix/redux'; import TrafficLight from '../generated/traffic-light.ts'; export const store = configureStore({ reducer: combineReducers({ /* ... */ }), middleware: getDefaultMiddleware => getDefaultMiddleware().concat( createMiddleware( TrafficLight, ({ type, payload }) => (type !== 'yantrix/trafficLight') ? null : TrafficLight.createAction('Switch', payload), ({ state, context }) => ({ type: 'changeTrafficLight', // assume this action is handled elsewhere in Redux payload: { color: state, counter: context.counter } }) ) ) }); ``` -------------------------------- ### Link Local Package Globally Source: https://github.com/tfcp68/yantrix/blob/main/docs/contributing/01_advanced_managment.md Make a local package available system-wide, similar to a global npm installation. This is useful for CLI tools. ```sh pnpm link --global ``` ```sh pnpm link --global /packages/ ``` -------------------------------- ### Install Dependencies for Generated Typescript Automata Source: https://github.com/tfcp68/yantrix/blob/main/packages/cli/README.md After generating Typescript Automata, install the required '@yantrix/automata' and '@yantrix/functions' packages using your preferred package manager. ```bash # Via NPM $ npm install @yantrix/automata @yantrix/functions ``` ```bash # Via Yarn $ yarn add @yantrix/automata @yantrix/functions ``` ```bash # Via PNPM $ pnpm install @yantrix/automata @yantrix/functions ``` ```bash # ✨ Auto-detection $ npx nypm install @yantrix/automata @yantrix/functions ``` -------------------------------- ### Complete Slider Component Example Source: https://context7.com/tfcp68/yantrix/llms.txt Implements a bounded slider with min/max constraints and demonstrates various state transitions like reset, enable/disable, increment, decrement, and set value. Requires initialization with bounds and provides functions to interact with the slider's state. ```typescript // slider.mermaid content would be: /* stateDiagram-v2 direction LR [*] --> ENABLED: RESET (min=0, max=100) ENABLED --> DISABLED: DISABLE DISABLED --> ENABLED: ENABLE ENABLED --> SETTING: SET (value) SETTING --> ENABLED: [-] ENABLED --> INCREMENT: INCREASE (by=1) INCREMENT --> ENABLED: [-] ENABLED --> DECREMENT: DECREASE (by=1) DECREMENT --> ENABLED: [-] note left of ENABLED +Init #{min, max} <= $min, $max end note note right of SETTING +ByPass #{value} <= min(#max, max(#min, $value)) end note note right of INCREMENT +ByPass #{value} <= min(#max, max(#min, add(#value, $by))) end note note right of DECREMENT +ByPass #{value} <= min(#max, max(#min, diff($by, #value))) end note note right of [*] #{min, max, value} end note */ // After running: yantrix codegen ./slider.mermaid -o ./Slider.ts -c Slider -l TypeScript import Slider from './Slider'; // Initialize slider with bounds const sliderController = new Slider(); sliderController.dispatch( Slider.createAction('RESET', { min: -1000, max: 1000, }) ); // Increment by custom amount const increaseBy50 = () => sliderController.dispatch( Slider.createAction('INCREASE', { by: 50 }) ); // Decrement by custom amount const decreaseBy50 = () => sliderController.dispatch( Slider.createAction('DECREASE', { by: 50 }) ); // Set to specific value (bounded by min/max) const setToValue = (percentage: number) => { const { context } = sliderController.getContext(); const { min, max } = context; const value = min + percentage * (max - min); sliderController.dispatch( Slider.createAction('SET', { value }) ); }; // Get current value const getValue = () => sliderController.getContext().context.value; // Check if slider is disabled const isDisabled = () => Slider.hasState(sliderController, 'DISABLED'); // Toggle enabled state const toggleEnabled = () => { if (isDisabled()) { sliderController.dispatch(Slider.createAction('ENABLE', {})); } else { sliderController.dispatch(Slider.createAction('DISABLE', {})); } }; // Usage increaseBy50(); console.log('Value after increase:', getValue()); // 50 setToValue(0.75); // Set to 75% of range console.log('Value at 75%:', getValue()); // 500 (75% of -1000 to 1000) decreaseBy50(); console.log('Value after decrease:', getValue()); // 450 ``` -------------------------------- ### Basic Checkbox State Diagram Source: https://github.com/tfcp68/yantrix/blob/main/docs/concepts/999_design_examples.md Illustrates a simple checkbox FSM with ON and OFF states, toggled by a single action. Starts in the unchecked state. ```mermaid stateDiagram-v2 direction LR OFF --> ON: TOGGLE ON --> OFF: TOGGLE note left of OFF +Init end note ``` -------------------------------- ### Reducer Transformer Example Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/160_transformers.md Reducer Transformers translate from State+Action/Payload to State/Context and can be injected into FSMs at compile time. This example shows property assignment from reducer outputs. ```plaintext #{propertyA, propertyB} = reducerA(#propertyA, $payloadA, reducerB(#propertyB, $payloadB) ``` -------------------------------- ### Example State Reducer Function Source: https://github.com/tfcp68/yantrix/blob/main/docs/concepts/500_codegen.md Shows the final structure of a reducer function for a specific state, including the compiled context object. ```typescript stateValue: (prevContext, payload, functionDictionary, automata) => { return { foo: (function(){ ... }()), bar: (function(){ ... }()), }; } ``` -------------------------------- ### State Helpers Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/150_JSAPI.md Explains how to use helper functions to get numeric state IDs and check the current state of an FSM instance. ```APIDOC ## State Helpers Internally, `IAutomata` operates on numeric states. To address `States` from the diagram, they must be wrapped in a helper: ### Get State ID ```javascript import Slider from '../slider_controller.js'; Slider.getState('ENABLED'); // returns a numeric internal id of this State, or Null if it's incorrect ``` There's also a helper to check if the `FSM` is in a particular `State` right now: ### Check Current State ```javascript const SliderInstance = new Slider({ min: 1, max: 10, value: 5, }); Slider.hasState(SliderInstance, 'ENABLED'); // true // this is the same as Slider.getState('ENABLED') === SliderInstance.getContext().state; ``` ``` -------------------------------- ### Example Reducer Object Structure Source: https://github.com/tfcp68/yantrix/blob/main/docs/concepts/500_codegen.md Illustrates the structure of the generated reducer object, where each key is a state value and the corresponding value is a reducer function. ```typescript const reducer = { 1: (prevContext, payload, functionDictionary, automata) => { return { /* compiled context for state 1 */ }; }, 2: (prevContext, payload, functionDictionary, automata) => { return prevContext; }, // ... }; ``` -------------------------------- ### Create an RTK Slice with FSM Integration Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/200_redux.md Demonstrates how to create a Redux Toolkit slice from a Finite State Machine definition. This setup uses `createFSMSlice` to integrate the FSM's state and actions into the Redux store. ```typescript import { combineReducers, configureStore } from '@reduxjs/toolkit'; const YantrixSlice = createFSMSlice({ name: TrafficLight.id, fsm: TrafficLight, contextToRedux: context => context, // optional, default mapper }); ``` -------------------------------- ### Build for Production Source: https://github.com/tfcp68/yantrix/blob/main/docs/examples/100_redux.md Command to build the project for production deployment. ```bash pnpm build ``` -------------------------------- ### Run tests Source: https://github.com/tfcp68/yantrix/blob/main/docs/contributing/index.md Executes the test suite to verify changes. ```bash pnpm run test ``` -------------------------------- ### Model Transformer Example Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/160_transformers.md Model Transformers are context-free functions that mutate the Data Model. This example shows incrementing a counter using the add function and a global counter function. ```plaintext #{counter} <= add(№counter, increaseGlobalCounter($value)) ``` -------------------------------- ### Define ByPass State Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/100_data_objects.md Example of a state marked with the +ByPass flag to propagate actions automatically. ```mermaid stateDiagram-v2 direction LR A --> BYPASS: Action1 B --> BYPASS: Action2 BYPASS --> EXIT: [-] note right of BYPASS +ByPass end note ``` -------------------------------- ### Define State Context and Reducers Source: https://context7.com/tfcp68/yantrix/llms.txt Use notes attached to states to define initial context and reducer logic for state transitions. ```mermaid stateDiagram-v2 [*] --> ENABLED: RESET (min=0, max=100) ENABLED --> DISABLED: DISABLE DISABLED --> ENABLED: ENABLE ENABLED --> SETTING: SET (value) SETTING --> ENABLED: [-] ENABLED --> INCREMENT: INCREASE (by=1) INCREMENT --> ENABLED: [-] ENABLED --> DECREMENT: DECREASE (by=1) DECREMENT --> ENABLED: [-] %% Default context (copied through all transitions) note right of [*] #{min, max, value} end note %% Initial state with Init flag and reducers note left of ENABLED +Init #{min, max} <= $min, $max end note %% ByPass state - auto-transitions to next state note right of SETTING +ByPass #{value} <= min(#max, max(#min, $value)) end note note right of INCREMENT +ByPass #{value} <= min(#max, max(#min, add(#value, $by))) end note note right of DECREMENT +ByPass #{value} <= min(#max, max(#min, diff($by, #value))) end note ``` -------------------------------- ### Implement Forks and Predicates Source: https://context7.com/tfcp68/yantrix/llms.txt Utilize choice nodes to handle conditional branching and predicate-based transitions within state diagrams. ```mermaid stateDiagram-v2 [*] --> INIT: START (counter) INIT --> WORKING: [-] %% Fork node for conditional transitions state isFinished <> WORKING --> isFinished: REDUCE (value) %% Predicate-based transition isFinished --> END: isGreater($value, #counter) %% Default path (no predicate) isFinished --> WORKING %% Nested forks state checkType <> WORKING --> checkType: CHECK checkType --> TYPE_A: isEqual($type, 'A') checkType --> TYPE_B: isEqual($type, 'B') checkType --> TYPE_DEFAULT note right of INIT +ByPass +Init #{counter} <= $counter = 10 end note note left of WORKING #{counter} <= add(#counter, neg($value = 1)) end note note right of END #{counter} <= 0 end note ``` -------------------------------- ### Use FSM with useFSM hook Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/199_react.md Implement state reading and action dispatching using the useFSM hook. ```javascript import { useFSM } from '@yantrix/react'; import TrafficLight from '../generated/traffic-light.ts'; const ToggleComponent = () => { // creates a singleton FSM const { getContext, dispatch } = useFSM(TrafficLight); // Event handlers are redux-like and can be wrapped in React.useCallback const clickHandler = () => dispatch({ action: TrafficLight.getAction('switch'), }); // obtains a value from FSM Context const { counter } = getContext().context; // defines a mapping between FSM State and a CSS class property const bgClasses = { [TrafficLight.getState('Red')]: 'bg-red', [TrafficLight.getState('RedYellow')]: 'bg-red bg-yellow', [TrafficLight.getState('Yellow')]: 'bg-yellow', [TrafficLight.getState('Green')]: 'bg-green', }; const defaultClass = 'bg-white'; // Key-based dispatching is eloquent and extendable with no effort const className = bgClasses[getContext().state] ?? defaultClass; return (
{counter}
); }; ``` -------------------------------- ### Get Numeric Action ID Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/150_JSAPI.md Use the static 'getAction' helper to retrieve the internal numeric ID for a given action name. ```javascript Slider.getAction('DISABLE'); Slider.getAction('ENABLE'); ``` -------------------------------- ### Typescript Support Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/150_JSAPI.md Illustrates how dictionaries for actions and states are available as types in TypeScript projects. ```APIDOC ## Typescript In typescript versions [Dictionaries](#dictionaries) are available as types too: ```typescript import { actionMap, stateMap, TActionLiteral, TStateLiteral } from '../slider_controller.js'; type TActionLiteral = keyof typeof actionMap; type TStateLiteral = keyof typeof stateMap; ``` ``` -------------------------------- ### Initialize context with getDefaultContext Source: https://github.com/tfcp68/yantrix/blob/main/docs/concepts/500_codegen.md Generates an initial context function based on the StartState, or returns an identity function if no state is found. ```ts function getDefaultContext(props) { const state = props.stateDictionary.getStateValues({ keys: [StartState] })[0]; if (state) { const ctx = getContextTransition({ diagram: props.diagram, expressions: props.expressions, stateDictionary: props.stateDictionary, value: state, }); return `const getDefaultContext = (prevContext, payload) => { const ctx = ${ctx} return Object.assign({}, prevContext, ctx); } `; } return `const getDefaultContext = (prevContext, payload) => { return prevContext }`; } ``` ```ts const getDefaultContext = (prevContext, payload) => { const ctx = ; return Object.assign({}, prevContext, ctx); }; ``` -------------------------------- ### Define Execution Flow Sequence Diagram Source: https://github.com/tfcp68/yantrix/blob/main/docs/examples/1000_todo.md Illustrates the interaction between the UI, the To-Do list logic, and persistent storage. ```mermaid sequenceDiagram participant Interface participant ToDoList participant Storage Storage->>ToDoList: loadList(list) ToDoList->>Interface: update(list) loop alt adding item Interface->>ToDoList: addItem(id, item) else remove item Interface->>ToDoList: removeItem(id) else clear list Interface->>ToDoList: clearList() end ToDoList->>Storage: saveList(list) ToDoList->>Interface: update(list) end ``` -------------------------------- ### Context Transformer with Multiple Assignments Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/160_transformers.md This example demonstrates multiple assignments within a Context Transformer, utilizing sanitize and validate functions for email and password processing. ```plaintext #{email, password, input_error} <= sanitize(#email), sanitize(#password), validate(#email, #password)} ``` -------------------------------- ### Generic Transformer Examples Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/160_transformers.md These are built-in pure functions that operate on any contract type and map values. They serve as basic building blocks for data manipulation and can be user-defined. ```plaintext add($value1, $value2) ``` ```plaintext find(#listValue, 'id', 4) ``` ```plaintext mult(avg(#listValue), $count) ``` -------------------------------- ### Define Key List Syntax Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/120_values_and_constants.md Syntax definition for declaring property key lists and expressions. ```text KEY_ITEM::=[=] KEY_LIST::=KEY_ITEM[,KEY_ITEM...] ``` -------------------------------- ### Configure Yantrix Project Source: https://github.com/tfcp68/yantrix/blob/main/docs/examples/1000_todo.md YAML configuration file for mapping FSMs, sequences, and adapters to a TypeScript target. ```yaml Target: Typescript # the output language FSM: # state diagram files are loaded into FSMs with arbitrary aliases ToDoList: ./src/fsm/ToDoList.ytx # Sequence diagram is describing the main thread of the micro-app Sequence: ./src/sequence/todo.ytx # Adapters are modules that implement Participants from the sequence diagram Adapters: ToDoList: ToDoList # referencing an FSM alias creates EventAdapter Interface: ./src/ui/reactAdapter.ts # referencing a self-made adapter for the target language Storage: Yantrix/LocalStorageAdapter # referencing a premade Yantrix package ``` -------------------------------- ### Codegen Dependency Installation Notification Source: https://github.com/tfcp68/yantrix/blob/main/packages/cli/README.md This message is displayed during the generation process, informing the user about additional packages required for the chosen output language, such as '@yantrix/automata' and '@yantrix/functions' for Typescript. ```bash Since you have chosen the *-script language, you need to install additional packages to work with the generated Automata: - @yantrix/automata - @yantrix/functions ``` -------------------------------- ### Numeric Predicate Functions Source: https://context7.com/tfcp68/yantrix/llms.txt Use these functions to perform conditional checks on numeric values within FSMs. Examples include checking for even/odd, positive/negative, integer, greater/less than, and equality. ```mermaid stateDiagram-v2 [*] --> CHECK: START (value, list, obj) state numCheck <> state listCheck <> state objCheck <> CHECK --> numCheck: VALIDATE_NUMBER CHECK --> listCheck: VALIDATE_LIST CHECK --> objCheck: VALIDATE_OBJECT %% Numeric predicates numCheck --> EVEN: isEven($value) numCheck --> ODD: isOdd($value) numCheck --> POSITIVE: isPositive($value) numCheck --> NEGATIVE: isNegative($value) numCheck --> INTEGER: isInteger($value) numCheck --> GREATER: isGreater($value, 100) numCheck --> LESS: isLess($value, 0) numCheck --> EQUAL: isEqual($value, 50) numCheck --> DEFAULT_NUM %% Lookup predicates listCheck --> CONTAINS_ITEM: contains($list, 'target') listCheck --> HAS_INDEX: has($list, 5) listCheck --> DEFAULT_LIST %% Object predicates objCheck --> HAS_KEY: has($obj, 'requiredKey') objCheck --> CONTAINS_VALUE: contains($obj, 'searchValue') objCheck --> IS_NULL: isNull($obj) objCheck --> DEFAULT_OBJ %% Compound predicates with logical operators state compound <> CHECK --> compound: COMPLEX_CHECK compound --> ALL_TRUE: all(isPositive($value), isInteger($value), isLess($value, 1000)) compound --> ANY_TRUE: any(isEven($value), isGreater($value, 50)) compound --> NONE_TRUE: none(isNegative($value), isNull($obj)) compound --> NEGATED: not(isEqual($value, 0)) compound --> DEFAULT_COMPOUND ``` -------------------------------- ### Context Transformer Example Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/160_transformers.md Context Transformers translate Contexts between each other and are used within Reducers to update internal FSM data when changing States. They are defined as part of the State Dictionary. ```plaintext #{stepIndex} <= nextStep(#stepIndex) ``` -------------------------------- ### Define Conditional Forking Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/100_data_objects.md Demonstrates how to use a choice node to branch states based on predicate conditions. ```mermaid stateDiagram-v2 state Fork <> Fork --> State1: isGreater($value, #counter) Fork --> State2: isZero($value) Fork --> State3 ``` -------------------------------- ### Get Numeric State ID Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/150_JSAPI.md Use the static 'getState' helper to retrieve the internal numeric ID for a given state name. Returns null if the state name is invalid. ```javascript import Slider from '../slider_controller.js'; Slider.getState('ENABLED'); // returns a numeric internal id of this State, or Null if it's incorrect ``` -------------------------------- ### Basic Asynchronous Data Loader Source: https://github.com/tfcp68/yantrix/blob/main/docs/concepts/999_design_examples.md A minimal Mermaid state diagram representing the basic states of an asynchronous request: Init, Loading, Ready, and Error. ```mermaid stateDiagram-v2 Init-->Loading Loading-->Ready Loading-->Error ``` -------------------------------- ### Polymorphic 'contains' Function Examples Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/140_functions.md The `contains` function demonstrates parameter polymorphism, adapting its behavior based on the type of the first argument (Object, List, or String). It always returns a Binary type. ```plaintext ''' if "var" is an Object, checks if a "keyName" property exists in it contains(var, keyName = 'propertyName') ''' if "var" is a List, it checks for an index existence instead contains(var, index = 1) ''' if "var" is a String, checks if it contains a substring contains(var, substring = 'searchString') ``` -------------------------------- ### Create and Dispatch Action Payload Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/150_JSAPI.md Use the static 'createAction' helper to construct a payload for an action, optionally including a value. Then, use 'dispatch' to send the action to the FSM. ```javascript const payload = Slider.createAction('RESET', { min: 0, max: 50, }); Slider.dispatch(payload); ``` -------------------------------- ### Event Flow with Event Bus and Adapters Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/200_redux.md Illustrates the sequence of interactions between Redux Actions, Event Bus, Event Adapters, and FSMs, including the asynchronous dispatch of new Actions. ```mermaid sequenceDiagram useDispatch ->> Action Creator: Action Action Creator ->> Event Bus: Event Meta Event Bus ->>+ Event Adapter: Event Meta Event Adapter ->>+ FSM: FSM Payload FSM ->> FSM: Reducer FSM ->>- Event Adapter: FSM Context Event Adapter ->>- Event Bus: Event Meta Event Bus -->> Redux Store: Action Redux Store ->> Redux Store: Reducer Redux Store -->> Subscribers: Store State ``` -------------------------------- ### Prepare Context Item for Reducer Source: https://github.com/tfcp68/yantrix/blob/main/docs/concepts/500_codegen.md Converts a single `contextDescription` block into `key: expression` pairs for the reducer. Requires a list of expressions. ```javascript ctxRes.push(...getContextItem({ ctx, expressions })) ``` -------------------------------- ### Create Redux Toolkit Slice Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/200_redux.md Initialize a Redux Toolkit slice using the generated FSM. ```typescript import { createFSMSlice } from '@yantrix/redux'; // import a generated FSM import TrafficLight from '../generated/traffic-light.ts'; // provide an integration id as action prefix const YantrixSliceId = 'yantrix'; const YantrixSlice = createFSMSlice(TrafficLight); ``` -------------------------------- ### Generate Action-to-State Lookup Table Source: https://github.com/tfcp68/yantrix/blob/main/docs/concepts/500_codegen.md Builds a lookup table mapping `State x Action -> NextState (+predicate)` for the generated automata. This table is crucial for determining the next state based on the current state and action. ```javascript serializer.getActionToStateFromState(props) ``` -------------------------------- ### Best Practice Asynchronous Data Loader Source: https://github.com/tfcp68/yantrix/blob/main/docs/concepts/999_design_examples.md An improved Mermaid state diagram for an async call, including an initial state and explicit transitions for SUCCESS and FAIL. Uses CALL action for initiation. ```mermaid stateDiagram-v2 direction LR [*]-->Init:CALL Init-->Loading: CALL Loading-->Ready: SUCCESS Loading-->Error: FAIL note left of Init +ByPass end note ``` -------------------------------- ### Define To-Do List State Diagram Source: https://github.com/tfcp68/yantrix/blob/main/docs/examples/1000_todo.md Defines the state transitions for adding, removing, and clearing items in a list using Mermaid syntax. ```mermaid stateDiagram-v2 direction LR LIST --> ADD: AddItem LIST --> REMOVE: RemoveItem REMOVE --> LIST: [-] ADD --> LIST: [-] LIST-->RESET: ClearList RESET --> LIST: [-] note right of ADD #{list} <= setAttr(#list, $id=uniqId(), $item) +ByPass end note note left of LIST #{list = {}} +Init end note note right of REMOVE #{list} <= unsetAttr(#list, $id) +ByPass end note note right of RESET #{list} <= {} +ByPass end note ``` -------------------------------- ### Manage multiple FSM instances Source: https://github.com/tfcp68/yantrix/blob/main/docs/integrations/199_react.md Create separate FSM instances by providing a unique handle to the useFSM hook. ```tsx const Toggler = ({ id: string }) => { const { dispatch } = useFSM({ fsm: TrafficLight, id }); const clickHandler = React.useCallback( () => dispatch({ action: TrafficLight.getAction('switch') }), [dispatch] ); return (
); }; const Counter = ({ id: string }) => { const { getContext } = useFSM({ fsm: TrafficLight, id }); const { counter } = getContext(); return
{counter}
; }; // The parent component creates a unique ID that makes both children Components use the same FSM const TrafficLight = () => { const [id, setId] = useState(Math.random().toFixed(6)); return (
); }; ``` -------------------------------- ### Dropdown FSM State Diagram Source: https://github.com/tfcp68/yantrix/blob/main/docs/concepts/999_design_examples.md This Mermaid diagram visualizes the Finite State Machine for a dropdown component, illustrating states like INIT, CLOSED, OPEN, and SELECTED, along with their transitions triggered by various events and actions. ```mermaid stateDiagram-v2 [*] --> INIT: RESET (optionsList) INIT --> CLOSED: [-] CLOSED --> OPEN: OPEN OPEN --> CLOSED: CLOSE OPEN --> SELECTED: SELECT (index) SELECTED --> CLOSED: CLOSE note right of INIT +Init +ByPass #{ items, selectedIndex } <= sortBy($optionsList, 'id'), 0 end note note left of CLOSED subscribe/click => OPEN emit/dropdownClose end note note left of SELECTED #{ selectedIndex } <= (index) emit/selected (index) <= #{ selectedIndex } subscribe/selected CLOSE end note note right of OPEN emit/dropdownOpen subscribe/click SELECT (index) subscribe/clickOutside CLOSE end note note left of [*] #( items = [], selectedIndex = -1 } end note ``` -------------------------------- ### Handle Nulls with Default Values Source: https://github.com/tfcp68/yantrix/blob/main/docs/syntax/120_values_and_constants.md Shows how default values interact with function results that may return Null. ```text ''' in this example, value2 can become Null after the computation ''' if "funcValue" call returns Null, even though value2 has a default value #{value1, value2} <= #value1 = 1, funcValue(#value2 = 1) ''' however, if also assigned on the left side, it resolves to a default value #{value1, value2 = 1} <= #value1 = 1, funcValue(#value2 = 1) ``` -------------------------------- ### Create New Package in Yantrix Monorepo Source: https://github.com/tfcp68/yantrix/blob/main/docs/contributing/01_advanced_managment.md Use this command in the root of the yantrix monorepository to create a new package. The script automatically adds the '@yantrix/' organization prefix. ```sh pnpm create-package [new-package-description] ```