-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.js
357 lines (314 loc) · 9.74 KB
/
graph.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import * as d3 from 'https://cdn.jsdelivr.net/npm/d3@7/+esm';
import { GraphDataProvider } from './graph-data-provider.js';
/**
* @typedef {{x: number, y: number, width: number, height: number}} BoundingBox
* @typedef {{id: number, text: string, bbox?: BoundingBox, x?: number, y?: number}} Node
* @typedef {{source: Node, target: Node}} Link
* @typedef {{nodes: Node[], links: Link[]}} GraphData
*/
class WordGraph extends HTMLElement {
/**
* Creates a new WordGraph element.
*/
constructor() {
super();
this.shadow = this.attachShadow({ mode: 'open' });
}
/**
* Runs when the element is added to the DOM. Initializes the canvas and
* loads the data.
*/
connectedCallback() {
this.initializeCanvas();
this.loadDataAndSetupGraph();
this.initializeResizeListener();
}
/**
* Updates the canvas size when the element is resized.
*/
initializeResizeListener() {
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
if (entry.target === this) {
this.updateCanvasSize(entry);
}
}
});
resizeObserver.observe(this);
}
/**
* Initializes the canvas element and sets up the drawing context.
*/
initializeCanvas() {
this.canvas = document.createElement('canvas');
this.shadow.appendChild(this.canvas);
this.context = this.canvas.getContext('2d');
this.updateCanvasSize();
}
/**
* Gets the charge strength of the nodes in the graph. The charge strength
* is based on the size of the canvas.
* @returns {number} The charge strength.
*/
getChargeStrength() {
return Math.min(this.canvas.width, this.canvas.height) < 600 ? -50 : -100;
}
/**
* Gets the font size of the nodes in the graph. The font size is based on
* the size of the canvas.
* @returns {number} The font size.
*/
getFontSize() {
return Math.min(this.canvas.width, this.canvas.height) < 600 ? 11 : 15;
}
/**
* Updates the size of the canvas based on the current element's dimensions.
* @param {ResizeObserverEntry | undefined} entry The resize observer entry.
* If not provided, the element's bounding client rect is used.
*/
updateCanvasSize(entry) {
const rect = entry?.contentRect ?? this.getBoundingClientRect();
this.canvas.width = rect.width;
this.canvas.height = rect.height;
// Update the simulation center.
if (this.simulation) {
this.simulation
.force(
'center',
d3.forceCenter(this.canvas.width / 2, this.canvas.height / 2)
)
.force('charge', d3.forceManyBody().strength(this.getChargeStrength()));
}
}
/**
* Loads data from 'data.json' and sets up the graph.
*/
loadDataAndSetupGraph() {
const graphDataProvider = new GraphDataProvider();
graphDataProvider.getRandomData().then((data) => {
this.setupGraph(data);
});
}
/**
* Sets up the graph using the given data.
*
* @param {Object} data The data used to set up the graph.
*/
setupGraph(data) {
const { nodes, links } = data;
const simulation = this.createSimulation(nodes, links);
this.simulation = simulation;
this.addMouseInteraction(simulation, nodes);
this.handleSimulationUpdates(simulation, nodes, links);
}
/**
* Prepares graph data by transforming the input data into a format suitable
* for graph visualization.
* @param {Object} data The input data containing links and nodes.
* @param {[string, string][]} data.links The links between nodes.
* @param {string[]} data.nodes The nodes in the graph.
* @returns {GraphData} The prepared graph data.
*/
prepareGraphData(data) {
const links = data.links.map((link) => ({
source: link[0],
target: link[1],
}));
const nodes = data.nodes.map((node) => ({ id: node }));
return { nodes, links };
}
/**
* Creates a force simulation for the given nodes and links.
* @param {Node[]} nodes The array of nodes.
* @param {Link[]} links The array of links.
* @returns {Object} The force simulation object.
*/
createSimulation(nodes, links) {
return d3
.forceSimulation(nodes)
.force(
'link',
d3
.forceLink(links)
.id((node) => node.id)
.strength(0.05)
)
.force('charge', d3.forceManyBody().strength(this.getChargeStrength()))
.force('collision', d3.forceCollide().radius(20))
.force(
'center',
d3.forceCenter(this.canvas.width / 2, this.canvas.height / 2)
)
.alphaTarget(0.5);
}
/**
* Adds mouse interaction, such that nodes are repelled by the mouse cursor.
* @param {Object} simulation The simulation object.
* @param {Node[]} nodes The array of nodes.
*/
addMouseInteraction(simulation, nodes) {
let mouseX, mouseY;
this.canvas.addEventListener('mousemove', (event) => {
const rect = this.canvas.getBoundingClientRect();
mouseX = event.clientX - rect.left;
mouseY = event.clientY - rect.top;
let forceApplied = false;
simulation.force('mouse', (alpha) => {
if (forceApplied) return;
forceApplied = true;
nodes.forEach((node) => {
const dx = node.x - mouseX;
const dy = node.y - mouseY;
const distance = Math.sqrt(dx * dx + dy * dy);
const force = (alpha * 50 * -1) / distance;
if (distance < 50) {
node.vx -= force * dx;
node.vy -= force * dy;
}
});
});
});
}
/**
* Handles simulation updates by updating node positions and drawing the graph.
* @param {Simulation} simulation The simulation object.
* @param {Node[]} nodes The array of nodes.
* @param {Link[]} links The array of links.
*/
handleSimulationUpdates(simulation, nodes, links) {
simulation.on('tick', () => {
this.updateNodePositions(nodes);
this.drawGraph(nodes, links);
});
window.addEventListener('unload', () => simulation.stop());
}
/**
* Updates the positions of the nodes on the canvas, such that they are
* contained within the canvas.
* @param {Node[]} nodes The array of nodes.
*/
updateNodePositions(nodes) {
const { width, height } = this.canvas;
nodes.forEach((node) => {
if (!node.bbox) return;
node.x = Math.max(
node.bbox.width / 2,
Math.min(width - node.bbox.width / 2, node.x)
);
node.y = Math.max(
node.bbox.height / 2,
Math.min(height - node.bbox.height / 2, node.y)
);
});
}
/**
* Draws a graph on the canvas.
* @param {Node[]} nodes The array of nodes.
* @param {Link[]} links The array of links.
*/
drawGraph(nodes, links) {
this.clearCanvas();
this.drawLinks(links);
this.drawNodes(nodes);
}
/**
* Clears the canvas by removing all drawn content.
*/
clearCanvas() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
/**
* Draws links between nodes on the canvas.
* @param {Link[]} links The array of links.
*/
drawLinks(links) {
const ctx = this.context;
ctx.save();
ctx.globalAlpha = 0.6;
ctx.strokeStyle = '#00ffff';
ctx.beginPath();
links.forEach((link) => {
ctx.moveTo(link.source.x, link.source.y);
ctx.lineTo(link.target.x, link.target.y);
});
ctx.stroke();
ctx.restore();
}
/**
* Draws the nodes on the canvas.
* @param {Node[]} nodes The array of nodes.
*/
drawNodes(nodes) {
const ctx = this.context;
ctx.save();
ctx.font = `${this.getFontSize()}px Lora`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
nodes.forEach((node) => {
this.drawNode(ctx, node);
});
ctx.restore();
}
/**
* Draws a node on the canvas.
*
* @param {CanvasRenderingContext2D} ctx The rendering context of the canvas.
* @param {Node} node The node to draw.
*/
drawNode(ctx, node) {
const textMetrics = ctx.measureText(node.text);
const textWidth = textMetrics.width;
const textHeight = parseInt(ctx.font, 10);
const borderRadius = 15;
const padding = 5;
const rectX = node.x - textWidth / 2 - padding;
const rectY = node.y - textHeight / 2 - padding;
const rectWidth = textWidth + 2 * padding;
const rectHeight = textHeight + 2 * padding;
if (!node.bbox) {
node.bbox = {
x: rectX,
y: rectY,
width: rectWidth,
height: rectHeight,
};
}
ctx.fillStyle = '#1b1b1b';
this.drawRoundedRect(
ctx,
rectX,
rectY,
rectWidth,
rectHeight,
borderRadius
);
ctx.fill();
ctx.fillStyle = '#fff';
ctx.fillText(node.text, node.x, node.y);
}
/**
* Draws a rounded rectangle on the canvas.
*
* @param {CanvasRenderingContext2D} ctx The rendering context of the canvas.
* @param {number} x The x-coordinate of the top-left corner of the rectangle.
* @param {number} y The y-coordinate of the top-left corner of the rectangle.
* @param {number} width The width of the rectangle.
* @param {number} height The height of the rectangle.
* @param {number} radius The radius of the rounded corners.
*/
drawRoundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
}
// Register the custom element so that it can be used in HTML.
customElements.define('word-graph', WordGraph);