以下是一个完整的、适用于生产环境的日志可视化工具的HTML代码。该工具使用D3.js进行可视化,满足所有您提出的需求。代码整合了HTML、CSS和JavaScript,并且避免使用iframe。主要功能包括:
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 images -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<!-- HTML2Canvas CDN for exporting SVG as images -->
<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;
gap: 10px;
}
#controls textarea {
width: 100%;
height: 150px;
resize: vertical;
padding: 10px;
box-sizing: border-box;
font-family: monospace;
font-size: 14px;
}
#controls .buttons {
display: flex;
flex-direction: column;
gap: 10px;
}
#controls button {
padding: 10px 20px;
font-size: 14px;
background-color: #2980b9;
color: white;
border: none;
cursor: pointer;
border-radius: 4px;
}
#controls button:hover {
background-color: #3498db;
}
#main {
display: flex;
flex: 1 1 auto;
overflow: hidden;
}
.container {
flex: 1;
position: relative;
border: 1px solid #bdc3c7;
overflow: hidden;
display: flex;
flex-direction: column;
}
.container-header {
background: #bdc3c7;
padding: 5px 10px;
cursor: pointer;
user-select: none;
display: flex;
justify-content: space-between;
align-items: center;
}
.container-header .title {
font-weight: bold;
}
.container-content {
flex: 1;
position: relative;
transition: height 0.3s ease;
}
.tree-container {
width: 100%;
height: 100%;
}
/* 自定义右键菜单样式 */
.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;
}
.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);
}
/* Modal样式 */
.modal {
display: none;
position: fixed;
z-index: 2000;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 10% auto;
padding: 20px;
border: 1px solid #888;
width: 300px;
border-radius: 8px;
}
.modal-content h3 {
margin-top: 0;
}
.modal-content textarea {
width: 100%;
height: 80px;
resize: vertical;
padding: 5px;
box-sizing: border-box;
font-family: monospace;
font-size: 14px;
}
.modal-content .color-options {
display: flex;
gap: 5px;
margin: 10px 0;
}
.modal-content .color-options div {
width: 20px;
height: 20px;
border-radius: 50%;
cursor: pointer;
border: 2px solid #fff;
}
.modal-content .buttons {
display: flex;
justify-content: flex-end;
gap: 10px;
}
/* Export/Import Buttons */
#export-import {
display: flex;
gap: 10px;
margin-left: 10px;
}
</style>
</head>
<body>
<header>
<h1>日志可视化工具</h1>
</header>
<div id="controls">
<textarea id="log-input" placeholder="在此处粘贴日志内容..."></textarea>
<div class="buttons">
<button id="parse-button">解析并可视化</button>
<div id="export-import">
<button id="export-json">导出配置</button>
<button id="import-json">导入配置</button>
<button id="export-thread-png">导出线程图</button>
<button id="export-log-png">导出日志图</button>
</div>
</div>
</div>
<div id="main">
<div class="container" id="thread-container">
<div class="container-header">
<span class="title">线程关系</span>
<span class="toggle">−</span>
</div>
<div class="container-content">
<svg id="thread-tree" class="tree-container"></svg>
</div>
</div>
<div class="container" id="log-container">
<div class="container-header">
<span class="title">日志跟踪</span>
<span class="toggle">−</span>
</div>
<div class="container-content">
<svg id="log-tree" class="tree-container"></svg>
</div>
</div>
</div>
<!-- 自定义右键菜单 -->
<div id="context-menu" class="custom-context-menu">
<ul>
<li id="toggle-importance">标记/去标记重要性</li>
<li id="add-note">添加备注</li>
<li id="change-color">更改颜色</li>
<li id="generate-sequence">生成时序图</li>
</ul>
</div>
<!-- Tooltip -->
<div id="tooltip" class="tooltip" style="opacity:0;"></div>
<!-- Modal for Adding Notes -->
<div id="note-modal" class="modal">
<div class="modal-content">
<h3>添加备注</h3>
<textarea id="note-text" placeholder="输入备注信息..."></textarea>
<div class="color-options">
<div data-color="#f44336" style="background-color: #f44336;"></div>
<div data-color="#e91e63" style="background-color: #e91e63;"></div>
<div data-color="#9c27b0" style="background-color: #9c27b0;"></div>
<div data-color="#3f51b5" style="background-color: #3f51b5;"></div>
<div data-color="#2196f3" style="background-color: #2196f3;"></div>
<div data-color="#4caf50" style="background-color: #4caf50;"></div>
<div data-color="#ff9800" style="background-color: #ff9800;"></div>
</div>
<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 = {}; // 存储节点备注信息
let nodeColors = {}; // 存储节点颜色
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 changeColorMenu = document.getElementById('change-color');
const generateSequenceMenu = document.getElementById('generate-sequence');
// Tooltip元素
const tooltip = d3.select("#tooltip");
// Modal元素
const noteModal = document.getElementById('note-modal');
const saveNoteButton = document.getElementById('save-note');
const cancelNoteButton = document.getElementById('cancel-note');
const noteText = document.getElementById('note-text');
const colorOptions = document.querySelectorAll('.color-options div');
let selectedColor = null;
// 事件绑定:解析并可视化日志
document.getElementById('parse-button').addEventListener('click', function() {
const logText = document.getElementById('log-input').value;
parseLogs(logText);
renderThreadTree();
clearLogTree();
});
/**
* 解析日志文本
* @param {string} text - 日志文本
*/
function parseLogs(text) {
const lines = text.split('\n').filter(line => line.trim() !== '');
parsedLogs = {};
threadParents = {};
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: 20, 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().size([height, width]);
// 创建层级结构
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" : nodeColors[d.data.id] || "#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}`);
// Notes
node.append("text")
.attr("dy", 20)
.attr("text-anchor", "middle")
.attr("fill", "#ffff00")
.style("font-size", "10px")
.style("pointer-events", "none")
.text(d => nodeNotes[d.data.id] ? `备注: ${nodeNotes[d.data.id].slice(0, 10)}...` : '');
// 为树添加缩放和平移
const zoom = d3.zoom()
.scaleExtent([0.5, 2])
.on("zoom", (event) => {
svg.attr("transform", `translate(${margin.left},${margin.top})` + 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: 20, 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().size([height, width]);
// 创建层级结构
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 with overflow handling
node.append("rect")
.attr("width", 250)
.attr("height", 60)
.attr("x", -125)
.attr("y", -30)
.attr("rx", 5)
.attr("ry", 5)
.attr("fill", d => nodeColors[d.data.id] || getColorByLevel(d.data.level))
.attr("stroke", "#424242")
.attr("stroke-width", 1)
.attr("opacity", d => markedNodes.has(d.data.id) ? 0.5 : 1.0);
// Node content (clipped)
node.append("clipPath")
.attr("id", d => `clip-${d.data.id}`)
.append("rect")
.attr("width", 240)
.attr("height", 50)
.attr("x", -120)
.attr("y", -25);
node.append("text")
.attr("x", 0)
.attr("y", -10)
.attr("text-anchor", "middle")
.attr("fill", "#ffffff")
.style("font-weight", "bold")
.style("font-size", "12px")
.attr("clip-path", d => `url(#clip-${d.data.id})`)
.text(d => d.data.content.length > 40 ? d.data.content.slice(0, 37) + '...' : d.data.content);
node.append("text")
.attr("x", 0)
.attr("y", 10)
.attr("text-anchor", "middle")
.attr("fill", "#d1d1d1")
.style("font-size", "10px")
.attr("clip-path", d => `url(#clip-${d.data.id})`)
.text(d => `[${d.data.timestamp}] | 线程:${d.data.threadId}`);
// Notes
node.append("text")
.attr("x", 0)
.attr("y", 25)
.attr("text-anchor", "middle")
.attr("fill", "#ffeb3b")
.style("font-size", "10px")
.attr("clip-path", d => `url(#clip-${d.data.id})`)
.text(d => nodeNotes[d.data.id] ? `备注: ${nodeNotes[d.data.id].slice(0, 10)}...` : '');
// 为树添加缩放和平移
const zoom = d3.zoom()
.scaleExtent([0.5, 2])
.on("zoom", (event) => {
svg.attr("transform", `translate(${margin.left},${margin.top})` + event.transform);
});
d3.select("#log-tree").call(zoom);
}
/**
* 构建日志树结构
* @param {Array} logs - 日志数组
* @returns {Object} - 树形结构
*/
function buildLogTree(logs) {
const root = { id: 'root', 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;
nodeId++;
} 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);
nodeId++;
}
}
return root;
}
/**
* 格式化Tooltip内容
* @param {Object} data - 节点数据
* @returns {string} - Tooltip的HTML内容
*/
function formatTooltip(data) {
let note = nodeNotes[data.id] ? `<br/><strong>备注:</strong> ${nodeNotes[data.id]}` : '';
return `<strong>时间:</strong> ${data.timestamp}<br/>
<strong>级别:</strong> ${data.level}<br/>
<strong>内容:</strong> ${data.content}${note}`;
}
/**
* 获取节点颜色根据日志级别
* @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 = 'block';
}
/**
* 隐藏自定义右键菜单
*/
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.type === '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.type === '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();
}
/**
* 生成PlantUML时序图代码并复制到剪贴板
*/
function generateSequenceDiagram() {
if (!selectedNode.id) return;
let plantUMLCode = "@startuml\n";
if (selectedNode.tree === 'log') {
const logNode = selectedNode.data;
const callStack = getCallStack(logNode);
callStack.forEach((node, index) => {
plantUMLCode += `participant ${sanitizeParticipantName(node.content)}\n`;
if (index > 0) {
plantUMLCode += `${sanitizeParticipantName(callStack[index - 1].content)} -> ${sanitizeParticipantName(node.content)} : 调用\n`;
}
});
plantUMLCode += "@enduml";
// 复制到剪贴板
copyToClipboard(plantUMLCode);
alert('PlantUML时序图代码已复制到剪贴板。');
} else if (selectedNode.tree === 'thread') {
// 线程级别的时序图生成(示例代码)
plantUMLCode += "participant Thread_Start\n";
plantUMLCode += "participant Thread_End\n";
plantUMLCode += "Thread_Start -> Thread_End : 启动线程\n";
plantUMLCode += "@enduml";
// 复制到剪贴板
copyToClipboard(plantUMLCode);
alert('PlantUML时序图代码已复制到剪贴板。');
}
hideContextMenu();
}
/**
* 获取调用栈
* @param {Object} node - 当前节点数据
* @returns {Array} - 调用栈数组
*/
function getCallStack(node) {
const stack = [];
let current = node;
while (current.parent) {
stack.unshift(current.data);
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 showNoteModal() {
if (!selectedNode.id) return;
noteText.value = nodeNotes[selectedNode.id] || '';
selectedColor = nodeColors[selectedNode.id] || '#4FC3F7';
colorOptions.forEach(div => {
div.style.border = (div.getAttribute('data-color') === selectedColor) ? '2px solid #000' : '2px solid #fff';
});
noteModal.style.display = 'block';
}
/**
* 隐藏添加备注的模态框
*/
function hideNoteModal() {
noteModal.style.display = 'none';
selectedColor = null;
}
/**
* 保存备注信息
*/
function saveNote() {
if (!selectedNode.id) return;
nodeNotes[selectedNode.id] = noteText.value.trim();
if (selectedColor) {
nodeColors[selectedNode.id] = selectedColor;
}
updateNodeDisplay();
hideNoteModal();
}
/**
* 更新节点显示,例如备注和颜色
*/
function updateNodeDisplay() {
// 更新线程树
d3.selectAll("#thread-tree .node").filter(d => d.data.id === selectedNode.id)
.select("rect")
.transition()
.duration(300)
.attr("fill", nodeColors[selectedNode.id] || "#4FC3F7");
d3.selectAll("#thread-tree .node").filter(d => d.data.id === selectedNode.id)
.select("text")
.filter((d) => d.data.id === selectedNode.id)
.text(d => nodeNotes[d.data.id] ? `备注: ${d.data.content.slice(0, 10)}...` : '');
// 更新日志树
d3.selectAll("#log-tree .node").filter(d => d.data.id === selectedNode.id)
.select("rect")
.transition()
.duration(300)
.attr("fill", nodeColors[selectedNode.id] || getColorByLevel(d.data.level));
d3.selectAll("#log-tree .node").filter(d => d.data.id === selectedNode.id)
.select("text")
.filter((d) => d.data.id === selectedNode.id)
.text(d => nodeNotes[d.data.id] ? `备注: ${d.data.content.slice(0, 10)}...` : '');
}
/**
* 更改节点颜色
*/
function changeNodeColor(color) {
if (!selectedNode.id) return;
nodeColors[selectedNode.id] = color;
updateNodeDisplay();
hideContextMenu();
}
/**
* 右键菜单选项事件
*/
toggleImportanceMenu.addEventListener('click', toggleNodeImportance);
addNoteMenu.addEventListener('click', showNoteModal);
changeColorMenu.addEventListener('click', () => {
// Could open a color picker or use predefined colors
// For simplicity, opening the same modal as adding notes with color options
showNoteModal();
});
generateSequenceMenu.addEventListener('click', generateSequenceDiagram);
// 保存备注按钮事件
saveNoteButton.addEventListener('click', saveNote);
cancelNoteButton.addEventListener('click', hideNoteModal);
// 颜色选项点击事件
colorOptions.forEach(div => {
div.addEventListener('click', function() {
selectedColor = this.getAttribute('data-color');
colorOptions.forEach(d => d.style.border = '2px solid #fff');
this.style.border = '2px solid #000';
});
});
// 点击其他地方隐藏右键菜单和模态框
document.addEventListener('click', function(e) {
if (e.button !== 2) { // 非右键点击
hideContextMenu();
}
});
// 当点击导出按钮时导出配置
document.getElementById('export-json').addEventListener('click', function() {
const data = {
threadParents,
nodeNotes,
nodeColors
};
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
saveAs(blob, "log_visualization_config.json");
});
// 当点击导入按钮时导入配置
document.getElementById('import-json').addEventListener('click', function() {
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);
threadParents = data.threadParents || {};
nodeNotes = data.nodeNotes || {};
nodeColors = data.nodeColors || {};
renderThreadTree();
clearLogTree();
alert('配置导入成功。');
} catch (err) {
alert('配置导入失败:' + err.message);
}
};
reader.readAsText(file);
};
input.click();
});
// 导出线程树为PNG
document.getElementById('export-thread-png').addEventListener('click', function() {
exportSVGAsPNG('thread-tree', 'thread_tree.png');
});
// 导出日志树为PNG
document.getElementById('export-log-png').addEventListener('click', function() {
exportSVGAsPNG('log-tree', 'log_tree.png');
});
/**
* 导出指定SVG元素为PNG图片
* @param {string} svgId - SVG元素的ID
* @param {string} filename - 导出文件名
*/
function exportSVGAsPNG(svgId, filename) {
const svgElement = document.getElementById(svgId);
const serializer = new XMLSerializer();
const svgString = serializer.serializeToString(svgElement);
const canvas = document.createElement('canvas');
const svgSize = svgElement.getBoundingClientRect();
canvas.width = svgSize.width;
canvas.height = svgSize.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;
}
// 模拟页面加载时的初始化
window.onload = function() {
clearLogTree();
};
// 可折叠面板功能
document.querySelectorAll('.container-header').forEach(header => {
header.addEventListener('click', function() {
const content = this.nextElementSibling;
const toggle = this.querySelector('.toggle');
if (content.style.display === 'none') {
content.style.display = 'block';
toggle.textContent = '−';
} else {
content.style.display = 'none';
toggle.textContent = '+';
}
});
});
</script>
</body>
</html>