Code Monkey home page Code Monkey logo

react-sigma's Introduction

react-sigma's People

Contributors

adam4lexander avatar dsebastien avatar grothendeick avatar jacomyal avatar jakobhansen-blai avatar kristof-mattei avatar maheshchandra10 avatar mbongard avatar mifopen avatar sim51 avatar willwur 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

react-sigma's Issues

Sigma instances are not killed when component is unmounted

I have an application where I mount and unmount often my sigma component, while I have another instance behind that is always there.
At some point, since the sigma instances are not killed which makes the WebGL contexts leak, the main instance (the one behind) stopped working.

Display mixed node type doesn't work

  • React-sigma-v2 version: ^3.0.3"
  • Sigma.js version : "^2.3.1"
  • Graphology version : "^0.25.0"
  • Operating system: Ubuntu 20.04
  • Web browser: chrome 106.0.5249.103 (64-bit)

Steps to reproduce

  • Have a graph with multiple types (circle, image, etc) leads to error, in my specific example, it was a mix of image nodes and regular/circle nodes

Expected behavior

Image nodes would show as images
Regular/Circle nodes would show as circles

Actual behavior

Exactly the same error as the one reported in this ticket: #32 (comment)

Uncaught TypeError: Cannot read properties of undefined (reading 'process')
at Sigma.process (sigma.js?2055:622:1)
at Sigma._refresh (sigma.js?2055:698:1)
at Sigma.refresh (sigma.js?2055:1191:1)
Additionally, include (as appropriate) console logs, stacktraces, screenshots, and other debug info.

Adding React components inbetween Sigma.js layers

Is your feature request related to a problem? Please describe.
In sigma, you can add html elements inbetween layers as seen in #19. This is nice and all, but seems like it only works with normal html elements, not react components.

I'm attempting to create a node hover render DOM layer to pop up information not unlike the hover view in the main Sigmajs.org demo, except not being limited to manual drawing in a canvas context. These popups would ideally live above the drawing layers and below the event layers, not unlike the current hover layer, but inserting elements directly to the dom goes against the React paradigm plus the fact it seems like you can't do it anyway.

Describe the solution you'd like
Some "react" way of inserting components inbetween layers. One way could be having an override or alternative <SigmaContainer> that needs to have its layers manually added as children by the developer so layers can be added or moved around to their wishes.

Describe alternatives you've considered
Realistically, I can probably just find a way for the dom element(s) to be event transparent, but having it as a real layer feels cleaner.

Invalid graph instance - when trying to add nodes then using the input bar

Problem

Hello everyone, I'm trying to dynamically add nodes with some sort of click or modal, or anything. But the moment I start to use the search bar from or the modal or anything that contains an input box, I get this

  • [error](react-dom.development.js:22839 Uncaught Error: Sigma: invalid graph instance.)
  • and The above error occurred in the <ForwardRef> component:

I haven't seen any examples where you can dynamically add individual nodes one by one with some sort of input box, which is why I'm posting here

Code

Here is the code. I simplified it to just have the <SearchControl /> and still get the same error

import { useEffect, useState } from "react";
import MultiUndirectedGraph from "graphology";
import { SigmaContainer, useLoadGraph, useRegisterEvents, ControlsContainer, SearchControl } from "@react-sigma/core";
import "@react-sigma/core/lib/react-sigma.min.css";
import { v4 as uuidv4 } from 'uuid'; 

const TestPage = () => {
  const [graph, setGraph] = useState(new MultiUndirectedGraph());

  const GraphEvents = () => {
    const registerEvents = useRegisterEvents();

    useEffect(() => {
      // Register the events
      registerEvents({
        click: (event) => {
          // graph = new MultiUndirectedGraph();
          setGraph(
            graph.addNode(uuidv4(), { x: event.x, y: event.y, label: "A", size: 10, color: "#FA4F40" })
          );
          console.log("click", event.x, event.y)
        },
      });
    }, [registerEvents]);

    return null;
  };
  return (
    <div className="static w-screen h-screen">
      <SigmaContainer 
        id="container"
        graph={graph}
        settings={{ renderEdgeLabels: true}}
      >
        <ControlsContainer>
          <SearchControl />
        </ControlsContainer>
        <GraphEvents />
      </SigmaContainer>
    </div>
  );
};

export default TestPage

More info

  • Sigma.js version : 2.4.0
  • Graphology version : 0.25.1
  • Operating system: Windows 10
  • Web browser: Chrome
  • Steps to reproduce
  • Expected behavior: Click the graph to create a new node, then use the search bar to type whatever I want (eventually would like to create a new node, etc)
  • Actual behavior: error after creating a new node and then typing into the search bar

Declaration File

Example bug report

Could not find a declaration file for module '@react-sigma/core'. '/home/user/personal/network-graph-test/node_modules/@react-sigma/core/lib/react-sigma_core.esm.min.js' implicitly has an 'any' type.
  There are types at '/home/user/personal/network-graph-test/node_modules/@react-sigma/core/lib/index.d.ts', but this result could not be resolved when respecting package.json "exports". The '@react-sigma/core' library may need to update its package.json or typings.

@react-sigma/core 3.4.0
**Sigma.js version:**2.4.0
Graphology version: 0.25.1
Operating System: Windows 11/WSL2
Web browser: Chrome

Steps to reproduce

Just ran normal installation steps. Just have no typing's. Unsure if this intended.

Adding cluster layer

Hi... Sorry this might be a noob question..
Is it possible to insert a div layer between canvas layers that are inside of the SigmaContainer?
I'm trying to add cluster layer like shown in this example, which I found from sigma.js github repo: https://codesandbox.io/s/github/jacomyal/sigma.js/tree/main/examples/clusters-labels?file=/index.ts:379-455

I have const container = document.getElementById('sigma-container') inside of and it's always null, presumably because it's located inside of the said element. I know this might now even be related to react-sigma-v2 specifically, but I'd really appreciate it if someone can point me in a direction!

Refacto E2E tests

Screenshot are blank for now ... don't know why ...
Perhaps it's due to those deprecations :

RUNNING E2E INTEGRATION TESTS - MAKE SURE PORT 3000 IS NOT IN USAGE
(node:2738) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.
(Use node --trace-deprecation ... to show where the warning was created)
(node:2738) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.

Problem with working on Unix

Im developing graph-map web application on React using sigma.js and react-sigma modules. While i have been developing it on my windows 10 os, everything was fine, but when i put it on macOS or linux (even Docker container), i've got this type of error:

ERROR in ./src/components/sigma_render.tsx
Module not found: Error: Default condition should be last one

sigma_render.tsx - the only component, where i use react-sigma

Here is my code sigma_renderer code:

import { FC, useEffect, useState } from "react";
import Graph from "graphology";
import {SigmaContainer, SearchControl, ControlsContainer, ZoomControl, FullScreenControl, } from "@react-sigma/core";
import "@react-sigma/core/lib/react-sigma.min.css";
import Loader from "./Loader";
import {useTypeSelector} from "./hooks/useTypeSelector";
import {fetchNodes} from "./store/action-creators/node";
import {useActions, useCheckBox} from "./hooks/useActions";
import {fetchFilter} from "./store/action-creators/filter"
import Events from "./useRegisterEvents";
import {store} from "./store";
import Modal from "./Modal";
import { CheckBox } from "./CheckBox";
import {Auth} from "./Auth";

const DemoGraph: React.FC<{}> = () => {
const [content, setContent] = useState({
x: 0,
y: 0
})

store.subscribe(() => {
    // @ts-ignore
    setContent(store.getState().modal.modalData.content)

});

const {data, error, loading} = useTypeSelector(state => state.node)
const {dataCheckState} = useTypeSelector(state => state.checkBox)
const {loading1} = useTypeSelector(state => state.modal)

const {fetchNodes} = useActions()
const{fetchFilter} = useCheckBox()
useEffect(()=>{
    fetchNodes()
    fetchFilter()
}, [])


    const qgraph = new Graph();

    for (let key in data) {
        if (store.getState().checkBox.dataCheckState[key]) {
            for (let i = 0; i < data[key].objects.length; i++) {
                qgraph.addNode(data[key].objects[i].id, {
                    x: data[key].objects[i].x, y: data[key].objects[i].y, size: (data[key].objects[i].size)**0.5 + 1,
                    label: data[key].objects[i].name, color: data[key].objects[i].color
                });
                console.log(data[key].objects[i].id)
            }
        }
    }
    for (let key in data) {
        if (store.getState().checkBox.dataCheckState[key]) {
            for (let i = 0; i < data[key].links.length; i++)
                if (qgraph.hasNode(data[key].links[i][1]) && qgraph.hasNode(data[key].links[i][0]))
                    qgraph.addEdge(data[key].links[i][0], data[key].links[i][1], {type: 'arrow', size: 2})
            console.log('render')
        }
    }
console.log(store.getState().checkBox.dataCheckState)
return (
    <SigmaContainer
        graph={qgraph}
        style={{width: "100vw",
            height: "100vh"}}
        settings={{
            defaultEdgeType: "arrow",
            labelDensity: 0.07,
            labelGridCellSize: 60,
            labelRenderedSizeThreshold: 15,
            labelFont: "Lato, sans-serif",
            zIndex: true,
        }}
    >
        {!(store.getState().auth.flag) && [<Auth login={''} password={''} flag={false}/>]}
        {store.getState().auth.flag && [
            <div>
            <Loader active={loading}/>
            <Loader active={loading1}/>
            {error && [<p>{error}</p>]}
            <Events/>
            <Modal data={store.getState().modal.modalData}/>
            <CheckBox dataCheckBox={store.getState().checkBox.dataCheckState}/>
            <ControlsContainer position={"bottom-right"}>
                <ZoomControl />
                <FullScreenControl />
            </ControlsContainer>
            <ControlsContainer position={"top-right"}>
                <SearchControl style={{ width: "200px" }} />
            </ControlsContainer>
            </div>
]}

    </SigmaContainer>
);

};

export default DemoGraph;

I think, there is problem in package.json in react-sigma, there are some incorrect dependencies. Becouse when i use dockerfile:

FROM node:20

EXPOSE 4000

WORKDIR /frontend

COPY . .

RUN npm ci

CMD npm run start

with .dockerignore

node_modules

There is an error, but when i copy node_modules without .dockerignore everything is working

Module not found: Can't resolve 'tslib'

Hello,

I was getting the following error:

./node_modules/react-sigma-v2/lib/esm/SigmaContainer.js:4:0
Module not found: Can't resolve 'tslib'

I solved it by installing tslib: yarn add tslib
Maybe it would be a good idea to add this to the documentation (dependencies)?

Broken example in the setup documentation

Someone asked on Stack Overflow about a simple detail in the setup documentation, and while trying to get it to work on my side, I figured that the documented example doesn't work out of the box.

To make it work, I needed to install a couple more dependencies then documented:

  • lodash
  • graphology-types

And I needed to update the code to the following:

export const LoadGraph = () => {
  // first change to the example
  const loadGraph = useLoadGraph();

  // also wrapped the graph instantiation side-effect
  useEffect(() => {
    const graph = new Graph();

    graph.addNode("first", {
      // Missing required position
      x: 1,
      y: 1,

      size: 15,
      label: "My first node",
      color: "#FA4F40"
    });

    // Calling the function that was missing from the example
    loadGraph(graph);
  }, [loadGraph]);

  // Returning null to get a valid component
  return null;
};

Edit react-sigma-example

I'm not even sure it's the best way to use react-sigma as I've never used it before, though the hello world style example is definitely broken.

type image undefined

Thanks for your work on this great module. i am refactoring my code to use this module instead of the old react sigma module to render neo4j data. I use a reworked version of the neosig code to map the fields etc. I load the graph into a state and render this state so that the graph is rendered after the data is loaded and processed. I followed this example carefully to add images to nodes:
#32

The graph renders fine unless I set type: image in the addNode function in which case I get the error:

sigma.js:622 Uncaught TypeError: Cannot read properties of undefined (reading 'process')
    at Sigma.process (sigma.js:622:1)
    at Sigma._refresh (sigma.js:698:1)
    at sigma.js:720:1

code extracts below (full module is 450 lines but can share more as useful):

import { SigmaContainer, ControlsContainer, ZoomControl, FullScreenControl, SearchControl, useRegisterEvents } from "@react-sigma/core";
import getNodeProgramImage from "sigma/rendering/webgl/programs/node.image";
import { MultiDirectedGraph } from "graphology";
import "@react-sigma/core/lib/react-sigma.min.css";


const App: FC = () => {
    var sublist = []
    const newgraph = new MultiDirectedGraph();
    const [isLoading, setLoading] = useState(true);
    const [rendergraph, setRendergraph] = useState('');`

...
function Neo4jToSigmaNode(node) {
    //try {if (node.labels){
       // if (node.properties.comment){var nc = node.properties.comment}else{var nc = "Enter Comment"}}}catch{}
        let id = (node.identity.toString())
        newgraph.addNode(id, {y: Math.random(),  x: Math.random(),   label: node.properties.name ,size: 3, type: "image",  image: "https://pbs.twimg.com/profile_images/554245151866900481/Qm1dEySq_200x200.png" })
        return ;
    }
<div style={{ height: "500px",  position: 'relative', left: '5px', top: '0px', right: '5px', bottom: '5px'}}>Chart {toggle}
                        <SigmaContainer    clickNode={onClickNode}  graph={rendergraph}  settings={{
                            nodeProgramClasses: { image: getNodeProgramImage()},
                            labelDensity: 0.07,
                            labelGridCellSize: 60,
                            labelRenderedSizeThreshold: 15,
                            labelFont: "Lato, sans-serif"}} ></SigmaContainer></div>

I have checked that my node add function is adding the type: image and image: url fields to node.attributes.

I'm struggling with how to diagnose this. I suppose the error could be an artifact of me loading the graph into the state then rendering the state value. But it could also be a bug.

Many thanks
Ian

labelColor and edgeLabelColor not behaving as expected

labelColor and edgeLabelColor not behaving as expected

  • React-sigma-v2 version: 3.0.3
  • Sigma.js version : 2.3.1
  • Graphology version : 0.25.0
  • Operating system: Mac and CodeSandbox
  • Web browser: (for example Firefox 82.0.2)

Steps to reproduce

Use either of the following settings in a graph

settings={{
    edgeLabelColor: "#0f0",
    labelColor: "#f00"
  }}

Reproducible CodeSandbox link

Expected behaviour

Edge labels are coloured green and node labels are coloured red

Actual behaviour

Edge labels are coloured black and node labels are not legible

Note

I've used Sigma.js in the past but I'm somewhat new to React so there is a chance I may be using the library incorrectly

I18N for controls

It is possible to customize the render of most of controllers, but not the title of the button ...
This is an issue for I18N application

Tooltip support when a node event happens (dbl click, hover, etc)

Feature request template

A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
I do not think there is a current way where we can have a tooltip when we for example double-click on a node, something like this existed in the form of a plug-in Sigma 1.0, I wonder if we have this in react sigma.

Error after deleting a node

Hello,
I'm brand new using the lib.
I'm trying to add, for testing purpose, a doubleclick on a node to drop it. But I catch th following error:
Uncaught NotFoundGraphError: Graph.neighbors: could not find the "48309" node in the graph., which seems pretty normal, because I just deleted.
I tried to use a cleaning function in the graph.on('nodeDropped'), but I can't get it working.
Can you help me?
Best regards

react-18
react-sigma 3.0.0

Parallel edges and curved arrows

Hi, may I ask if it's possible to have curved arrows and parallel edges in @react-sigma? As far as I have tried out the library, it appears that having multiple edges between two nodes will result in a white screen with an error message prompting that two nodes can only have one edge. For my use case, it would be of great importance, especially with curved arrows for presenting multiple edges between two nodes in a well-readable way.

@dunnock/react-sigma has support for it, though I reckon that adding these features would significantly facilitate the use of Sigma in React.

Dynamically changing/setting arrow size of an edge

Is your feature request related to a problem? Please describe.
Being able to dynamically set arrow size without affecting the edge size (by dynamically I mean allow the user to do via input)

Describe the solution you'd like
Something close to the canvas solution we previously had in v1 (canvas version) maybe?

<SigmaContainer
                        settings={{
                            nodeProgramClasses: {image: getNodeProgramImage(), circle: CircleNodeProgram},
                            edgeProgramClasses: {
                                arrow: ArrowEdgeProgram,
                            },
                            minArrowSize: 100, //here the minArrowSize can be dynamically set
                            ...graphSettings,
                        }}
                        style={{height: '100%', background: props.noBackground ? 'white' : mainBackgroundColor}}
                    >

TypeScript improvements

Hello there!

I'm interested in contributing a few TypeScript improvements to this project, as I plan on using it for a PoC.

I have already forked the project and made some changes for better type safety: https://github.com/dsebastien/react-sigma-v2/commits/main

One thing that is not clear for me is this: https://github.com/sim51/react-sigma-v2/blob/main/src/index.ts#L21

Can you tell me what NodeKey is supposed to be? It's not defined at the moment it seems. For now I've tried using import { NodeKey } from "graphology-types";, which is in fact string | number, but then I get errors in the complete.tsx example, where the code always expects the hoveredNode state to be a string.

useRegisterEvents silently modified sigma settings

I have had some trouble with the following code:

if (
eventTypes.some((event) => ["clickEdge", "rightClickEdge", "doubleClickEdge", "downEdge"].includes(event)) &&
sigmaSettings.enableEdgeClickEvents === false
) {
edgeSettings["enableEdgeClickEvents"] = true;
reverseEdgeSettings["enableEdgeClickEvents"] = false;
}
if (
eventTypes.some((event) => ["enterEdge", "leaveEdge"].includes(event)) &&
sigmaSettings.enableEdgeHoverEvents === false
) {
edgeSettings["enableEdgeHoverEvents"] = true;
reverseEdgeSettings["enableEdgeHoverEvents"] = false;
}
if (eventTypes.some((event) => ["wheelEdge"].includes(event)) && sigmaSettings.enableEdgeWheelEvents === false) {
edgeSettings["enableEdgeWheelEvents"] = true;
reverseEdgeSettings["enableEdgeWheelEvents"] = false;
}
if (Object.keys(edgeSettings).length > 0) {
setSettings(edgeSettings);
}

I have no problem with higher order libraries and/or wrappers that create new abstractions or syntactic sugar on top of existing libraries. This is what react-sigma does on many sides, that makes me happily use it in my React applications.

However, on that very decision, I think it's a design mistake: react-sigma provides both useSetSettings to manage sigma's settings, and useRegisterEvents to handle events, and as a developer, I do not expect useRegisterEvents to affect settings.

I understand this decision is made because you thought it makes no sense to listen to edge events while having edge interactions disabled in the settings. Here are some precise issues I have with this situation:

  1. I could use the settings to toggle edge interaction in an app, without wanting to change my event listeners. Sigma allows it, so I would expect react-sigma to work the same way, and it would be hard to find where the issue is (this is a similar situation to what led me to write this ticket in the first place)
  2. The way it's done allows many bugs to occur. One example:
    1. I bind a listener on edge events while settings are set to false
    2. I set the settings to true right after
    3. I unbind the events later
    4. At this point, the settings are back to false, while my code set them to true at some point (and I wouldn't expect them to be different)
  3. Same issue, with specifically enableEdgeHoverEvents set to "debounce"

I see 3 main ways to fix this issue:

  1. If you think it makes no sense to allow binding listeners to edge events while edge interaction settings are false, maybe sigma is wrong and we could address that directly in sigma
  2. If you still want to prevent your users from falling into that issue, you could clarify the situation, by creating a new react-sigma concept, that would take care both of sigma events and settings (useEdgeEvents, for example).
  3. Finally, you could want to keep the APIs as close to sigma's as possible, but still educate your users on these kind of potential mistakes. For instance, you could use console.warn when some code tries to listen to edge events while the edge settings are false

Updating the edge size causes the edges to dissapear

Example bug report

Modification of the node default color in the settings has no effect

**React-sigma-v2 version: ^3.0.3"
**Sigma.js version : "^2.3.1"
**Graphology version : "^0.25.0"
**Operating system: Ubuntu 20.04
**Web browser: chrome 106.0.5249.103 (64-bit)

Steps to reproduce

what I am trying to do is to change the size of the edge using a formula that we have, where it depends on minEdgeSize and maxEdgeSize

const size = minEdgeSize + (maxEdgeSize - minEdgeSize) * (e.weight?e.weight:0); now the problem is,this causes the edges to disappear for some reason

this useEffect causes edges to disappear:

useEffect(()=>{
        const {minEdgeSize, maxEdgeSize} = graphSettings;
        graph.updateEachEdgeAttributes((edgeId, e)=>{
            const size = minEdgeSize + (maxEdgeSize - minEdgeSize) * (e.weight?e.weight:0);

            return {
                ...e,
                size,
            };
        });
    }, [graphSettings.minEdgeSize, graphSettings.maxEdgeSize]);

and yes, the size here is a valid integer value

initially, here's how I add edges to the network:

visibleEdges.forEach((edge)=>{
        graph.addDirectedEdge(edge.source, edge.target, {type: 'arrow', color: 'rgb(94, 91, 91)', size: edge.size?edge.size:1});
    });

here's the sigma container:

<SigmaContainer
            settings={{
                nodeProgramClasses: {image: getNodeProgramImage(), circle: CircleNodeProgram},
                edgeProgramClasses: {
                    arrow: ArrowEdgeProgram,
                },
                ...graphSettings,
            }}
            style={{height: '500px', background: props.noBackground ? 'white' : mainBackgroundColor}}
        >

and I get the arrow program from here:

import ArrowEdgeProgram from 'sigma/rendering/webgl/programs/edge.arrow';

Expected behavior

Edges sizes get modified

Actual behavior

Edges disappear when I just add this useEffect to the code

SetSettings cast number into string?

context:

  • React-sigma-v2 version: 0.0.6
  • Sigma.js version : 2.0.0-beta8
  • Graphology version : 0.19.3

Steps to reproduce:

import {  useSetSettings,
} from "react-sigma-v2";

const MyComponent = () => {
  const setSettings = useSetSettings();
  setSettings({labelDensity:0.07})
}
  • Expected behavior: set the labelDensity accordingly
  • Actual behavior: throw Settings: invalid `labelDensity`. Expecting a positive number.
  • workaround :
const sigma = useSigma()
sigma.setSetting("labelDensity", 0.07);

Camera is reset when graph is updated

When a new graph prop value is given to some SigmaContainer instance, the camera is reset. I was expecting the camera to remain the same.

The reason is visible here:

if (containerRef.current !== null) {
const sigGraph = graph ? (typeof graph === "function" ? new graph() : graph) : new Graph();
instance = new Sigma(sigGraph, containerRef.current, { allowInvalidContainer: true, ...sigmaSettings.current });
}
setSigma(instance);

The fix would be to copy the camera state if an instance exists already, and set it to the new instance's camera right after it's created. Something like:

const cameraState = instance ? instance.getCamera().getState() : null;

// [...] existing code that remounts the instance

if (cameraState) instance.getCamera().setState(cameraState);

External control : forward Sigma ref

It can be cool to be able to forward the Sigma ref when using the SigmaContainer.
This will allow user to control the graph & Sigma outside SigmaContainer tree.

Example :

export const ExternalView: FC = () => {
  const [sigma, setSigma] = useState<Sigma | null>(null);

  useEffect(() => {
    if (sigma) {
      const graph = sigma.getGraph();
      graph.addNode("A", { x: 0, y: 0, label: "Node A", size: 10 });
      graph.addNode("B", { x: 1, y: 1, label: "Node B", size: 10 });
      graph.addEdgeWithKey("rel1", "A", "B", { label: "REL_1" });
    }
  }, [sigma]);

  return <SigmaContainer ref={setSigma} />;
};

Edge labels do not appear in the example

Summary:
edge names dont display properly on the example at https://sim51.github.io/react-sigma/docs/example. I'm trying to follow the example to implement react-sigma myself, but am also facing the problem of edges not showing. it would be great if the example showed the full code as well.

Screen Shot 2022-06-27 at 10 00 30 PM

To help us understand your issue, please specify important details, primarily:

  • React-sigma-v2 version: 1.3.0
  • Sigma.js version : X.Y.Z
  • Graphology version : X.Y.Z
  • Operating system: Mac OS
  • Web browser: Chrome, Safari, Brave are tested to have this error
  • Steps to reproduce: see https://sim51.github.io/react-sigma/docs/example, edge names dont display
  • Expected: edge names show
  • Actual behavior: no edge names

`ref` is not generic

ref is not generic

ref is not generic. This causes a mismatch between ref={setSigma} and the actual type of setSigma.

We give it setSigma: React.Dispatch<React.SetStateAction<Sigma<MyGraph> | null>>

but the ref enforces setSigma: React.Dispatch<React.SetStateAction<Sigma<AbstractGraph<Attributes, Attributes, Attributes>> | null>>

React-sigma-v2: 3.4.2
Sigma.js version: 2.4.0
Graphology version: 0.25.4
Operating System: LG Laundry machine OS
Web browser: Edge 120.0.0

Steps to reproduce

Check the live example https://codesandbox.io/p/sandbox/react-sigma-example-forked-9mks58?file=%2Fsrc/App.tsx

Expected behavior

I can use setSigma with custom graph type so I can get better intellisense

Actual behavior

Computer says no:

image

Note

If the issue has an inactivity of 30 days, it becomes stale.
With an additional inactivity of 14 days, the issue is closed

NotFoundGraphError: Graph.setNodeAttribute: could not find the "undefined" node in the graph.

Hello,

I'm trying to enable dragging of nodes but I'm getting the following error:

NotFoundGraphError: Graph.setNodeAttribute: could not find the "undefined" node in the graph.

On the following line:

graph.setNodeAttribute(draggedNode, "highlighted", true);

Here is the code:

    sigma.on("downNode", (e) => {
            setIsDragging(true);
            setDraggedNode(e.node);

            alert("Node: " + e.node);
            alert("Has node: " + graph.hasNode(draggedNode));

            graph.setNodeAttribute(draggedNode, "highlighted", true);
            sigma.getCamera().disable();
        });

The first alert shows the node, the second alert says "false" (so it can't find the node).

Here's the full code:

import React, {useEffect, useState} from "react";
import {useSigma, useSetSettings, useRegisterEvents} from "react-sigma-v2";
import {random} from "graphology-layout"
import forceAtlas2 from "graphology-layout-forceatlas2";

// References
// https://graphology.github.io/
export const NetworkGraph = ({nodes, links, setSigma}) => {
    const sigma = useSigma();
    const graph = sigma.getGraph();
    const registerEvents = useRegisterEvents();
    const setSettings = useSetSettings();
    const [hoveredNode, setHoveredNode] = useState();
    const [draggedNode, setDraggedNode] = useState();
    const [isDragging, setIsDragging] = useState(false);

    setSigma(sigma);

    useEffect(() => {
        nodes.forEach((node) => {
            if (!graph.hasNode(node.id)) {
                graph.addNode(node.id, { label: node.id, color: "#FF0", size: 10 });
            }
        })
        links.forEach((link) => {
            if (!graph.hasEdge(link.target, link.source)) {
                graph.addEdge(link.target, link.source, { color: "#CCC", size: 1 });
            }
        })

        random.assign(graph);
        forceAtlas2.assign(graph, {
            iterations: 150,
            settings: {
                gravity: 0
            }
        });

        registerEvents({
            enterNode: event => setHoveredNode(event.node),
            leaveNode: () => setHoveredNode(null),
        });

        sigma.on("downNode", (e) => {
            setIsDragging(true);
            setDraggedNode(e.node);

            alert("Node: " + e.node);
            alert("Has node: " + graph.hasNode(draggedNode));

            graph.setNodeAttribute(draggedNode, "highlighted", true);
            sigma.getCamera().disable();
        });

        sigma.getMouseCaptor().on("mousemove", (e) => {
            if (!isDragging || !draggedNode) return;

            const pos = sigma.viewportToGraph(e);

            graph.setNodeAttribute(draggedNode, "x", pos.x);
            graph.setNodeAttribute(draggedNode, "y", pos.y);
        });

        sigma.getMouseCaptor().on("mouseup", () => {
            if (draggedNode) {
                graph.removeNodeAttribute(draggedNode, "highlighted");
            }
            setIsDragging(false);
            setDraggedNode(null);
            sigma.getCamera().enable();
        });

        sigma.getMouseCaptor().on("mousedown", () => {
            if (!sigma.getCustomBBox()) sigma.setCustomBBox(sigma.getBBox());
        });
    }, [nodes, links])

    useEffect(() => {
        setSettings({
            nodeReducer: (node, data) => {
                const newData = { ...data, highlighted: data.highlighted || false };

                if (hoveredNode) {
                    if (node === hoveredNode || graph.neighbors(hoveredNode).includes(node)) {
                        newData.highlighted = true;
                    } else {
                        newData.color = "#E2E2E2";
                        newData.highlighted = false;
                    }
                }
                return newData;
            },
            edgeReducer: (edge, data) => {
                const graph = sigma.getGraph();
                const newData = { ...data, hidden: false };

                if (hoveredNode && !graph.extremities(edge).includes(hoveredNode)) {
                    newData.hidden = true;
                }
                return newData;
            },
        });
    }, [hoveredNode])
    
    return null;
}

Any idea why it's not able to find the node from the event?

Hard working with a CSS framework (Bootstrap, for instance)

I am right now trying to integrate react-sigma-v2 in a Bootstrap based application, and the custom-buttons example does not quite fit:
https://github.com/sim51/react-sigma-v2/blob/e4c0ff5e936e04c2d7da1e16893512a8923a65d8/examples/custom-buttons.tsx#L62-L68

I can't simply give a custom class to the button ("btn btn-outline-dark" with Bootstrap, for instance), because the class goes to the parent. And it's not that bad for the zoom / fullscreen buttons since they are based on very usable and simple hooks (even if I think they should be more visible in the examples), but the SearchControl is quite unusable for me and I end up copying the whole source in my app...

I think most web developers using React have, one way or another, some constraints on their markup and/or CSS (internal constraints or framework constraints), and covering those constraints with some custom props will never be good enough. As a user, I really would prefer a well designed suite of hooks to enables those features. And I'm sure exposing components with basic default markups for other users is acceptable, but should be considered secondary.

A good inspiration for this is react-dropzone for instance.

UsageGraphError: Graph.addNode: the "Jessica" node already exist in the graph.

Hello again,

I'm having trouble getting ForceAtlas2 to work.

The following code works:

import React from "react";
import {useSigma} from "react-sigma-v2";
import {random} from "graphology-layout"

export const NetworkGraph = ({nodes, links}) => {
    const sigma = useSigma();
    const graph = sigma.getGraph();

    graph.addNode("Jessica", { label: "Jessica", x: 0, y: 1, color: "#FF0", size: 10 });
    graph.addNode("Truman", { label: "Truman", x: 1, y: 0, color: "#00F", size: 10 });
    graph.addEdge("Jessica", "Truman", { color: "#CCC", size: 1 });

    random.assign(graph);

    return null;
}

But calling https://graphology.github.io/standard-library/layout-forceatlas2.html after the random assign doesn't:

forceAtlas2.assign(graph);
UsageGraphError: Graph.addNode: the "Jessica" node already exist in the graph.

Do you know what could be the issue?

Images are not show in nodes in NextJS

I am setting up a Graphology Graph and trying to display it using React Sigma and I have registered the nodeProgram. Here are some relevant parts of my code:

Here's how I have set SigmaContainer:

      <SigmaContainer
        style={{ height: "600px", width: "100%" }}
        graph={graph}
        settings={{
          nodeProgramClasses: { image: getNodeProgramImage() },
          defaultNodeType: "image",
          defaultEdgeType: "arrow",
          labelDensity: 0.07,
          labelGridCellSize: 60,
          labelRenderedSizeThreshold: 15,
          labelFont: "Lato, sans-serif",
          zIndex: true,
        }}
      >
        <GraphEvents />
      </SigmaContainer> 

And here is how I setup the nodes:

  const graph = new MultiDirectedGraph();
  for (let i = 0; i < network.nodes.size(); i++) {
    try {
      graph.addNode(i.toString(), {
        molCounts: network.molCounts.get(i),
        size: network.molCounts.get(i),
        smiles: network.nodes.get(i),
        nodeType: smilesList.includes(network.nodes.get(i))
          ? "whole"
          : "fragment",
        type: "image",
        image: "./unknown.svg",
      });
    } catch {
      console.error("Error in adding node to graph");
    }

I have taken the SVG file from this repo and when I change the SVG file to something else that does not exist, I see an error so the image is being searched but it is just not displayed.

Here's a screenshot:

Screenshot 2024-03-11 at 15 10 58
  • React-sigma-v2 version: 3.4.2
  • Sigma.js version : 2.4.0
  • Graphology version : 0.25.4
  • Operating system: Macbook Pro Apple Silicon
  • Web browser: Firefox

Images for nodes

Feature request template

I'm trying to use images for nodes like this as it is specified in this example

    graph.addNode(id, {
                        x: Math.random(),
                        y: Math.random(),
                        type: 'image',     
                        image: './image.svg',
                        size: 5,
                        label: "Label",
                        color: "#17AEFF" 
                     })

The problem is that when I specify type: 'image', I get this error

React-sigma error

I've also tried using this settings:

 <SigmaContainer 
      settings={{ defaultNodeType: "image" }}>

Is there a way of using images for nodes? Am I missing something?

I think I should render Sigma container with the property nodeProgramClasses but I don't know if it is possible to access this property

make the arrow of edge bigger

Guidelines

Please note that GitHub issues are only meant for bug reports/feature requests.
If you have questions on how to use Recat & Sigma.js, please ask on StackOverflow instead of creating an issue here.

Feature request template

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

beforeRender / afterRender events not implemented?

Sigma exposes beforeRender and afterRender events in its AdditionalEvents. Registering them doesn't do anything, and further investigation yields there is no mention of them in react-sigma's useRegisterEvents.ts. Implementing them would be much appreciated, thanks!

ReferenceError: window is not defined

Hello,

I'm using NextJS and was getting:

ReferenceError: window is not defined

I solved this by using a dynamic import for the Sigma container:

import dynamic from "next/dynamic";

const SigmaContainer = dynamic(import("react-sigma-v2").then(mod => mod.SigmaContainer), {ssr: false})

Maybe it would be a good idea to add this to the documentation for people using NextJS?

Instantiating with a given graph instance

Currently, as I understand, react-sigma-v2 always initializes itself its own graphology instance.

In some of my applications, I tend to separate my views tree from my data logic, and I like to load my data and to initialize the graphology instance myself. Also, I've had other cases with a graphology instance that always exists (for graph algorithms, for instance), but that is not always displayed using sigma. Finally, as I write right now a classic app rendering GEXF graphs on web pages, it feels really weird to have to instantiate the SigmaContainer React component before having an actual graph to give. I always start by managing my data, and then, I deal with rendering.

For those cases, it would really help to allow giving react-sigma-v2 a graphology instance.

Error: Cannot use import statement outside a module

Example bug report

Modification of the node default color in the settings has no effect

React-sigma-v2: 3.2.0
Sigma.js version: 2.4.0
Graphology version: 0.25.1
Operating System: Fedora 37, GNOME
Web browser: Mozilla Firefox 110.0

Steps to reproduce

Check the live example https://codesandbox.io/p/sandbox/wandering-pine-ev7d3h?file=%2Fcomponents%2FNodeGraph.tsx&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A5%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A5%7D%5D

Expected behavior

No errors on browser refresh

Actual behavior

I got an error:

image

Note

If the issue has an inactivity of 30 days, it becomes stale.
With an additional inactivity of 14 days, the issue is closed

Typo in example code

In project/packages/examples/src/common/SampleGraph.tsx on line 17 the word assign in assignCircular is spelled assing.

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.