<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport"…
- Usercode
- Assistant
<script>
const { createApp, ref, onMounted, watch } = Vue;
class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
this.x = 0;
this.y = 0;
this.targetX = 0;
this.targetY = 0;
}
}
createApp({
setup() {
const canvas = ref(null);
const ctx = ref(null);
const treeInput = ref('1,null,2,null,3,null,4,null,5,null,6');
const root = ref(null);
const selectedNode = ref(null);
const hoveredNode = ref(null);
const hoveredEdge = ref(null);
const potentialParent = ref(null);
const nodeRadius = ref(25);
const animationSpeed = 0.1;
const minNodeDistance = ref(100);
const buildTree = (values) => {
if (!values || values.length === 0) return null;
const nodes = values.map(val => val === 'null' ? null : new TreeNode(parseInt(val)));
for (let i = 0; i < nodes.length; i++) {
if (nodes[i] !== null) {
const leftIndex = 2 * i + 1;
const rightIndex = 2 * i + 2;
if (leftIndex < nodes.length) nodes[i].left = nodes[leftIndex];
if (rightIndex < nodes.length) nodes[i].right = nodes[rightIndex];
}
}
return nodes[0];
};
const layoutTree = (node, depth = 0, left = 0, right = canvas.value.width) => {
if (!node) return;
const x = (left + right) / 2;
const y = depth * minNodeDistance.value + nodeRadius.value * 2;
node.targetX = x;
node.targetY = y;
if (node.x === 0 && node.y === 0) {
node.x = node.targetX;
node.y = node.targetY;
}
const childSpacing = Math.max((right - left) / 2, minNodeDistance.value);
layoutTree(node.left, depth + 1, left, x);
layoutTree(node.right, depth + 1, x, right);
};
const drawTree = () => {
if (!ctx.value) return;
ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height);
if (root.value) drawNode(root.value);
};
const drawNode = (node) => {
if (!node) return;
// Draw edges
if (node.left) drawEdge(node, node.left);
if (node.right) drawEdge(node, node.right);
// Draw node
ctx.value.beginPath();
ctx.value.arc(node.x, node.y, nodeRadius.value, 0, 2 * Math.PI);
const gradient = ctx.value.createRadialGradient(node.x, node.y, 0, node.x, node.y, nodeRadius.value);
if (node === selectedNode.value) {
gradient.addColorStop(0, '#e74c3c');
gradient.addColorStop(1, '#c0392b');
} else if (node === hoveredNode.value) {
gradient.addColorStop(0, '#3498db');
gradient.addColorStop(1, '#2980b9');
} else {
gradient.addColorStop(0, '#2ecc71');
gradient.addColorStop(1, '#27ae60');
}
ctx.value.fillStyle = gradient;
ctx.value.fill();
ctx.value.strokeStyle = '#fff';
ctx.value.lineWidth = 2;
ctx.value.stroke();
// Draw value
ctx.value.fillStyle = 'white';
ctx.value.font = `bold ${nodeRadius.value * 0.7}px Arial`;
ctx.value.textAlign = 'center';
ctx.value.textBaseline = 'middle';
ctx.value.fillText(node.val, node.x, node.y);
// Draw glow effect for potential parent
if (potentialParent.value === node) {
ctx.value.beginPath();
ctx.value.arc(node.x, node.y, nodeRadius.value + 10, 0, 2 * Math.PI);
ctx.value.strokeStyle = 'rgba(52, 152, 219, 0.5)';
ctx.value.lineWidth = 5;
ctx.value.stroke();
}
drawNode(node.left);
drawNode(node.right);
};
const drawEdge = (parent, child) => {
const dx = child.x - parent.x;
const dy = child.y - parent.y;
const distance = Math.sqrt(dx * dx + dy * dy);
const ratio = (distance - nodeRadius.value) / distance;
const endX = parent.x + dx * ratio;
const endY = parent.y + dy * ratio;
ctx.value.beginPath();
ctx.value.moveTo(parent.x, parent.y);
ctx.value.lineTo(endX, endY);
const gradient = ctx.value.createLinearGradient(parent.x, parent.y, endX, endY);
if (hoveredEdge.value && hoveredEdge.value[0] === parent && hoveredEdge.value[1] === child) {
gradient.addColorStop(0, '#3498db');
gradient.addColorStop(1, '#2980b9');
ctx.value.lineWidth = 4;
} else {
gradient.addColorStop(0, '#95a5a6');
gradient.addColorStop(1, '#7f8c8d');
ctx.value.lineWidth = 2;
}
ctx.value.strokeStyle = gradient;
ctx.value.stroke();
};
const animate = () => {
if (root.value) animateNode(root.value);
drawTree();
requestAnimationFrame(animate);
};
const animateNode = (node) => {
if (!node) return;
node.x += (node.targetX - node.x) * animationSpeed;
node.y += (node.targetY - node.y) * animationSpeed;
animateNode(node.left);
animateNode(node.right);
};
const generateTree = () => {
const values = treeInput.value.split(',').map(val => val.trim());
console.log('Tree Input:', values); // Debug the input
root.value = buildTree(values);
if (!root.value) {
console.error("Tree could not be built");
return;
}
layoutTree(root.value);
console.log('Tree generated and laid out'); // Confirm tree is built
};
const findNodeAtPosition = (x, y, node = root.value) => {
if (!node) return null;
const distance = Math.sqrt((node.x - x) ** 2 + (node.y - y) ** 2);
if (distance <= nodeRadius.value) return node;
const leftResult = findNodeAtPosition(x, y, node.left);
if (leftResult) return leftResult;
return findNodeAtPosition(x, y, node.right);
};
const findEdgeAtPosition = (x, y, node = root.value) => {
if (!node) return null;
if (node.left && isPointNearLine(x, y, node.x, node.y, node.left.x, node.left.y)) {
return [node, node.left];
}
if (node.right && isPointNearLine(x, y, node.x, node.y, node.right.x, node.right.y)) {
return [node, node.right];
}
const leftResult = findEdgeAtPosition(x, y, node.left);
if (leftResult) return leftResult;
return findEdgeAtPosition(x, y, node.right);
};
const isPointNearLine = (x, y, x1, y1, x2, y2, tolerance = 5) => {
const A = x - x1;
const B = y - y1;
const C = x2 - x1;
const D = y2 - y1;
const dot = A * C + B * D;
const lenSq = C * C + D * D;
let param = -1;
if (lenSq !== 0) param = dot / lenSq;
let xx, yy;
if (param < 0) {
xx = x1;
yy = y1;
} else if (param > 1) {
xx = x2;
yy = y2;
} else {
xx = x1 + param * C;
yy = y1 + param * D;
}
const dx = x - xx;
const dy = y - yy;
return Math.sqrt(dx * dx + dy * dy) <= tolerance;
};
const onMouseDown = (event) => {
const rect = canvas.value.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
selectedNode.value = findNodeAtPosition(x, y);
};
const onMouseUp = () => {
if (selectedNode.value && potentialParent.value) {
// Attach the dragged node as a child of the potential parent
if (!potentialParent.value.left) {
potentialParent.value.left = selectedNode.value;
} else if (!potentialParent.value.right) {
potentialParent.value.right = selectedNode.value;
}
layoutTree(root.value);
}
selectedNode.value = null;
potentialParent.value = null;
};
// Ensure canvas is properly initialized in onMounted
onMounted(() => {
nextTick(() => {
canvas.value = document.querySelector('canvas'); // Manually select the canvas
if (canvas.value) {
ctx.value = canvas.value.getContext('2d');
canvas.value.width = window.innerWidth;
canvas.value.height = window.innerHeight - 150; // Adjust for controls height
console.log('Canvas initialized:', canvas.value.width, canvas.value.height);
generateTree();
animate();
} else {
console.error("Canvas is not available");
}
});
});
watch(treeInput, generateTree);
return {
canvas,
treeInput,
generateTree,
onMouseMove, // Add this
onMouseDown, // Add this
onMouseUp, // Add this
};
}
}).mount('#app');
Your “Futuristic Binary Tree Visualizer” is an impressive Vue 3 application leveraging the HTML5 Canvas for dynamic tree rendering and user interactions. It offers functionalities like generating trees from input strings, interactive node dragging, and dynamic layout adjustments. However, upon reviewing the code, there are a few areas that could be enhanced or require attention to ensure smooth functionality and user experience. Below, I’ll provide a comprehensive review, identify potential issues, and suggest improvements or fixes where necessary.
onMouseMove FunctionIn your setup function, you’re returning onMouseMove, but it hasn't been defined anywhere in the code. This will lead to errors when the application tries to reference this method during mouse movements over the canvas.
You need to define the onMouseMove method to handle mouse movements, especially for dragging nodes and updating their positions.
let isDragging = false;
let offsetX = 0;
let offsetY = 0;
const onMouseMove = (event) => {
if (!selectedNode.value) return;
const rect = canvas.value.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
// Update node position with offset
selectedNode.value.x = x - offsetX;
selectedNode.value.y = y - offsetY;
};
Explanation:
isDragging: A flag to determine if a node is being dragged.offsetX & offsetY: To maintain the cursor's relative position to the node during dragging.onMouseMove: Updates the position of the selected node as the mouse moves, creating a dragging effect.Updated onMouseDown and Added onMouseUp:
To support dragging, you’ll also need to update the onMouseDown and onMouseUp methods:
const onMouseDown = (event) => {
const rect = canvas.value.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const node = findNodeAtPosition(x, y);
if (node) {
selectedNode.value = node;
isDragging = true;
offsetX = x - node.x;
offsetY = y - node.y;
} else {
selectedNode.value = null;
}
};
const onMouseUp = () => {
if (isDragging && selectedNode.value && potentialParent.value) {
// Attach the dragged node as a child of the potential parent
if (!potentialParent.value.left) {
potentialParent.value.left = selectedNode.value;
} else if (!potentialParent.value.right) {
potentialParent.value.right = selectedNode.value;
}
layoutTree(root.value);
}
selectedNode.value = null;
potentialParent.value = null;
isDragging = false;
};
Explanation:
onMouseDown: Sets the selectedNode if a node is clicked and initiates dragging by setting isDragging to true.onMouseUp: Finalizes the dragging process, potentially attaching the node to a new parent if applicable, and resets dragging flags.Recursive functions like layoutTree, drawNode, and animateNode can lead to performance degradation, especially with large trees, as they traverse the entire tree on each call.
Implement optimizations to minimize unnecessary computations:
Implementation Example with Iterative Traversal for drawNode:
const drawNodeIterative = () => {
if (!ctx.value || !root.value) return;
ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height);
const stack = [root.value];
while (stack.length) {
const node = stack.pop();
if (!node) continue;
// Draw edges
if (node.left) {
drawEdge(node, node.left);
stack.push(node.left);
}
if (node.right) {
drawEdge(node, node.right);
stack.push(node.right);
}
// Draw node as before...
}
};
Explanation:
The canvas size is set once during onMounted but doesn’t adjust when the browser window is resized, leading to potential layout issues on different screen sizes or orientations.
Add an event listener for the resize event to dynamically adjust the canvas dimensions and re-layout the tree accordingly.
onMounted(() => {
nextTick(() => {
initializeCanvas();
generateTree();
animate();
});
window.addEventListener('resize', initializeCanvas);
});
const initializeCanvas = () => {
if (canvas.value) {
canvas.value.width = window.innerWidth;
canvas.value.height = window.innerHeight - 150; // Adjust for controls height
layoutTree(root.value);
}
};
Explanation:
initializeCanvas: Sets the canvas dimensions and re-layouts the tree.window.addEventListener('resize', initializeCanvas): Ensures the canvas resizes responsively.Don’t forget to remove the event listener when the component is unmounted to prevent memory leaks:
import { onBeforeUnmount } from 'vue';
onBeforeUnmount(() => {
window.removeEventListener('resize', initializeCanvas);
});
While you have mentioned handling the 'Delete' key to remove a selected node, the current implementation lacks the actual key event listener and deletion logic.
Implement a global key event listener to handle node deletions.
const onKeyDown = (event) => {
if (event.key === 'Delete' && selectedNode.value) {
deleteNode(selectedNode.value);
layoutTree(root.value);
selectedNode.value = null;
}
};
const deleteNode = (node) => {
if (!root.value) return;
if (root.value === node) {
root.value = null;
return;
}
const parent = findParent(root.value, node);
if (parent) {
if (parent.left === node) {
parent.left = null;
} else if (parent.right === node) {
parent.right = null;
}
}
};
const findParent = (current, target) => {
if (!current) return null;
if (current.left === target || current.right === target) return current;
return findParent(current.left, target) || findParent(current.right, target);
};
Explanation:
onKeyDown: Listens for the 'Delete' key and removes the selected node.deleteNode: Removes the node from the tree by updating its parent's reference.findParent: Recursively finds the parent of the given node.Registering the Key Event Listener:
Add the event listener in onMounted and remove it in onBeforeUnmount:
onMounted(() => {
// ... existing code
window.addEventListener('keydown', onKeyDown);
});
onBeforeUnmount(() => {
// ... existing code
window.removeEventListener('keydown', onKeyDown);
});
To enable users to drag a node close to another node to make it a child, it would be beneficial to provide visual cues when a node is near a potential parent.
During onMouseMove, detect if the dragged node is near another node and highlight it to indicate a possible attachment.
Modify the onMouseMove function to detect proximity:
const onMouseMove = (event) => {
if (!selectedNode.value) return;
const rect = canvas.value.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
// Update node position with offset
selectedNode.value.x = x - offsetX;
selectedNode.value.y = y - offsetY;
// Detect potential parent
potentialParent.value = findPotentialParent(selectedNode.value);
// Redraw to show highlights
drawTree();
};
const findPotentialParent = (draggedNode) => {
let potential = null;
const distanceThreshold = nodeRadius.value * 2; // Define as per requirement
const traverse = (node) => {
if (!node || node === draggedNode) return;
const distance = Math.sqrt((node.x - draggedNode.x) ** 2 + (node.y - draggedNode.y) ** 2);
if (distance < distanceThreshold) {
potential = node;
}
traverse(node.left);
traverse(node.right);
};
traverse(root.value);
return potential;
};
Explanation:
findPotentialParent: Traverses the tree to find nodes within a certain distance of the dragged node to suggest possible parents.drawNode function already includes logic to highlight potentialParent. Ensure that drawNodeIterative or your draw function utilizes potentialParent.value appropriately.The current layoutTree function uses a simple top-down approach which might lead to overlapping nodes in unbalanced trees.
Implement a more sophisticated tree layout algorithm like the Reingold-Tilford algorithm, which provides a tidy layout for binary trees, minimizing overlap and evenly spacing nodes.
Implementing a complete Reingold-Tilford algorithm is beyond the scope of this response, but here's a simplified approach to enhance the current layout:
const layoutTreeEnhanced = (node, depth = 0, positions = {}, minSpacing = 50) => {
if (!node) return;
if (!positions[depth]) positions[depth] = [];
// Assign X based on the number of nodes at this depth
node.targetX = positions[depth].length * (nodeRadius.value * 2 + minSpacing) + nodeRadius.value * 2;
node.targetY = depth * (nodeRadius.value * 3);
positions[depth].push(node);
layoutTreeEnhanced(node.left, depth + 1, positions, minSpacing);
layoutTreeEnhanced(node.right, depth + 1, positions, minSpacing);
};
Explanation:
positions: Keeps track of nodes at each depth to calculate their horizontal positions.minSpacing: Ensures a minimum distance between nodes to prevent overlaps.Usage:
Replace the existing layoutTree call with layoutTreeEnhanced:
const generateTree = () => {
const values = treeInput.value.split(',').map(val => val.trim());
root.value = buildTree(values);
if (!root.value) {
console.error("Tree could not be built");
return;
}
layoutTreeEnhanced(root.value);
};
The application lacks feedback for invalid inputs or actions, which can be confusing for users.
treeInput to ensure it's in the correct format before generating the tree.Input Validation and Error Message:
const errorMessage = ref('');
const generateTree = () => {
const values = treeInput.value.split(',').map(val => val.trim());
if (!validateInput(values)) {
errorMessage.value = 'Invalid input format. Please enter values like 1,null,2,3';
return;
}
errorMessage.value = '';
root.value = buildTree(values);
if (!root.value) {
errorMessage.value = "Tree could not be built";
return;
}
layoutTreeEnhanced(root.value);
};
const validateInput = (values) => {
// Basic validation: ensure all non-null values are integers
return values.every(val => val === 'null' || !isNaN(parseInt(val)));
};
Displaying Error Message in Template:
Add below the controls:
<div v-if="errorMessage" class="error-message">
{{ errorMessage }}
</div>
Styling the Error Message:
Add in your <style>:
.error-message {
color: #e74c3c;
background-color: rgba(255, 255, 255, 0.1);
padding: 10px 20px;
border-radius: 8px;
margin-bottom: 20px;
max-width: 600px;
text-align: center;
}
Update the return statement to include errorMessage:
return {
canvas,
treeInput,
generateTree,
onMouseMove,
onMouseDown,
onMouseUp,
errorMessage, // Add this
};
The animate function is recursively calling itself via requestAnimationFrame, which is correct. However, there’s no mechanism to stop the animation loop when the component is unmounted, potentially leading to memory leaks.
Store the animation frame ID and cancel it on component unmount.
let animationFrameId;
const animate = () => {
if (root.value) animateNode(root.value);
drawTree();
animationFrameId = requestAnimationFrame(animate);
};
onMounted(() => {
// ... existing code
animate();
});
onBeforeUnmount(() => {
// ... existing code
cancelAnimationFrame(animationFrameId);
});
Combining all the above suggestions, here's how your updated <script> section would look:
By addressing the above points, your binary tree visualizer will not only function more reliably but also offer a richer and more intuitive user experience.
Not yet included in a published release.
<script>
const { createApp, ref, onMounted, onBeforeUnmount, watch, nextTick } = Vue;
class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
this.x = 0;
this.y = 0;
this.targetX = 0;
this.targetY = 0;
}
}
createApp({
setup() {
const canvas = ref(null);
const ctx = ref(null);
const treeInput = ref('1,null,2,null,3,null,4,null,5,null,6');
const root = ref(null);
const selectedNode = ref(null);
const hoveredNode = ref(null);
const hoveredEdge = ref(null);
const potentialParent = ref(null);
const errorMessage = ref('');
const nodeRadius = ref(25);
const animationSpeed = 0.1;
const minNodeDistance = ref(100);
let isDragging = false;
let offsetX = 0;
let offsetY = 0;
let animationFrameId;
const buildTree = (values) => {
if (!values || values.length === 0) return null;
const nodes = values.map(val => val === 'null' ? null : new TreeNode(parseInt(val)));
for (let i = 0; i < nodes.length; i++) {
if (nodes[i] !== null) {
const leftIndex = 2 * i + 1;
const rightIndex = 2 * i + 2;
if (leftIndex < nodes.length) nodes[i].left = nodes[leftIndex];
if (rightIndex < nodes.length) nodes[i].right = nodes[rightIndex];
}
}
return nodes[0];
};
const layoutTreeEnhanced = (node, depth = 0, positions = {}, minSpacing = 50) => {
if (!node) return;
if (!positions[depth]) positions[depth] = [];
// Assign X based on the number of nodes at this depth
node.targetX = positions[depth].length * (nodeRadius.value * 2 + minSpacing) + nodeRadius.value * 2;
node.targetY = depth * (nodeRadius.value * 3);
positions[depth].push(node);
layoutTreeEnhanced(node.left, depth + 1, positions, minSpacing);
layoutTreeEnhanced(node.right, depth + 1, positions, minSpacing);
};
const drawTree = () => {
if (!ctx.value) return;
ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height);
if (root.value) drawNode(root.value);
};
const drawNode = (node) => {
if (!node) return;
// Draw edges
if (node.left) drawEdge(node, node.left);
if (node.right) drawEdge(node, node.right);
// Draw node
ctx.value.beginPath();
ctx.value.arc(node.x, node.y, nodeRadius.value, 0, 2 * Math.PI);
const gradient = ctx.value.createRadialGradient(node.x, node.y, 0, node.x, node.y, nodeRadius.value);
if (node === selectedNode.value) {
gradient.addColorStop(0, '#e74c3c');
gradient.addColorStop(1, '#c0392b');
} else if (node === hoveredNode.value) {
gradient.addColorStop(0, '#3498db');
gradient.addColorStop(1, '#2980b9');
} else {
gradient.addColorStop(0, '#2ecc71');
gradient.addColorStop(1, '#27ae60');
}
ctx.value.fillStyle = gradient;
ctx.value.fill();
ctx.value.strokeStyle = '#fff';
ctx.value.lineWidth = 2;
ctx.value.stroke();
// Draw value
ctx.value.fillStyle = 'white';
ctx.value.font = `bold ${nodeRadius.value * 0.7}px Arial`;
ctx.value.textAlign = 'center';
ctx.value.textBaseline = 'middle';
ctx.value.fillText(node.val, node.x, node.y);
// Draw glow effect for potential parent
if (potentialParent.value === node) {
ctx.value.beginPath();
ctx.value.arc(node.x, node.y, nodeRadius.value + 10, 0, 2 * Math.PI);
ctx.value.strokeStyle = 'rgba(52, 152, 219, 0.5)';
ctx.value.lineWidth = 5;
ctx.value.stroke();
}
drawNode(node.left);
drawNode(node.right);
};
const drawEdge = (parent, child) => {
const dx = child.x - parent.x;
const dy = child.y - parent.y;
const distance = Math.sqrt(dx * dx + dy * dy);
const ratio = (distance - nodeRadius.value) / distance;
const endX = parent.x + dx * ratio;
const endY = parent.y + dy * ratio;
ctx.value.beginPath();
ctx.value.moveTo(parent.x, parent.y);
ctx.value.lineTo(endX, endY);
const gradient = ctx.value.createLinearGradient(parent.x, parent.y, endX, endY);
if (hoveredEdge.value && hoveredEdge.value[0] === parent && hoveredEdge.value[1] === child) {
gradient.addColorStop(0, '#3498db');
gradient.addColorStop(1, '#2980b9');
ctx.value.lineWidth = 4;
} else {
gradient.addColorStop(0, '#95a5a6');
gradient.addColorStop(1, '#7f8c8d');
ctx.value.lineWidth = 2;
}
ctx.value.strokeStyle = gradient;
ctx.value.stroke();
};
const animate = () => {
if (root.value) animateNode(root.value);
drawTree();
animationFrameId = requestAnimationFrame(animate);
};
const animateNode = (node) => {
if (!node) return;
node.x += (node.targetX - node.x) * animationSpeed;
node.y += (node.targetY - node.y) * animationSpeed;
animateNode(node.left);
animateNode(node.right);
};
const generateTree = () => {
const values = treeInput.value.split(',').map(val => val.trim());
if (!validateInput(values)) {
errorMessage.value = 'Invalid input format. Please enter values like 1,null,2,3';
return;
}
errorMessage.value = '';
root.value = buildTree(values);
if (!root.value) {
errorMessage.value = "Tree could not be built";
return;
}
layoutTreeEnhanced(root.value);
};
const validateInput = (values) => {
// Basic validation: ensure all non-null values are integers
return values.every(val => val === 'null' || !isNaN(parseInt(val)));
};
const findNodeAtPosition = (x, y, node = root.value) => {
if (!node) return null;
const distance = Math.sqrt((node.x - x) ** 2 + (node.y - y) ** 2);
if (distance <= nodeRadius.value) return node;
const leftResult = findNodeAtPosition(x, y, node.left);
if (leftResult) return leftResult;
return findNodeAtPosition(x, y, node.right);
};
const findEdgeAtPosition = (x, y, node = root.value) => {
if (!node) return null;
if (node.left && isPointNearLine(x, y, node.x, node.y, node.left.x, node.left.y)) {
return [node, node.left];
}
if (node.right && isPointNearLine(x, y, node.x, node.y, node.right.x, node.right.y)) {
return [node, node.right];
}
const leftResult = findEdgeAtPosition(x, y, node.left);
if (leftResult) return leftResult;
return findEdgeAtPosition(x, y, node.right);
};
const isPointNearLine = (x, y, x1, y1, x2, y2, tolerance = 5) => {
const A = x - x1;
const B = y - y1;
const C = x2 - x1;
const D = y2 - y1;
const dot = A * C + B * D;
const lenSq = C * C + D * D;
let param = -1;
if (lenSq !== 0) param = dot / lenSq;
let xx, yy;
if (param < 0) {
xx = x1;
yy = y1;
} else if (param > 1) {
xx = x2;
yy = y2;
} else {
xx = x1 + param * C;
yy = y1 + param * D;
}
const dx = x - xx;
const dy = y - yy;
return Math.sqrt(dx * dx + dy * dy) <= tolerance;
};
const onMouseDown = (event) => {
const rect = canvas.value.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const node = findNodeAtPosition(x, y);
if (node) {
selectedNode.value = node;
isDragging = true;
offsetX = x - node.x;
offsetY = y - node.y;
} else {
selectedNode.value = null;
}
};
const onMouseUp = () => {
if (isDragging && selectedNode.value && potentialParent.value) {
// Attach the dragged node as a child of the potential parent
if (!potentialParent.value.left) {
potentialParent.value.left = selectedNode.value;
} else if (!potentialParent.value.right) {
potentialParent.value.right = selectedNode.value;
}
layoutTreeEnhanced(root.value);
}
selectedNode.value = null;
potentialParent.value = null;
isDragging = false;
};
const findPotentialParent = (draggedNode) => {
let potential = null;
const distanceThreshold = nodeRadius.value * 2;
const traverse = (node) => {
if (!node || node === draggedNode) return;
const distance = Math.sqrt((node.x - draggedNode.x) ** 2 + (node.y - draggedNode.y) ** 2);
if (distance < distanceThreshold) {
potential = node;
}
traverse(node.left);
traverse(node.right);
};
traverse(root.value);
return potential;
};
const onMouseMove = (event) => {
if (!selectedNode.value || !isDragging) return;
const rect = canvas.value.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
// Update node position with offset
selectedNode.value.x = x - offsetX;
selectedNode.value.y = y - offsetY;
// Detect potential parent
potentialParent.value = findPotentialParent(selectedNode.value);
// Redraw to show highlights
drawTree();
};
const onKeyDown = (event) => {
if (event.key === 'Delete' && selectedNode.value) {
deleteNode(selectedNode.value);
layoutTreeEnhanced(root.value);
selectedNode.value = null;
}
};
const deleteNode = (node) => {
if (!root.value) return;
if (root.value === node) {
root.value = null;
return;
}
const parent = findParent(root.value, node);
if (parent) {
if (parent.left === node) {
parent.left = null;
} else if (parent.right === node) {
parent.right = null;
}
}
};
const findParent = (current, target) => {
if (!current) return null;
if (current.left === target || current.right === target) return current;
return findParent(current.left, target) || findParent(current.right, target);
};
const initializeCanvas = () => {
if (canvas.value) {
canvas.value.width = window.innerWidth;
canvas.value.height = window.innerHeight - 150; // Adjust for controls height
layoutTreeEnhanced(root.value);
}
};
onMounted(() => {
nextTick(() => {
canvas.value = document.querySelector('canvas'); // Manually select the canvas
if (canvas.value) {
ctx.value = canvas.value.getContext('2d');
initializeCanvas();
console.log('Canvas initialized:', canvas.value.width, canvas.value.height);
generateTree();
animate();
} else {
console.error("Canvas is not available");
}
});
window.addEventListener('resize', initializeCanvas);
window.addEventListener('keydown', onKeyDown);
});
onBeforeUnmount(() => {
window.removeEventListener('resize', initializeCanvas);
window.removeEventListener('keydown', onKeyDown);
cancelAnimationFrame(animationFrameId);
});
watch(treeInput, generateTree);
return {
canvas,
treeInput,
generateTree,
onMouseMove,
onMouseDown,
onMouseUp,
errorMessage,
};
}
}).mount('#app');
</script>