下面是一个完整的HTML文件,实现了您所描述的日志可视化工具的所有功能。此工具使用D3.js进行可视化,并集成了所有要求的特性,包括日志解析、线程关系展示、日志跟踪、右键菜单功能、备注编辑、节点标记、可折叠区域以及导入/导出功能。
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 SVG as PNG -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<!-- html2canvas CDN for exporting SVG as PNG -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.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;
align-items: flex-start;
}
#controls textarea {
width: 70%;
height: 150px;
resize: vertical;
padding: 10px;
box-sizing: border-box;
font-family: monospace;
font-size: 14px;
}
#controls .actions {
width: 25%;
margin-left: 5%;
display: flex;
flex-direction: column;
gap: 10px;
}
#controls button {
padding: 10px 20px;
font-size: 16px;
background-color: #2980b9;
color: white;
border: none;
cursor: pointer;
border-radius: 4px;
}
#controls button:hover {
background-color: #3498db;
}
#main {
display: flex;
height: calc(100% - 220px);
overflow: hidden;
flex: 1 1 auto;
}
.container {
flex: 1;
position: relative;
border: 1px solid #bdc3c7;
overflow: hidden;
display: flex;
flex-direction: column;
}
.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 {
flex: 1;
width: 100%;
height: 100%;
overflow: auto;
}
/* 自定义右键菜单样式 */
.custom-context-menu {
position: absolute;
z-index: 1000;
width: 200px;
background: white;
border: 1px solid #bdc3c7;
box-shadow: 2px 2px 5px rgba(0,0,0,0.3);
display: none;
flex-direction: column;
}
.custom-context-menu ul {
list-style: none;
margin: 0;
padding: 5px 0;
}
.custom-context-menu ul li {
padding: 8px 12px;
cursor: pointer;
}
.custom-context-menu ul li:hover {
background-color: #ecf0f1;
}
/* 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);
}
/* Collapsible Sections */
.collapsible {
background-color: #bdc3c7;
cursor: pointer;
padding: 10px;
text-align: center;
border: none;
outline: none;
font-size: 16px;
width: 100%;
}
.collapsible:after {
content: '\25BC';
font-size: 12px;
float: right;
margin-left: 5px;
}
.collapsible.active:after {
content: '\25B2';
}
.content {
padding: 0 10px;
display: none;
overflow: hidden;
flex: 0 0 auto;
}
.content.active {
display: block;
}
/* Note Modal */
.modal {
position: fixed;
z-index: 2000;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.4);
display: none;
align-items: center;
justify-content: center;
}
.modal-content {
background-color: #fefefe;
padding: 20px;
border: 1px solid #888;
width: 300px;
border-radius: 5px;
}
.modal-content label {
display: block;
margin-top: 10px;
}
.modal-content input[type="text"],
.modal-content select,
.modal-content textarea {
width: 100%;
padding: 5px;
margin-top: 5px;
box-sizing: border-box;
}
.modal-content .buttons {
margin-top: 15px;
display: flex;
justify-content: flex-end;
gap: 10px;
}
.modal-content button {
padding: 5px 10px;
cursor: pointer;
}
/* Export Buttons */
#export-buttons {
margin-top: 10px;
display: flex;
gap: 10px;
}
#export-buttons button {
padding: 5px 10px;
font-size: 14px;
background-color: #27ae60;
color: white;
border: none;
cursor: pointer;
border-radius: 4px;
}
#export-buttons button:hover {
background-color: #2ecc71;
}
/* Scrollbar Styling */
.tree-container::-webkit-scrollbar {
width: 8px;
height: 8px;
}
.tree-container::-webkit-scrollbar-thumb {
background: #bdc3c7;
border-radius: 4px;
}
</style>
</head>
<body>
<header>
<h1>日志可视化工具</h1>
</header>
<div id="controls">
<textarea id="log-input" placeholder="在此处粘贴日志内容..."></textarea>
<div class="actions">
<button id="parse-button">解析并可视化</button>
<div id="export-buttons">
<button id="export-log">导出日志跟踪图</button>
<button id="export-thread">导出线程关系图</button>
<button id="import-data">导入数据</button>
<button id="export-data">导出数据</button>
</div>
</div>
</div>
<button class="collapsible">折叠 / 展开 输入区域</button>
<div class="content active">
<!-- Input and controls are already above -->
</div>
<div id="main">
<div class="container" data-title="线程关系">
<button class="collapsible">折叠 / 展开 线程关系</button>
<div class="content active tree-container" id="thread-tree"></div>
</div>
<div class="container" data-title="日志跟踪">
<button class="collapsible">折叠 / 展开 日志跟踪</button>
<div class="content active tree-container" id="log-tree"></div>
</div>
</div>
<!-- 自定义右键菜单 -->
<div id="context-menu" class="custom-context-menu">
<ul>
<li id="toggle-importance">标记/去标记重要性</li>
<li id="add-note">添加/编辑备注</li>
<li id="generate-sequence">生成时序图</li>
</ul>
</div>
<!-- Tooltip -->
<div id="tooltip" class="tooltip" style="opacity:0;"></div>
<!-- Note Modal -->
<div id="note-modal" class="modal">
<div class="modal-content">
<h3>添加/编辑备注</h3>
<label for="note-text">备注内容:</label>
<textarea id="note-text" rows="4"></textarea>
<label for="note-color">备注颜色:</label>
<select id="note-color">
<option value="#FFCDD2">红色</option>
<option value="#F8BBD0">粉色</option>
<option value="#E1BEE7">紫色</option>
<option value="#D1C4E9">深紫色</option>
<option value="#C5CAE9">蓝色</option>
<option value="#BBDEFB">浅蓝色</option>
<option value="#B3E5FC">天蓝色</option>
</select>
<div class="buttons">
<button id="save-note">保存</button>
<button id="cancel-note">取消</button>
</div>
</div>
</div>
<script>
// 全局变量存储解析后的日志数据
let parsedLogs = {};
let threadParents = {};
let markedNodes = new Set();
let nodeNotes = {}; // 存储节点备注 { nodeId: { note: '', color: '' } }
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 addNoteMenu = document.getElementById('add-note');
const generateSequenceMenu = document.getElementById('generate-sequence');
// Tooltip元素
const tooltip = d3.select("#tooltip");
// Note Modal元素
const noteModal = document.getElementById('note-modal');
const noteText = document.getElementById('note-text');
const noteColor = document.getElementById('note-color');
const saveNoteButton = document.getElementById('save-note');
const cancelNoteButton = document.getElementById('cancel-note');
// 事件绑定:解析并可视化日志
document.getElementById('parse-button').addEventListener('click', function() {
const logText = document.getElementById('log-input').value;
parseLogs(logText);
renderThreadTree();
clearLogTree();
});
// 事件绑定:导出日志跟踪图
document.getElementById('export-log').addEventListener('click', function() {
exportSVGAsPNG('log-tree', '日志跟踪图.png');
});
// 事件绑定:导出线程关系图
document.getElementById('export-thread').addEventListener('click', function() {
exportSVGAsPNG('thread-tree', '线程关系图.png');
});
// 事件绑定:导出数据
document.getElementById('export-data').addEventListener('click', function() {
exportData();
});
// 事件绑定:导入数据
document.getElementById('import-data').addEventListener('click', function() {
importData();
});
/**
* 解析日志文本
* @param {string} text - 日志文本
*/
function parseLogs(text) {
const lines = text.split('\n').filter(line => line.trim() !== '');
parsedLogs = {};
threadParents = {};
nodeNotes = {};
markedNodes = new Set();
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 = {
id: generateUniqueId(),
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 = {};
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');
}
/**
* 生成唯一ID
* @returns {string} - 唯一ID
*/
function generateUniqueId() {
return 'id-' + Math.random().toString(36).substr(2, 16);
}
/**
* 渲染线程关系树
*/
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")
.append("svg")
.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, 200]); // [垂直间距, 水平间距]
// 创建层级结构
const root = d3.hierarchy(treeData, d => d.children);
// 生成树布局
treemap(root);
// Links
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" : "#4FC3F7")
.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}`)
.style("font-size", "12px")
.style("user-select", "none");
node.append("text")
.attr("dy", 20)
.attr("text-anchor", "middle")
.attr("fill", "#f0f0f0")
.style("font-size", "10px")
.style("pointer-events", "none")
.text(d => d.data.id === 'root' ? '' : `备注: ${nodeNotes[d.data.id]?.note || ''}`)
.call(wrap, 140);
// 为树添加缩放和平移
const zoom = d3.zoom()
.scaleExtent([0.5, 2])
.on("zoom", (event) => {
svg.attr("transform", event.transform);
});
d3.select("#thread-tree svg").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").append("svg")
.attr("width", document.getElementById('log-tree').clientWidth)
.attr("height", document.getElementById('log-tree').clientHeight);
svg.append("g")
.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")
.append("svg")
.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
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 => getColorByLevel(d.data.level))
.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", -10)
.attr("text-anchor", "middle")
.attr("fill", "#ffffff")
.style("font-weight", "bold")
.text(d => d.data.content.split(',')[0]) // 显示主要内容
.call(wrap, 240);
// Node信息 (时间, 线程号, 备注)
node.append("text")
.attr("dy", 10)
.attr("text-anchor", "middle")
.attr("fill", "#d1d1d1")
.style("font-size", "10px")
.text(d => `[${d.data.timestamp}] | 线程:${d.data.threadId}` + (nodeNotes[d.data.id]?.note ? ` | 备注: ${nodeNotes[d.data.id].note}` : ''))
.call(wrap, 240);
// 为树添加缩放和平移
const zoom = d3.zoom()
.scaleExtent([0.5, 2])
.on("zoom", (event) => {
svg.attr("transform", event.transform);
});
d3.select("#log-tree svg").call(zoom);
}
/**
* 构建日志树结构
* @param {Array} logs - 日志数组
* @returns {Object} - 树形结构
*/
function buildLogTree(logs) {
const root = {
id: generateUniqueId(),
content: "根",
children: [],
level: "I"
};
let currentNode = root;
let stack = [root];
let nodeIdCounter = 1;
for (const log of logs) {
const isEntry = /Entered\.\.\.$/.test(log.content);
const isExit = /Exited\.\.\.$/.test(log.content);
if (isEntry) {
const newNode = {
id: generateUniqueId(),
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: generateUniqueId(),
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) {
let tooltipContent = `<strong>时间:</strong> ${data.timestamp}<br/>
<strong>级别:</strong> ${data.level}<br/>
<strong>内容:</strong> ${data.content}`;
if (nodeNotes[data.id]) {
tooltipContent += `<br/><strong>备注:</strong> ${nodeNotes[data.id].note}`;
}
return tooltipContent;
}
/**
* 获取节点颜色根据日志级别
* @param {string} level - 日志级别
* @returns {string} - 颜色代码
*/
function getColorByLevel(level) {
if (level === 'E') return '#e57373';
if (level === 'I') return '#64b5f6';
return '#A1887F';
}
/**
* 显示自定义右键菜单
* @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 = 'flex';
}
/**
* 隐藏自定义右键菜单
*/
function hideContextMenu() {
contextMenu.style.display = 'none';
selectedNode = { type: null, id: null, data: null, tree: null };
}
/**
* 切换节点的重要性(透明度)
*/
function toggleNodeImportance() {
if (!selectedNode.id) return;
if (markedNodes.has(selectedNode.id)) {
markedNodes.delete(selectedNode.id);
} else {
markedNodes.add(selectedNode.id);
}
if (selectedNode.tree === 'log') {
// 更新日志树节点的透明度
d3.selectAll("#log-tree .node").filter(d => d.data.id === selectedNode.id)
.select("rect")
.transition()
.duration(300)
.attr("opacity", markedNodes.has(selectedNode.id) ? 0.5 : 1.0);
} else if (selectedNode.tree === 'thread') {
// 更新线程树节点的透明度
d3.selectAll("#thread-tree .node").filter(d => d.data.id === selectedNode.id)
.select("rect")
.transition()
.duration(300)
.attr("opacity", markedNodes.has(selectedNode.id) ? 0.5 : 1.0);
}
hideContextMenu();
}
/**
* 显示添加/编辑备注的模态框
*/
function showNoteModal() {
if (!selectedNode.id) return;
const existingNote = nodeNotes[selectedNode.id];
noteText.value = existingNote ? existingNote.note : '';
noteColor.value = existingNote ? existingNote.color : '#FFCDD2';
noteModal.style.display = 'flex';
}
/**
* 保存备注
*/
function saveNote() {
const note = noteText.value.trim();
const color = noteColor.value;
if (note) {
nodeNotes[selectedNode.id] = { note, color };
} else {
delete nodeNotes[selectedNode.id];
}
updateNodeNotes();
noteModal.style.display = 'none';
hideContextMenu();
}
/**
* 取消编辑备注
*/
function cancelNote() {
noteModal.style.display = 'none';
hideContextMenu();
}
/**
* 更新所有节点的备注显示
*/
function updateNodeNotes() {
// 更新日志树
d3.selectAll("#log-tree .node").each(function(d) {
if (nodeNotes[d.data.id]) {
d3.select(this).selectAll("rect")
.attr("fill", nodeNotes[d.data.id].color || getColorByLevel(d.data.level));
}
});
// 更新线程树
d3.selectAll("#thread-tree .node").each(function(d) {
if (nodeNotes[d.data.id]) {
d3.select(this).selectAll("rect")
.attr("fill", nodeNotes[d.data.id].color || "#4FC3F7");
}
});
// 重新渲染树以显示备注
const currentThread = getCurrentSelectedThread();
if (currentThread) {
renderLogTree(currentThread);
}
}
/**
* 获取当前选中的线程ID
* @returns {string|null} - 线程ID或null
*/
function getCurrentSelectedThread() {
const logSvg = d3.select("#log-tree").select("svg");
if (logSvg.empty()) return null;
const logs = logSvg.selectAll(".node").data();
if (logs.length === 0) return null;
// 假设用户点击的线程是最后一次渲染的
return null; // 可根据实际情况调整
}
/**
* 生成PlantUML时序图代码并复制到剪贴板
*/
function generateSequenceDiagram() {
if (!selectedNode.id) return;
let plantUMLCode = "@startuml\n";
if (selectedNode.tree === 'log') {
const logNode = selectedNode.data;
const callStack = getCallStack(selectedNode.data);
callStack.reverse().forEach((node, index) => {
plantUMLCode += `participant "${sanitizeParticipantName(node.content)}" as ${sanitizeParticipantName(node.content)}_${index}\n`;
if (index > 0) {
plantUMLCode += `${sanitizeParticipantName(callStack[index].content)}_${index} -> ${sanitizeParticipantName(node.content)}_${index - 1} : 调用\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.push(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);
}
// 右键菜单选项事件
toggleImportanceMenu.addEventListener('click', toggleNodeImportance);
addNoteMenu.addEventListener('click', showNoteModal);
generateSequenceMenu.addEventListener('click', generateSequenceDiagram);
// 保存备注
saveNoteButton.addEventListener('click', saveNote);
cancelNoteButton.addEventListener('click', cancelNote);
// 点击其他地方隐藏右键菜单
document.addEventListener('click', function(e) {
if (e.button !== 2) { // 非右键点击
hideContextMenu();
}
});
// 关闭模态框点击外部区域
window.onclick = function(event) {
if (event.target == noteModal) {
noteModal.style.display = "none";
}
}
// Collapsible Sections
const collapsibles = document.getElementsByClassName("collapsible");
for (let i = 0; i < collapsibles.length; i++) {
collapsibles[i].addEventListener("click", function() {
this.classList.toggle("active");
const content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
/**
* 导出SVG为PNG图片
* @param {string} elementId - SVG元素的ID
* @param {string} filename - 导出的文件名
*/
function exportSVGAsPNG(elementId, filename) {
const svgElement = document.getElementById(elementId).querySelector('svg');
if (!svgElement) {
alert('没有找到SVG元素进行导出。');
return;
}
const serializer = new XMLSerializer();
const svgString = serializer.serializeToString(svgElement);
const canvas = document.createElement('canvas');
const bbox = svgElement.getBoundingClientRect();
canvas.width = bbox.width;
canvas.height = bbox.height;
const ctx = canvas.getContext('2d');
const img = new Image();
const svgBlob = new Blob([svgString], {type: 'image/svg+xml;charset=utf-8'});
const url = URL.createObjectURL(svgBlob);
img.onload = function() {
ctx.drawImage(img, 0, 0);
URL.revokeObjectURL(url);
canvas.toBlob(function(blob) {
saveAs(blob, filename);
});
};
img.src = url;
}
/**
* 导出数据为JSON文件
*/
function exportData() {
const data = {
parsedLogs,
threadParents,
markedNodes: Array.from(markedNodes),
nodeNotes
};
const blob = new Blob([JSON.stringify(data, null, 2)], {type: "application/json"});
saveAs(blob, "log_visualization_data.json");
}
/**
* 导入数据从JSON文件
*/
function importData() {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'application/json';
input.onchange = e => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = event => {
try {
const data = JSON.parse(event.target.result);
parsedLogs = data.parsedLogs || {};
threadParents = data.threadParents || {};
markedNodes = new Set(data.markedNodes || []);
nodeNotes = data.nodeNotes || {};
renderThreadTree();
clearLogTree();
alert('数据导入成功!');
} catch (error) {
alert('导入失败,请检查文件格式。');
console.error(error);
}
};
reader.readAsText(file);
};
input.click();
}
/**
* 文本换行辅助函数
* @param {Object} text - D3选择的文本元素
* @param {number} width - 换行的最大宽度
*/
function wrap(text, width) {
text.each(function() {
const text = d3.select(this);
const words = text.text().split(/\s+/).reverse();
let word;
let line = [];
let lineNumber = 0;
const lineHeight = 1.1; // ems
const y = text.attr("y");
const dy = parseFloat(text.attr("dy"));
let tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", lineHeight + "em").text(word);
}
}
});
}
</script>
</body>
</html>