@@ -21,6 +21,7 @@ export interface Node extends d3.SimulationNodeDatum {
21
21
group : string ;
22
22
color : string ;
23
23
radius : number ;
24
+ text ?: string ;
24
25
}
25
26
26
27
export interface Link extends d3 . SimulationLinkDatum < Node > {
@@ -82,12 +83,13 @@ const ForceGraph: React.FC<ForceGraphProps> = ({
82
83
) ;
83
84
84
85
useEffect ( ( ) => {
85
- const svg = d3 . select ( svgRef . current ) . attr ( "style" , "max-width: 100%; height: auto;" ) ;
86
+ const svg = d3 . select ( svgRef . current ) ;
86
87
87
88
// Add a line for each link, and a circle for each node.
88
89
const link = svg . select ( "g.links" ) . selectAll ( "line" ) . data ( links ) ;
89
90
90
91
const node = svg . select ( "g.nodes" ) . selectAll ( "circle" ) . data ( nodes ) ;
92
+ const nodeText = svg . select ( "g.nodes" ) . selectAll ( "text" ) . data ( nodes ) ;
91
93
92
94
// node.append("title").text(d => d.id);
93
95
@@ -105,6 +107,7 @@ const ForceGraph: React.FC<ForceGraphProps> = ({
105
107
. attr ( "y2" , d => ( d . target as Node ) . y ?? 0 ) ;
106
108
107
109
node . attr ( "cx" , d => d . x ) . attr ( "cy" , d => d . y ) ;
110
+ nodeText . attr ( "x" , d => d . x ) . attr ( "y" , d => d . y + 4 ) ;
108
111
} ) ;
109
112
110
113
// Reheat the simulation when drag starts, and fix the subject position.
@@ -143,7 +146,7 @@ const ForceGraph: React.FC<ForceGraphProps> = ({
143
146
width = { width }
144
147
height = { height }
145
148
viewBox = { `${ - width / 2 } ${ - height / 2 } ${ width } , ${ height } ` }
146
- style = { { height : "auto" } }
149
+ style = { { height : "auto" , maxWidth : "100%" } }
147
150
>
148
151
< g className = "links" stroke = "#999" strokeOpacity = { 0.6 } >
149
152
{ links . map ( ( link , i ) => (
@@ -152,7 +155,20 @@ const ForceGraph: React.FC<ForceGraphProps> = ({
152
155
</ g >
153
156
< g className = "nodes" stroke = "#fff" strokeWidth = { 1.5 } >
154
157
{ nodes . map ( ( node , i ) => (
155
- < circle key = { i } r = { radius ( node . radius ) } fill = { color ( node . group ) } />
158
+ < >
159
+ < circle key = { i } r = { radius ( node . radius ) } fill = { color ( node . group ) } />
160
+ < text
161
+ textAnchor = "middle"
162
+ alignmentBaseline = "middle"
163
+ style = { { userSelect : "none" , cursor : "default" , pointerEvents : "none" } }
164
+ fontFamily = "Inter, Helvetica, Arial, sans-serif"
165
+ fontSize = { 10 }
166
+ strokeWidth = { 0 }
167
+ fill = "#fff"
168
+ >
169
+ { node . text }
170
+ </ text >
171
+ </ >
156
172
) ) }
157
173
</ g >
158
174
</ svg >
0 commit comments