Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how do I use its triggerFit method in react 18? #623

Open
linonetwo opened this issue Jul 12, 2023 · 3 comments
Open

how do I use its triggerFit method in react 18? #623

linonetwo opened this issue Jul 12, 2023 · 3 comments

Comments

@linonetwo
Copy link

This is an old reace code written in "react": "^15.6.2", "react-dom": "^15.6.2",, how do I use its triggerFit method in react 18?

  TheGraph.App = React.createFactory(createReactClass({
    displayName: 'TheGraphApp',
    mixins,
    getDefaultProps() {
      return {
        onEdgeSelection: null,
      };
    },
    triggerFit(event) {
      const fit = geometryutils.findFit(this.props.graph, this.props.width, this.props.height, TheGraph.config.nodeSize);
      this.setState({
        x: fit.x,
        y: fit.y,
        scale: fit.scale,
      });
    },
    render() {
      // omit variable setups
      const appContents = [
        canvas,
        svg,
      ];
      const containerOptions = TheGraph.merge(TheGraph.config.app.container, { style: { width: this.state.width, height: this.state.height } });
      containerOptions.className += ` ${scaleClass}`;
      return TheGraph.factories.app.createAppContainer.call(this, containerOptions, appContents);
    },
  }));

this code is from a npm package, I can't modify its code, I just need a workaround or hack to access the method when I use this component like

  const appReference = useRef<HTMLDivElement>(null);
return <TheGraph.App
        ref={appReference}
        readonly={readonly}
        height={window.innerHeight}
        width={window.innerWidth - sidebarWidth}
        offsetX={sidebarWidth}
        getMenuDef={getMenuDef}
        onPanScale={handlePanScale}
        {...props}
      />

this component was created by React.createFactory(createReactClass({})), how can it be functional components?

But when I run the code, it did throw error Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?, why?


ChatGPT4:

The issue you're encountering is due to a fundamental shift in the way React handles components from version 15.6.2 to version 18.

In the version 15.6.2 of your code, the component was created using createReactClass, a function that creates a class-based component with lifecycle methods, and allows you to access methods (like triggerFit) via refs.

In contrast, the warning you're seeing in version 18 is because React has shifted towards function components and hooks. Function components can't be given refs to access their inner methods like class components, hence the warning. Instead, React.forwardRef is suggested, which can be used to access DOM or class components, but not functions within functional components.

Unfortunately, if you can't modify the original npm package code, it's not going to be possible to directly call the triggerFit method from outside. As the library's API doesn't provide a way to do that, it seems the library is designed for its methods to be internal.

One potential workaround would be to clone the npm package, modify it to expose the triggerFit method (for example, by adding it as a prop), and then use your modified version.

Here is an example of how you could modify the component to allow the triggerFit function to be called externally:

  TheGraph.App = React.createFactory(createReactClass({
    displayName: 'TheGraphApp',
    mixins,
    getDefaultProps() {
      return {
        onEdgeSelection: null,
        triggerFit: null, // add triggerFit in defaultProps
      };
    },
    triggerFit(event) {
      const fit = geometryutils.findFit(this.props.graph, this.props.width, this.props.height, TheGraph.config.nodeSize);
      this.setState({
        x: fit.x,
        y: fit.y,
        scale: fit.scale,
      });

      if (this.props.triggerFit) {
        this.props.triggerFit(fit);
      }
    },
    render() {
      // omit variable setups
      const appContents = [
        canvas,
        svg,
      ];
      const containerOptions = TheGraph.merge(TheGraph.config.app.container, { style: { width: this.state.width, height: this.state.height } });
      containerOptions.className += ` ${scaleClass}`;
      return TheGraph.factories.app.createAppContainer.call(this, containerOptions, appContents);
    },
  }));

And then in your component:

return <TheGraph.App
        readonly={readonly}
        height={window.innerHeight}
        width={window.innerWidth - sidebarWidth}
        offsetX={sidebarWidth}
        getMenuDef={getMenuDef}
        onPanScale={handlePanScale}
        triggerFit={(fit) => { /* you now have access to the fit result */ }}
        {...props}
      />

This will allow you to execute any code you want after triggerFit is called.

Remember to maintain your modified version of the library and keep track of any updates to the original one. In the long run, it might be beneficial to migrate to a library that is actively maintained and compatible with the latest React versions.

@linonetwo
Copy link
Author

Anyone can transform the code in react 18? (With help of GPT?)

@linonetwo
Copy link
Author

linonetwo commented Jul 14, 2023

No need for GPT4, it don't know the solution. But I try to use pnpm patch to create a new props to pass in a useRef

  1. copy usage from

domEvents: true,
inputClass: hammerhacks.Input,
recognizers: [
[Hammer.Tap, { }],
[Hammer.Press, { time: 500 }],
[Hammer.Pan, { direction: Hammer.DIRECTION_ALL, threshold: 5 }],
[Hammer.Pinch, { }],
],
});
// Gesture event for pan
domNode.addEventListener('panstart', this.onTrackStart);

to fix nav drag bug caused by hammerjs/hammer.js#806

  1. add
     componentDidMount: function () {
+      // make sure user side parent context can access methods defined here
+      if (this.props.getEditorRef !== undefined) {
+        this.props.getEditorRef.current = this;
+      }

to allow inject react 18 ref

const editorReference = useRef<ITheGraphEditor>();
getEditorRef={editorReference}

The full patch:

diff --git a/the-graph/the-graph-app.js b/the-graph/the-graph-app.js
index 08aa19642e811c336fdc5c1ea99b6b9906109d5b..c21d6f9470d4ebd609c6553688a7074bc4657391 100644
--- a/the-graph/the-graph-app.js
+++ b/the-graph/the-graph-app.js
@@ -167,6 +167,7 @@ module.exports.register = function (context) {
         onPanScale: null,
         onNodeSelection: null,
         onEdgeSelection: null,
+        getEditorRef: null,
       };
     },
     getInitialState: function() {
@@ -424,6 +425,10 @@ module.exports.register = function (context) {
       this.hideContext();
     },
     componentDidMount: function () {
+      // make sure user side parent context can access methods defined here
+      if (this.props.getEditorRef !== undefined) {
+        this.props.getEditorRef.current = this;
+      }
       var domNode = ReactDOM.findDOMNode(this.refs.svg);
 
       // Unselect edges and nodes
diff --git a/the-graph-nav/the-graph-nav.js b/the-graph-nav/the-graph-nav.js
index 206975d0fc2b3efb89d18b2543830c1922cd740d..cdbcbd1b9e5f1fc60cafa0f105c32dd40b0d25f1 100644
--- a/the-graph-nav/the-graph-nav.js
+++ b/the-graph-nav/the-graph-nav.js
@@ -1,7 +1,9 @@
 
 var React = require('react');
+const ReactDOM = require('react-dom');
 var createReactClass = require('create-react-class');
-var Hammer = require('hammerjs');
+const Hammer = require('hammerjs');
+const hammerhacks = require('../the-graph/hammer.js');
 var thumb = require('../the-graph-thumb/the-graph-thumb.js');
 
 function calculateStyleFromTheme(theme) {
@@ -20,19 +22,19 @@ function calculateStyleFromTheme(theme) {
   return style;
 }
 
-function renderViewRectangle(context, viewrect, props) {
+function renderViewRectangle(context, viewrect, style) {
 
-  context.clearRect(0, 0, props.width, props.height);
-  context.fillStyle = props.outsideFill;
+  context.clearRect(0, 0, style.width, style.height);
+  context.fillStyle = style.outsideFill;
 
   // Scaled view rectangle
-  var x = Math.round( (props.viewrectangle[0]/props.scale - props.thumbrectangle[0]) * props.thumbscale );
-  var y = Math.round( (props.viewrectangle[1]/props.scale - props.thumbrectangle[1]) * props.thumbscale );
-  var w = Math.round( props.viewrectangle[2] * props.thumbscale / props.scale );
-  var h = Math.round( props.viewrectangle[3] * props.thumbscale / props.scale );
+  var x = Math.round( (style.viewrectangle[0]/style.scale - style.thumbrectangle[0]) * style.thumbscale );
+  var y = Math.round( (style.viewrectangle[1]/style.scale - style.thumbrectangle[1]) * style.thumbscale );
+  var w = Math.round( style.viewrectangle[2] * style.thumbscale / style.scale );
+  var h = Math.round( style.viewrectangle[3] * style.thumbscale / style.scale );
 
   var hide = false;
-  if (x<0 && y<0 && w>props.width-x && h>props.height-y) {
+  if (x<0 && y<0 && w>style.width-x && h>style.height-y) {
     // Hide map
     hide = true;
     return {
@@ -48,35 +50,35 @@ function renderViewRectangle(context, viewrect, props) {
   if (x < 0) { 
     w += x; 
     x = 0;
-    viewrect.style.borderLeftColor = props.viewBoxBorder2;
+    viewrect.style.borderLeftColor = style.viewBoxBorder2;
   } else {
-    viewrect.style.borderLeftColor = props.viewBoxBorder;
-    context.fillRect(0, 0, x, props.height);
+    viewrect.style.borderLeftColor = style.viewBoxBorder;
+    context.fillRect(0, 0, x, style.height);
   }
   // Top
   if (y < 0) { 
     h += y; 
     y = 0;
-    viewrect.style.borderTopColor = props.viewBoxBorder2;
+    viewrect.style.borderTopColor = style.viewBoxBorder2;
   } else {
-    viewrect.style.borderTopColor = props.viewBoxBorder;
+    viewrect.style.borderTopColor = style.viewBoxBorder;
     context.fillRect(x, 0, w, y);
   }
   // Right
-  if (w > props.width-x) { 
-    w = props.width-x;
-    viewrect.style.borderRightColor = props.viewBoxBorder2;
+  if (w > style.width-x) { 
+    w = style.width-x;
+    viewrect.style.borderRightColor = style.viewBoxBorder2;
   } else {
-    viewrect.style.borderRightColor = props.viewBoxBorder;
-    context.fillRect(x+w, 0, props.width-(x+w), props.height);
+    viewrect.style.borderRightColor = style.viewBoxBorder;
+    context.fillRect(x+w, 0, style.width-(x+w), style.height);
   }
   // Bottom
-  if (h > props.height-y) { 
-    h = props.height-y;
-    viewrect.style.borderBottomColor = props.viewBoxBorder2;
+  if (h > style.height-y) { 
+    h = style.height-y;
+    viewrect.style.borderBottomColor = style.viewBoxBorder2;
   } else {
-    viewrect.style.borderBottomColor = props.viewBoxBorder;
-    context.fillRect(x, y+h, w, props.height-(y+h));
+    viewrect.style.borderBottomColor = style.viewBoxBorder;
+    context.fillRect(x, y+h, w, style.height-(y+h));
   }
 
   // Size and translate rect
@@ -139,8 +141,7 @@ var Component = createReactClass({
   },
   getInitialState: function() {
     return {
-      thumbscale: 1.0,
-      currentPan: [0.0, 0.0],
+      panStartPoint: [0.0, 0.0],
     };
   },
   render: function() {
@@ -193,19 +194,17 @@ var Component = createReactClass({
     ]);
   },
   componentDidUpdate: function() {
-    this._updatePan();
     this._renderElements();
   },
   componentDidMount: function() {
-    this._updatePan();
     this._renderElements();
     this._setupEvents();
   },
   _refThumbCanvas: function(canvas) {
-      this._thumbContext = canvas.getContext('2d');
+      this._thumbContext = canvas?.getContext?.('2d');
   },
   _refViewboxCanvas: function(canvas) {
-      this._viewboxContext = canvas.getContext('2d');
+      this._viewboxContext = canvas?.getContext?.('2d');
   },
   _refViewboxElement: function(el) {
       this._viewboxElement = el;
@@ -218,40 +217,49 @@ var Component = createReactClass({
     //this.state.thumbscale = t.scale;
     renderViewboxFromProps(this._viewboxContext, this._viewboxElement, t, this.props);
   },
-  _updatePan: function() {
-    this.state.currentPan = [
-      -(this.props.viewrectangle[0]),
-      -(this.props.viewrectangle[1]),
-    ];
+  onDragOrPan: function ({ deltaX, deltaY }) {
+    if (this.props.onPanTo) {
+      // Calculate where event pans to, in editor coordinates
+      var x = this.state.panStartPoint[0];
+      var y = this.state.panStartPoint[1];
+      var panscale = 1 / this.props.viewscale;
+      const speedupFactorX = this.props.viewrectangle[2] / this.props.width * 2;
+      const speedupFactorY = this.props.viewrectangle[3] / this.props.height * 2;
+      x -= deltaX / panscale * speedupFactorX;
+      y -= deltaY / panscale * speedupFactorY;
+      var panTo = { x: Math.round(x), y: Math.round(y) };
+      this.props.onPanTo(panTo, event);
+    }
+  },
+  onTrackStart(event) {
+    this.state.panStartPoint[0] = -this.props.viewrectangle[0];
+    this.state.panStartPoint[1] = -this.props.viewrectangle[1];
+    this._topElement.addEventListener('panmove', this.onTrack);
+    this._topElement.addEventListener('panend', this.onTrackEnd);
+  },
+  onTrack(event) {
+    this.onDragOrPan({
+      deltaX: event.gesture.deltaX,
+      deltaY: event.gesture.deltaY,
+    });
+  },
+  onTrackEnd(event) {
+    // Don't click app (unselect)
+    event.stopPropagation();
+    this._topElement.removeEventListener('panmove', this.onTrack);
+    this._topElement.removeEventListener('panend', this.onTrackEnd);
   },
   _setupEvents: function() {
     this.hammer = new Hammer.Manager(this._topElement, {
+      domEvents: true,
+      inputClass: hammerhacks.Input,
       recognizers: [
-        [ Hammer.Tap ],
-        [ Hammer.Pan, { direction: Hammer.DIRECTION_ALL } ],
+        [Hammer.Tap],
+        [Hammer.Pan, { direction: Hammer.DIRECTION_ALL, threshold: 5 }],
       ],
     });
-    this.hammer.on('tap', (function(event) {
-      if (this.props.onTap) {
-        this.props.onTap(null, event);
-      }
-    }).bind(this));
-    this.hammer.on('panmove', (function(event) {
-      if (this.props.onPanTo) {
-        // Calculate where event pans to, in editor coordinates
-        var x = this.state.currentPan[0];
-        var y = this.state.currentPan[1];
-        var panscale = this.state.thumbscale / this.props.viewscale;
-        x -= event.deltaX / panscale;
-        y -= event.deltaY / panscale;
-        var panTo = { x: Math.round(x), y: Math.round(y) };
-        // keep track of the current pan, because prop/component update
-        // may be delayed, or never arrive.
-        this.state.currentPan[0] = panTo.x;
-        this.state.currentPan[1] = panTo.y;
-        this.props.onPanTo(panTo, event);
-      }
-    }).bind(this));
+    this.hammer.on('tap', (event) => this.props.onTap(event));
+    this._topElement.addEventListener('panstart', (event) => this.onTrackStart(event));
   }
 });

linonetwo added a commit to tiddly-gittly/TidGi-Desktop that referenced this issue Jul 14, 2023
@linonetwo
Copy link
Author

If this project is alive, I can send a PR for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant