Giter Site home page Giter Site logo

Comments (4)

phlickey avatar phlickey commented on May 14, 2024 8

Hey @dSecret ,

Have been trying to figure out this example myself today as well. Using the mapValues method from lodash kind of obscures what's really going on under the hood. Basically, what it's doing is mapping the default actions to actions that update the state of the container class.

The example below makes use of state with hooks and shows a little more verbosely how the action callbacks work. If you were using redux, this is where you would dispatch actions.

import React, {useState, useEffect} from "react";
import {FlowChart} from "@mrblenny/react-flow-chart";
import * as actions from "@mrblenny/react-flow-chart/src/container/actions";
export default function ChatEditor(){
    let [chart, updateChart] = useState({
        offset:{
            x: 0,
            y: 0
        },
        nodes : {
            node1: {
                id: "node1",
                type: "output-only",
                position: {
                    x: 0,
                    y: 0
                },
                ports: {
                    port1:{
                        id: "port1",
                        type: "output",
                        properties:{
                            value: "yes"
                        }
                    },
                    port2:{
                        id: "port2",
                        type: "output",
                        properties:{
                            value: "no"
                        }
                    }
                }
            },
            node2 :{
                id: "node2",
                position: {
                    x: 300,
                    y: 100
                },
                type: "input-output",
                ports: {
                    port3 :{
                        id : "port3",
                        type: "output"
                    },
                    port4 :{
                        id : "port4",
                        type: "input"
                    }
                }
            }
        },
        links: {

        },
        selected: {},
        hovered: {}
    });

    let stateActionCallbacks = Object.keys(actions).reduce((obj,key,idx)=>{
        obj[key] = (...args)=>{
            let action = actions[key];
            let newChartTransformer = action(...args);
            let newChart = newChartTransformer(chart);
            updateChart({...chart, ...newChart});
            return newChart;
        };
        return obj;
    },{});
    return(
        <FlowChart
            chart={chart}
            callbacks={stateActionCallbacks}
        />
    )
}

from react-flow-chart.

mkellogg91 avatar mkellogg91 commented on May 14, 2024 3

@phlickey 's answer worked for me also wish I would have found it sooner ;( . I modified it a little since I'm using react class components to use setState instead of hooks.

my version of the callback mapping looked like this:

const stateActionCallbacks = Object.keys(actions).reduce((obj, key, idx) => {
      obj[key] = (...args) => {
        let action = actions[key];
        let newChartTransformer = action(...args);
        let newChart = newChartTransformer(this.state.chart);
        this.setState({
          chart: { ...this.state.chart, ...newChart }
        });
        return newChart;
      };
      return obj;
    }, {});

from react-flow-chart.

LucianoGanga avatar LucianoGanga commented on May 14, 2024 1

I'd like to share what I did in order to allow triggering custom functions on certain events:

It needs improvements with the types, as I'm not an expert on that.

  const customCallbacks = useMemo<{ [key: string]: any }>(() => {
    return {
      onNodeClick: ({ nodeId }: { nodeId: string }) => {
        console.log('clicked', nodeId)
        handleNodeClick(nodeId)
      }
    }
  }, [handleNodeClick])

  const stateActionCallbacks = useMemo(() => {
    return Object.entries(actions).reduce(
      (
        acc: { [key: string]: any },
        [actionKey, action]: [string, (...args: any) => any]
      ) => {
        acc[actionKey] = (...args: any) => {
          const newChartTransformer = action(...args)
          const newChart = newChartTransformer(chart)
          if (customCallbacks[actionKey]) {
            customCallbacks[actionKey](...args)
          }
          setChart({ ...newChart })
          return newChart
        }
        return acc
      },
      {}
    ) as IFlowChartCallbacks
  }, [chart, customCallbacks])

Also. I've noticed that having FlowChart inside a component, triggers the rendering on the upper components (as it should do in React).

For that reason and to avoid unnecessary re-rendering, I've put the FlowChart inside a memo before using it in my app. This is how my custom FlowChart component looks like on my project:

import React, { memo, useMemo, useState, useCallback } from 'react'

import * as actions from '@mrblenny/react-flow-chart/src/container/actions'
import { FlowChart, IFlowChartCallbacks } from '@mrblenny/react-flow-chart'

import NodeInner from '../components/NodeInner'

import { chartSimple } from '../chartSimple'

export default memo(({ handleNodeClick }: any) => {
  const [chart, setChart] = useState(chartSimple)

  const NodeInnerCustom = useCallback(
    (props) => <NodeInner {...props} handleNodeClick={handleNodeClick} />,
    [handleNodeClick]
  )

  const customCallbacks = useMemo<{ [key: string]: any }>(() => {
    return {
      onNodeClick: ({ nodeId }: { nodeId: string }) => {
        console.log('Clicked!', nodeId)
        handleNodeClick(nodeId)
      }
    }
  }, [handleNodeClick])

  const stateActionCallbacks = useMemo(() => {
    return Object.entries(actions).reduce(
      (
        acc: { [key: string]: any },
        [actionKey, action]: [string, (...args: any) => any]
      ) => {
        acc[actionKey] = (...args: any) => {
          const newChartTransformer = action(...args)
          const newChart = newChartTransformer(chart)
          if (customCallbacks[actionKey]) {
            customCallbacks[actionKey](...args)
          }
          setChart({ ...newChart })
          return newChart
        }
        return acc
      },
      {}
    ) as IFlowChartCallbacks
  }, [chart, customCallbacks])

  return (
    <FlowChart
      chart={chart}
      callbacks={stateActionCallbacks}
      Components={{
        NodeInner: NodeInnerCustom
      }}
    />
  )
})

Cheers!
Lucho

from react-flow-chart.

v4irajvimu avatar v4irajvimu commented on May 14, 2024

Hey @dSecret ,

Have been trying to figure out this example myself today as well. Using the mapValues method from lodash kind of obscures what's really going on under the hood. Basically, what it's doing is mapping the default actions to actions that update the state of the container class.

The example below makes use of state with hooks and shows a little more verbosely how the action callbacks work. If you were using redux, this is where you would dispatch actions.

import React, {useState, useEffect} from "react";
import {FlowChart} from "@mrblenny/react-flow-chart";
import * as actions from "@mrblenny/react-flow-chart/src/container/actions";
export default function ChatEditor(){
    let [chart, updateChart] = useState({
        offset:{
            x: 0,
            y: 0
        },
        nodes : {
            node1: {
                id: "node1",
                type: "output-only",
                position: {
                    x: 0,
                    y: 0
                },
                ports: {
                    port1:{
                        id: "port1",
                        type: "output",
                        properties:{
                            value: "yes"
                        }
                    },
                    port2:{
                        id: "port2",
                        type: "output",
                        properties:{
                            value: "no"
                        }
                    }
                }
            },
            node2 :{
                id: "node2",
                position: {
                    x: 300,
                    y: 100
                },
                type: "input-output",
                ports: {
                    port3 :{
                        id : "port3",
                        type: "output"
                    },
                    port4 :{
                        id : "port4",
                        type: "input"
                    }
                }
            }
        },
        links: {

        },
        selected: {},
        hovered: {}
    });

    let stateActionCallbacks = Object.keys(actions).reduce((obj,key,idx)=>{
        obj[key] = (...args)=>{
            let action = actions[key];
            let newChartTransformer = action(...args);
            let newChart = newChartTransformer(chart);
            updateChart({...chart, ...newChart});
            return newChart;
        };
        return obj;
    },{});
    return(
        <FlowChart
            chart={chart}
            callbacks={stateActionCallbacks}
        />
    )
}

this worked for me. thanks.

from react-flow-chart.

Related Issues (20)

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.