← All proposals

Context: AgentTree

A tree of agent cards: the lead on top, its sub-agents side by side below, their helpers under them, joined by thin connectors.

Net-new componentOpen in Storybook

proposals/AgentTree/AgentTreeLight.tsx137 lines · View on GitHub
import { useEffect, useRef } from 'react';

export interface AgentTreeLightHop {
	/**
	 * `true` when the light runs from the child up to its parent.
	 */
	back: boolean;
	/**
	 * Path of the connector this hop runs along. A hop without one is skipped.
	 */
	d?: string;
}

export interface AgentTreeLightProps {
	/**
	 * The connectors the light runs along, in order.
	 */
	hops: AgentTreeLightHop[];
	/**
	 * Called as the light reaches the receiving card.
	 */
	onArrive: () => void;
	/**
	 * Called when the light has run out.
	 */
	onDone: () => void;
}

// One light per hop, this long in milliseconds; a longer path runs a little
// longer.
const HOP_DURATION = 520;
// The light is this long in SVG user units, drawn as stacked dashes of falling
// length so it is clear in the middle and fades to nothing at both ends.
const LIGHT_LENGTH = 44;
const LAYERS = 8;

/**
 * A handoff: a short light that runs along each connector on its way, up a
 * branch backwards and down one forwards. Decorative: the live region of the
 * tree announces the handoff.
 */
export const AgentTreeLight = ({
	hops,
	onArrive,
	onDone,
}: AgentTreeLightProps) => {
	const refs = useRef<(SVGPathElement | null)[][]>([]);
	const done = useRef(onDone);
	done.current = onDone;
	const arrive = useRef(onArrive);
	arrive.current = onArrive;

	useEffect(() => {
		let delay = 0;
		const animations: Animation[] = [];

		hops.forEach((hop, index) => {
			const layer = (refs.current[index] ?? []).filter(
				(el): el is SVGPathElement => el !== null,
			);
			if (!layer.length) return;
			const length = layer[0].getTotalLength();
			const duration = Math.max(
				380,
				Math.min(HOP_DURATION * 1.4, HOP_DURATION * (length / 160)),
			);
			layer.forEach((el, k) => {
				const dash = (LIGHT_LENGTH * (LAYERS - k)) / LAYERS;
				el.style.strokeDasharray = `${dash} ${length + LIGHT_LENGTH * 2}`;
				// The light's middle travels from just before the start to just
				// past the end.
				const offset = (center: number) => -(center - dash / 2);
				const from = -LIGHT_LENGTH / 2;
				const to = length + LIGHT_LENGTH / 2;
				animations.push(
					el.animate(
						[
							{
								opacity: 1,
								strokeDashoffset: offset(hop.back ? to : from),
							},
							{
								opacity: 1,
								strokeDashoffset: offset(hop.back ? from : to),
							},
						],
						{
							delay,
							duration,
							easing: 'cubic-bezier(0.45, 0, 0.3, 1)',
							fill: 'both',
						},
					),
				);
			});
			delay += duration - 80;
		});

		const last = animations[animations.length - 1];
		if (!last) {
			arrive.current();
			done.current();
			return;
		}
		// The card lights up as the light's middle reaches it; the light itself
		// runs on and out.
		const timer = window.setTimeout(
			() => arrive.current(),
			Math.max(0, delay + 80 - 120),
		);
		last.onfinish = () => done.current();
		return () => {
			window.clearTimeout(timer);
			animations.forEach((animation) => animation.cancel());
		};
		// The hops are measured once, when the light starts.
	}, []);

	return (
		<g className='pds-agent-tree__light'>
			{hops.map((hop, index) =>
				hop.d
					? Array.from({ length: LAYERS }, (_, k) => (
							<path
								d={hop.d}
								key={`${index}-${k}`}
								ref={(el) => {
									(refs.current[index] ??= [])[k] = el;
								}}
							/>
						))
					: null,
			)}
		</g>
	);
};