GithubHelp home page GithubHelp logo

nocode-js / sequential-workflow-editor Goto Github PK

View Code? Open in Web Editor NEW
81.0 4.0 8.0 510 KB

Powerful workflow editor builder for any workflow designer.

Home Page: https://nocode-js.com/

License: MIT License

CSS 1.78% JavaScript 2.93% TypeScript 95.23% Shell 0.07%
workflow workflow-builder workflow-editor workflow-model citizen-developers

sequential-workflow-editor's Introduction

Sequential Workflow Editor

Sequential Workflow Editor

Build Status License: MIT View this project on NPM

Powerful workflow editor builder for sequential workflows. Written in TypeScript. Mainly designed to work with the Sequential Workflow Designer component. To execute your model you may use the Sequential Workflow Machine or any other workflow engine. It supports front-end and back-end strict validation of the model. 0 external dependencies.

๐Ÿ“ Check the documentation for more details.

๐Ÿคฉ Don't miss the pro version.

๐Ÿ‘€ Examples

Pro:

๐Ÿš€ Installation

Install the sequential-workflow-editor-model package in your front-end project or your common project for front-end and back-end (check this article):

npm i sequential-workflow-editor-model

Install the sequential-workflow-editor package in your front-end project:

npm i sequential-workflow-editor

๐ŸŽฌ Usage

At the beginning you need to create a model of your workflow for the editor. In this short tutorial let's consider the following workflow:

import { Definition, Step } from 'sequential-workflow-model';

export interface MyDefinition extends Definition {
  properties: {
    inputs: VariableDefinitions;
  };
}

export interface LogStep extends Step {
  type: 'log';
  componentType: 'task';
  properties: {
    message: string;
  };
}

Now we can create a model for the step:

import { createStepModel, createStringValueModel } from 'sequential-workflow-editor-model';

export const logStepModel = createStepModel<LogStep>('log', 'task', step => {
  step.property('message')
    .value(
      createStringValueModel({
        minLength: 1
      })
    )
    .label('Message to log');
});

If your workflow contains global properties you can create a root model:

import { createRootModel, createVariableDefinitionsValueModel } from 'sequential-workflow-editor-model';

export const rootModel = createRootModel<MyDefinition>(root => {
  root.property('inputs')
    .value(
      createVariableDefinitionsValueModel({})
    );
);

Now we can create a definition model:

import { createDefinitionModel } from 'sequential-workflow-editor-model';

export const definitionModel = createDefinitionModel<MyDefinition>(model => {
  model.valueTypes(['string', 'number']);
  model.root(rootModel);
  model.steps([logStepModel]);
});

To create an editor provider you need to pass a definition model to the EditorProvider.create method. The provider requires a unique identifier generator. You can use the Uid class from the sequential-workflow-designer package.

import { EditorProvider } from 'sequential-workflow-editor';
import { Uid } from 'sequential-workflow-designer';

export const editorProvider = EditorProvider.create(definitionModel, {
  uidGenerator: Uid.next
});

We have everything to attach the editor provider to a designer. For the Sequential Workflow Designer you need to pass the following options:

import { Designer } from 'sequential-workflow-designer';

const designer = Designer.create(placeholder, startDefinition, {
  editors: {
    rootEditorProvider: editorProvider.createRootEditorProvider(),
    stepEditorProvider: editorProvider.createStepEditorProvider()
  },
  validator: {
    step: editorProvider.createStepValidator(),
    root: editorProvider.createRootValidator()
  },
  // ...
});

That's it! Check the source code of our demo to see the final code.

๐Ÿ’ก License

This project is released under the MIT license.

sequential-workflow-editor's People

Contributors

b4rtaz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

sequential-workflow-editor's Issues

Add more support for i18n

It seems that the alert strings in this file (or more) model/src/validator/variable-name-validator.ts have not been converted using context.i18n:

export function variableNameValidator(name: string): string | null {
        if (!name) {
                return 'Variable name is required.';
        }
        if (name.length > MAX_LENGTH) {
                return `Variable name must be ${MAX_LENGTH} characters or less.`;
        }
        if (!/^[A-Za-z][a-zA-Z_0-9-]*$/.test(name)) {
                return 'Variable name contains invalid characters.';
        }
        return null;
}

Could you please provide support for this?

In react app, how to get the value of global editor?

In react app, how to get the value of global editor?
I try to use hook useGlobalEditor, but throw exception.

react_devtools_backend_compact.js:12966 React Router caught the following error during render Error: Cannot find global editor context
    at useGlobalEditor (index.js:75:11)
    at WorkflowEditor (WorkflowEditor.tsx:54:106)
    at fm (react-dom.development.js:1:152112)
    at react-dom.development.js:1:196268
    at Hg (react-dom.development.js:1:197617)
    at qw (react-dom.development.js:1:244731)
    at Lw (react-dom.development.js:1:237660)
    at _w (react-dom.development.js:1:237542)
    at Nw (react-dom.development.js:1:237304)
    at mw (react-dom.development.js:1:234875) 

Help with createStepModel

Hi, I'm trying to move your example code from the component to a model.ts file. This code.

public readonly toolboxConfiguration: ToolboxConfiguration = {
		groups: [
			{
				name: 'Step',
				steps: [
					this.createTaskStep(null, 'save', 'Save file', {"velocity": "0"}),
					this.createTaskStep(null, 'text', 'Send email', {"velocity": "0"}),
					this.createTaskStep(null, 'task', 'Create task', {"velocity": "0"}),
					this.createIfStep(null, [], []),
					this.createContainerStep(null, [])
				]
			}
		]
	};


	private createTaskStep(id: any, type: any, name: any, properties: any) {
		return {
			id,
			componentType: 'task',
			type,
			name,
			properties: properties || {}
		};
	}


	private createIfStep(id: any, _true: any, _false: any) {
		return {
			id,
			componentType: 'switch',
			type: 'if',
			name: 'If',
			branches: {
				'true': _true,
				'false': _false
			},
			properties: {}
		};
	}

	createContainerStep(id: any, steps: any) {
		return {
			id,
			componentType: 'container',
			type: 'loop',
			name: 'Loop',
			properties: {},
			sequence: steps
		};
	}


sequential-workflow-model.ts


// Define a model for an Email Task Step
export const emailTaskModel = createStepModel<Step>('email', 'task', step => {
  // Define the "recipient" property
  step.property('recipient')
    .value(createStringValueModel({
      minLength: 1, // Minimum length of 1 character
    }))
    .label('Recipient');

  // Define the "subject" property
  step.property('subject')
    .value(createStringValueModel({
      minLength: 1, // Minimum length of 1 character
    }))
    .label('Email Subject');

  // Define the "message" property
  step.property('message')
    .value(createStringValueModel({
      minLength: 1, // Minimum length of 1 character
    }))
    .label('Email Message');
});

// Define your custom step types as interfaces if needed
export interface TaskStep extends Step {
  type: string; // Type of task (e.g., 'save', 'text', 'task')
  name: string; // Human-readable name for the task
  velocity: string; // A string representing the "speed" or priority of the task
  // Add any other task-specific properties here
}

export interface IfStep extends Step {
  condition: string; // The condition to evaluate, represented as a string
  branches: {
				'true': true,
				'false': false
			};
  // Any additional properties related to conditional execution
}


export interface ContainerStep extends Step {
  sequence: Step[]; // An array of steps that are part of this container
  // Additional properties that define how the steps in the sequence are executed
}


// Use createStepModel to define your custom steps
export const taskStepModel = createStepModel<TaskStep>('task', 'task', step => {
 step.property('type')
    .value(createStringValueModel({
      // Example configuration: Adjust these properties as needed
      minLength: 1,

    }))
    .label('Task Type');

  step.property('name')
    .value(createStringValueModel({
      minLength: 1, // Minimum length of 1 character
    }))
    .label('Task Name');

  step.property('velocity')
    .value(createStringValueModel({
      // Convert the string pattern to a RegExp object
      pattern: new RegExp('^[0-9]+$'), // Ensures the velocity is a number
    }))
    .label('Velocity');
});


export const ifStepModel = createStepModel<IfStep>('if', 'switch', step => {
  step.property('condition')
    .value(createStringValueModel({
      minLength: 1, // Assuming a simple condition represented as a string
    }))
    .label('Condition');
;
});


export const containerStepModel = createStepModel<ContainerStep>('loop', 'container', step => {
  // Assuming sequence needs to be an array of step IDs or similar identifiers
  step.property('sequence')
    .value(createStringValueModel({
      minLength: 1, // Adjust based on how sequences are represented
    }))
    .label('Sequence');

  // Container-specific properties can be added here
});




export const rootModel = createRootModel<MyDefinition>(root => {
  root.property('inputs')
    .value(
      createVariableDefinitionsValueModel({})
    );
});


export const definitionModel = createDefinitionModel<MyDefinition>(model => {
  model.valueTypes(['string', 'number']);
  model.root(rootModel);
  model.steps([logStepModel, taskStepModel, ifStepModel, containerStepModel, emailTaskModel]);
});


export const editorProvider = EditorProvider.create(definitionModel, {
    uidGenerator: Uid.next,

});
`

calling it like this from the component

this.toolboxConfiguration = { groups: editorProvider.getToolboxGroups() };

the taskStepModel and emailTaskModel seem to work but the ifStepModel and containerStepModel give a lot of errors.

Any suggestions?

Dynamically extending parallelStepModel - angular

Hi, great application.

I'm trying to add and remove branches using the Angular version. like in this example

https://nocode-js.github.io/sequential-workflow-designer/examples/multi-conditional-switch.html

https://github.com/nocode-js/sequential-workflow-designer/blob/7ca5488da7a5b42419c9f764f004354e6ebb4245/examples/assets/multi-conditional-switch.js

I'm having a lot of difficulty with the TypeScripts restrictions; maybe you can offer some suggestions.

I tried many techniques. This is the code I have now. I am able to add the steps to the designer but not the editor panel.

I am trying to update the parallelStepModel before calling const editorRoot = originalStepEditorProvider(step, context, definition, false), but I can't get it to work. I'm not even sure if this is the best approach.

Thank you in advance.

export interface ParallelStep extends BranchedStep {
  componentType: 'switch';
  type: 'parallel';
  name;
  properties: {
      'Condition 0': Dynamic<NullableAnyVariable | string | number | boolean>;
      'Condition 1': Dynamic<NullableAnyVariable | string | number | boolean>;
      'Condition 2': Dynamic<NullableAnyVariable | string | number | boolean>;
      'Condition 3': Dynamic<NullableAnyVariable | string | number | boolean>;
      'Condition 4': Dynamic<NullableAnyVariable | string | number | boolean>;
      'Condition 5': Dynamic<NullableAnyVariable | string | number | boolean>;
  };
    branches: {
    'Condition 0': Step[];
    'Condition 1': Step[];
    'Condition 2': Step[];
    'Condition 3': Step[];
    'Condition 4': Step[];
    'Condition 5': Step[];
  };
}

model.ts
export const parallelStepModel = createBranchedStepModel<ParallelStep>('parallel', 'switch', step => {
  // Step Name Generation
  step.name().value(
    createGeneratedStringValueModel({
      generator(context) {
        return 'Parallel Condition';
      }
    })
  );

  // Step Category and Description
  step.category('Logic');
  step.description('Check condition and execute different branches.');

  // Dynamic Value Model for Conditions
  const dynamicValueModel = createDynamicValueModel({
    models: [
      createNullableAnyVariableValueModel({
        isRequired: true,
        valueTypes: ['string', 'number', 'boolean']
      }),
      createStringValueModel({}),
      createNumberValueModel({}),
      createBooleanValueModel({})
    ]
  });

  // Set Properties for Conditions
  step.property('Condition 0').value(dynamicValueModel);
  step.property('Condition 1').value(dynamicValueModel);
  step.property('Condition 2').value(dynamicValueModel);


  // Set Branches for Conditions
  step.branches().value(
    createBranchesValueModel({
      branches: {
        'Condition 0': [],  // These branches are populated dynamically when creating the step
        'Condition 1': [],
        'Condition 2': []
      }
    })
  );

});


component.ts

function appendButton(root: HTMLElement, label: string, step: Step | BranchedStep, context) {

  const button = document.createElement('button');
  button.textContent = label;
  button.addEventListener('click', () => {
    if ('branches' in step) {
      if (!step.branches) {
        step.branches = {};

      }

      // Calculate the next sequence number
      const existingBranchKeys = Object.keys(step.branches);
      let maxSequence = 2; // Start from 2 because we will increment it for the next branch
      existingBranchKeys.forEach(key => {
        const sequenceNum = parseInt(key.replace(/^\D+/g, '')); // Remove non-digit characters and parse
        if (!isNaN(sequenceNum) && sequenceNum > maxSequence) {
          maxSequence = sequenceNum;
        }
      });

      const nextSequence = maxSequence + 1;
      const branchName = `Condition ${nextSequence}`;



      // Add a new branch with a sequence number. Initialize as an empty array or with a default step object
      step.branches[branchName] = []; // Assuming branches are arrays of steps
      step.properties[branchName] = {
          "modelId": "nullableAnyVariable",
          "value": null
        },

      // Optionally, if you need to initialize with a default step, you could do something like:
      // step.branches[branchName] = [{ /* Default step object structure */ }];

      // Notify the context that children have changed
      context.notifyChildrenChanged();
      		const branch = document.createElement('div');
          branch.className = 'switch-branch';

          const title = document.createElement('h4');
          title.innerText = "name";

          const label = document.createElement('label');
          label.innerText = 'Condition: ';

          root.appendChild(title);
          root.appendChild(label);
            const dynamicValueModel = createDynamicValueModel({
    models: [
      createNullableAnyVariableValueModel({
        isRequired: true,
        valueTypes: ['string', 'number', 'boolean']
      }),
      createStringValueModel({}),
      createNumberValueModel({}),
      createBooleanValueModel({})
    ]
  });
            console.log('dynamicValueModel', dynamicValueModel)
      appendConditionEditor(root,
        dynamicValueModel, value => {
			step.properties[branchName] = value;
			context.notifyPropertiesChanged();
		});
    }
  });

  // Append the button to the root element provided
  root.appendChild(button);
}

public ngOnInit() {
    this.isLoading = true;
    this.store.pipe(
      takeUntil(this._destroyed)
    ).subscribe((state: any) => {
      if (state.auth?.user) {
        this.userState = state.auth.user;
      }
    });
    const docPayload = {
      collections: ['WorkflowDefinition'],
      // filter: {'account_id': 1}
      data: null
    }
    const tablePayload = {
      tables: ['User'],
      data: null
    }
    this.store.dispatch(ResourcesPageActions.getDocumentData({payload: docPayload}));
    this.store.dispatch(ResourcesPageActions.getTableData({payload: tablePayload}));
    this.dropdownListAry['Boolean'] = [{id: false, name: 'False'}, {id: true, name: 'True'}]

    const editorProvider = EditorProvider.create(definitionModel, {
      uidGenerator: Uid.next
    });
    const activatedDefinition = editorProvider.activateDefinition();
    console.log('activatedDefinition', activatedDefinition)

    this.stepEditorProvider = editorProvider.createStepEditorProvider();
    this.rootEditorProvider = editorProvider.createRootEditorProvider();
    const originalStepEditorProvider = this.stepEditorProvider;


    this.stepEditorProvider = (step: Step | BranchedStep, context, definition) => {
      // Create a new root div as the base for our custom editor UI
      const root = document.createElement('div');
      root.className = "sqd-editor sqd-step-editor";

      // Use the original provider to get the editor component, if needed
      console.log('step', step)
      this.addNewCondition('Condition 3')
      const editorRoot = originalStepEditorProvider(step, context, definition, false);
      console.log('editorRoot', editorRoot)

      // Type guard to check if step is of type that has branches
      if ('branches' in step && step.type === 'parallel') {
        appendButton(root, 'Add Condition', step, context);
      }
      editorRoot.appendChild(root);
      return editorRoot;

    };

    this.validatorConfiguration = {
      root: editorProvider.createRootValidator(),
      step: editorProvider.createStepValidator()
    };
    this.toolboxConfiguration = {
      groups: editorProvider.getToolboxGroups()
    };

    this.updateDefinitionJSON();
  }

Multi Value Array/Dictionary

Dear Team,

I'd like to express my appreciation for the Workflow Editor. Its user-friendly interface and versatile features made it easy to get started. However, as I delve deeper into its capabilities, I've encountered challenges beyond my current abilities.

I'm currently exploring the Workflow Editor and its capabilities. Specifically, I'm uncertain about how to add a Multi-Value Array or Dictionary to a step. Could you please provide guidance on this matter, or clarify if it's not supported? For example, I'd like to create a dictionary with animals described by Type, Size, and Name.

Thank you for your assistance.

Best regards,
Max

export const anyVariablesStepModel = createStepModel<TransitionVariablesStepModel>('animal', 'task', step => { step.property('Animal') .label('Animal Entry') .value( [ { createChoiceValueModel({ choices: ["Dog", "Cat", "Mouse"] }) }, { createNumberValueModel({ defaultValue: size.Default, min: size.Min, max: size.Max }); }, { createStringValueModel({ defaultValue: animalName }) } );

How to use the Sequential Workflow Editor in react

I try to use the sequential-workflow-editor with sequential-workflow-designer-react.
But i can't find the option globalEditorProvider and stepEditorProvider in SequentialWorkflowDesigner component.
You can help me to use the sequential-workflow-editor in react?

Returning or passing variables between steps

I appreciate your work on this library, very cool!

Just so you know, I am not sure it makes a big difference, but I am using the React designer.

I have been trying to figure out the standard way to handle this rather than building a custom variable service of some sort.

Step A - Performs a computation and stores it to a variable
Step B - Uses the variable/return from the previous step

It seems that the scope is limited to the step itself when the variable is defined within the step.

image

However, I need to use the result of Step A and feed that into Step B. It is not available here

image

From the docs

When a variable is defined in the parent scope, it can be accessed in the child scope, but not vice versa.

Is the "log" step in the image not a child of the "output" step? It seems they are more treated as independent functions rather than a parent/child relationship

What is the best way to handle this scenario? Essentially a return variable from one step and use that return variable in the next step.

Output Step

interface OuputStep extends Step {
  type: 'output'
  componentType: 'task'
  properties: {
    output: NullableVariableDefinition
    showVariable: NullableVariable
  }
}

export const Output = createStepModel<OuputStep>('output', 'task', (step) => {
  step.category('Output')
  step.label('Output')
  step.property('output').value(
    createNullableVariableDefinitionValueModel({
      valueType: 'number',
      isRequired: true,
      defaultValue: {
        name: 'test',
        type: 'number',
      },
    })
  )
  step
    .property('showVariable')
    .value(
      createNullableVariableValueModel({
        isRequired: true,
        valueType: 'number',
      })
    )
    .label('Value to Log')
})

Log Step

interface ValueLogStepDef extends Step {
  componentType: 'task'
  properties: {
    valueToLog: NullableVariable
    alert: boolean
  }
}

export const ValueLog = createStepModel<ValueLogStepDef>('log', 'task', (step) => {
  step.category('Tracing')

  step
    .property('valueToLog')
    .value(
      createNullableVariableValueModel({
        isRequired: true,
        valueType: 'number',
      })
    )
    .label('Value to Log')

  step.property('alert').value(createBooleanValueModel({})).label('Alert?')
})

Definition

  const definitionModel = useMemo(
    () =>
      createDefinitionModel<T>((model) => {
        model.valueTypes(['string', 'number'])
        model.root(rootModel)
        model.steps([OutputStep, ValueLogStep])
      }),
    []
  )

Thank you very much!

How can I dynamically update the task name

How can I dynamically update the task name to include one of the property values? Here is my model. I'm trying to have the name = 'Say or Ask ' + property('question') value.

export const questionTaskModel = createStepModel('question', 'task', step => {
step.category('Questions');
step.name().value(createGeneratedStringValueModel({
generator(context) {
return 'Say or Ask' ;
}
}));
step.property('question').value(
createChoiceValueModel({
choices: ['Text'],
defaultValue: ''
})
).label('Script');
step.property('question_id')
.value(createStringValueModel({

}))
.label('Question ID');

});

Dynamic definition model & steps

Hi!
I'm triying to create steps on realtime, which means that my backend sends the information about which steps will be used and the corresponding definition of them.
In my case, I have a variable with all the steps and the definition about them, and now I have a React Component that loops for all of them and generate the Step content. But I would like to use the swd-editor to avoid developing validations & features that the editor has.


export interface LogStep extends Step {
  type: 'log';
  componentType: 'task';
  properties: {
    message: string;
  };
}



export const definitionModel = createDefinitionModel<MyDefinition>(model => {
  model.valueTypes(['string', 'number']);
  model.root(rootModel);
  model.steps([logStepModel]);
});

Is there any chance to generate the StepTypes and definition model dynamically based on schema data sent from the backend?

Thanks in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.