Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

feat(editor): Alt+arrows move to the flowchart node that's visually next (#12502)

David Luzar2610ebae0cbd
diff --git a/packages/element/src/flowchart.ts b/packages/element/src/flowchart.ts
index abc266e947..172c95d290 100644
--- a/packages/element/src/flowchart.ts
+++ b/packages/element/src/flowchart.ts
@@ -1,12 +1,6 @@
import { invariant, toBrandedType, type Bounds } from "@excalidraw/common";
-import {
- clamp,
- type GlobalPoint,
- pointFrom,
- PRECISION,
- type LocalPoint,
-} from "@excalidraw/math";
+import { clamp, pointFrom, PRECISION } from "@excalidraw/math";
import type {
AppState,
@@ -15,15 +9,6 @@ import type {
import { bindBindingElement } from "./binding";
import { updateElbowArrowPoints } from "./elbowArrow";
-import {
- HEADING_DOWN,
- HEADING_LEFT,
- HEADING_RIGHT,
- HEADING_UP,
- compareHeading,
- headingForPointFromElement,
- type Heading,
-} from "./heading";
import { LinearElementEditor } from "./linearElementEditor";
import { mutateElement } from "./mutateElement";
import {
@@ -35,7 +20,7 @@ import { aabbForElement } from "./bounds";
import { elementsAreInFrameBounds, elementOverlapsWithFrame } from "./frame";
import {
isBindableElement,
- isElbowArrow,
+ isArrowElement,
isFrameElement,
isFlowchartNodeElement,
} from "./typeChecks";
@@ -117,25 +102,31 @@ const getConnectedFlowchartNodes = (
node: ExcalidrawBindableElement,
elementsMap: ElementsMap,
): ExcalidrawBindableElement[] => {
- const arrows = [...elementsMap.values()].filter(isElbowArrow);
+ // one pass over the scene, so the walk below costs the size of the chart,
+ // not chart nodes × all arrows in the scene
+ const neighbors = new Map<string, string[]>();
+ const addNeighbor = (from: string, to: string) => {
+ const list = neighbors.get(from);
+ if (list) {
+ list.push(to);
+ } else {
+ neighbors.set(from, [to]);
+ }
+ };
+ for (const element of elementsMap.values()) {
+ if (isArrowElement(element) && element.startBinding && element.endBinding) {
+ addNeighbor(element.startBinding.elementId, element.endBinding.elementId);
+ addNeighbor(element.endBinding.elementId, element.startBinding.elementId);
+ }
+ }
+
const visited = new Set<string>([node.id]);
const queue: string[] = [node.id];
const connected: ExcalidrawBindableElement[] = [];
- while (queue.length > 0) {
- const currentId = queue.shift()!;
- for (const arrow of arrows) {
- const startId = arrow.startBinding?.elementId;
- const endId = arrow.endBinding?.elementId;
-
- let neighborId: string | undefined;
- if (startId === currentId) {
- neighborId = endId;
- } else if (endId === currentId) {
- neighborId = startId;
- }
-
- if (!neighborId || visited.has(neighborId)) {
+ for (let i = 0; i < queue.length; i++) {
+ for (const neighborId of neighbors.get(queue[i]) ?? []) {
+ if (visited.has(neighborId)) {
continue;
}
@@ -462,22 +453,28 @@ const createBindingArrow = (
};
};
+// Alt+arrow navigation moves to whichever node of the flowchart *looks* next
+// in the pressed direction, picking the nearest node of the first non-empty
+// tier:
+// 1. nodes in line with the current one (sharing its row for left/right, its
+// column for up/down)
+// 2. nodes linked to the current one whose center lies past its edge in the
+// pressed direction, at any angle
+// 3. nodes whose center lies within the 45° cone of the pressed direction
+// (an X through the current node's center)
+// 4. any other node whose center lies past the current one's edge, so a
+// direction only does nothing when there's nothing that way at all
+// Near-ties (within 10%) go to a node the current one links to, then to one
+// linking to it, then to the one more level with the current one's center,
+// then reading order (the upper one for left/right, the left one for
+// up/down).
+const NAVIGATION_TIE_TOLERANCE = 0.1;
+
export class FlowChartNavigator {
isExploring: boolean = false;
- // nodes that are ONE link away (successor and predecessor both included)
- private sameLevelNodes: ExcalidrawElement[] = [];
- private sameLevelIndex: number = 0;
- // set it to the opposite of the defalut creation direction
- private direction: LinkDirection | null = null;
- // for speedier navigation
- private visitedNodes: Set<ExcalidrawElement["id"]> = new Set();
clear() {
this.isExploring = false;
- this.sameLevelNodes = [];
- this.sameLevelIndex = 0;
- this.direction = null;
- this.visitedNodes.clear();
}
exploreByDirection(
@@ -489,206 +486,140 @@ export class FlowChartNavigator {
return null;
}
- // clear if going at a different direction
- if (direction !== this.direction) {
- this.clear();
- }
-
- // add the current node to the visited
- if (!this.visitedNodes.has(element.id)) {
- this.visitedNodes.add(element.id);
- }
-
- /**
- * CASE:
- * - already started exploring, AND
- * - there are multiple nodes at the same level, AND
- * - still going at the same direction, AND
- *
- * RESULT:
- * - loop through nodes at the same level
- *
- * WHY:
- * - provides user the capability to loop through nodes at the same level
- */
- if (
- this.isExploring &&
- direction === this.direction &&
- this.sameLevelNodes.length > 1
- ) {
- this.sameLevelIndex =
- (this.sameLevelIndex + 1) % this.sameLevelNodes.length;
-
- return this.sameLevelNodes[this.sameLevelIndex].id;
- }
+ const next = FlowChartNavigator.findNodeInDirection(
+ element,
+ elementsMap,
+ direction,
+ );
- const nodes = [
- ...FlowChartNavigator.getSuccessors(element, elementsMap, direction),
- ...FlowChartNavigator.getPredecessors(element, elementsMap, direction),
- ];
-
- /**
- * CASE:
- * - just started exploring at the given direction
- *
- * RESULT:
- * - go to the first node in the given direction
- */
- if (nodes.length > 0) {
- this.sameLevelIndex = 0;
- this.isExploring = true;
- this.sameLevelNodes = nodes;
- this.direction = direction;
- this.visitedNodes.add(nodes[0].id);
-
- return nodes[0].id;
+ if (!next) {
+ return null;
}
- /**
- * CASE:
- * - (just started exploring or still going at the same direction) OR
- * - there're no nodes at the given direction
- *
- * RESULT:
- * - go to some other unvisited linked node
- *
- * WHY:
- * - provide a speedier navigation from a given node to some predecessor
- * without the user having to change arrow key
- */
- if (direction === this.direction || !this.isExploring) {
- if (!this.isExploring) {
- // just started and no other nodes at the given direction
- // so the current node is technically the first visited node
- // (this is needed so that we don't get stuck between looping through )
- this.visitedNodes.add(element.id);
- }
-
- const otherDirections: LinkDirection[] = [
- "up",
- "right",
- "down",
- "left",
- ].filter((dir): dir is LinkDirection => dir !== direction);
-
- const otherLinkedNodes = otherDirections
- .map((dir) => [
- ...FlowChartNavigator.getSuccessors(element, elementsMap, dir),
- ...FlowChartNavigator.getPredecessors(element, elementsMap, dir),
- ])
- .flat()
- .filter((linkedNode) => !this.visitedNodes.has(linkedNode.id));
-
- for (const linkedNode of otherLinkedNodes) {
- if (!this.visitedNodes.has(linkedNode.id)) {
- this.visitedNodes.add(linkedNode.id);
- this.isExploring = true;
- this.direction = direction;
- return linkedNode.id;
- }
- }
- }
+ this.isExploring = true;
- return null;
+ return next.id;
}
- private static getNodeRelatives(
- type: "predecessors" | "successors",
+ private static findNodeInDirection(
node: ExcalidrawBindableElement,
elementsMap: ElementsMap,
direction: LinkDirection,
) {
- const items = [...elementsMap.values()].reduce(
- (
- acc: { relative: ExcalidrawBindableElement; heading: Heading }[],
- el,
- ) => {
- let oppositeBinding;
- if (
- isElbowArrow(el) &&
- // we want check existence of the opposite binding, in the direction
- // we're interested in
- (oppositeBinding =
- el[type === "predecessors" ? "startBinding" : "endBinding"]) &&
- // similarly, we need to filter only arrows bound to target node
- el[type === "predecessors" ? "endBinding" : "startBinding"]
- ?.elementId === node.id
- ) {
- const relative = elementsMap.get(oppositeBinding.elementId);
-
- if (!relative) {
- return acc;
- }
-
- invariant(
- isBindableElement(relative),
- "not an ExcalidrawBindableElement",
- );
-
- const edgePoint = (
- type === "predecessors" ? el.points[el.points.length - 1] : [0, 0]
- ) as Readonly<LocalPoint>;
-
- const heading = headingForPointFromElement(
- node,
- aabbForElement(node, elementsMap),
- [edgePoint[0] + el.x, edgePoint[1] + el.y] as Readonly<GlobalPoint>,
- );
-
- acc.push({
- relative,
- heading,
- });
+ const horizontal = direction === "left" || direction === "right";
+ const sign = direction === "right" || direction === "down" ? 1 : -1;
+ const [minX, minY, maxX, maxY] = aabbForElement(node, elementsMap);
+ const [nodeMainStart, nodeMainEnd, nodeCrossStart, nodeCrossEnd] =
+ horizontal ? [minX, maxX, minY, maxY] : [minY, maxY, minX, maxX];
+ const nodeMainCenter = (nodeMainStart + nodeMainEnd) / 2;
+ const nodeCrossCenter = (nodeCrossStart + nodeCrossEnd) / 2;
+ const nodeEdge = sign > 0 ? nodeMainEnd : nodeMainStart;
+
+ const successors = new Set<string>();
+ const predecessors = new Set<string>();
+ for (const element of elementsMap.values()) {
+ if (
+ isArrowElement(element) &&
+ element.startBinding &&
+ element.endBinding
+ ) {
+ if (element.startBinding.elementId === node.id) {
+ successors.add(element.endBinding.elementId);
+ }
+ if (element.endBinding.elementId === node.id) {
+ predecessors.add(element.startBinding.elementId);
}
- return acc;
+ }
+ }
+ const linkRank = (id: string) =>
+ successors.has(id) ? 0 : predecessors.has(id) ? 1 : 2;
+
+ const candidates = getConnectedFlowchartNodes(node, elementsMap).flatMap(
+ (candidate) => {
+ const bounds = aabbForElement(candidate, elementsMap);
+ const [mainStart, mainEnd, crossStart, crossEnd] = horizontal
+ ? [bounds[0], bounds[2], bounds[1], bounds[3]]
+ : [bounds[1], bounds[3], bounds[0], bounds[2]];
+ const mainCenter = (mainStart + mainEnd) / 2;
+ const crossCenter = (crossStart + crossEnd) / 2;
+
+ if ((mainCenter - nodeMainCenter) * sign <= 0) {
+ return [];
+ }
+
+ // positive when the boxes are apart along that axis, negative when
+ // they overlap
+ const mainGap = Math.max(
+ mainStart - nodeMainEnd,
+ nodeMainStart - mainEnd,
+ );
+ const crossGap = Math.max(
+ crossStart - nodeCrossEnd,
+ nodeCrossStart - crossEnd,
+ );
+ const inCone =
+ Math.abs(mainCenter - nodeMainCenter) >=
+ Math.abs(crossCenter - nodeCrossCenter);
+ // either center falls within the other node's span, so the two mostly
+ // share a row (column) — a sliver of overlap between neighboring rows
+ // doesn't count
+ const inLine =
+ (nodeCrossStart < crossCenter && crossCenter < nodeCrossEnd) ||
+ (crossStart < nodeCrossCenter && nodeCrossCenter < crossEnd);
+ const pastEdge = (mainCenter - nodeEdge) * sign > 0;
+
+ const tier = inLine
+ ? 0
+ : pastEdge && linkRank(candidate.id) < 2
+ ? 1
+ : inCone
+ ? 2
+ : pastEdge
+ ? 3
+ : null;
+
+ if (tier === null) {
+ return [];
+ }
+
+ return [
+ {
+ node: candidate,
+ tier,
+ distance:
+ tier === 0
+ ? Math.max(mainGap, 0)
+ : Math.hypot(Math.max(mainGap, 0), Math.max(crossGap, 0)),
+ crossCenter,
+ },
+ ];
},
- [],
);
- switch (direction) {
- case "up":
- return items
- .filter((item) => compareHeading(item.heading, HEADING_UP))
- .map((item) => item.relative);
- case "down":
- return items
- .filter((item) => compareHeading(item.heading, HEADING_DOWN))
- .map((item) => item.relative);
- case "right":
- return items
- .filter((item) => compareHeading(item.heading, HEADING_RIGHT))
- .map((item) => item.relative);
- case "left":
- return items
- .filter((item) => compareHeading(item.heading, HEADING_LEFT))
- .map((item) => item.relative);
+ if (!candidates.length) {
+ return null;
}
- }
-
- private static getSuccessors(
- node: ExcalidrawBindableElement,
- elementsMap: ElementsMap,
- direction: LinkDirection,
- ) {
- return FlowChartNavigator.getNodeRelatives(
- "successors",
- node,
- elementsMap,
- direction,
- );
- }
- private static getPredecessors(
- node: ExcalidrawBindableElement,
- elementsMap: ElementsMap,
- direction: LinkDirection,
- ) {
- return FlowChartNavigator.getNodeRelatives(
- "predecessors",
- node,
- elementsMap,
- direction,
- );
+ const topTier = Math.min(...candidates.map((candidate) => candidate.tier));
+ const pool = candidates.filter((candidate) => candidate.tier === topTier);
+ const nearest = Math.min(...pool.map((candidate) => candidate.distance));
+ const tolerance = Math.max(nearest * NAVIGATION_TIE_TOLERANCE, 1);
+ // how far a candidate's center is off the current node's center line;
+ // within a pixel it's a tie (symmetric layouts), left to reading order
+ const offset = (candidate: typeof pool[number]) =>
+ Math.abs(candidate.crossCenter - nodeCrossCenter);
+ const compareOffsets = (a: typeof pool[number], b: typeof pool[number]) =>
+ Math.abs(offset(a) - offset(b)) > 1 ? offset(a) - offset(b) : 0;
+
+ return pool
+ .filter((candidate) => candidate.distance <= nearest + tolerance)
+ .sort(
+ (a, b) =>
+ linkRank(a.node.id) - linkRank(b.node.id) ||
+ compareOffsets(a, b) ||
+ a.crossCenter - b.crossCenter ||
+ a.distance - b.distance,
+ )[0].node;
}
}
diff --git a/packages/element/tests/flowchart.test.tsx b/packages/element/tests/flowchart.test.tsx
index 9aa2732bc2..c26ad78fea 100644
--- a/packages/element/tests/flowchart.test.tsx
+++ b/packages/element/tests/flowchart.test.tsx
@@ -9,7 +9,10 @@ import {
unmountComponent,
} from "@excalidraw/excalidraw/tests/test-utils";
-import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
+import type {
+ ExcalidrawElement,
+ NonDeletedExcalidrawElement,
+} from "@excalidraw/element/types";
unmountComponent();
@@ -591,189 +594,228 @@ describe("flow chart navigation", () => {
expect(h.state.selectedElementIds[rightMostNode.id]).toBe(true);
});
- it("multiple nodes at each level", () => {
- /**
- * from the perspective of the first node, there're four layers, and
- * there are four nodes at the second layer
- *
- * -> ▨
- * ▨ -> ▨ -> ▨ -> ▨ -> ▨
- * -> ▨
- * -> ▨
- */
-
- API.clearSelection();
- const rectangle = API.createElement({
- type: "rectangle",
- width: 200,
- height: 100,
- });
-
- API.setElements([rectangle]);
- API.setSelectedElements([rectangle]);
-
- Keyboard.withModifierKeys({ ctrl: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- });
- Keyboard.keyUp(KEYS.CTRL_OR_CMD);
-
- Keyboard.withModifierKeys({ ctrl: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- });
- Keyboard.keyUp(KEYS.CTRL_OR_CMD);
-
- Keyboard.withModifierKeys({ ctrl: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- });
- Keyboard.keyUp(KEYS.CTRL_OR_CMD);
-
- Keyboard.withModifierKeys({ ctrl: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- });
- Keyboard.keyUp(KEYS.CTRL_OR_CMD);
-
- const secondNode = h.elements[1];
- const rightMostNode = h.elements[h.elements.length - 2];
-
- API.setSelectedElements([rectangle]);
- Keyboard.withModifierKeys({ ctrl: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- });
- Keyboard.keyUp(KEYS.CTRL_OR_CMD);
-
- API.setSelectedElements([rectangle]);
+ const createNode = (key: string) => {
Keyboard.withModifierKeys({ ctrl: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- });
- Keyboard.keyUp(KEYS.CTRL_OR_CMD);
-
- API.setSelectedElements([rectangle]);
- Keyboard.withModifierKeys({ ctrl: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
+ Keyboard.keyPress(key);
});
Keyboard.keyUp(KEYS.CTRL_OR_CMD);
+ return h.app.scene
+ .getNonDeletedElements()
+ .find((el) => h.state.selectedElementIds[el.id])!;
+ };
- API.setSelectedElements([rectangle]);
-
- // because of same level cycling,
- // going right five times should take us back to the second node again
+ const navigate = (...keys: string[]) => {
Keyboard.withModifierKeys({ alt: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
+ keys.forEach((key) => Keyboard.keyPress(key));
});
Keyboard.keyUp(KEYS.ALT);
- expect(h.state.selectedElementIds[secondNode.id]).toBe(true);
+ };
- // from the second node, going right three times should take us to the rightmost node
- Keyboard.withModifierKeys({ alt: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- });
- Keyboard.keyUp(KEYS.ALT);
- expect(h.state.selectedElementIds[rightMostNode.id]).toBe(true);
+ const expectSelected = (element: ExcalidrawElement) => {
+ expect(Object.keys(h.state.selectedElementIds)).toEqual([element.id]);
+ };
- Keyboard.withModifierKeys({ alt: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_LEFT);
- Keyboard.keyPress(KEYS.ARROW_LEFT);
- Keyboard.keyPress(KEYS.ARROW_LEFT);
- Keyboard.keyPress(KEYS.ARROW_LEFT);
- });
- Keyboard.keyUp(KEYS.ALT);
- expect(h.state.selectedElementIds[rectangle.id]).toBe(true);
+ const node = (x: number, y: number, width = 200, height = 80) =>
+ API.createElement({ type: "rectangle", x, y, width, height });
+
+ const link = (
+ from: ExcalidrawElement,
+ to: ExcalidrawElement,
+ elbowed = true,
+ ) =>
+ API.createElement({
+ type: "arrow",
+ elbowed,
+ startBinding: {
+ elementId: from.id,
+ fixedPoint: [0.5, 0.5],
+ mode: "orbit",
+ },
+ endBinding: { elementId: to.id, fixedPoint: [0.5, 0.5], mode: "orbit" },
+ });
+
+ it("moves to the node that's visually in that direction", () => {
+ /**
+ * A → B → C
+ * ↓
+ * D
+ * ↓
+ * F ← E
+ */
+ const a = API.createElement({ type: "rectangle", width: 200, height: 100 });
+ API.setElements([a]);
+ API.setSelectedElements([a]);
+
+ const b = createNode(KEYS.ARROW_RIGHT);
+ createNode(KEYS.ARROW_RIGHT);
+ const d = createNode(KEYS.ARROW_DOWN);
+ const e = createNode(KEYS.ARROW_DOWN);
+ const f = createNode(KEYS.ARROW_LEFT);
+
+ // straight up, not along the arrow back to E
+ navigate(KEYS.ARROW_UP);
+ expectSelected(b);
+
+ // nothing to the right of E
+ API.setSelectedElements([e]);
+ navigate(KEYS.ARROW_RIGHT);
+ expectSelected(e);
+
+ // F is the only node more below A than beside it
+ API.setSelectedElements([a]);
+ navigate(KEYS.ARROW_DOWN);
+ expectSelected(f);
+
+ // B and F are equally far: the upper one wins
+ API.setSelectedElements([d]);
+ navigate(KEYS.ARROW_LEFT);
+ expectSelected(b);
+
+ // A sits between the rows, overlapping D's row by a sliver: that doesn't
+ // put D in line with it, so the much nearer B wins
+ API.updateElement(a, { y: a.y + 100.2 });
+ API.setSelectedElements([a]);
+ navigate(KEYS.ARROW_RIGHT);
+ expectSelected(b);
});
- it("take the most obvious link when possible", () => {
+ it("breaks ties by links, alignment and reading order", () => {
/**
- * ▨ → ▨ ▨ → ▨
- * ↓ ↑
- * ▨ → ▨
+ * X ←┐
+ * B
+ * A ─┤
+ * C
+ * Y ←┘
*/
-
- API.clearSelection();
- const rectangle = API.createElement({
+ // at a fractional y, B and C are equally level with A only up to float
+ // noise, which mustn't decide between them
+ const a = API.createElement({
type: "rectangle",
+ y: 0.7,
width: 200,
height: 100,
});
-
- API.setElements([rectangle]);
- API.setSelectedElements([rectangle]);
+ API.setElements([a]);
+ API.setSelectedElements([a]);
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.ARROW_RIGHT);
- });
- Keyboard.keyUp(KEYS.CTRL_OR_CMD);
-
- Keyboard.withModifierKeys({ ctrl: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_DOWN);
- });
- Keyboard.keyUp(KEYS.CTRL_OR_CMD);
-
- Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.ARROW_RIGHT);
});
Keyboard.keyUp(KEYS.CTRL_OR_CMD);
+ const [b, c] = h.app.scene
+ .getNonDeletedElements()
+ .filter((el) => el.type === "rectangle" && el.id !== a.id)
+ .sort((el1, el2) => el1.y - el2.y);
+
+ API.setSelectedElements([b]);
+ const x = createNode(KEYS.ARROW_LEFT);
+ API.setSelectedElements([c]);
+ const y = createNode(KEYS.ARROW_LEFT);
+ API.updateElement(y, { y: y.y + 10 });
+
+ // siblings aren't linked, but C is right below B
+ API.setSelectedElements([b]);
+ navigate(KEYS.ARROW_DOWN);
+ expectSelected(c);
+
+ // A and Y are about equally far: C links to Y
+ navigate(KEYS.ARROW_LEFT);
+ expectSelected(y);
+
+ // B and C are equally far, both linked and equally level: the upper one
+ // wins
+ API.setSelectedElements([a]);
+ navigate(KEYS.ARROW_RIGHT);
+ expectSelected(b);
+
+ // A and X are equally far: B links to X, even right after coming from A
+ API.setSelectedElements([a]);
+ navigate(KEYS.ARROW_RIGHT, KEYS.ARROW_LEFT);
+ expectSelected(x);
+
+ // P and Q are both in line with N, equally far and linked from it: P is
+ // level with N's center, Q is higher
+ const n = node(0, 0, 200, 200);
+ const q = node(300, -30);
+ const p = node(300, 60);
+ API.setElements([n, q, p, link(n, q), link(n, p)]);
+ API.setSelectedElements([n]);
+ navigate(KEYS.ARROW_RIGHT);
+ expectSelected(p);
+
+ // links still come first
+ API.setElements([n, q, p, link(n, q)]);
+ API.setSelectedElements([n]);
+ navigate(KEYS.ARROW_RIGHT);
+ expectSelected(q);
+ });
- Keyboard.withModifierKeys({ ctrl: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_UP);
- });
- Keyboard.keyUp(KEYS.CTRL_OR_CMD);
-
- Keyboard.withModifierKeys({ ctrl: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- });
- Keyboard.keyUp(KEYS.CTRL_OR_CMD);
-
- // last node should be the one that's selected
- const rightMostNode = h.elements[h.elements.length - 2];
- expect(rightMostNode.type).toBe("rectangle");
- expect(h.state.selectedElementIds[rightMostNode.id]).toBe(true);
-
- Keyboard.withModifierKeys({ alt: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_LEFT);
- Keyboard.keyPress(KEYS.ARROW_LEFT);
- Keyboard.keyPress(KEYS.ARROW_LEFT);
- Keyboard.keyPress(KEYS.ARROW_LEFT);
- Keyboard.keyPress(KEYS.ARROW_LEFT);
- });
- Keyboard.keyUp(KEYS.ALT);
-
- expect(h.state.selectedElementIds[rectangle.id]).toBe(true);
-
- // going any direction takes us to the predecessor as well
- const predecessorToRightMostNode = h.elements[h.elements.length - 4];
- expect(predecessorToRightMostNode.type).toBe("rectangle");
-
- API.setSelectedElements([rightMostNode] as NonDeletedExcalidrawElement[]);
- Keyboard.withModifierKeys({ alt: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_RIGHT);
- });
- Keyboard.keyUp(KEYS.ALT);
- expect(h.state.selectedElementIds[rightMostNode.id]).not.toBe(true);
- expect(h.state.selectedElementIds[predecessorToRightMostNode.id]).toBe(
- true,
- );
- API.setSelectedElements([rightMostNode] as NonDeletedExcalidrawElement[]);
- Keyboard.withModifierKeys({ alt: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_UP);
- });
- Keyboard.keyUp(KEYS.ALT);
- expect(h.state.selectedElementIds[rightMostNode.id]).not.toBe(true);
- expect(h.state.selectedElementIds[predecessorToRightMostNode.id]).toBe(
- true,
- );
- API.setSelectedElements([rightMostNode] as NonDeletedExcalidrawElement[]);
- Keyboard.withModifierKeys({ alt: true }, () => {
- Keyboard.keyPress(KEYS.ARROW_DOWN);
- });
- Keyboard.keyUp(KEYS.ALT);
- expect(h.state.selectedElementIds[rightMostNode.id]).not.toBe(true);
- expect(h.state.selectedElementIds[predecessorToRightMostNode.id]).toBe(
- true,
- );
+ it("prefers nodes in line, then linked, then in the cone, then any ahead", () => {
+ // to the left of S, A shares its row while B is linked to S but lower
+ let s = node(450, 170);
+ let a = node(0, 170);
+ let b = node(150, 530);
+ const c = node(750, 170);
+ API.setElements([s, a, b, c, link(s, c), link(c, a), link(s, b)]);
+ API.setSelectedElements([s]);
+ navigate(KEYS.ARROW_LEFT);
+ expectSelected(a);
+
+ // nothing shares S's row: A, linked to S, lies past S's right edge (if
+ // mostly above it) and wins over B, which is more to the right but isn't
+ // linked (through plain arrows, which link nodes just like elbow ones)
+ const d = node(300, 80);
+ a = node(300, 260);
+ b = node(580, 520);
+ s = node(0, 620);
+ API.setElements([
+ d,
+ a,
+ b,
+ s,
+ link(d, a, false),
+ link(d, b, false),
+ link(a, s, false),
+ ]);
+ API.setSelectedElements([s]);
+ navigate(KEYS.ARROW_RIGHT);
+ expectSelected(a);
+
+ // below S, A is in the cone while the nearer B is more beside S than
+ // below it
+ const e = node(0, -300);
+ s = node(0, 0);
+ a = node(150, 400);
+ b = node(400, 150);
+ API.setElements([e, s, a, b, link(e, s), link(e, a), link(e, b)]);
+ API.setSelectedElements([s]);
+ navigate(KEYS.ARROW_DOWN);
+ expectSelected(a);
+
+ // A's center is more to the right of S's than below it, so A is in the
+ // cone and beats the farther F, though A's nearest corner is more below
+ // S than beside it (while below S, the linked B wins)
+ s = node(300, 270);
+ a = node(580, 470);
+ b = node(0, 630);
+ const f = node(900, 400);
+ API.setElements([
+ d,
+ s,
+ a,
+ b,
+ f,
+ link(d, s),
+ link(d, a),
+ link(s, b),
+ link(d, f),
+ ]);
+ API.setSelectedElements([s]);
+ navigate(KEYS.ARROW_RIGHT);
+ expectSelected(a);
+ API.setSelectedElements([s]);
+ navigate(KEYS.ARROW_DOWN);
+ expectSelected(b);
});
});
diff --git a/packages/excalidraw/CHANGELOG.md b/packages/excalidraw/CHANGELOG.md
index 84f3c5d175..f2050e6f76 100644
--- a/packages/excalidraw/CHANGELOG.md
+++ b/packages/excalidraw/CHANGELOG.md
@@ -13,6 +13,12 @@ Please add the latest change on the top under the correct section.
## Unreleased
+### Flowchart navigation (2026-10-30) [#12502](https://github.com/excalidraw/excalidraw/pull/12502)
+
+- Alt+arrow keys move the selection to the flowchart node that's visually next in that direction, whether or not it's linked to the selected node. They used to follow only the arrows bound to the pressed side, cycle through siblings on repeated presses, and fall back to any linked node when nothing was that way.
+- The nearest node of the first non-empty tier wins: nodes in line (sharing the row for ←/→, the column for ↑/↓), then linked nodes whose center lies past the selected node's edge, then nodes whose center lies within the 45° cone of the pressed direction, then any node whose center lies past that edge. Near-ties go to linked nodes, then the node more level with the selected one's center, then reading order.
+- Nodes connected by plain (non-elbow) arrows now count as part of the flowchart too, both for Alt+arrow navigation and for the nodes Ctrl+arrows keeps new nodes clear of.
+
### Export API: `exportScene` (2026-10-18) [#12347](https://github.com/excalidraw/excalidraw/pull/12347)
Breaking. `exportToCanvas`, `exportToBlob` and `exportToSvg` (in both `@excalidraw/excalidraw` and `@excalidraw/utils`) are replaced by a single `exportScene`, and every rendering option moved from `appState` into an explicit `config`.