projectstorm / react-diagrams

a super simple, no-nonsense diagramming library written in react that just works
https://projectstorm.cloud/react-diagrams
MIT License
8.65k stars 1.17k forks source link

Getting visible ports information #897

Closed sinanyaman95 closed 2 years ago

sinanyaman95 commented 2 years ago

Is here a way to get the ids of the visible ports (i.e. not zoomed out or dragged out of view from canvas)? In my case, I have large amount of ports and some of them are not visible in canvas unless canvas is dragged or diagram is zoomed out. I want to get information about visible ports, and if there is a way to do it, I will attach listeners to zoom and canvas drag to update the information.

sinanyaman95 commented 2 years ago

Managed to implement a function, getting help from the zoomToFit function in react-diagrams:

  getVisiblePorts = () => {
    const visiblePortIds = []
    const canvasRect = this.engine.getCanvas().getBoundingClientRect()
    const offsetY = this.engine.getModel().getOffsetY()
    const offsetX = this.engine.getModel().getOffsetX()
    const zoom = this.engine.getModel().getZoomLevel()
    const nodes = this.engine.getModel().getNodes()
    const margin = zoom / 100
    nodes.forEach(node => {
      if (node.getPosition().x * margin + offsetX > -200 && node.getPosition().x * margin + offsetX < canvasRect.width) {
        const ports = node.getPorts()
        Object.keys(ports).forEach(key => {
          const port = ports[key]
          if (port.getPosition().y * margin + offsetY > -100 && port.getPosition().y * margin + offsetY < canvasRect.height) {
            visiblePortIds.push(port.getID())
          }
        })
      }
    })
    return visiblePortIds
  }