html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>日志可视化工具</title>
<!-- D3.js CDN -->
<script src="https://d3js.org/d3.v7.min.js"></script>
<!-- FileSaver.js CDN for exporting -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<!-- jscolor for color picker -->
<script src="https://jscolor.com/releases/2.4.5/jscolor.js"></script>
<!-- 基本样式 -->
<style>
body, html {
margin: 0;
padding: 0;
height: 100%;
font-family: Arial, sans-serif;
overflow: hidden;
display: flex;
flex-direction: column;
}
header {
padding: 10px;
background-color: #2c3e50;
color: white;
text-align: center;
flex: 0 0 auto;
}
#controls {
padding: 10px;
background-color: #ecf0f1;
overflow: auto;
flex: 0 0 auto;
display: flex;
flex-direction: column;
transition: all 0.3s ease;
}
#controls.collapsed {
height: 30px;
}
#controls textarea {
width: 100%;
height: 150px;
resize: vertical;
padding: 10px;
box-sizing: border-box;
font-family: monospace;
font-size: 14px;
transition: opacity 0.3s ease;
}
#controls.collapsed textarea {
height: 0;
padding: 0;
opacity: 0;
}
#controls button {
margin-top: 10px;
padding: 10px 20px;
font-size: 16px;
background-color: #2980b9;
color: white;
border: none;
cursor: pointer;
border-radius: 4px;
transition: background-color 0.3s ease;
}
#controls button:hover {
background-color: #3498db;
}
#main {
display: flex;
height: 100%;
flex: 1 1 auto;
overflow: hidden;
}
.container {
flex: 1;
position: relative;
border: 1px solid #bdc3c7;
overflow: hidden;
display: flex;
flex-direction: column;
transition: all 0.3s ease;
}
.container.collapsed {
width: 0;
flex: 0 0 auto;
}
.container::after {
content: attr(data-title);
position: absolute;
top: 5px;
left: 10px;
background: rgba(255,255,255,0.8);
padding: 2px 5px;
border-radius: 3px;
font-weight: bold;
z-index: 1;
}
.tree-container {
width: 100%;
height: 100%;
}
/* 自定义右键菜单样式 */
.custom-context-menu {
position: absolute;
z-index: 1000;
width: 220px;
background: white;
border: 1px solid #bdc3c7;
box-shadow: 2px 2px 5px rgba(0,0,0,0.3);
display: none;
border-radius: 4px;
overflow: hidden;
}
.custom-context-menu ul {
list-style: none;
margin: 0;
padding: 5px 0;
}
.custom-context-menu ul li {
padding: 8px 12px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
}
.custom-context-menu ul li:hover {
background-color: #ecf0f1;
}
.custom-context-menu ul li input[type="color"] {
border: none;
padding: 0;
margin: 0;
width: 20px;
height: 20px;
cursor: pointer;
}
/* Tooltip样式 */
.tooltip {
position: absolute;
text-align: left;
width: auto;
padding: 10px;
font: 12px sans-serif;
background: rgba(255, 255, 255, 0.9);
border: 1px solid #bdc3c7;
border-radius: 4px;
pointer-events: none;
box-shadow: 2px 2px 5px rgba(0,0,0,0.3);
}
/* 导出和导入按钮 */
#export-import {
margin-top: 10px;
display: flex;
gap: 10px;
}
#export-import button {
flex: 1;
}
/* Collapsible Headers */
.collapse-header {
background-color: #bdc3c7;
padding: 5px 10px;
cursor: pointer;
user-select: none;
display: flex;
align-items: center;
justify-content: space-between;
}
.collapse-header:hover {
background-color: #95a5a6;
}
.collapse-icon {
font-size: 12px;
}
</style>
</head>
<body>
<header>
<h1>日志可视化工具</h1>
</header>
<div id="controls">
<div class="collapse-header" id="toggle-controls">
<span>日志输入与控制</span>
<span class="collapse-icon">▼</span>
</div>
<textarea id="log-input" placeholder="在此处粘贴日志内容..."></textarea>
<button id="parse-button">解析并可视化</button>
<div id="export-import">
<button id="export-button">导出图片</button>
<button id="import-button">导入日志</button>
<input type="file" id="import-file" accept=".txt" style="display: none;">
</div>
</div>
<div id="main">
<div class="container" data-title="线程关系" id="thread-container">
<div class="collapse-header" id="toggle-thread">
<span>线程关系</span>
<span class="collapse-icon">▼</span>
</div>
<svg id="thread-tree" class="tree-container"></svg>
</div>
<div class="container" data-title="日志跟踪" id="log-container">
<div class="collapse-header" id="toggle-log">
<span>日志跟踪</span>
<span class="collapse-icon">▼</span>
</div>
<svg id="log-tree" class="tree-container"></svg>
</div>
</div>
<!-- 自定义右键菜单 -->
<div id="context-menu" class="custom-context-menu">
<ul>
<li id="toggle-importance">标记/去标记重要性</li>
<li id="add-note">添加备注
<input type="text" id="note-input" placeholder="备注内容" style="margin-left: 10px; display: none;">
<div id="color-picker-container" style="margin-left: 10px; display: none;">
<input class="jscolor" id="color-picker" value="ffffff">
</div>
<button id="save-note" style="margin-left: 10px; display: none;">保存</button>
</li>
<li id="generate-sequence">生成时序图</li>
</ul>
</div>
<!-- Tooltip -->
<div id="tooltip" class="tooltip" style="opacity:0;"></div>
<script>
// 全局变量存储解析后的日志数据
let parsedLogs = {};
let threadParents = {};
let markedNodes = new Set();
let nodeNotes = {}; // 存储节点备注和颜色
let selectedNode = {
type: null, // 'thread' 或 'log'
id: null,
data: null,
tree: null
};
// 右键菜单元素
const contextMenu = document.getElementById('context-menu');
const toggleImportanceMenu = document.getElementById('toggle-importance');
const generateSequenceMenu = document.getElementById('generate-sequence');
const addNoteMenu = document.getElementById('add-note');
const noteInput = document.getElementById('note-input');
const colorPickerContainer = document.getElementById('color-picker-container');
const colorPicker = document.getElementById('color-picker');
const saveNoteButton = document.getElementById('save-note');
// Tooltip元素
const tooltip = d3.select("#tooltip");
// 控制区域折叠
document.getElementById('toggle-controls').addEventListener('click', function() {
const controls = document.getElementById('controls');
const icon = this.querySelector('.collapse-icon');
controls.classList.toggle('collapsed');
icon.textContent = controls.classList.contains('collapsed') ? '▲' : '▼';
});
// 线程关系折叠
document.getElementById('toggle-thread').addEventListener('click', function() {
const container = document.getElementById('thread-container');
const icon = this.querySelector('.collapse-icon');
container.classList.toggle('collapsed');
icon.textContent = container.classList.contains('collapsed') ? '▲' : '▼';
});
// 日志跟踪折叠
document.getElementById('toggle-log').addEventListener('click', function() {
const container = document.getElementById('log-container');
const icon = this.querySelector('.collapse-icon');
container.classList.toggle('collapsed');
icon.textContent = container.classList.contains('collapsed') ? '▲' : '▼';
});
// 事件绑定:解析并可视化日志
document.getElementById('parse-button').addEventListener('click', function() {
const logText = document.getElementById('log-input').value;
parseLogs(logText);
renderThreadTree();
clearLogTree();
});
// 导出按钮
document.getElementById('export-button').addEventListener('click', function() {
exportVisualization();
});
// 导入按钮
document.getElementById('import-button').addEventListener('click', function() {
document.getElementById('import-file').click();
});
// 导入文件处理
document.getElementById('import-file').addEventListener('change', function(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
const content = e.target.result;
document.getElementById('log-input').value = content;
document.getElementById('parse-button').click();
};
reader.readAsText(file);
});
/**
* 解析日志文本
* @param {string} text - 日志文本
*/
function parseLogs(text) {
const lines = text.split('\n').filter(line => line.trim() !== '');
parsedLogs = {};
threadParents = {};
markedNodes.clear();
nodeNotes = {};
const logEntries = [];
const regex = /^(I|E)\d{3}:(\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})\((\d+)\|(\d+)\)Sum\.Rpt: (.+)$/;
for (const line of lines) {
const match = line.match(regex);
if (match) {
const [_, level, timestamp, processId, threadId, content] = match;
const log = { level, timestamp, processId, threadId, content, raw: line };
logEntries.push(log);
if (!parsedLogs[threadId]) {
parsedLogs[threadId] = [];
}
parsedLogs[threadId].push(log);
}
}
// 处理线程关系
inferThreadRelationships(logEntries);
}
/**
* 推断线程之间的关系
* 简化假设:一个线程的启动时间在另一个线程的启动时间之后,则视为子线程
* @param {Array} logEntries - 所有日志条目
*/
function inferThreadRelationships(logEntries) {
// 获取每个线程的最早时间
const threadStartTimes = {};
for (const threadId in parsedLogs) {
const firstLog = parsedLogs[threadId][0];
// 假设日期为10-26,年份为2023
const date = new Date(`2023-10-26T${convertTimestamp(firstLog.timestamp)}Z`);
threadStartTimes[threadId] = date;
}
// 排序线程按开始时间
const sortedThreads = Object.keys(threadStartTimes).sort((a, b) => threadStartTimes[a] - threadStartTimes[b]);
if (sortedThreads.length === 0) return;
// 使用虚拟根节点
threadParents['root'] = null; // 虚拟根
// 第一线程作为根线程的子线程
for (let i = 0; i < sortedThreads.length; i++) {
const childThread = sortedThreads[i];
if (i === 0) {
threadParents[childThread] = 'root';
} else {
// 根据启动时间找到最近的一个父线程
let parentThread = 'root';
for (let j = i - 1; j >= 0; j--) {
const potentialParent = sortedThreads[j];
if (threadStartTimes[potentialParent] < threadStartTimes[childThread]) {
parentThread = potentialParent;
break;
}
}
threadParents[childThread] = parentThread;
}
}
}
/**
* 转换时间戳为ISO格式
* @param {string} timestamp - 原始时间戳(MM-DD HH:MM:SS.mmm)
* @returns {string} - 转换后的时间戳(HH:MM:SS.mmm)
*/
function convertTimestamp(timestamp) {
return timestamp.replace(' ', 'T');
}
/**
* 渲染线程关系树
*/
function renderThreadTree() {
// 清除旧的SVG
d3.select("#thread-tree").selectAll("*").remove();
// 构建树形结构数据,包括虚拟根
const treeData = buildThreadTree('root', threadParents);
const margin = { top: 20, right: 200, bottom: 20, left: 200 },
width = document.getElementById('thread-tree').clientWidth - margin.left - margin.right,
height = document.getElementById('thread-tree').clientHeight - margin.top - margin.bottom;
const svg = d3.select("#thread-tree")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// 创建树布局,使用固定的节点大小
const treemap = d3.tree()
.nodeSize([100, 300]); // [垂直间距, 水平间距]
// 创建层级结构
const root = d3.hierarchy(treeData, d => d.children);
// 生成树布局
treemap(root);
// Links
const link = svg.selectAll(".link")
.data(root.links())
.enter().append("path")
.attr("class", "link")
.attr("d", d3.linkHorizontal()
.x(d => d.y)
.y(d => d.x))
.attr("fill", "none")
.attr("stroke", "#ccc")
.attr("stroke-width", 2);
// Nodes
const node = svg.selectAll(".node")
.data(root.descendants())
.enter().append("g")
.attr("class", "node")
.attr("transform", d => `translate(${d.y},${d.x})`)
.on("click", (event, d) => {
if (d.data.id !== 'root') { // 排除虚拟根
const threadId = d.data.id;
renderLogTree(threadId);
}
})
.on("contextmenu", (event, d) => {
event.preventDefault();
if (d.data.id !== 'root') { // 排除虚拟根
selectedNode = { type: 'thread', id: d.data.id, data: d.data, tree: 'thread' };
showContextMenu(event.pageX, event.pageY);
}
});
// Node rectangles
node.append("rect")
.attr("width", 150)
.attr("height", 40)
.attr("x", -75)
.attr("y", -20)
.attr("rx", 5)
.attr("ry", 5)
.attr("fill", d => d.data.id === 'root' ? "#ffffff00" : getNodeColor(d))
.attr("stroke", d => d.data.id === 'root' ? "none" : "#0288D1")
.attr("stroke-width", 2)
.attr("opacity", d => markedNodes.has(d.data.id) ? 0.5 : 1.0);
// Node labels
node.append("text")
.attr("dy", 5)
.attr("text-anchor", "middle")
.attr("fill", "#ffffff")
.style("pointer-events", "none")
.text(d => d.data.id === 'root' ? '' : `线程 ${d.data.id}`);
// 附加备注
node.append("text")
.attr("dy", 20)
.attr("text-anchor", "middle")
.attr("fill", "#d1d1d1")
.style("font-size", "10px")
.text(d => nodeNotes[d.data.id]?.note || '');
// 为树添加缩放和平移
const zoom = d3.zoom()
.scaleExtent([0.5, 2])
.on("zoom", (event) => {
svg.attr("transform", event.transform);
});
d3.select("#thread-tree").call(zoom);
}
/**
* 构建线程树结构,包括虚拟根
* @param {string} rootId - 虚拟根ID
* @param {Object} parents - 线程父子关系
* @returns {Object} - 树形结构
*/
function buildThreadTree(rootId, parents) {
const node = { id: rootId, children: [] };
for (const child in parents) {
if (parents[child] === rootId && child !== 'root') {
node.children.push(buildThreadTree(child, parents));
}
}
return node;
}
/**
* 清除日志树
*/
function clearLogTree() {
d3.select("#log-tree").selectAll("*").remove();
const svg = d3.select("#log-tree");
svg.append("text")
.attr("x", "50%")
.attr("y", "50%")
.attr("text-anchor", "middle")
.attr("fill", "#7f8c8d")
.text("请选择左侧的线程以查看日志");
}
/**
* 渲染指定线程的日志树
* @param {string} threadId - 线程ID
*/
function renderLogTree(threadId) {
const logs = parsedLogs[threadId];
if (!logs) {
alert('没有找到该线程的日志。');
return;
}
// 构建层级结构
const treeData = buildLogTree(logs);
// 清除旧的SVG
d3.select("#log-tree").selectAll("*").remove();
const margin = { top: 20, right: 200, bottom: 20, left: 200 },
width = document.getElementById('log-tree').clientWidth - margin.left - margin.right,
height = document.getElementById('log-tree').clientHeight - margin.top - margin.bottom;
const svg = d3.select("#log-tree")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// 创建树布局,使用固定的节点大小
const treemap = d3.tree()
.nodeSize([80, 400]); // [垂直间距, 水平间距]
// 创建层级结构
const root = d3.hierarchy(treeData, d => d.children);
// 生成树布局
treemap(root);
// Links
const link = svg.selectAll(".link")
.data(root.links())
.enter().append("path")
.attr("class", "link")
.attr("d", d3.linkHorizontal()
.x(d => d.y)
.y(d => d.x))
.attr("fill", "none")
.attr("stroke", "#ccc")
.attr("stroke-width", 2);
// Nodes
const node = svg.selectAll(".node")
.data(root.descendants())
.enter().append("g")
.attr("class", "node")
.attr("transform", d => `translate(${d.y},${d.x})`)
.on("contextmenu", (event, d) => {
event.preventDefault();
selectedNode = { type: 'log', id: d.data.id, data: d.data, tree: 'log' };
showContextMenu(event.pageX, event.pageY);
})
.on("mouseover", (event, d) => {
tooltip.transition().duration(200).style("opacity", .9);
tooltip.html(formatTooltip(d.data))
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 28) + "px");
})
.on("mouseout", () => {
tooltip.transition().duration(500).style("opacity", 0);
});
// Node rectangles
node.append("rect")
.attr("width", 250)
.attr("height", 60)
.attr("x", -125)
.attr("y", -30)
.attr("rx", 5)
.attr("ry", 5)
.attr("fill", d => getNodeColor(d))
.attr("stroke", "#424242")
.attr("stroke-width", 1)
.attr("opacity", d => markedNodes.has(d.data.id) ? 0.5 : 1.0);
// Node主要内容
node.append("text")
.attr("dy", -5)
.attr("text-anchor", "middle")
.attr("fill", "#ffffff")
.style("font-weight", "bold")
.text(d => truncateText(d.data.content, 40));
// 节点时间和线程信息
node.append("text")
.attr("dy", 15)
.attr("text-anchor", "middle")
.attr("fill", "#d1d1d1")
.style("font-size", "10px")
.text(d => `[${d.data.timestamp}] | 线程:${d.data.threadId}`);
// 节点备注
node.append("text")
.attr("dy", 30)
.attr("text-anchor", "middle")
.attr("fill", node => nodeNotes[d.data.id]?.color || "#d1d1d1")
.style("font-size", "10px")
.text(d => nodeNotes[d.data.id]?.note || '');
// 为树添加缩放和平移
const zoom = d3.zoom()
.scaleExtent([0.5, 2])
.on("zoom", (event) => {
svg.attr("transform", event.transform);
});
d3.select("#log-tree").call(zoom);
}
/**
* 构建日志树结构
* @param {Array} logs - 日志数组
* @returns {Object} - 树形结构
*/
function buildLogTree(logs) {
const root = { id: 0, content: "根", children: [], level: "I" };
let currentNode = root;
let stack = [root];
let nodeId = 1;
for (const log of logs) {
const isEntry = /Entered\.\.\.$/.test(log.content);
const isExit = /Exited\.\.\.$/.test(log.content);
if (isEntry) {
const newNode = {
id: nodeId++,
content: log.content.replace(/ Entered\.\.\.$/, ''),
timestamp: log.timestamp,
threadId: log.threadId,
level: log.level,
children: []
};
currentNode.children.push(newNode);
stack.push(newNode);
currentNode = newNode;
} else if (isExit) {
if (stack.length > 1) {
stack.pop();
currentNode = stack[stack.length - 1];
}
} else {
const newNode = {
id: nodeId++,
content: log.content,
timestamp: log.timestamp,
threadId: log.threadId,
level: log.level,
children: []
};
currentNode.children.push(newNode);
}
}
return root;
}
/**
* 格式化Tooltip内容
* @param {Object} data - 节点数据
* @returns {string} - Tooltip的HTML内容
*/
function formatTooltip(data) {
return `<strong>时间:</strong> ${data.timestamp}<br/>
<strong>级别:</strong> ${data.level}<br/>
<strong>内容:</strong> ${data.content}`;
}
/**
* 获取节点颜色根据日志级别和备注
* @param {Object} d - 节点数据
* @returns {string} - 颜色代码
*/
function getNodeColor(d) {
if (nodeNotes[d.data.id]?.color) {
return `#${nodeNotes[d.data.id].color}`;
}
if (d.data.level === 'E') return '#e57373';
if (d.data.level === 'I') return '#64b5f6';
return '#A1887F';
}
/**
* 截断文本并添加省略号
* @param {string} text - 原始文本
* @param {number} maxLength - 最大长度
* @returns {string} - 截断后的文本
*/
function truncateText(text, maxLength) {
if (text.length <= maxLength) return text;
return text.substring(0, maxLength) + '...';
}
/**
* 显示自定义右键菜单
* @param {number} x - 鼠标点击的X坐标
* @param {number} y - 鼠标点击的Y坐标
*/
function showContextMenu(x, y) {
contextMenu.style.left = `${x}px`;
contextMenu.style.top = `${y}px`;
contextMenu.style.display = 'block';
// Reset note inputs
noteInput.style.display = 'none';
colorPickerContainer.style.display = 'none';
saveNoteButton.style.display = 'none';
}
/**
* 隐藏自定义右键菜单
*/
function hideContextMenu() {
contextMenu.style.display = 'none';
selectedNode = { type: null, id: null, data: null, tree: null };
// Reset note inputs
noteInput.value = '';
noteInput.style.display = 'none';
colorPickerContainer.style.display = 'none';
saveNoteButton.style.display = 'none';
}
/**
* 切换节点的重要性(透明度)
*/
function toggleNodeImportance() {
if (!selectedNode.id) return;
if (markedNodes.has(selectedNode.id)) {
markedNodes.delete(selectedNode.id);
} else {
markedNodes.add(selectedNode.id);
}
updateNodeOpacity(selectedNode);
hideContextMenu();
}
/**
* 更新节点的透明度
* @param {Object} nodeInfo - 选中的节点信息
*/
function updateNodeOpacity(nodeInfo) {
const selector = nodeInfo.tree === 'log' ? "#log-tree .node" : "#thread-tree .node";
d3.selectAll(`${selector}`)
.filter(d => d.data.id === nodeInfo.id)
.select("rect")
.transition()
.duration(300)
.attr("opacity", markedNodes.has(nodeInfo.id) ? 0.5 : 1.0);
}
/**
* 生成PlantUML时序图代码并复制到剪贴板
*/
function generateSequenceDiagram() {
if (!selectedNode.id) return;
let plantUMLCode = "@startuml\n";
if (selectedNode.tree === 'log') {
const logNode = selectedNode.data;
const callStack = getCallStack(logNode);
// Create participants
callStack.forEach((node, index) => {
plantUMLCode += `participant ${sanitizeParticipantName(node.content)} as "${truncateText(node.content, 10)}"\n`;
});
// Create interactions
for (let i = 1; i < callStack.length; i++) {
plantUMLCode += `${sanitizeParticipantName(callStack[i-1].content)} -> ${sanitizeParticipantName(callStack[i].content)} : 调用\n`;
}
plantUMLCode += "@enduml";
// 复制到剪贴板
copyToClipboard(plantUMLCode);
alert('PlantUML时序图代码已复制到剪贴板。');
} else if (selectedNode.tree === 'thread') {
// 线程级别的时序图生成(可根据需求扩展)
alert('线程级别的时序图生成尚未实现。');
}
hideContextMenu();
}
/**
* 获取调用栈
* @param {Object} node - 当前节点数据
* @returns {Array} - 调用栈数组
*/
function getCallStack(node) {
const stack = [];
let current = node;
while (current.parent) {
stack.unshift(current);
current = current.parent.data;
}
return stack;
}
/**
* 清理和格式化参与者名称
* @param {string} name - 原始名称
* @returns {string} - 清理后的名称
*/
function sanitizeParticipantName(name) {
return name.replace(/[^a-zA-Z0-9_\-]/g, '_');
}
/**
* 复制文本到剪贴板
* @param {string} text - 要复制的文本
*/
function copyToClipboard(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand('copy');
} catch (err) {
console.error('复制失败', err);
}
document.body.removeChild(textarea);
}
/**
* 导出可视化为图片
*/
function exportVisualization() {
const threadSVG = document.getElementById('thread-tree');
const logSVG = document.getElementById('log-tree');
const serializeSVG = (svg) => {
const serializer = new XMLSerializer();
let source = serializer.serializeToString(svg);
if(!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){
source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
}
source = '<?xml version="1.0" standalone="no"?>\r\n' + source;
return source;
};
const svgThreads = serializeSVG(threadSVG);
const svgLogs = serializeSVG(logSVG);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const imgThreads = new Image();
const imgLogs = new Image();
const svgBlobThreads = new Blob([svgThreads], {type: 'image/svg+xml;charset=utf-8'});
const urlThreads = URL.createObjectURL(svgBlobThreads);
imgThreads.src = urlThreads;
const svgBlobLogs = new Blob([svgLogs], {type: 'image/svg+xml;charset=utf-8'});
const urlLogs = URL.createObjectURL(svgBlobLogs);
imgLogs.src = urlLogs;
imgThreads.onload = () => {
canvas.width = imgThreads.width + imgLogs.width;
canvas.height = Math.max(imgThreads.height, imgLogs.height);
ctx.drawImage(imgThreads, 0, 0);
imgLogs.onload = () => {
ctx.drawImage(imgLogs, imgThreads.width + 20, 0); // 20px padding
URL.revokeObjectURL(urlThreads);
URL.revokeObjectURL(urlLogs);
canvas.toBlob(function(blob) {
saveAs(blob, "visualization.png");
});
};
};
}
// 右键菜单选项事件
toggleImportanceMenu.addEventListener('click', toggleNodeImportance);
generateSequenceMenu.addEventListener('click', generateSequenceDiagram);
addNoteMenu.addEventListener('click', function() {
noteInput.style.display = 'inline-block';
colorPickerContainer.style.display = 'inline-block';
saveNoteButton.style.display = 'inline-block';
});
saveNoteButton.addEventListener('click', function() {
const note = noteInput.value.trim();
const color = colorPicker.value.slice(1); // Remove '#'
if (note === '') {
alert('备注内容不能为空。');
return;
}
nodeNotes[selectedNode.id] = { note, color };
updateNodeNoteDisplay(selectedNode);
hideContextMenu();
});
/**
* 更新节点备注显示
* @param {Object} nodeInfo - 选中的节点信息
*/
function updateNodeNoteDisplay(nodeInfo) {
const selector = nodeInfo.tree === 'log' ? "#log-tree .node" : "#thread-tree .node";
d3.selectAll(`${selector}`)
.filter(d => d.data.id === nodeInfo.id)
.select("text:last-child")
.text(d => nodeNotes[d.data.id]?.note || '')
.attr("fill", d => nodeNotes[d.data.id]?.color ? `#${nodeNotes[d.data.id].color}` : "#d1d1d1");
}
// 点击其他地方隐藏右键菜单
document.addEventListener('click', function(e) {
if (e.button !== 2) { // 非右键点击
hideContextMenu();
}
});
// 防止右键菜单在窗口外被截断
window.addEventListener('resize', hideContextMenu);
</script>
</body>
</html>