import { createSelector } from '@reduxjs/toolkit' import _difference from 'lodash/difference' import { ActionType } from '../actions/types' import { RootState } from '../store' const selectSelf = (state: RootState) => state /** * Select all workflow relations sequence correctly by ordered * @returns */ export const selectNormalizedActionRelationsSequence = () => createSelector(selectSelf, (state: RootState) => { const { actions, relations } = state const [source] = actions.filter(({ type }) => type === ActionType.SOURCE) const [root] = relations.filter(({ actName }) => actName === source.name) let normalizedRelations = [root] let curr = root let i = 0 while (i < relations.length) { const [next] = relations.filter(({ id }) => id === curr.rel[0]) if (!next) break normalizedRelations = [...normalizedRelations, next] curr = next i++ } return normalizedRelations }) /** * Select a normalized state snapshot * (actions, relations, pipeline is in correct order head -> tail) * @returns */ export const selectNormalizedState = () => createSelector(selectSelf, (state: RootState) => { const relations = selectNormalizedActionRelationsSequence()(state) const actions = relations.map(relation => { return state.actions.filter(act => act.name === relation.actName)[0] }) const pipeline = relations.map(relation => { return state.pipeline.filter(pl => pl.id === relation.id)[0] }) return { actions, relations, pipeline, } }) /** * Select all missed or disconnected relations * @returns */ export const selectAllMissedActionRelations = () => createSelector(selectSelf, (state: RootState) => { const relations = selectNormalizedActionRelationsSequence()(state) return _difference(state.relations, relations) })