"use client"; import { useContext, useEffect, 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 { ProjectionNode } from "@/lib/canvas-bindings/projection"; import type { CanvasNode } from "@/lib/canvas"; 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 type { EditingLease } from "./editing-lease"; import { EdgeEditing } from "./edge-editing"; import { EdgeToolbarControls } from "./edge-toolbar"; import styles from "./canvas.module.css"; function connector(node: InternalNode, handle: string | null | undefined, fallback: ConnectorSide): Connector { const port = Array.isArray(node.data.ports)?node.data.ports.find((port) => port && `port:${port.id}` === handle):undefined; const hints=(node.data as ProjectionNode['data']).__headlessFallback?.handles; const projectedSide=Array.isArray(hints)?hints.find(item=>item&&item.id===handle&&['top','right','bottom','left'].includes(item.side))?.side:undefined; const side = projectedSide ?? (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; } function nativeConnector(x:number,y:number,side:ConnectorSide):Connector{ const normals={top:{x:0,y:-1},right:{x:1,y:0},bottom:{x:0,y:1},left:{x:-1,y:0}}; return {point:{x,y},normal:normals[side]}; } function Marker({ id, value, color }: { id: string; value?: EdgeMarker; color: string }) { const type = value?.type || "none"; if (type === "none") return null; return ; } export function CanvasEdge(props: EdgeProps) { const source = useInternalNode(props.source), target = useInternalNode(props.target); const editing = useContext(EdgeEditing); const flow = useReactFlow(); const { zoom } = useViewport(); const reduce = useReducedMotion(); const [selectedKnot, setSelectedKnot] = useState(null); const gesture = useRef<{ capture: Element; controller: AbortController; pointerId: number; lease?: EditingLease['path']>; id: string; part: "position" | "in" | "out" | "startControl" | "endControl" } | null>(null); const pointerHandlers = useRef<{ move(event: PointerEvent): void; stop(event: PointerEvent): void; cancel(event: PointerEvent): void } | null>(null); useEffect(() => () => { const current = gesture.current; gesture.current = null; current?.controller.abort(); current?.lease?.cancel(); if (current?.capture.hasPointerCapture(current.pointerId)) current.capture.releasePointerCapture(current.pointerId); }, []); if (!source || !target) return null; const from = (source.data as ProjectionNode['data']).__headlessRecord ? nativeConnector(props.sourceX,props.sourceY,props.sourcePosition) : connector(source, props.sourceHandleId, "right"), to = (target.data as ProjectionNode['data']).__headlessRecord ? nativeConnector(props.targetX,props.targetY,props.targetPosition) : 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, id: string, part: NonNullable["part"]) { event.preventDefault(); event.stopPropagation(); // The SVG control can be replaced by a projection update. The view surface survives it. const capture = event.currentTarget.closest('[data-headless-canvas]') ?? event.currentTarget.closest('.react-flow') ?? event.currentTarget; const lease = editing.begin(props.id); if (lease === false) return; const controller = new AbortController(); gesture.current = { id, part, capture, controller, pointerId: event.pointerId, lease: lease && typeof lease === 'object' ? lease : undefined }; setSelectedKnot(id); const owned = (input: Event) => (input as globalThis.PointerEvent).pointerId === event.pointerId; capture.addEventListener('pointermove', input => { if (owned(input)) pointerHandlers.current?.move(input as unknown as PointerEvent); }, { signal: controller.signal }); capture.addEventListener('pointerup', input => { if (owned(input)) pointerHandlers.current?.stop(input as unknown as PointerEvent); }, { signal: controller.signal }); for (const name of ['pointercancel', 'lostpointercapture']) capture.addEventListener(name, input => { if (owned(input) && gesture.current) pointerHandlers.current?.cancel(input as unknown as PointerEvent); }, { signal: controller.signal }); capture.setPointerCapture(event.pointerId); } function move(event: PointerEvent) { 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 }; } } } if (current.lease) current.lease.preview(next); else editing.patch(props.id, { ...data, path: next }, true); } function stop(event: PointerEvent) { if (!gesture.current) return; event.stopPropagation(); const current = gesture.current; move(event); gesture.current = null; current.controller.abort(); if (current.lease) current.lease.commit(); else editing.finish?.(); if (current.capture.hasPointerCapture(current.pointerId)) current.capture.releasePointerCapture(current.pointerId); } function cancel(_event: PointerEvent) { const current = gesture.current; gesture.current = null; if (!current) return; current.controller.abort(); if (current.lease) current.lease.cancel(); else editing.cancel?.(); if (current.capture.hasPointerCapture(current.pointerId)) current.capture.releasePointerCapture(current.pointerId); } pointerHandlers.current = { move, stop, cancel }; const control = (point: { x: number; y: number }, id: string, part: NonNullable["part"], label: string) => start(event, id, part)} onPointerMove={move} onPointerUp={stop} onPointerCancel={cancel} onLostPointerCapture={(event) => { if (gesture.current) cancel(event); }} 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 { event.preventDefault(); event.stopPropagation(); add(flow.screenToFlowPosition({ x: event.clientX, y: event.clientY })); }}> {props.selected && } {animated && (animation.effect === "flow" || !animation.effect ? : )} {props.selected && <> 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) => event.stopPropagation()}> {control(knot.position, knot.id, "position", `曲线点 ${index + 1}`)} {selectedKnot === knot.id && <>{control(plus(knot.position, knot.in), knot.id, "in", "进入控制柄")}{control(plus(knot.position, knot.out), knot.id, "out", "离开控制柄")}} )} {control(segments[0][1], "start", "startControl", "起点控制柄")} {control(segments.at(-1)![2], "end", "endControl", "终点控制柄")} } ; } export function CanvasConnectionLine(props: ConnectionLineComponentProps) { 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 } }; return ; }