Code Monkey home page Code Monkey logo

gojs-react's Introduction

gojs-react

By Northwoods Software for GoJS

This project provides React components for GoJS Diagrams, Palettes, and Overviews to simplify usage of GoJS within a React application. See the gojs-react-basic project for example usage and the Intro page on using GoJS with React for more information. Some more detail on the implementation of these components can be found here.

npm open issues

Installation

gojs-react can be installed via NPM or used via CDN. This package has peer dependencies on GoJS and React, so make sure those are also installed or included on your page.

NPM

npm install --save gojs-react

CDN

<script src="https://unpkg.com/gojs-react/dist/gojsreact.production.min.js"></script>

Usage

This package provides three components - ReactDiagram, ReactPalette, and ReactOverview - corresponding to the related GoJS classes. The gojs-react-basic repository provides example usage. Feel free to use these components as examples for setting up your own React components for GoJS. If you'd like to do so, we suggest reading more about the implementation of these components here.

<ReactDiagram
  ref={this.diagramRef}
  divClassName='diagram-component'
  style={{ backgroundColor: '#eee' }}
  initDiagram={this.initDiagram}
  nodeDataArray={this.props.nodeDataArray}
  linkDataArray={this.props.linkDataArray}
  modelData={this.props.modelData}
  onModelChange={this.props.onModelChange}
  skipsDiagramUpdate={this.props.skipsDiagramUpdate}
/>

<ReactPalette
  initPalette={this.initPalette}
  divClassName='palette-component'
  style={{ backgroundColor: '#eee' }}
  nodeDataArray={[{ key: 0, text: 'Alpha' }]}
/>

<ReactOverview
  initOverview={this.initOverview}
  divClassName='overview-component'
  style={{ backgroundColor: '#eee' }}
  observedDiagram={this.state.observed}
/>

Component Props

initDiagram/initPalette/initOverview

Specifies a function that is reponsible for initializing and returning a GoJS Diagram, Palette, or Overview. This is where the model and templates should be instantiated. Node and link data do not need to be set up here, as they will be passed in as separate props.

In the case of an Overview, this is an optional property and when not provided, an Overview with default properties and centered content will be created.

function initDiagram() {
  const $ = go.GraphObject.make;

  const diagram = $(go.Diagram,
    {
      'undoManager.isEnabled': true,  // must be set to allow for model change listening
      // 'undoManager.maxHistoryLength': 0,  // uncomment disable undo/redo functionality
      model: $(go.GraphLinksModel, {
        linkKeyProperty: 'key'  // this should always be set when using a GraphLinksModel
      })
    });

  diagram.nodeTemplate =
    $(go.Node, 'Auto',  // the Shape will go around the TextBlock
      $(go.Shape, 'RoundedRectangle', { strokeWidth: 0, fill: 'white' },
        // Shape.fill is bound to Node.data.color
        new go.Binding('fill', 'color')),
      $(go.TextBlock,
        { margin: 8 },  // some room around the text
        // TextBlock.text is bound to Node.data.key
        new go.Binding('text', 'key'))
    );

  return diagram;
}

divClassName

Specifies the CSS classname to add to the rendered div. This should usually specify a width/height.

.diagram-component {
  width: 400px;
  height: 400px;
  border: 1px solid black;
}

Optional - style

Specifies the style object to add to the rendered div. Uses React.CSSProperties. Using divClassName is preferred.

style: { backgroundColor: '#333' }

nodeDataArray (ReactDiagram and ReactPalette only)

Specifies the array of nodes for the Diagram's model.

Properties should not be removed when setting state, but rather set to undefined if they are no longer needed; GoJS avoids destructive merging.

nodeDataArray: [
  { key: 'Alpha', color: 'lightblue' },
  { key: 'Beta', color: 'orange' },
  { key: 'Gamma', color: 'lightgreen' },
  { key: 'Delta', color: 'pink' }
]

Optional - linkDataArray (ReactDiagram and ReactPalette only)

Specifies the array of links for the Diagram's model, only needed when using a GraphLinksModel, not for Models or TreeModels. If using a GraphLinksModel, make sure to set the GraphLinksModel's linkKeyProperty in the init function.

Properties should not be removed when setting state, but rather set to undefined if they are no longer needed; GoJS avoids destructive merging.

linkDataArray: [
  { key: -1, from: 'Alpha', to: 'Beta' },
  { key: -2, from: 'Alpha', to: 'Gamma' },
  { key: -3, from: 'Beta', to: 'Beta' },
  { key: -4, from: 'Gamma', to: 'Delta' },
  { key: -5, from: 'Delta', to: 'Alpha' }
]

Optional - modelData (ReactDiagram and ReactPalette only)

Specifies a modelData object for the Diagram's model, only necessary when using properties that will be shared by the model as a whole. See Model.modelData.

Optional - skipsDiagramUpdate (ReactDiagram only)

Specifies whether the component should skip updating, often set to true when updating state originating from a GoJS model change. This flag is checked during shouldComponentUpdate. Because GoJS Palettes are read-only by default, this prop is not present on ReactPalette.

Optional - onModelChange (ReactDiagram only)

Specifies a function to be called when a GoJS transaction has completed. This function will typically be responsible for updating React/Redux state.

It is important that state updates made in this function include setting skipsDiagramUpdate to true since the changes are known by GoJS. It will fire even when a GoJS change originated from a state update, as there could be side effects that occur in GoJS. It's a good idea to properly filter out any unnecessary changes before updating state.

Because GoJS Palettes are read-only by default, this prop is not present on ReactPalette. Although there won't be user-driven changes to a Palette's model due to the read-only nature of Palettes, changes to the nodeDataArray, linkDataArray, or modelData props described above allow for a Palette's model to be changed, if necessary.

function handleModelChange(data) {
  const insertedNodeKeys = data.insertedNodeKeys;
  const modifiedNodeData = data.modifiedNodeData;
  const removedNodeKeys = data.removedNodeKeys;
  const insertedLinkKeys = data.insertedLinkKeys;
  const modifiedLinkData = data.modifiedLinkData;
  const removedLinkKeys = data.removedLinkKeys;

  // ... make state changes
}

observedDiagram (ReactOverview only)

Specifies the go.Diagram which the Overview will observe.

Component Methods

getDiagram/getPalette/getOverview

Gets a reference to the GoJS Diagram/Palette/Overview.

const diagram = this.diagramRef.current.getDiagram();
if (diagram instanceof go.Diagram) {
  // ...
}

clear (ReactDiagram and ReactPalette only)

Clears the diagram and allows the next update to be treated as an initial load of the model.

// clear out the diagram
this.diagramRef.current.clear();
// provide new diagram data, which will be treated as initial data
this.setState({
  nodeDataArray: [
    { key: 'Epsilon', color: 'lightblue' },
    { key: 'Zeta', color: 'orange' },
    { key: 'Eta', color: 'lightgreen' },
    { key: 'Theta', color: 'pink' }
  ],
  linkDataArray: [
    { key: -1, from: 'Epsilon', to: 'Zeta' },
    { key: -2, from: 'Epsilon', to: 'Eta' },
    { key: -3, from: 'Zeta', to: 'Zeta' },
    { key: -4, from: 'Zeta', to: 'Theta' },
    { key: -5, from: 'Theta', to: 'Epsilon' }
  ]
});

License

This project is intended to be used alongside GoJS, and is covered by the GoJS software license.

Copyright 1998-2023 by Northwoods Software Corporation.

gojs-react's People

Contributors

dependabot[bot] avatar jonchardy avatar simonsarris avatar walternorthwoods 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  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  avatar  avatar  avatar  avatar  avatar

gojs-react's Issues

question

你好,这个怎么运行呢

Updating state with different nodeDataArray does not recompute group

Setting a new NodeDataArray with different group create issue.

Ex array :

[{
   key:1
   name:"child",
   category:"child",
   group:2
},
{
   key:2
   name:"group",
   isGroup:true
   category:"group"
}]

Then we use setState with :

[{
   key:1
   name:"child",
   category:"child",
},
{
   key:2
   name:"group",
   isGroup:true
   category:"group"
}]

And the node "child" will still be inside the group.
It seems like those lines are missing from gojs-react :

diagram.startTransaction(); diagram.updateAllRelationshipsFromData(); diagram.updateAllTargetBindings(); diagram.commitTransaction("update");

onModelChange not triggered unless UndoManager.isEnabled

Hi.

I have a few different diagrams (Layered, Force, Radial, Sankey, etc) and I wanted to migrate from react-gojs to your official version. First thing I notice it is new addition of the toIncrementalData, this method is called in the onModelChange. So far so good, until we want to disable undoManager. Then onModelChange it is not triggered anymore.

https://codesandbox.io/s/interesting-gauss-9pofo

In that url you could find a modification of your example(https://github.com/NorthwoodsSoftware/gojs-react-basic). The only 2 things I modified from the original it is:
Added console.log in the handleModelChange in App.tsx
Changed "undoManager.isEnabled": false in Diagram.tsx

What I detected is in const dataChanges = e.model!.toIncrementalData(e); in Diagram file it is always null with this options to false, meanwhile if you put to true is working as expected.

I report it as issues because I expected this is called no matter if undoManager is or not enable, but maybe I missing something.

Regards.

Diagram scrollMargin parameter bug

Hi! I think I found a bug in gojs-react.
Im trying to run my gojs app using React and Electron. During my rewrite I noticed that scrollMargin parameter in 'go.Diagram' was causing the following errors:

go.js:773 Uncaught TypeError: this.Yq is not a function
    at Q.set (go.js:773)
    at zj (go.js:651)
    at Ll (go.js:929)
    at Jl (go.js:924)
    at Object.initDiagram (DiagramWrapper.tsx:70)
    at ReactDiagram../node_modules/gojs-react/lib/esm/gojsreact.js.ReactDiagram.componentDidMount (gojsreact.js:23)
    at commitLifeCycles (react-dom.development.js:22101)
    at commitLayoutEffects (react-dom.development.js:25344)
    at HTMLUnknownElement.callCallback (react-dom.development.js:336)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:385)

and

react-dom.development.js:12212 Uncaught TypeError: this.Yq is not a function
    at Q.set (go.js:773)
    at zj (go.js:651)
    at Ll (go.js:929)
    at Jl (go.js:924)
    at Object.initDiagram (DiagramWrapper.tsx:70)
    at ReactDiagram../node_modules/gojs-react/lib/esm/gojsreact.js.ReactDiagram.componentDidMount (gojsreact.js:23)
    at commitLifeCycles (react-dom.development.js:22101)
    at commitLayoutEffects (react-dom.development.js:25344)
    at HTMLUnknownElement.callCallback (react-dom.development.js:336)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:385)

And NOTHING shows on the screen. Even stuff unrelated to GoJS.
It's something about this 'Yq' function. I haven't looked into it deeper. Here's my code for reference:

  • Not working:
const diagram =
      $(go.Diagram,
        {
            scrollMargin: 2000,
            [other params]
        });

  • Working:
const diagram =
      $(go.Diagram,
        {
            [other params]
        });

FIX
For anyone having this problem: only removing this parameter worked for me so that's I guess what you have to do until it's fixed if you want your app to show anything.

If anyone knows a workaround without tradeoffs please share.

Trying to set undefined property "mode" on object: Diagram

os: linux ubuntu 16.04
node: 15.0.1
gojs: 2.1.31
gojs-react: 1.0.10
react: 17.0.1
webpack: 5.10.0

Trying to start following this project README but getting such error. After removing it, gojs start to complain that GraphLinksModel.linkKeyProperty must be not empty string.

Using modelData from https://gojs.net/latest/samples/flowchart.html

Debugging shows that passing modelData, nodeDataArray and linkDataArray to component not helping at all, linkKeyPropety is empty string same as dataArray.

ReactDiagram update with new links passed from props but ignores change of nodes

When I pass new props.project.nodes array, it gets ignored - however new link in props.project.edgescorrectly displays. Is there anything I could be doing wrong?
Both values are obtained through the same GraphQL query.

// Diagram usage

export function ProjectDiagram(props: GetProject) {
  return (
    <div>
      <ReactDiagram
        skipsDiagramUpdate={false}
        initDiagram={initDiagram}
        divClassName="diagram-component"
        nodeDataArray={props.project.nodes.map((node) => ({
          key: node.uniqueName,
          text: node.uniqueName,
        }))}
        linkDataArray={props.project.edges.map((edge) => ({
          key: edge.id,
          from: edge.sourceNodeId,
          to: edge.targetNodeId,
        }))}
        onModelChange={handleModelChange}
      />
    </div>
  );
}
// GraphQL query which's results are in props

export const GET_PROJECT = gql`
  query GetProject($id: String!) {
    project(id: $id) {
      id
      name
      createdAt
      edges {
        id
        sourceNodeId
        targetNodeId
      }
      nodes {
        uniqueName
      }
      users {
        id
        role
      }
    }
  }
`;

Cant initialise Reactpalatte

I am converting the javascript palette code to reactjs but cant able to pass "myDiagram" object from initDiagram to initPalette. Please provide a way to do it

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.