It looks like you're attempting to build a hierarchical tree visualization using D3.js based on data generated with FreeMarker templating. Let's walk through your code and see if we can identify any issues or improvements to ensure it works as expected.
Overview of Your Code
-
Data Generation: You're using FreeMarker to generate a JavaScript array of data objects, each representing a node in the tree with fields like lvl, id, parent_id, lang_value_ru, and type_.
-
Hierarchy Construction: The buildHierarchy function takes the flat array of items and constructs a hierarchical structure suitable for D3.js.
-
Visualization with D3.js: Using D3.js, you create a tree layout and render the nodes and links (edges) on an SVG canvas.
Potential Issues and Solutions
1. Handling the Root Node in buildHierarchy
Issue: The function assumes that there is a single root node where parent_id === null. If the root node isn't found, accessing root.id will throw an error.
Solution: Add a check to ensure the root node exists. If not, handle the error gracefully or provide a meaningful message.
Modified Code:
function buildHierarchy(items) {
const root = items.find((item) => item.parent_id === null);
if (!root) {
throw new Error("Root node not found. Ensure there's an item with parent_id === null.");
}
const nodesMap = new Map(
items.map((item) => [item.id, { ...item, children: [] }])
);
items.forEach((item) => {
if (item.parent_id !== null) {
const parent = nodesMap.get(item.parent_id);
if (parent) {
parent.children.push(nodesMap.get(item.id));
} else {
console.warn(`Parent with id ${item.parent_id} not found for item ${item.id}.`);
}
}
});
return nodesMap.get(root.id);
}
2. Handling Missing Parent Nodes
Issue: If an item's parent_id does not correspond to any item's id in your data, nodesMap.get(item.parent_id) will return undefined, leading to errors when trying to access .children.
Solution: Before pushing a child to a parent, check if the parent exists.
Modified Code: See the if (parent) check in the code snippet above.
3. Ensuring Data Integrity
Recommendation: Validate your data to ensure that all parent_id references are valid and that there are no circular dependencies.
Possible Validation Function:
function validateData(items) {
const ids = new Set(items.map(item => item.id));
let isValid = true;
items.forEach(item => {
if (item.parent_id !== null && !ids.has(item.parent_id)) {
console.error(`Invalid parent_id ${item.parent_id} for item ${item.id}`);
isValid = false;
}
});
return isValid;
}
if (!validateData(data)) {
throw new Error("Data validation failed.");
}
4. Tree Layout Configuration
Issue: The size of the tree layout might not be appropriate for your data, causing nodes to overlap or not display correctly.
Solution: Adjust the size parameters based on your SVG dimensions and the data.
Example:
const width = 960;
const height = 600;
const tree = d3.tree().size([height, width - 160]); // Adjust as needed.
5. Text Label Positioning
Issue: The text labels might overlap with the nodes or not display properly, especially for leaf nodes.
Solution: Adjust the x attribute and text-anchor based on whether a node has children.
Modified Code:
node
.append("text")
.attr("dy", "0.31em")
.attr("x", (d) => (d.children ? -10 : 10))
.attr("text-anchor", (d) => (d.children ? "end" : "start"))
.text((d) => d.data.lang_value_ru)
.clone(true)
.lower()
.attr("stroke", "white");
Adding a white stroke (outline) can improve text readability.
Complete Revised Code
Putting it all together, here's the revised script section:
<script>
// Assuming 'data' is correctly populated by FreeMarker.
function validateData(items) {
const ids = new Set(items.map(item => item.id));
let isValid = true;
items.forEach(item => {
if (item.parent_id !== null && !ids.has(item.parent_id)) {
console.error(`Invalid parent_id ${item.parent_id} for item ${item.id}`);
isValid = false;
}
});
return isValid;
}
if (!validateData(data)) {
throw new Error("Data validation failed.");
}
function buildHierarchy(items) {
const root = items.find((item) => item.parent_id === null);
if (!root) {
throw new Error("Root node not found. Ensure there's an item with parent_id === null.");
}
const nodesMap = new Map(
items.map((item) => [item.id, { ...item, children: [] }])
);
items.forEach((item) => {
if (item.parent_id !== null) {
const parent = nodesMap.get(item.parent_id);
if (parent) {
parent.children.push(nodesMap.get(item.id));
} else {
console.warn(`Parent with id ${item.parent_id} not found for item ${item.id}.`);
}
}
});
return nodesMap.get(root.id);
}
const hierarchyData = d3.hierarchy(buildHierarchy(data));
const width = 960;
const height = 600;
const svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
const g = svg.append("g").attr("transform", "translate(40,0)");
const tree = d3.tree().size([height, width - 160]);
const linkGenerator = d3
.linkHorizontal()
.x((d) => d.y)
.y((d) => d.x);
const treeData = tree(hierarchyData);
const link = g
.selectAll(".link")
.data(treeData.links())
.enter()
.append("path")
.attr("class", "link")
.attr("d", linkGenerator)
.style("fill", "none")
.style("stroke", "#ccc");
const node = g
.selectAll(".node")
.data(treeData.descendants())
.enter()
.append("g")
.attr("class", "node")
.attr("transform", (d) => `translate(${d.y},${d.x})`);
node.append("circle").attr("r", 5);
node
.append("text")
.attr("dy", "0.31em")
.attr("x", (d) => (d.children ? -10 : 10))
.attr("text-anchor", (d) => (d.children ? "end" : "start"))
.text((d) => d.data.lang_value_ru)
.clone(true)
.lower()
.attr("stroke", "white");
</script>
Additional Tips
-
Debugging: Use console.log statements to inspect variables at different stages, especially inside loops and conditionals.
console.log("Hierarchy Data:", hierarchyData);
-
Styling: Consider adding CSS styles to improve the appearance of the tree.
<style>
.node circle {
fill: steelblue;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
}
</style>
-
Responsiveness: If you want the SVG to be responsive, adjust the width and height attributes accordingly and consider using viewBox.
svg.attr("viewBox", `0 0 ${width} ${height}`).attr("preserveAspectRatio", "xMinYMin meet");
Conclusion
By making these adjustments, your hierarchical tree visualization should work more reliably. If you encounter further issues or have specific questions about parts of the code, feel free to ask!