SPB Git

Repository Public

DiagramSvg.tsx 8.3 KB 160 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Sheet8 * File             : src/renderer/diagram/DiagramSvg.tsx9 * Module           : renderer10 * Repository       : https://git.spboucher.ai/sheet11 * Project Website  : https://sheet.spboucher.ai12 * Created          : 2026-11-1713 * Last Modified    : 2026-11-1714 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import type { ReactNode } from "react";44import { TONES, type Tone } from "@/schema";45import { IconInSvg } from "../icons";46import { V, toneSoftVar, toneVar } from "../tone";47import { EDGE_FONT, GROUP_FONT, LABEL_FONT, SUBLABEL_FONT, type DiagramLayout, type NodeBox } from "./layout";4849export interface DiagramHighlight { nodes: string[]; edges: string[] }50export interface DiagramSvgProps {51  layout: DiagramLayout;52  /** Makes marker ids unique when several diagrams share a page. */53  idPrefix: string;54  /** Accessible name (the block's alt, or its title). */55  title?: string; desc?: string;56  /** Everything outside the highlight is dimmed. */57  highlight?: DiagramHighlight;58  /** Fixed pixel size (standalone export). By default the SVG fills its container up to its natural width. */59  width?: number; height?: number;60  className?: string;61}6263const n1 = (v: number): number => Math.round(v * 10) / 10;6465function shape(n: NodeBox, strokeWidth: number): ReactNode {66  const l = n.left, t = n.top, w = n.width, h = n.height, r = l + w, b = t + h;67  const paint = { fill: toneSoftVar(n.tone), stroke: toneVar(n.tone), strokeWidth, strokeLinejoin: "round" } as const;68  switch (n.shape) {69    case "rect": return <rect x={l} y={t} width={w} height={h} rx={3} {...paint} />;70    case "round": return <rect x={l} y={t} width={w} height={h} rx={11} {...paint} />;71    case "pill": return <rect x={l} y={t} width={w} height={h} rx={h / 2} {...paint} />;72    case "circle": return <ellipse cx={n.x} cy={n.y} rx={w / 2} ry={h / 2} {...paint} />;73    case "diamond": return <polygon points={`${n.x},${t} ${r},${n.y} ${n.x},${b} ${l},${n.y}`} {...paint} />;74    case "hexagon": { const i = n1(Math.min(18, w * 0.18)); return <polygon points={`${l + i},${t} ${r - i},${t} ${r},${n.y} ${r - i},${b} ${l + i},${b} ${l},${n.y}`} {...paint} />; }75    case "cylinder": {76      const ry = 7, rx = w / 2;77      return <>78        <path d={`M${l} ${t + ry}A${rx} ${ry} 0 0 1 ${r} ${t + ry}V${b - ry}A${rx} ${ry} 0 0 1 ${l} ${b - ry}Z`} {...paint} />79        <path d={`M${l} ${t + ry}A${rx} ${ry} 0 0 0 ${r} ${t + ry}`} fill="none" stroke={toneVar(n.tone)} strokeWidth={strokeWidth} />80      </>;81    }82    case "note": {83      const f = 12;84      return <>85        <path d={`M${l} ${t}H${r - f}L${r} ${t + f}V${b}H${l}Z`} {...paint} />86        <path d={`M${r - f} ${t}V${t + f}H${r}`} fill="none" stroke={toneVar(n.tone)} strokeWidth={strokeWidth} strokeLinejoin="round" />87      </>;88    }89  }90}9192const DASH: Record<"solid" | "dashed" | "dotted", string | undefined> = { solid: undefined, dashed: "7 5", dotted: "1.5 5.5" };9394/** Pure SVG drawing of a computed layout. No hooks, no browser API: server components, client components, export. */95export function DiagramSvg({ layout, idPrefix, title, desc, highlight, width, height, className }: DiagramSvgProps) {96  const vb = layout.viewBox;97  const hn = highlight ? new Set(highlight.nodes) : null, he = highlight ? new Set(highlight.edges) : null;98  const tonesUsed = TONES.filter((tone) => layout.edges.some((e) => e.tone === tone && e.arrow !== "none"));99  const marker = (tone: Tone) => `${idPrefix}-arrow-${tone}`;100  const dim = (on: boolean) => (highlight ? (on ? "sh-dg-on" : "sh-dg-dim") : undefined);101  const dimOpacity = (on: boolean) => (highlight && !on ? 0.2 : undefined);102  return (103    <svg className={className ?? "sh-diagram-svg"} viewBox={`${vb.x} ${vb.y} ${vb.width} ${vb.height}`} width={width ?? vb.width} height={height ?? vb.height}104      role="img" aria-label={title} fontFamily={V.fontBody} preserveAspectRatio="xMidYMid meet">105      {title ? <title>{title}</title> : null}106      {desc ? <desc>{desc}</desc> : null}107      <defs>108        {tonesUsed.map((tone) => (109          <marker key={tone} id={marker(tone)} viewBox="0 0 10 10" refX="8.6" refY="5" markerWidth="6.5" markerHeight="6.5" orient="auto-start-reverse">110            <path d="M1.2 1.6 9 5 1.2 8.4Z" fill={toneVar(tone)} stroke={toneVar(tone)} strokeWidth="1" strokeLinejoin="round" />111          </marker>112        ))}113      </defs>114      {layout.groups.map((g) => (115        <g key={g.id} data-group-id={g.id} opacity={highlight ? 0.55 : undefined} className={highlight ? "sh-dg-group" : undefined}>116          <rect x={g.x} y={g.y} width={g.width} height={g.height} rx={14} fill={toneSoftVar(g.tone)} fillOpacity={0.38} stroke={toneVar(g.tone)} strokeOpacity={0.55} strokeWidth={1.2} strokeDasharray="5 4" />117          <text x={g.labelX} y={g.labelY} fontSize={GROUP_FONT.size} fontWeight={GROUP_FONT.weight} letterSpacing="0.08em" fill={toneVar(g.tone)}>{g.label.toUpperCase()}</text>118        </g>119      ))}120      {layout.edges.map((e) => {121        const on = he ? he.has(e.id) : true;122        return (123          <path key={e.id} data-edge-id={e.id} className={dim(on)} opacity={dimOpacity(on)} d={e.d} fill="none" stroke={toneVar(e.tone)}124            strokeWidth={highlight && on ? 2.4 : 1.6} strokeLinecap="round" strokeLinejoin="round" strokeDasharray={DASH[e.style]}125            markerEnd={e.arrow !== "none" ? `url(#${marker(e.tone)})` : undefined} markerStart={e.arrow === "both" ? `url(#${marker(e.tone)})` : undefined} />126        );127      })}128      {layout.nodes.map((n) => {129        const on = hn ? hn.has(n.id) : true;130        return (131          <g key={n.id} data-node-id={n.id} className={dim(on)} opacity={dimOpacity(on)}>132            {shape(n, highlight && on ? 2.6 : 1.5)}133            {n.icon && n.iconBox ? <IconInSvg name={n.icon} x={n.iconBox.x} y={n.iconBox.y} size={n.iconBox.size} color={toneVar(n.tone)} /> : null}134            <text textAnchor="middle" fontSize={LABEL_FONT.size} fontWeight={LABEL_FONT.weight} fill={V.ink}>135              {n.labelLines.map((line, i) => <tspan key={i} x={n.textX} y={n.labelBaselines[i]}>{line}</tspan>)}136            </text>137            {n.sublabelLines.length ? (138              <text textAnchor="middle" fontSize={SUBLABEL_FONT.size} fontWeight={SUBLABEL_FONT.weight} fill={V.muted}>139                {n.sublabelLines.map((line, i) => <tspan key={i} x={n.textX} y={n.sublabelBaselines[i]}>{line}</tspan>)}140              </text>141            ) : null}142          </g>143        );144      })}145      {layout.edges.map((e) => {146        if (!e.label) return null;147        const on = he ? he.has(e.id) : true;148        return (149          <g key={e.id} data-edge-label={e.id} className={dim(on)} opacity={dimOpacity(on)}>150            <rect x={e.label.x} y={e.label.y} width={e.label.width} height={e.label.height} rx={6} fill={V.surface} stroke={V.line} strokeWidth={1} />151            <text textAnchor="middle" fontSize={EDGE_FONT.size} fontWeight={EDGE_FONT.weight} fill={V.muted}>152              {e.label.lines.map((line, i) => <tspan key={i} x={e.label!.cx} y={e.label!.baselines[i]}>{line}</tspan>)}153            </text>154          </g>155        );156      })}157    </svg>158  );159}160
Files main
Menu

Theme