Search

Combo Path Finding

Graph Analysis

Find shortest paths between items inside combos.

Combo Path Finding
View live example →

Switch between traversal methods using the buttons above the chart, or click on new nodes to change the path.

Shortest paths can be different if you traverse items in your network using summary links at the top chart level, or content links in the underlying chart level.

To find paths using combos, which are also in the underlying level, make a new object that models combos as nodes.

You need to import the shortestPaths method from the ReGraph analysis module.

See also

import React, { useEffect, useRef, useState } from "react";
import { createRoot } from "react-dom/client";

import cloneDeep from "lodash/cloneDeep";
import each from "lodash/each";
import has from "lodash/has";
import includes from "lodash/includes";
import merge from "lodash/merge";
import { Chart } from "regraph";
import { shortestPaths } from "regraph/analysis";

import { data, positions as defaultPositions } from "./data";
import { style } from "@ci/theme/rg/js/storyStyles";

function isNode(item) {
  return !has(item, "id1");
}

const pathLink = {
  ...style.selectMain,
  width: 6,
};

const endNode = {
  border: { ...style.selectMain, width: 4 },
};

const pathNode = {
  ...endNode,
  label: { ...style.darkLabel },
  color: "transparent",
};

export const Demo = () => <ComboPaths items={data()} positions={                  } />;

function ComboPaths(props) {
  const { items, positions } = props;
  const [state, setState] = useState({
    from: undefined,
    to: undefined,
    combine: { properties: ["group"] },
    traverseCombos: false,
    paths: undefined,
  });

  const topLevelGraph = useRef({});
  const parentComboLookup = useRef({});

  useEffect(() => {
    const setInitialPath = async () => {
      const { traverseCombos } = state;
      await updatePath({ from: "a", to: "b", traverseCombos });
    };
    setInitialPath();
  }, []);

  const updatePath = async ({ from, to, traverseCombos }) => {
    let newPaths;
    if (from && to) {
      const { onePath } = await shortestPaths(
        traverseCombos ? topLevelGraph.current : items,
        from,
        to,
        {
          direction: "any",
        }
      );
      newPaths = onePath;
    }
    setState((current) => {
      return {
        from,
        to,
        traverseCombos,
        paths: newPaths,
        combine: { ...current.combine },
      };
    });
  };

  const combineNodesHandler = ({ setStyle, id, nodes }) => {
    const defaultCombo = {
      arrange: "none",
      border: { color: "#c0c0c0", width: 3 },
      label: { text: "" },
    };
    each(nodes, (node, childId) => {
      parentComboLookup.current[childId] = id;
    });
    const { from, to, paths } = state;
    if (id === from || id === to) {
      setStyle(merge({}, defaultCombo, endNode, { color: "white" }));
      return;
    }
    if (paths && includes(paths, id)) {
      setStyle(merge({}, defaultCombo, pathNode));
      return;
    }
    setStyle(defaultCombo);
  };

  const combineLinksHandler = ({ setStyle, id, id1, id2 }) => {
    const { traverseCombos, paths } = state;
    topLevelGraph.current[id] = { id1, id2 };

    // Ensure nodes outside combos are included in top level graph
    topLevelGraph.current[id1] = {};
    topLevelGraph.current[id2] = {};

    if (paths && includes(paths, id)) {
      setStyle(pathLink);
      return;
    }

    setStyle({
      color: "#c0c0c0",
      width: 3,
      contents: !traverseCombos,
      summary: traverseCombos,
    });
  };

  const itemPressHandler = async (id) => {
    const { from, to, traverseCombos } = state;

    let newFrom = from;
    let newTo = to;

    // Clicking on an item in a combo when traversing combos sets id to the combo id
    if (traverseCombos && parentComboLookup.current[id]) {
      /* eslint-disable-next-line no-param-reassign */
      id = parentComboLookup.current[id];
    }
    // if pressing the background or pressing on a link
    // or clicking on a combo when traversing nodes
    if (
      id === null ||
      (items[id] && !isNode(items[id])) ||
      (topLevelGraph.current[id] && !isNode(topLevelGraph.current[id])) ||
      (!traverseCombos && !items[id])
    ) {
      // then we clear the ends
      newFrom = undefined;
      newTo = undefined;
    } else if (id !== from && id !== to) {
      if (!from) {
        newFrom = id;
      } else if (!to) {
        newTo = id;
      } else {
        newFrom = to;
        newTo = id;
      }
    }
    await updatePath({ from: newFrom, to: newTo, traverseCombos });
  };

  const clickHandler = ({ preventDefault, id }) => {
    itemPressHandler(id);
    preventDefault();
  };

  // stop nodes being dragged
  const dragHandler = ({ preventDefault, type }) => {
    if (type === "node") {
      preventDefault();
    }
  };

  const styledItems = () => {
    const { from, to, paths } = state;
    const styled = {};
    if (from && items[from]) {
      styled[from] = merge(cloneDeep(items[from]), endNode);
    }
    if (to && items[to]) {
      styled[to] = merge(cloneDeep(items[to]), endNode);
    }
    if (paths) {
      paths.forEach((id) => {
        // style items along the path
        if (!styled[id] && items[id]) {
          const item = items[id];
          const pathStyle = isNode(item) ? pathNode : pathLink;
          styled[id] = merge(cloneDeep(item), pathStyle);
        }
      });
    }
    return { ...items, ...styled };
  };

  const setTraverseCombos = async (val) => {
    const { from: stateFrom, to: stateTo } = state;
    const from = stateFrom === "a" || stateFrom === "b" ? stateFrom : null;
    const to = stateTo === "a" || stateTo === "b" ? stateTo : null;
    await updatePath({ from, to, traverseCombos: val });
  };

  return (
    <div className="story">
      <div className="options">
        {" "}
        <button
          type="button"
          className={ state.traverseCombos ? "active" : ""}
          onClick={() => setTraverseCombos(false)}
        >
          Traverse Nodes
        </button>
        <button
          type="button"
          className={state.traverseCombos ? "active" : ""}
          onClick={() => setTraverseCombos(true)}
        >
          Traverse Combos
        </button>
      </div>
      <div className="chart-wrapper">
        <Chart
          items={styledItems()}
          positions={positions}
          combine={state.combine}
          animation={{ animate: false }}
          onClick={clickHandler}
          onDragStart={dragHandler}
          onCombineNodes={combineNodesHandler}
          onCombineLinks={combineLinksHandler}
          options={{
            navigation: false,
            overview: false,
            selection: { color: "rgba(0,0,0,0)", labelColor: "black" },
          }}
        />
      </div>
    </div>
  );
}

const root = createRoot(document.getElementById("regraph"));
root.render(<Demo />);
import { style } from "@ci/theme/rg/js/storyStyles";

function data() {
  return {
    a: {
      label: { text: "a", ...style.primaryLabel1 },
      ...style.primary1,
    },
    b: {
      label: { text: "b", ...style.primaryLabel1 },
      ...style.primary1,
    },
    1: {
      data: { group: "combo1" },
      label: { text: "1", ...style.primaryLabel1 },
      ...style.primary1,
    },
    2: {
      data: { group: "combo1" },
      label: { text: "2", ...style.primaryLabel1 },
      ...style.primary1,
    },
    3: {
      data: { group: "combo1" },
      label: { text: "3", ...style.primaryLabel1 },
      ...style.primary1,
    },
    4: {
      data: { group: "combo1" },
      label: { text: "4", ...style.primaryLabel1 },
      ...style.primary1,
    },
    5: {
      data: { group: "combo2" },
      label: { text: "5", ...style.primaryLabel1 },
      ...style.primary1,
    },
    6: {
      data: { group: "combo2" },
      label: { text: "6", ...style.primaryLabel1 },
      ...style.primary1,
    },
    7: {
      data: { group: "combo3" },
      label: { text: "7", ...style.primaryLabel1 },
      ...style.primary1,
    },
    8: {
      data: { group: "combo3" },
      label: { text: "8", ...style.primaryLabel1 },
      ...style.primary1,
    },
    9: {
      data: { group: "combo3" },
      label: { text: "9", ...style.primaryLabel1 },
      ...style.primary1,
    },
    "a-1": {
      id1: "a",
      id2: "1",
      ...style.link,
    },
    "1-2": {
      id1: "1",
      id2: "2",
      ...style.link,
    },
    "2-3": {
      id1: "2",
      id2: "3",
      ...style.link,
    },
    "3-4": {
      id1: "3",
      id2: "4",
      ...style.link,
    },
    "4-b": {
      id1: "4",
      id2: "b",
      ...style.link,
    },
    "a-5": {
      id1: "a",
      id2: "5",
      ...style.link,
    },
    "5-6": {
      id1: "5",
      id2: "6",
      ...style.link,
    },
    "6-7": {
      id1: "6",
      id2: "7",
      ...style.link,
    },
    "7-8": {
      id1: "7",
      id2: "8",
      ...style.link,
    },
    "8-9": {
      id1: "8",
      id2: "9",
      ...style.link,
    },
    "b-7": {
      id1: "b",
      id2: "7",
      ...style.link,
    },
  };
}

function positions() {
  return {
    1: { x: -34.75, y: -164.5 },
    2: { x: -15.75, y: -240.5 },
    3: { x: 35.25000000000001, y: -195.5 },
    4: { x: 15.25, y: -119.5 },
    5: { x: -150, y: 145 },
    6: { x: -150, y: 215 },
    7: { x: 138.33333333333334, y: 136.66666666666666 },
    8: { x: 193.33333333333334, y: 191.66666666666666 },
    9: { x: 118.33333333333334, y: 211.66666666666666 },
    a: { x: -380, y: 0 },
    b: { x: 380, y: 0 },
    _combonode_combo1: { x: 0, y: -180 },
    _combonode_combo2: { x: -150, y: 180 },
    _combonode_combo3: { x: 150, y: 180 },
  };
}

export { data, positions };
<!doctype html>
<html>
  <body>
    <div id="regraph" style="height: 100vh"></div>
    <script type="module" src="./code.jsx"></script>
  </body>
</html>

Terms of use

These terms do not alter or supersede any existing agreements between you (or your employer) and us.

By accessing or using any Content you agree to be bound by these Terms of Use. Please review these terms carefully before using the website.

The contents of this website, including but not limited to any text, code samples, API references, schemas, interactive tools, and other materials (collectively, the 'Content'), are made available for informational and internal evaluation purposes only. All intellectual property rights in the Content are reserved. No licence is granted to use the Content for any commercial purpose, or to copy, distribute, modify, reverse-engineer, or incorporate any part of the Content into any product or service, without our prior written consent.

This Content is provided “as is” and “as available,” without any representations, warranties, or guarantees of any kind, whether express or implied, including but not limited to implied warranties of merchantability, fitness for a particular purpose, non-infringement, or accuracy. To the fullest extent permitted by applicable law, we expressly exclude and disclaim all implied warranties, conditions, and other terms that might otherwise be implied.

We disclaim all liability for any loss or damage, whether direct, indirect, incidental, consequential, or otherwise, arising from any reliance placed on the Content or from your use of it, to the fullest extent permitted by applicable law. By continuing to access or use the Content, you acknowledge and agree to these terms.