Integrate Canvas V2 subgraphs, editable edges and AI runs

This commit is contained in:
2026-11-06 19:59:56 +08:00
parent 3478daeccb
commit 05d96abd0e
35 changed files with 1626 additions and 443 deletions
+113 -16
View File
@@ -1,27 +1,124 @@
"use client";
import { BaseEdge, useInternalNode, type ConnectionLineComponentProps, type EdgeProps, type InternalNode } from "@xyflow/react";
import { useContext, useRef, useState, type PointerEvent } from "react";
import { BaseEdge, useInternalNode, useReactFlow, useViewport, type ConnectionLineComponentProps, type EdgeProps, type InternalNode } from "@xyflow/react";
import { useReducedMotion } from "motion/react";
import type { CanvasNode } from "@/lib/canvas";
import { connectorBezier, nodeConnector, type ConnectorSide } from "@/lib/canvas-geometry";
import { connectorBezier, nodeConnector, type ConnectorSide, type Connector } from "@/lib/canvas-geometry";
import { curvePath, curveSegments, cubicPoint, insertCurveKnot, minus, plus } from "@/lib/canvas-curves";
import type { CanvasEdgeModel, EdgeMarker } from "@/lib/canvas-v2";
import { EdgeEditing } from "./edge-editing";
import { EdgeToolbarControls } from "./edge-toolbar";
import styles from "./canvas.module.css";
function connector(node: InternalNode<CanvasNode>, handle: string | null | undefined, fallback: ConnectorSide) {
const side = handle === "top" || handle === "right" || handle === "bottom" || handle === "left" ? handle : fallback;
return nodeConnector({ ...node, position: node.internals.positionAbsolute }, side);
function connector(node: InternalNode<CanvasNode>, handle: string | null | undefined, fallback: ConnectorSide): Connector {
const port = node.data.ports?.find((port) => `port:${port.id}` === handle);
const side = handle === "top" || handle === "right" || handle === "bottom" || handle === "left" ? handle : port?.direction === "input" ? "left" : port ? "right" : fallback;
const result = nodeConnector({ ...node, position: node.internals.positionAbsolute }, side);
if (port) {
const peers = node.data.ports!.filter((item) => item.direction === port.direction);
result.point.y += ((peers.indexOf(port) + 1) / (peers.length + 1) - .5) * (node.measured?.height || node.height || 400);
}
return result;
}
export function CanvasEdge(props: EdgeProps) {
const source = useInternalNode<CanvasNode>(props.source);
const target = useInternalNode<CanvasNode>(props.target);
function Marker({ id, value, color }: { id: string; value?: EdgeMarker; color: string }) {
const type = value?.type || "none";
if (type === "none") return null;
return <marker id={id} viewBox="0 0 12 12" markerWidth={value?.size || 12} markerHeight={value?.size || 12} refX={11} refY={6} orient="auto-start-reverse" markerUnits="userSpaceOnUse">
<path d={type === "triangle" ? "M1 1L11 6L1 11Z" : type === "open-arrow" ? "M1 1L11 6L1 11" : type === "diamond" ? "M1 6L6 1L11 6L6 11Z" : type === "square" ? "M1 1H11V11H1Z" : "M11 6a5 5 0 1 0-10 0a5 5 0 1 0 10 0"} fill={type === "open-arrow" ? "none" : value?.filled !== false ? color : "#fffefb"} stroke={color} strokeWidth={1.2} />
</marker>;
}
export function CanvasEdge(props: EdgeProps<CanvasEdgeModel>) {
const source = useInternalNode<CanvasNode>(props.source), target = useInternalNode<CanvasNode>(props.target);
const editing = useContext(EdgeEditing);
const flow = useReactFlow();
const { zoom } = useViewport();
const reduce = useReducedMotion();
const [selectedKnot, setSelectedKnot] = useState<string | null>(null);
const gesture = useRef<{ id: string; part: "position" | "in" | "out" | "startControl" | "endControl" } | null>(null);
if (!source || !target) return null;
const from = connector(source, props.sourceHandleId, "right");
const to = connector(target, props.targetHandleId, "left");
return <BaseEdge id={props.id} path={connectorBezier(from, to)} style={{ ...props.style, strokeLinecap: "round" }} markerStart={props.markerStart} markerEnd={props.markerEnd} interactionWidth={props.interactionWidth} />;
const from = connector(source, props.sourceHandleId, "right"), to = connector(target, props.targetHandleId, "left");
const data = props.data || {}, appearance = data.appearance || {}, animation = data.animation || {};
const segments = curveSegments(from, to, data.path), path = curvePath(segments);
const midpoint = cubicPoint(segments[Math.floor(segments.length / 2)], .5);
const color = appearance.color || "#aa968b", width = appearance.width || 1.5;
const markerId = `edge-${props.id.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
const animated = !reduce && (animation.mode === "always" || animation.mode === "executing" && editing.active.has(props.id));
const knots = data.path?.knots || [];
function add(point?: { x: number; y: number }) {
if (knots.length >= 64) return;
const next = insertCurveKnot(from, to, data.path, point);
editing.patch(props.id, { ...data, path: next.path }); setSelectedKnot(next.knot.id);
}
function start(event: PointerEvent<SVGCircleElement>, id: string, part: NonNullable<typeof gesture.current>["part"]) {
event.preventDefault(); event.stopPropagation(); editing.begin(props.id); gesture.current = { id, part }; setSelectedKnot(id);
event.currentTarget.setPointerCapture(event.pointerId);
}
function move(event: PointerEvent<SVGCircleElement>) {
const current = gesture.current;
if (!current) return;
event.stopPropagation();
const point = flow.screenToFlowPosition({ x: event.clientX, y: event.clientY });
const next = structuredClone(data.path || { type: "bezier-chain" as const, knots: [] });
if (current.part === "startControl" || current.part === "endControl") next[current.part] = minus(point, current.part === "startControl" ? from.point : to.point);
else {
const knot = next.knots.find((knot) => knot.id === current.id);
if (!knot) return;
if (current.part === "position") knot.position = point;
else {
const vector = minus(point, knot.position), other = current.part === "in" ? "out" : "in";
const length = Math.hypot(knot[other].x, knot[other].y), nextLength = Math.hypot(vector.x, vector.y);
knot[current.part] = vector;
if (event.shiftKey) knot.mode = "symmetric";
if (knot.mode !== "corner") {
const scale = knot.mode === "symmetric" ? 1 : nextLength ? length / nextLength : 0;
knot[other] = { x: -vector.x * scale, y: -vector.y * scale };
}
}
}
editing.patch(props.id, { ...data, path: next }, true);
}
function stop(event: PointerEvent<SVGCircleElement>) {
event.stopPropagation(); gesture.current = null;
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
}
const control = (point: { x: number; y: number }, id: string, part: NonNullable<typeof gesture.current>["part"], label: string) => <circle key={part + id} cx={point.x} cy={point.y} r={(part === "position" ? 5 : 3.5) / zoom} className={styles.curveControl} fill={part === "position" ? "#fffefb" : "#a47764"} stroke="#a47764" strokeWidth={1 / zoom} role="button" aria-label={label} tabIndex={0}
onPointerDown={(event) => start(event, id, part)} onPointerMove={move} onPointerUp={stop} onPointerCancel={stop} onLostPointerCapture={() => { gesture.current = null; }} onClick={(event) => { event.stopPropagation(); setSelectedKnot(id); }}
onKeyDown={(event) => {
event.stopPropagation(); const delta = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[event.key];
if (delta) { event.preventDefault(); const next = structuredClone(data.path || { type: "bezier-chain" as const, knots: [] }); const vector = { x: delta[0] * (event.shiftKey ? 10 : 1), y: delta[1] * (event.shiftKey ? 10 : 1) };
if (part === "position") { const knot = next.knots.find((knot) => knot.id === id); if (knot) knot.position = plus(knot.position, vector); }
else if (part === "startControl" || part === "endControl") next[part] = plus(minus(point, part === "startControl" ? from.point : to.point), vector);
else return;
editing.patch(props.id, { ...data, path: next });
}
}} />;
return <g onDoubleClick={(event) => { event.preventDefault(); event.stopPropagation(); add(flow.screenToFlowPosition({ x: event.clientX, y: event.clientY })); }}>
<defs><Marker id={markerId + "-head"} value={appearance.head} color={color} /><Marker id={markerId + "-tail"} value={appearance.tail} color={color} /></defs>
{props.selected && <path d={path} fill="none" stroke="#a47764" strokeOpacity={.18} strokeWidth={width + 7 / zoom} pointerEvents="none" />}
<BaseEdge id={props.id} path={path} style={{ stroke: color, strokeWidth: width, opacity: appearance.opacity ?? 1, strokeDasharray: appearance.line === "dashed" ? "8 5" : appearance.line === "dotted" ? "1 5" : undefined, strokeLinecap: "round" }} markerStart={appearance.tail?.type && appearance.tail.type !== "none" ? `url(#${markerId}-tail)` : undefined} markerEnd={appearance.head?.type && appearance.head.type !== "none" ? `url(#${markerId}-head)` : undefined} interactionWidth={Math.max(20 / zoom, width + 8)} />
{animated && (animation.effect === "flow" || !animation.effect ? <g pointerEvents="none"><circle r={Math.max(3, width * 1.5)} fill={animation.color || "#fff"}><animateMotion path={path} dur={`${animation.durationMs || 1600}ms`} repeatCount="indefinite" keyPoints={animation.direction === "reverse" ? "1;0" : "0;1"} keyTimes="0;1" calcMode="linear" /></circle></g> : <path d={path} fill="none" pointerEvents="none" stroke={animation.color || "#fff"} strokeWidth={width + 1} strokeDasharray={animation.effect === "dash" ? "6 14" : undefined} className={animation.effect === "dash" ? styles.edgeDashAnimation : styles.edgePulseAnimation} style={{ animationDuration: `${animation.durationMs || 1600}ms`, animationDirection: animation.direction === "reverse" ? "reverse" : "normal" }} />)}
{props.selected && <>
<EdgeToolbarControls id={props.id} x={midpoint.x} y={midpoint.y - 24 / zoom} data={data} change={(data) => editing.patch(props.id, data)} count={knots.length} knotMode={(knots.find((knot) => knot.id === selectedKnot) || knots.at(-1))?.mode} changeKnotMode={(mode) => {
const next = structuredClone(data.path!); const knot = next.knots.find((knot) => knot.id === selectedKnot) || next.knots.at(-1); if (!knot) return;
knot.mode = mode; if (mode !== "corner") {
if (!Math.hypot(knot.out.x, knot.out.y)) knot.out = { x: -knot.in.x, y: -knot.in.y };
const length = Math.hypot(knot.out.x, knot.out.y), scale = mode === "symmetric" ? 1 : length ? Math.hypot(knot.in.x, knot.in.y) / length : 0;
knot.in = { x: -knot.out.x * scale, y: -knot.out.y * scale };
}
editing.patch(props.id, { ...data, path: next });
}} add={() => add()} remove={() => { const id = selectedKnot || knots.at(-1)?.id; editing.patch(props.id, { ...data, path: { ...data.path!, knots: knots.filter((knot) => knot.id !== id) } }); setSelectedKnot(null); }} />
{knots.map((knot, index) => <g key={knot.id} onDoubleClick={(event) => event.stopPropagation()}>
{control(knot.position, knot.id, "position", `曲线点 ${index + 1}`)}
{selectedKnot === knot.id && <><path d={`M${plus(knot.position, knot.in).x},${plus(knot.position, knot.in).y}L${knot.position.x},${knot.position.y}L${plus(knot.position, knot.out).x},${plus(knot.position, knot.out).y}`} fill="none" stroke="#a47764" strokeWidth={1 / zoom} pointerEvents="none" />{control(plus(knot.position, knot.in), knot.id, "in", "进入控制柄")}{control(plus(knot.position, knot.out), knot.id, "out", "离开控制柄")}</>}
</g>)}
{control(segments[0][1], "start", "startControl", "起点控制柄")}
{control(segments.at(-1)![2], "end", "endControl", "终点控制柄")}
</>}
</g>;
}
export function CanvasConnectionLine(props: ConnectionLineComponentProps<CanvasNode>) {
const from = connector(props.fromNode, props.fromHandle.id, "right");
const to = props.toNode && props.toHandle
? connector(props.toNode, props.toHandle.id, "left")
: { point: { x: props.toX, y: props.toY }, normal: { x: -from.normal.x, y: -from.normal.y } };
const to = props.toNode && props.toHandle ? connector(props.toNode, props.toHandle.id, "left") : { point: { x: props.toX, y: props.toY }, normal: { x: -from.normal.x, y: -from.normal.y } };
return <path fill="none" className="react-flow__connection-path" d={connectorBezier(from, to)} style={{ stroke: "#aa968b", strokeWidth: 1.5, ...props.connectionLineStyle, strokeLinecap: "round" }} />;
}