Search code examples
svelte

Move viewport to show particular set of nodes in Svelte Flow


I've created a svelte component Text2Chart that transforms algorithm (adhere to certain syntax) to flow chart using @xyflow/svelte library. When a user selects lines of algorithm in textarea, I highlight relevant nodes in flow chart. If the chart is not showing the selected nodes currently, I want to move the viewport to show selected nodes.

I couldn't find any API supported by Svelte Flow to set this. We're not allowed to make instance of svelte flow, and we can't use useSvelteFlow outside of tag scope.

People have advised a few hacks in discussion on Github. But I'm not able to understand how it has to be implemented.

I've create a component with following code and including it in SvelteProvider. It is executing but view port is not changing.

<script>
  import {
    useSvelteFlow
  } from '@xyflow/svelte';

  let svelteFlowElement;
  export let selection;
  export let nodes;

  function fitViewToSelection(selectedNodeIds, nodes) {
    if (selectedNodeIds) {
      const nd = nodes.filter(node => selectedNodeIds.includes(node.id));
      // console.log(nd)
      svelteFlowElement.setViewport(
        {nodes: nd});
      }
  }
  $: {
    if (selection && selection.nodeIds) {
      fitViewToSelection(selection.nodeIds, nodes);
    }
  }
  function adjustViewport(detail) {
    console.log("adjusting view")
    const { x, y, width, height } = detail;
    svelteFlowElement.setViewport({ x, y, width, height }, { padding: 20, duration: 200 });
  }

  $: {
    svelteFlowElement = useSvelteFlow();
  }
</script>

enter image description here


Solution

  • I have solved the issue by using fitView instead of setViewport.

    svelteFlowElement.fitView({
        nodes: nd,
        maxZoom: 1,
        duration: 200,
        // includeHiddenNodes: true
    });