1
0
Fork 0
polaris-task-force/src/components/frontend/intelligence/MissionCommandChainChart.tsx
Z8MB1E bff6a7a908 feat(intelligence): render mission chain of command as an editable org chart
Replace the per-person supervisor list as the primary chain-of-command
surface on the mission page with a layered DAG rendered on React Flow.
Both views share one draft; connections stay editable until the first
evaluation or cancellation locks them.

- getChainViewerState: always returns state (viewer-aware), replacing
  getChainEditorState's null-for-viewers contract so plain viewers see
  the chain read-only
- auto-layout wraps wide layers instead of shrinking past readability
- tactical dossier styling for nodes and canvas chrome
2026-12-01 10:18:26 -05:00

334 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import * as React from "react";
import {
Background,
BackgroundVariant,
BaseEdge,
Controls,
EdgeLabelRenderer,
Handle,
MarkerType,
Position,
ReactFlow,
ReactFlowProvider,
getSmoothStepPath,
useReactFlow,
type Edge,
type EdgeProps,
type EdgeTypes,
type Node,
type NodeProps,
type NodeTypes,
type OnConnect,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import { CHAIN_NODE_H, CHAIN_NODE_W, computeChainLayout } from "./chainLayout";
import type { ChainDraft } from "./chainDraftRules";
/**
* Org-chart view of a mission chain of command on a React Flow canvas.
* Tactical dossier styling (squared cards, mono rank strip, faint grid),
* auto-layout only: nodes are fixed by data, drag positions are not stored.
* Editing = drawing connections between cards and removing them; every change
* lands in the section-owned draft, shared with the List tab.
*/
export interface ChartParticipant {
id: number;
name: string;
rankIndex: number | null;
rankLabel: string | null;
}
interface PersonNodeData extends Record<string, unknown> {
name: string;
rankLabel: string | null;
/** True for the unlinked band: dashed border, dimmer chrome. */
unlinked: boolean;
connectable: boolean;
}
interface LabelNodeData extends Record<string, unknown> {
label: string;
}
type PersonNodeModel = Node<PersonNodeData, "chainPerson">;
type LabelNodeModel = Node<LabelNodeData, "chainBandLabel">;
interface ChainEdgeData extends Record<string, unknown> {
invalid: boolean;
removeable: boolean;
onRemove?: () => void;
}
function ChainPersonNodeCard({ data, selected }: NodeProps<PersonNodeModel>) {
return (
<div
data-testid={`chain-node-${data.name}`}
className={[
"flex h-full w-full flex-col justify-center rounded-none border px-3 py-1.5 backdrop-blur-sm transition-colors",
data.unlinked
? "border-dashed border-white/15 bg-black/40"
: "border-white/25 bg-zinc-900/90",
selected ? "border-white/60" : "hover:border-white/45",
].join(" ")}
>
<span
className={`truncate text-sm leading-snug font-semibold ${
data.unlinked ? "text-white/60" : "text-white"
}`}
>
{data.name}
</span>
<span className="font-mono text-[8px] uppercase tracking-widest text-white/45">
{data.rankLabel ?? "UNRANKED"}
</span>
{data.connectable && (
<>
<Handle
type="target"
id="t"
position={Position.Top}
className="!bg-white/45 hover:!bg-[#22d3ee]"
style={{ width: 10, height: 10, border: "1px solid rgba(0,0,0,0.6)" }}
/>
<Handle
type="source"
id="s"
position={Position.Bottom}
className="!bg-white/45 hover:!bg-[#22d3ee]"
style={{ width: 10, height: 10, border: "1px solid rgba(0,0,0,0.6)" }}
/>
</>
)}
</div>
);
}
function ChainBandLabelNode({ data }: NodeProps<LabelNodeModel>) {
return (
<div className="whitespace-nowrap font-mono text-[9px] uppercase tracking-widest text-white/40">
{data.label}
</div>
);
}
function ChainCommandEdge({ id, sourceX, sourceY, targetX, targetY, markerEnd, selected, data }: EdgeProps) {
const edgeData = data as ChainEdgeData | undefined;
const [path, labelX, labelY] = getSmoothStepPath({
sourceX,
sourceY,
targetX,
targetY,
sourcePosition: Position.Bottom,
targetPosition: Position.Top,
borderRadius: 8,
});
const stroke = edgeData?.invalid ? "#f87171" : "rgba(255,255,255,0.35)";
return (
<>
<BaseEdge
id={id}
path={path}
markerEnd={markerEnd}
style={{
stroke,
strokeWidth: edgeData?.invalid ? 2 : 1.5,
strokeDasharray: edgeData?.invalid ? "4 3" : undefined,
}}
/>
<EdgeLabelRenderer>
{selected && edgeData?.removeable && (
<div
className="nodrag nopan"
style={{
position: "absolute",
transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
pointerEvents: "all",
}}
>
<button
type="button"
aria-label="Remove command link"
title="Remove this command link"
onClick={(e) => {
e.stopPropagation();
edgeData.onRemove?.();
}}
onPointerDown={(e) => e.stopPropagation()}
className="flex h-4 w-4 items-center justify-center rounded-full border border-red-400/70 bg-black/85 font-mono text-[10px] leading-none text-red-300 hover:bg-red-500/25"
>
×
</button>
</div>
)}
</EdgeLabelRenderer>
</>
);
}
const nodeTypes: NodeTypes = {
chainPerson: ChainPersonNodeCard,
chainBandLabel: ChainBandLabelNode,
};
const edgeTypes: EdgeTypes = {
command: ChainCommandEdge,
};
/** Rank-aware auto-orientation lives with the rules; edges are directed. */
export interface MissionCommandChainChartProps {
participants: ChartParticipant[];
draft: ChainDraft;
/** `"supervisor->subordinate"` keys of draft links that break a rule. */
invalidKeys: Set<string>;
editable: boolean;
onAddLink: (supervisorId: number, subordinateId: number) => void;
onRemoveLink: (supervisorId: number, subordinateId: number) => void;
}
function ChartInner({
participants,
draft,
invalidKeys,
editable,
onAddLink,
onRemoveLink,
}: MissionCommandChainChartProps) {
const rf = useReactFlow();
const participantKey = participants.map((p) => p.id).join(",");
const layout = React.useMemo(() => {
const links = Object.entries(draft).flatMap(([subordinateId, supervisorIds]) =>
supervisorIds.map((supervisorId) => ({ supervisorId, subordinateId: Number(subordinateId) })),
);
return computeChainLayout({ participantIds: participants.map((p) => p.id), links });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [participantKey, draft]);
/** Participants with at least one command edge (either direction). */
const linked = React.useMemo(() => {
const set = new Set<number>();
for (const [subordinateId, supervisorIds] of Object.entries(draft)) {
if (supervisorIds.length > 0) {
set.add(Number(subordinateId));
for (const s of supervisorIds) set.add(s);
}
}
return set;
}, [draft]);
const nodes = React.useMemo<Node[]>(() => {
const flowNodes: Node[] = participants.map((p) => ({
id: String(p.id),
type: "chainPerson",
position: layout.positions.get(p.id) ?? { x: 0, y: 0 },
width: CHAIN_NODE_W,
height: CHAIN_NODE_H,
draggable: false,
data: {
name: p.name,
rankLabel: p.rankLabel,
unlinked: !linked.has(p.id),
connectable: editable,
} satisfies PersonNodeData,
}));
if (layout.bandTop !== null) {
// Caption above the first band card; shares its x so the two line up.
const firstUnlinked = participants.find((p) => !linked.has(p.id));
const x = firstUnlinked ? (layout.positions.get(firstUnlinked.id)?.x ?? 0) : 0;
flowNodes.push({
id: "chain-band-label",
type: "chainBandLabel",
position: { x, y: layout.bandTop - 26 },
draggable: false,
selectable: false,
focusable: false,
data: { label: "No command links" } satisfies LabelNodeData,
});
}
return flowNodes;
}, [participants, layout, linked, editable]);
const edges = React.useMemo<Edge[]>(
() =>
Object.entries(draft).flatMap(([subordinateIdText, supervisorIds]) => {
const subordinateId = Number(subordinateIdText);
return supervisorIds.map((supervisorId) => {
const invalid = invalidKeys.has(`${supervisorId}->${subordinateId}`);
return {
id: `${supervisorId}->${subordinateId}`,
source: String(supervisorId),
target: String(subordinateId),
sourceHandle: "s",
targetHandle: "t",
type: "command",
selectable: editable,
markerEnd: { type: MarkerType.ArrowClosed, width: 14, height: 14, color: invalid ? "#f87171" : "rgba(255,255,255,0.5)" },
data: {
invalid,
removeable: editable,
onRemove: () => onRemoveLink(supervisorId, subordinateId),
} satisfies ChainEdgeData,
};
});
}),
[draft, invalidKeys, editable, onRemoveLink],
);
const onConnect: OnConnect = React.useCallback(
(connection) => {
if (!editable || connection.source == null || connection.target == null) return;
onAddLink(Number(connection.source), Number(connection.target));
},
[editable, onAddLink],
);
// Re-fit when the participant set changes (RSVP churn after router.refresh).
React.useEffect(() => {
rf.fitView({ padding: 0.15, maxZoom: 1 });
}, [rf, participantKey]);
return (
<div
// Dark controls/attribution chrome lives in app/(frontend)/styles.css
// under .mission-chain-canvas (mirrors the frontend tech tree canvas).
className="mission-chain-canvas relative h-[420px] w-full overflow-hidden rounded-none border border-white/15 md:h-[560px]"
style={{ backgroundColor: "#05070a" }}
data-testid="chain-chart-canvas"
>
<ReactFlow
nodes={nodes}
edges={edges}
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
fitView
fitViewOptions={{ padding: 0.15, maxZoom: 1 }}
minZoom={0.2}
proOptions={{ hideAttribution: false }}
nodesDraggable={false}
nodesConnectable={editable}
nodesFocusable={false}
onConnect={onConnect}
>
<Background
variant={BackgroundVariant.Lines}
gap={28}
size={1}
color="rgba(255,255,255,0.055)"
/>
<Controls showInteractive={false} />
</ReactFlow>
</div>
);
}
export function MissionCommandChainChart(props: MissionCommandChainChartProps) {
return (
<ReactFlowProvider>
<ChartInner {...props} />
</ReactFlowProvider>
);
}