Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix: make graph tracing more kick-ass

Sidwebworks698d8b864ea7
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx
index 349c403499..98ee004f2e 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx
@@ -9,7 +9,6 @@ import {
type NodeMouseHandler,
type NodeTypes,
ReactFlow,
- ReactFlowProvider,
useEdgesState,
useNodesInitialized,
useNodesState,
@@ -17,6 +16,7 @@ import {
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { LuX } from "react-icons/lu";
import { useNavigate, useSearchParams } from "react-router";
import { useShallow } from "zustand/react/shallow";
import type {
@@ -81,11 +81,7 @@ type Props = {
};
export function TraceabilityGraph(props: Props) {
- return (
- <ReactFlowProvider>
- <TraceabilityGraphInner {...props} />
- </ReactFlowProvider>
- );
+ return <TraceabilityGraphInner {...props} />;
}
function TraceabilityGraphInner({
@@ -130,8 +126,10 @@ function TraceabilityGraphInner({
setView,
setSpacing,
setIsolate,
- setSelectedSingle,
- toggleSelected
+ toggleExcluded,
+ clearExcluded,
+ toggleAdditionalRoot,
+ clearAdditionalRoots
} = useTraceabilityStore(
useShallow((s) => ({
addExpansion: s.addExpansion,
@@ -143,10 +141,14 @@ function TraceabilityGraphInner({
setView: s.setView,
setSpacing: s.setSpacing,
setIsolate: s.setIsolate,
- setSelectedSingle: s.setSelectedSingle,
- toggleSelected: s.toggleSelected
+ toggleExcluded: s.toggleExcluded,
+ clearExcluded: s.clearExcluded,
+ toggleAdditionalRoot: s.toggleAdditionalRoot,
+ clearAdditionalRoots: s.clearAdditionalRoots
}))
);
+ const excludedIds = useTraceabilityStore((s) => s.excludedIds);
+ const additionalRootIds = useTraceabilityStore((s) => s.additionalRootIds);
const probeCacheRef = useRef<Map<string, LineagePayload>>(new Map());
const probedRef = useRef<Set<string>>(new Set());
@@ -225,13 +227,83 @@ function TraceabilityGraphInner({
const laidNodes = layoutResult?.nodes ?? EMPTY_NODES;
const laidEdges = layoutResult?.edges ?? EMPTY_EDGES;
- const [nodes, setNodes, onNodesChange] = useNodesState<Node>(
+ const [nodes, setNodes, onNodesChangeRaw] = useNodesState<Node>(
laidNodes as Node[]
);
const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>(
laidEdges as Edge[]
);
+ const shiftDownRef = useRef(false);
+ const [shiftHeld, setShiftHeld] = useState(false);
+ useEffect(() => {
+ const onDown = (e: KeyboardEvent) => {
+ // Auto-repeat fires keydown continuously; bail if already tracked.
+ if (e.key !== "Shift" || shiftDownRef.current) return;
+ shiftDownRef.current = true;
+ setShiftHeld(true);
+ };
+ const onUp = (e: KeyboardEvent) => {
+ if (e.key !== "Shift" || !shiftDownRef.current) return;
+ shiftDownRef.current = false;
+ setShiftHeld(false);
+ };
+ const onBlur = () => {
+ if (!shiftDownRef.current) return;
+ shiftDownRef.current = false;
+ setShiftHeld(false);
+ };
+ window.addEventListener("keydown", onDown);
+ window.addEventListener("keyup", onUp);
+ window.addEventListener("blur", onBlur);
+ return () => {
+ window.removeEventListener("keydown", onDown);
+ window.removeEventListener("keyup", onUp);
+ window.removeEventListener("blur", onBlur);
+ };
+ }, []);
+
+ const onNodesChange = useCallback(
+ (changes: Parameters<typeof onNodesChangeRaw>[0]) => {
+ if (shiftDownRef.current) {
+ const filtered = changes.filter((c) => c.type !== "select");
+ if (filtered.length > 0) onNodesChangeRaw(filtered);
+ return;
+ }
+ onNodesChangeRaw(changes);
+ },
+ [onNodesChangeRaw]
+ );
+
+ const selectionPathRef = useRef<{ nodeIds: Set<string> } | null>(null);
+ const additionalRootIdsRef = useRef<Set<string>>(additionalRootIds);
+ additionalRootIdsRef.current = additionalRootIds;
+ const excludedIdsRef = useRef<Set<string>>(excludedIds);
+ excludedIdsRef.current = excludedIds;
+
+ const onNodeClick = useCallback<NodeMouseHandler>(
+ (event, node) => {
+ if (event.shiftKey) {
+ const id = node.id;
+ if (excludedIdsRef.current.has(id)) {
+ toggleExcluded(id);
+ return;
+ }
+ if (additionalRootIdsRef.current.has(id)) {
+ toggleAdditionalRoot(id);
+ return;
+ }
+ const inPath = selectionPathRef.current?.nodeIds.has(id) ?? false;
+ if (inPath) toggleExcluded(id);
+ else toggleAdditionalRoot(id);
+ } else {
+ clearExcluded();
+ clearAdditionalRoots();
+ }
+ },
+ [toggleExcluded, toggleAdditionalRoot, clearExcluded, clearAdditionalRoots]
+ );
+
const [layoutAnimating, setLayoutAnimating] = useState(false);
useEffect(() => {
setNodes(laidNodes as Node[]);
@@ -242,10 +314,29 @@ function TraceabilityGraphInner({
return () => clearTimeout(t);
}, [laidNodes, laidEdges, setNodes, setEdges]);
- const selectedIds = useTraceabilityStore((s) => s.selectedIds);
+ const selectedIds = useMemo(() => {
+ const out: string[] = [];
+ for (let i = 0; i < nodes.length; i++) {
+ if (nodes[i].selected) out.push(nodes[i].id);
+ }
+ return out;
+ }, [nodes]);
const selectedIdSet = useMemo(() => new Set(selectedIds), [selectedIds]);
const selectedId = selectedIds[0] ?? null;
+ const selectNode = useCallback(
+ (id: string | null) => {
+ setNodes((ns) =>
+ ns.map((n) => {
+ const wantsSelected = id !== null && n.id === id;
+ if (n.selected === wantsSelected) return n;
+ return { ...n, selected: wantsSelected };
+ })
+ );
+ },
+ [setNodes]
+ );
+
const onExpandResult = useCallback(
(incoming: LineagePayload, originId: string) => {
const knownEntityIds = new Set(payload.entities.map((e) => e.id));
@@ -269,18 +360,6 @@ function TraceabilityGraphInner({
const { expand, isLoading: isExpanding } = useExpandNode(onExpandResult);
- const onNodeClick = useCallback<NodeMouseHandler>(
- (event, node) => {
- const shift = event.shiftKey;
- if (shift) {
- toggleSelected(node.id);
- return;
- }
- setSelectedSingle(node.id);
- },
- [setSelectedSingle, toggleSelected]
- );
-
const onExpandNode = useCallback(
(id: string, direction: "up" | "down" | "both") => {
const cached = probeCacheRef.current.get(id);
@@ -300,24 +379,23 @@ function TraceabilityGraphInner({
[removeExpansion]
);
- const onPaneClick = useCallback(() => {
- setSelectedSingle(null);
- }, [setSelectedSingle]);
-
const selectionPath = useAsyncSelectionPath(
tracingGraphManager,
edges as unknown as LineageEdge[],
- selectedIds
+ selectedIds,
+ excludedIds,
+ additionalRootIds
);
+ selectionPathRef.current = selectionPath;
const isolated = useMemo(() => {
- if (!isolate || selectedIds.length === 0) return null;
+ if (!isolate) return null;
+ if (selectedIds.length === 0 && additionalRootIds.size === 0) return null;
if (selectionPath) return selectionPath;
- return {
- nodeIds: new Set(selectedIds),
- edgeIds: new Set<string>()
- };
- }, [isolate, selectedIds, selectionPath]);
+ const nodeIds = new Set<string>(selectedIds);
+ for (const id of additionalRootIds) nodeIds.add(id);
+ return { nodeIds, edgeIds: new Set<string>() };
+ }, [isolate, selectedIds, additionalRootIds, selectionPath]);
const boundaryByNode = useMemo(() => {
const incoming = new Set<string>();
@@ -354,7 +432,8 @@ function TraceabilityGraphInner({
return nodes.map((n) => {
const isRoot = !isJobRoot && n.id === rootId;
const selected = selectedIdSet.has(n.id);
- const inPath = selectionPath?.nodeIds.has(n.id) ?? false;
+ const excluded = excludedIds.has(n.id);
+ const inPath = !excluded && (selectionPath?.nodeIds.has(n.id) ?? false);
const dimmed = isolated ? !isolated.nodeIds.has(n.id) : false;
const isExpanded = expansions.has(n.id);
const isEntity = (n.data as any)?.kind === "entity";
@@ -374,6 +453,7 @@ function TraceabilityGraphInner({
selected,
inPath,
dimmed,
+ excluded,
isExpanded,
canExpandUp,
canExpandDown,
@@ -395,6 +475,7 @@ function TraceabilityGraphInner({
expandable,
selectionPath,
containmentByEntity,
+ excludedIds,
onExpandNode,
onCollapseNode
]);
@@ -461,7 +542,7 @@ function TraceabilityGraphInner({
payload={payload}
rootId={rootId}
selectedId={selectedId}
- onSelect={(id) => setSelectedSingle(id)}
+ onSelect={(id) => selectNode(id)}
/>
</div>
<GraphToolbar
@@ -473,7 +554,7 @@ function TraceabilityGraphInner({
onViewChange={setView}
isolate={isolate}
onIsolateChange={setIsolate}
- hasSelection={selectedIds.length > 0}
+ hasSelection={selectedIds.length > 0 || additionalRootIds.size > 0}
onOpenSearch={() => setSearchOpen(true)}
spacing={spacing}
onSpacingChange={setSpacing}
@@ -482,7 +563,7 @@ function TraceabilityGraphInner({
open={searchOpen}
onOpenChange={setSearchOpen}
payload={payload}
- onSelect={(id) => setSelectedSingle(id)}
+ onSelect={(id) => selectNode(id)}
/>
</div>
);
@@ -519,8 +600,6 @@ function TraceabilityGraphInner({
edges={enrichedEdges as Edge[]}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
- onNodeClick={onNodeClick}
- onPaneClick={onPaneClick}
className="trace-fade-in"
style={{ opacity: fitted ? 1 : 0 }}
onNodeDragStart={(_, node) =>
@@ -541,6 +620,9 @@ function TraceabilityGraphInner({
edgesFocusable={false}
elevateNodesOnSelect={false}
onlyRenderVisibleElements
+ selectionKeyCode={null}
+ multiSelectionKeyCode={null}
+ onNodeClick={onNodeClick}
defaultEdgeOptions={{ type: "quantity", zIndex: 0 }}
>
<Background
@@ -575,7 +657,7 @@ function TraceabilityGraphInner({
onViewChange={setView}
isolate={isolate}
onIsolateChange={setIsolate}
- hasSelection={selectedIds.length > 0}
+ hasSelection={selectedIds.length > 0 || additionalRootIds.size > 0}
onRelayout={handleRelayout}
onOpenSearch={() => setSearchOpen(true)}
spacing={spacing}
@@ -588,7 +670,7 @@ function TraceabilityGraphInner({
open={searchOpen}
onOpenChange={setSearchOpen}
payload={payload}
- onSelect={(id) => setSelectedSingle(id)}
+ onSelect={(id) => selectNode(id)}
/>
{isExpanding && (
@@ -596,6 +678,51 @@ function TraceabilityGraphInner({
Loading...
</div>
)}
+
+ {(() => {
+ const traceCount =
+ selectionPath?.nodeIds.size ??
+ selectedIds.length + additionalRootIds.size;
+ const traceActive =
+ selectedIds.length > 0 ||
+ additionalRootIds.size > 0 ||
+ excludedIds.size > 0;
+ const visible = shiftHeld || traceActive;
+ if (!visible) return null;
+ const clearAll = () => {
+ if (selectedIds.length > 0) selectNode(null);
+ clearExcluded();
+ clearAdditionalRoots();
+ };
+ return (
+ <div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-20 flex items-center gap-1 rounded-full border border-border bg-card/95 backdrop-blur pl-2 pr-1 py-1 text-xs shadow-md">
+ {traceActive ? (
+ <>
+ <span className="px-1 tabular-nums font-medium">
+ {traceCount}
+ </span>
+ <span className="text-muted-foreground">in trace</span>
+ <button
+ type="button"
+ onClick={clearAll}
+ className="ml-1 flex items-center justify-center w-5 h-5 rounded-full text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
+ aria-label="Clear trace"
+ title="Clear trace"
+ >
+ <LuX className="w-3 h-3" />
+ </button>
+ </>
+ ) : (
+ <span className="px-1 flex items-center gap-1.5 text-muted-foreground">
+ <kbd className="rounded border border-border bg-muted px-1 py-px font-mono text-[10px] leading-none text-foreground">
+ Shift
+ </kbd>
+ click to add or remove
+ </span>
+ )}
+ </div>
+ );
+ })()}
</div>
);
}
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx
index 9ba68f1d07..34ba75eacc 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx
@@ -22,7 +22,6 @@ import { AttributeList, hasRenderedAttributes } from "./attributeRenderers";
import { ContainmentList } from "./ContainmentList";
import { ACTIVITY_KIND_META, activityKindFor } from "./metadata";
import { StepRecordsList } from "./StepRecordsList";
-import { useTraceabilityStore } from "./store";
import TrackedEntityStatus from "./TrackedEntityStatus";
import {
activityHeadline,
@@ -36,17 +35,20 @@ type SidebarProps = {
activity: Activity | null;
payload?: LineagePayload;
onSelect?: (id: string) => void;
+ selectedIds: string[];
+ focusedIndex: number;
+ onFocusedIndexChange: (i: number) => void;
};
export function TraceabilitySidebar({
entity,
activity,
payload,
- onSelect
+ onSelect,
+ selectedIds,
+ focusedIndex,
+ onFocusedIndexChange
}: SidebarProps) {
- const selectedIds = useTraceabilityStore((s) => s.selectedIds);
- const focusedIndex = useTraceabilityStore((s) => s.focusedIndex);
- const onFocusedIndexChange = useTraceabilityStore((s) => s.setFocusedIndex);
const { t } = useLingui();
const selectedNode = entity ?? activity;
const selectedNodeType = entity ? "entity" : "activity";
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/store.ts b/apps/erp/app/modules/inventory/ui/Traceability/store.ts
index 6808af1993..37a1a1a299 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/store.ts
+++ b/apps/erp/app/modules/inventory/ui/Traceability/store.ts
@@ -8,13 +8,12 @@ export type ViewMode = "graph" | "table";
type TraceabilityState = {
rootId: string | null;
- selectedIds: string[];
- focusedIndex: number;
isolate: boolean;
expansions: Map<string, LineagePayload>;
expandable: Set<string>;
exhausted: Set<string>;
excludedIds: Set<string>;
+ additionalRootIds: Set<string>;
// persisted preferences
direction: LayoutDirection;
@@ -23,11 +22,9 @@ type TraceabilityState = {
// actions
reset: (rootId: string) => void;
- setSelectedIds: (ids: string[]) => void;
- setSelectedSingle: (id: string | null) => void;
- toggleSelected: (id: string) => void;
- setFocusedIndex: (i: number) => void;
setIsolate: (next: boolean) => void;
+ toggleAdditionalRoot: (id: string) => void;
+ clearAdditionalRoots: () => void;
addExpansion: (originId: string, payload: LineagePayload) => void;
removeExpansion: (originId: string) => void;
resetExpansions: () => void;
@@ -44,13 +41,12 @@ export const useTraceabilityStore = create<TraceabilityState>()(
persist(
(set) => ({
rootId: null,
- selectedIds: [],
- focusedIndex: 0,
isolate: false,
expansions: new Map(),
expandable: new Set(),
exhausted: new Set(),
excludedIds: new Set(),
+ additionalRootIds: new Set(),
direction: "TB",
view: "graph",
spacing: SPACING.default,
@@ -58,43 +54,25 @@ export const useTraceabilityStore = create<TraceabilityState>()(
reset: (rootId) =>
set({
rootId,
- selectedIds: [],
- focusedIndex: 0,
isolate: false,
expansions: new Map(),
expandable: new Set(),
exhausted: new Set(),
- excludedIds: new Set()
+ excludedIds: new Set(),
+ additionalRootIds: new Set()
}),
- setSelectedIds: (ids) =>
- set((s) => ({
- selectedIds: ids,
- focusedIndex:
- ids.length === 0 ? 0 : Math.min(s.focusedIndex, ids.length - 1)
- })),
-
- setSelectedSingle: (id) =>
- set({
- selectedIds: id ? [id] : [],
- focusedIndex: 0
- }),
+ setIsolate: (next) => set({ isolate: next }),
- toggleSelected: (id) =>
+ toggleAdditionalRoot: (id) =>
set((s) => {
- const next = s.selectedIds.includes(id)
- ? s.selectedIds.filter((x) => x !== id)
- : [...s.selectedIds, id];
- return {
- selectedIds: next,
- focusedIndex:
- next.length === 0 ? 0 : Math.min(s.focusedIndex, next.length - 1)
- };
+ const next = new Set(s.additionalRootIds);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return { additionalRootIds: next };
}),
- setFocusedIndex: (i) => set({ focusedIndex: i }),
-
- setIsolate: (next) => set({ isolate: next }),
+ clearAdditionalRoots: () => set({ additionalRootIds: new Set() }),
addExpansion: (originId, payload) =>
set((s) => {
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/worker/TracingGraphManager.ts b/apps/erp/app/modules/inventory/ui/Traceability/worker/TracingGraphManager.ts
index 36ae69ec95..4d1ea1f7c3 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/worker/TracingGraphManager.ts
+++ b/apps/erp/app/modules/inventory/ui/Traceability/worker/TracingGraphManager.ts
@@ -6,7 +6,9 @@ type WorkerApi = {
layout: (input: LayoutInput) => LayoutResult;
selection: (
edges: LineageEdge[],
- rootIds: string[]
+ rootIds: string[],
+ excludedIds: string[],
+ additionalRootIds: string[]
) => SelectionPathResult | null;
};
@@ -47,16 +49,23 @@ export class TracingGraphManager {
async selection(
edges: LineageEdge[],
- rootIds: string[]
+ rootIds: string[],
+ excludedIds: string[],
+ additionalRootIds: string[]
): Promise<SelectionPathResult | null> {
const seq = ++this.selectionSeq;
if (this.proxy) {
- const result = await this.proxy.selection(edges, rootIds);
+ const result = await this.proxy.selection(
+ edges,
+ rootIds,
+ excludedIds,
+ additionalRootIds
+ );
if (this.disposed || seq !== this.selectionSeq) return null;
return result;
}
const { computeSelectionPath } = await import("./core");
if (this.disposed || seq !== this.selectionSeq) return null;
- return computeSelectionPath(edges, rootIds);
+ return computeSelectionPath(edges, rootIds, excludedIds, additionalRootIds);
}
}
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/worker/core.ts b/apps/erp/app/modules/inventory/ui/Traceability/worker/core.ts
index d620d5032b..3bc1a70080 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/worker/core.ts
+++ b/apps/erp/app/modules/inventory/ui/Traceability/worker/core.ts
@@ -5,7 +5,6 @@ import {
type LineageEdgeData,
type LineageNode,
type LineagePayload,
- lineagePathEdgesMulti,
payloadToFlow
} from "../utils";
@@ -49,39 +48,50 @@ function detectBackEdges(
edges: LineageEdge[]
): Set<string> {
const adj = new Map<string, string[]>();
- for (const e of edges) {
- if (!adj.has(e.source)) adj.set(e.source, []);
- adj.get(e.source)!.push(e.target);
+ for (let i = 0; i < edges.length; i++) {
+ const e = edges[i];
+ let arr = adj.get(e.source);
+ if (arr === undefined) {
+ arr = [];
+ adj.set(e.source, arr);
+ }
+ arr.push(e.target);
}
const visited = new Set<string>();
- const stack = new Set<string>();
+ const pathIdx = new Map<string, number>();
+ const path: string[] = [];
const back = new Set<string>();
- function dfs(id: string, path: string[]) {
- if (stack.has(id)) {
- const cycleStart = path.indexOf(id);
- if (cycleStart !== -1) {
- for (let i = cycleStart; i < path.length - 1; i++) {
- back.add(`${path[i]}->${path[i + 1]}`);
- }
- if (path.length > 0) back.add(`${path[path.length - 1]}->${id}`);
+ function dfs(id: string) {
+ const onStackAt = pathIdx.get(id);
+ if (onStackAt !== undefined) {
+ for (let i = onStackAt; i < path.length - 1; i++) {
+ back.add(`${path[i]}->${path[i + 1]}`);
}
+ back.add(`${path[path.length - 1]}->${id}`);
return;
}
if (visited.has(id)) return;
visited.add(id);
- stack.add(id);
+ pathIdx.set(id, path.length);
path.push(id);
- for (const next of adj.get(id) ?? []) dfs(next, path);
+ const neighbors = adj.get(id);
+ if (neighbors !== undefined) {
+ for (let i = 0; i < neighbors.length; i++) dfs(neighbors[i]);
+ }
path.pop();
- stack.delete(id);
+ pathIdx.delete(id);
}
- for (const n of nodes) if (!visited.has(n.id)) dfs(n.id, []);
+ for (let i = 0; i < nodes.length; i++) {
+ const id = nodes[i].id;
+ if (!visited.has(id)) dfs(id);
+ }
const backEdgeIds = new Set<string>();
- for (const e of edges) {
+ for (let i = 0; i < edges.length; i++) {
+ const e = edges[i];
if (back.has(`${e.source}->${e.target}`)) backEdgeIds.add(e.id);
}
return backEdgeIds;
@@ -164,25 +174,85 @@ export function computeFullLayout(input: LayoutInput): LayoutResult {
input.direction,
input.spacing
);
- const finalEdges: LineageEdge[] = weightedEdges.map((e) => ({
- ...e,
- data: {
- ...(e.data as LineageEdgeData),
- isBackEdge: backEdges.has(e.id),
- points: edgePoints.get(e.id)
- }
- }));
+ const finalEdges: LineageEdge[] = [];
+ for (let i = 0; i < weightedEdges.length; i++) {
+ const e = weightedEdges[i];
+ finalEdges.push({
+ ...e,
+ data: {
+ ...(e.data as LineageEdgeData),
+ isBackEdge: backEdges.has(e.id),
+ points: edgePoints.get(e.id)
+ }
+ });
+ }
return { nodes: positioned, edges: finalEdges };
}
export function computeSelectionPath(
edges: LineageEdge[],
- rootIds: string[]
+ rootIds: string[],
+ excludedIds: string[] = [],
+ additionalRootIds: string[] = []
): SelectionPathResult | null {
- if (rootIds.length === 0) return null;
- const r = lineagePathEdgesMulti(rootIds, edges);
+ if (rootIds.length === 0 && additionalRootIds.length === 0) return null;
+
+ const excludedSet = new Set(excludedIds);
+
+ // Build outgoing adjacency once in a single pass over edges.
+ // Skip back-edges and edges touching excluded nodes inline so we never
+ // allocate an intermediate `acyclic` array.
+ const outgoing = new Map<string, LineageEdge[]>();
+ for (let i = 0; i < edges.length; i++) {
+ const e = edges[i];
+ if (e.data?.isBackEdge) continue;
+ if (excludedSet.has(e.source) || excludedSet.has(e.target)) continue;
+ let arr = outgoing.get(e.source);
+ if (arr === undefined) {
+ arr = [];
+ outgoing.set(e.source, arr);
+ }
+ arr.push(e);
+ }
+
+ // Collect roots (primary + additional), dropping excluded.
+ const allRoots: string[] = [];
+ for (let i = 0; i < rootIds.length; i++) {
+ if (!excludedSet.has(rootIds[i])) allRoots.push(rootIds[i]);
+ }
+ for (let i = 0; i < additionalRootIds.length; i++) {
+ const id = additionalRootIds[i];
+ if (!excludedSet.has(id)) allRoots.push(id);
+ }
+ if (allRoots.length === 0) return null;
+
+ // Forward DFS from every root, sharing the adjacency map and visited
+ // sets across roots (a node visited from one root never revisits).
+ const edgeIds = new Set<string>();
+ const nodeIds = new Set<string>();
+ const stack: string[] = [];
+ for (let i = 0; i < allRoots.length; i++) {
+ const root = allRoots[i];
+ if (nodeIds.has(root)) continue;
+ nodeIds.add(root);
+ stack.push(root);
+ while (stack.length > 0) {
+ const cur = stack.pop()!;
+ const neighbors = outgoing.get(cur);
+ if (neighbors === undefined) continue;
+ for (let j = 0; j < neighbors.length; j++) {
+ const e = neighbors[j];
+ edgeIds.add(e.id);
+ if (!nodeIds.has(e.target)) {
+ nodeIds.add(e.target);
+ stack.push(e.target);
+ }
+ }
+ }
+ }
+
return {
- pathNodeIds: Array.from(r.nodeIds),
- pathEdgeIds: Array.from(r.edgeIds)
+ pathNodeIds: Array.from(nodeIds),
+ pathEdgeIds: Array.from(edgeIds)
};
}
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/worker/hooks.ts b/apps/erp/app/modules/inventory/ui/Traceability/worker/hooks.ts
index 6bd7d66e74..02df8e273a 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/worker/hooks.ts
+++ b/apps/erp/app/modules/inventory/ui/Traceability/worker/hooks.ts
@@ -52,27 +52,36 @@ export type SelectionPath = {
export function useAsyncSelectionPath(
manager: TracingGraphManager,
edges: LineageEdge[],
- selectedIds: string[]
+ selectedIds: string[],
+ excludedIds: Set<string>,
+ additionalRootIds: Set<string>
): SelectionPath | null {
const [path, setPath] = useState<SelectionPath | null>(null);
+ const excludedArray = useMemo(() => Array.from(excludedIds), [excludedIds]);
+ const additionalArray = useMemo(
+ () => Array.from(additionalRootIds),
+ [additionalRootIds]
+ );
useEffect(() => {
- if (selectedIds.length === 0) {
+ if (selectedIds.length === 0 && additionalArray.length === 0) {
setPath(null);
return;
}
let cancelled = false;
- manager.selection(edges, selectedIds).then((r) => {
- if (cancelled || r === null) return;
- setPath({
- nodeIds: new Set(r.pathNodeIds),
- edgeIds: new Set(r.pathEdgeIds)
+ manager
+ .selection(edges, selectedIds, excludedArray, additionalArray)
+ .then((r) => {
+ if (cancelled || r === null) return;
+ setPath({
+ nodeIds: new Set(r.pathNodeIds),
+ edgeIds: new Set(r.pathEdgeIds)
+ });
});
- });
return () => {
cancelled = true;
};
- }, [manager, edges, selectedIds]);
+ }, [manager, edges, selectedIds, excludedArray, additionalArray]);
return path;
}
diff --git a/apps/erp/app/routes/x+/traceability+/graph.tsx b/apps/erp/app/routes/x+/traceability+/graph.tsx
index fff86f2554..bff7da1920 100644
--- a/apps/erp/app/routes/x+/traceability+/graph.tsx
+++ b/apps/erp/app/routes/x+/traceability+/graph.tsx
@@ -3,7 +3,8 @@ import { Button, Loading, useHydrated, VStack } from "@carbon/react";
import { msg } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { ParentSize } from "@visx/responsive";
-import { useMemo } from "react";
+import { ReactFlowProvider, useReactFlow, useStore } from "@xyflow/react";
+import { useCallback, useMemo, useState } from "react";
import type { LoaderFunctionArgs } from "react-router";
import { Link, redirect, useLoaderData, useNavigation } from "react-router";
import { Empty } from "~/components";
@@ -15,7 +16,6 @@ import {
fetchLineageSubgraph
} from "~/modules/inventory/lineage.server";
import { clampDepth } from "~/modules/inventory/ui/Traceability/constants";
-import { useTraceabilityStore } from "~/modules/inventory/ui/Traceability/store";
import { TraceabilityGraph } from "~/modules/inventory/ui/Traceability/TraceabilityGraph";
import { TraceabilitySidebar } from "~/modules/inventory/ui/Traceability/TraceabilitySidebar";
import type { StepRecord } from "~/modules/inventory/ui/Traceability/utils";
@@ -180,6 +180,14 @@ async function collectStepRecordsForActivities(
}
export default function TraceabilityRoute() {
+ return (
+ <ReactFlowProvider>
+ <TraceabilityRouteInner />
+ </ReactFlowProvider>
+ );
+}
+
+function TraceabilityRouteInner() {
const {
entities,
inputs,
@@ -199,14 +207,37 @@ export default function TraceabilityRoute() {
const isHydrated = useHydrated();
const navigation = useNavigation();
- const selectedIds = useTraceabilityStore((s) => s.selectedIds);
- const focusedIndex = useTraceabilityStore((s) => s.focusedIndex);
- const setSelectedSingle = useTraceabilityStore((s) => s.setSelectedSingle);
+ // Selection lives in the React Flow store. Subscribe to the nodes ref
+ // (stable until xyflow updates it) and derive ids via useMemo so the
+ // returned array stays referentially stable across unrelated renders.
+ const flowNodes = useStore((s) => s.nodes);
+ const selectedIds = useMemo(() => {
+ const ids: string[] = [];
+ for (let i = 0; i < flowNodes.length; i++) {
+ if (flowNodes[i].selected) ids.push(flowNodes[i].id);
+ }
+ return ids;
+ }, [flowNodes]);
+ const [focusedIndex, setFocusedIndex] = useState(0);
const safeIndex =
selectedIds.length > 0 ? Math.min(focusedIndex, selectedIds.length - 1) : 0;
const focusedSelectedId = selectedIds[safeIndex] ?? null;
const sidebarId = focusedSelectedId ?? rootId;
+ const { setNodes } = useReactFlow();
+ const selectNode = useCallback(
+ (id: string | null) => {
+ setNodes((nodes) =>
+ nodes.map((n) => {
+ const wantsSelected = id !== null && n.id === id;
+ if (n.selected === wantsSelected) return n;
+ return { ...n, selected: wantsSelected };
+ })
+ );
+ },
+ [setNodes]
+ );
+
const selectedEntity =
(entities.find((e) => e?.id === sidebarId) as TrackedEntity | undefined) ??
null;
@@ -266,7 +297,10 @@ export default function TraceabilityRoute() {
stepRecords,
containments
}}
- onSelect={(id) => setSelectedSingle(id)}
+ onSelect={selectNode}
+ focusedIndex={safeIndex}
+ onFocusedIndexChange={setFocusedIndex}
+ selectedIds={selectedIds}
/>
)}
</div>
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 3665b9a9c6..7648d4b0d3 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Zurück"
msgid "Back to home"
msgstr "Zurück zur Startseite"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:226
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
msgid "Back to traceability"
msgstr "Zurück zur Rückverfolgbarkeit"
@@ -2689,7 +2689,7 @@ msgstr "Dokumentnamen kopieren"
msgid "Copy document unique identifier"
msgstr "Eindeutige Dokumentkennung kopieren"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:216
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Eindeutige Kennung des Problems kopieren"
msgid "Copy Job number"
msgstr "Job-Nummer kopieren"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:202
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
msgid "Copy link"
msgstr ""
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index d64f35e521..80e70798bc 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Back"
msgid "Back to home"
msgstr "Back to home"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:226
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
msgid "Back to traceability"
msgstr "Back to traceability"
@@ -2689,7 +2689,7 @@ msgstr "Copy document name"
msgid "Copy document unique identifier"
msgstr "Copy document unique identifier"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:216
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
msgid "Copy ID"
msgstr "Copy ID"
@@ -2705,7 +2705,7 @@ msgstr "Copy issue unique identifier"
msgid "Copy Job number"
msgstr "Copy Job number"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:202
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
msgid "Copy link"
msgstr "Copy link"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index cc2809dc61..1db33d0879 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Atrás"
msgid "Back to home"
msgstr "Volver al inicio"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:226
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
msgid "Back to traceability"
msgstr "Volver a trazabilidad"
@@ -2689,7 +2689,7 @@ msgstr "Copiar nombre del documento"
msgid "Copy document unique identifier"
msgstr "Copiar identificador único del documento"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:216
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Copiar identificador único del problema"
msgid "Copy Job number"
msgstr "Copiar número de trabajo"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:202
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
msgid "Copy link"
msgstr ""
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 8ca24f6dcf..77a1c2fb17 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Retour"
msgid "Back to home"
msgstr "Retour à l'accueil"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:226
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
msgid "Back to traceability"
msgstr "Retour à la traçabilité"
@@ -2689,7 +2689,7 @@ msgstr "Copier le nom du document"
msgid "Copy document unique identifier"
msgstr "Copier l'identifiant unique du document"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:216
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Copier l'identifiant unique du problème"
msgid "Copy Job number"
msgstr "Copier le numéro de travail"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:202
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
msgid "Copy link"
msgstr ""
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index fbdf0f1a39..2ad61f7685 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -1492,7 +1492,7 @@ msgstr "वापस"
msgid "Back to home"
msgstr "घर वापस जाएं"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:226
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
msgid "Back to traceability"
msgstr "ट्रेसेबिलिटी पर वापस जाएं"
@@ -2689,7 +2689,7 @@ msgstr "दस्तावेज़ का नाम कॉपी करें"
msgid "Copy document unique identifier"
msgstr "दस्तावेज़ की अद्वितीय पहचान की प्रतिलिपि बनाएँ"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:216
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "समस्या की अद्वितीय पहचान क
msgid "Copy Job number"
msgstr "जॉब नंबर कॉपी करें"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:202
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
msgid "Copy link"
msgstr ""
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 41e7320e35..bd66d7c4e4 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Indietro"
msgid "Back to home"
msgstr "Torna alla home"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:226
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
msgid "Back to traceability"
msgstr "Torna alla tracciabilità"
@@ -2689,7 +2689,7 @@ msgstr "Copia nome documento"
msgid "Copy document unique identifier"
msgstr "Copia identificatore univoco documento"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:216
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Copia identificatore univoco del problema"
msgid "Copy Job number"
msgstr "Copia numero lavoro"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:202
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
msgid "Copy link"
msgstr ""
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 55218504c0..b08b750883 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -1492,7 +1492,7 @@ msgstr "戻る"
msgid "Back to home"
msgstr "ホームに戻る"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:226
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
msgid "Back to traceability"
msgstr "トレーサビリティに戻る"
@@ -2689,7 +2689,7 @@ msgstr "ドキュメント名をコピー"
msgid "Copy document unique identifier"
msgstr "ドキュメントの一意の識別子をコピー"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:216
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "問題の一意の識別子をコピー"
msgid "Copy Job number"
msgstr "ジョブ番号をコピー"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:202
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
msgid "Copy link"
msgstr ""
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 71df22da53..7491cd189c 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Wstecz"
msgid "Back to home"
msgstr "Powrót do strony głównej"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:226
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
msgid "Back to traceability"
msgstr "Wróć do śledzenia"
@@ -2689,7 +2689,7 @@ msgstr "Skopiuj nazwę dokumentu"
msgid "Copy document unique identifier"
msgstr "Skopiuj unikalny identyfikator dokumentu"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:216
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Skopiuj unikalny identyfikator problemu"
msgid "Copy Job number"
msgstr "Skopiuj numer zadania"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:202
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
msgid "Copy link"
msgstr ""
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 0862673710..98d031e3bb 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Voltar"
msgid "Back to home"
msgstr "Voltar para casa"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:226
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
msgid "Back to traceability"
msgstr "Voltar para rastreabilidade"
@@ -2689,7 +2689,7 @@ msgstr "Copiar nome do documento"
msgid "Copy document unique identifier"
msgstr "Copiar identificador único do documento"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:216
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Copiar identificador único do problema"
msgid "Copy Job number"
msgstr "Copiar número do trabalho"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:202
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
msgid "Copy link"
msgstr ""
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index c8828ca8ad..20d5b3a207 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Назад"
msgid "Back to home"
msgstr "Вернуться на главную"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:226
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
msgid "Back to traceability"
msgstr "Вернуться к отслеживанию"
@@ -2689,7 +2689,7 @@ msgstr "Копировать имя документа"
msgid "Copy document unique identifier"
msgstr "Скопировать уникальный идентификатор документа"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:216
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Скопировать уникальный идентификатор
msgid "Copy Job number"
msgstr "Скопировать номер задания"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:202
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
msgid "Copy link"
msgstr ""
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 544dd2c01d..0037476c29 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -1492,7 +1492,7 @@ msgstr "返回"
msgid "Back to home"
msgstr "返回主页"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:226
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
msgid "Back to traceability"
msgstr "返回可追溯性"
@@ -2689,7 +2689,7 @@ msgstr "复制文档名称"
msgid "Copy document unique identifier"
msgstr "复制文档唯一标识符"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:216
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "复制问题唯一标识符"
msgid "Copy Job number"
msgstr "复制工作单号"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:202
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
msgid "Copy link"
msgstr ""