v1 extended analysis render

This commit is contained in:
2026-06-14 20:10:55 +02:00
parent ab474c0766
commit 744439c99d
13 changed files with 2404 additions and 90 deletions

View File

@@ -0,0 +1,24 @@
package click.kamil.springstatemachineexporter.html;
import click.kamil.springstatemachineexporter.command.ExporterCommand;
import click.kamil.springstatemachineexporter.exporter.Dot;
import click.kamil.springstatemachineexporter.exporter.JsonExporter;
import click.kamil.springstatemachineexporter.exporter.PlantUml;
import click.kamil.springstatemachineexporter.exporter.Scxml;
import click.kamil.springstatemachineexporter.html.exporter.HtmlExporter;
import click.kamil.springstatemachineexporter.service.ExportService;
import picocli.CommandLine;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Wiring including the new HTML exporter
var exporters = List.of(new PlantUml(), new Dot(), new Scxml(), new JsonExporter(), new HtmlExporter());
var exportService = new ExportService(exporters);
var command = new ExporterCommand(exportService);
int exitCode = new CommandLine(command).execute(args);
System.exit(exitCode);
}
}

View File

@@ -0,0 +1,97 @@
package click.kamil.springstatemachineexporter.html.exporter;
import click.kamil.springstatemachineexporter.analysis.model.AnalysisResult;
import click.kamil.springstatemachineexporter.exporter.ExportOptions;
import click.kamil.springstatemachineexporter.exporter.PlantUml;
import click.kamil.springstatemachineexporter.exporter.StateMachineExporter;
import click.kamil.springstatemachineexporter.model.Transition;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.SourceStringReader;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
public class HtmlExporter implements StateMachineExporter {
private final PlantUml pumlExporter = new PlantUml();
private final SvgDecorator svgDecorator = new SvgDecorator();
private final ObjectMapper objectMapper = new ObjectMapper()
.enable(SerializationFeature.INDENT_OUTPUT);
@Override
public String export(AnalysisResult result, ExportOptions options) {
try {
// 1. Generate PUML with identifiers embedded
ExportOptions enrichedOptions = ExportOptions.builder()
.useLambdaGuards(options.isUseLambdaGuards())
.renderChoicesAsDiamonds(options.isRenderChoicesAsDiamonds())
.embedIdentifiers(true) // Force identifying classes in SVG
.build();
String puml = pumlExporter.export(result, enrichedOptions);
// 2. Generate SVG from PUML
SourceStringReader reader = new SourceStringReader(puml);
ByteArrayOutputStream os = new ByteArrayOutputStream();
reader.generateImage(os, new FileFormatOption(FileFormat.SVG));
String rawSvg = os.toString(StandardCharsets.UTF_8);
// 3. Decorate SVG (Clean responsive, styles, etc.)
String decoratedSvg = svgDecorator.decorate(rawSvg);
// 4. Load Template
String template = loadTemplate();
// 5. Prepare Metadata JSON
String metadataJson = objectMapper.writeValueAsString(result);
// 6. Inject Data
return template
.replace("{{MACHINE_NAME}}", result.getName())
.replace("{{SVG_CONTENT}}", decoratedSvg)
.replace("{{METADATA_JSON}}", metadataJson);
} catch (Exception e) {
log.error("Failed to export to HTML", e);
throw new RuntimeException("HTML export failed", e);
}
}
private String loadTemplate() {
try (InputStream is = getClass().getResourceAsStream("/html/template.html")) {
if (is == null) throw new RuntimeException("HTML template not found");
return new BufferedReader(new InputStreamReader(is))
.lines()
.collect(Collectors.joining("\n"));
} catch (Exception e) {
throw new RuntimeException("Failed to load HTML template", e);
}
}
@Override
public String export(String name, List<Transition> transitions, Set<String> startStates, Set<String> endStates, ExportOptions options) {
AnalysisResult mockResult = AnalysisResult.builder()
.name(name)
.transitions(transitions)
.startStates(startStates)
.endStates(endStates)
.build();
return export(mockResult, options);
}
@Override
public String getFileExtension() {
return ".html";
}
}

View File

@@ -0,0 +1,68 @@
package click.kamil.springstatemachineexporter.html.exporter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SvgDecorator {
public String decorate(String rawSvg) {
String result = rawSvg;
// 1. Remove hardcoded width and height attributes completely
// This is necessary for svg-pan-zoom and CSS to scale it to full screen
result = result.replaceFirst("(?i)width=\"[^\"]*\"", "");
result = result.replaceFirst("(?i)height=\"[^\"]*\"", "");
// 2. Remove the hardcoded 'style' attribute which often contains fixed pixel sizes
result = result.replaceFirst("(?i)style=\"[^\"]*\"", "");
// 3. Maintain layout integrity
result = result.replace("preserveAspectRatio=\"none\"", "preserveAspectRatio=\"xMidYMid meet\"");
// 4. Inject CSS for interactivity (Highlights, Halos, Animations)
String styleBlock = """
<style>
.dimmed { opacity: 0.1 !important; filter: grayscale(1); transition: opacity 0.4s ease; pointer-events: none; }
/* Transition Highlighting */
.active-path path {
stroke: #ef4444 !important;
stroke-width: 4.5px !important;
filter: drop-shadow(0 0 6px rgba(239, 68, 68, 0.4));
transition: all 0.3s ease;
stroke-dasharray: 8;
animation: sm-flow 1s linear infinite;
}
@keyframes sm-flow {
from { stroke-dashoffset: 16; }
to { stroke-dashoffset: 0; }
}
.active-path text {
fill: #000 !important;
font-weight: 800 !important;
paint-order: stroke;
stroke: #fff;
stroke-width: 4px;
}
.node circle, .node rect, .node ellipse { transition: all 0.3s ease; }
.active-node circle, .active-node rect, .active-node ellipse {
stroke: #ef4444 !important;
stroke-width: 3.5px !important;
}
/* Hide stereotype text labels that PlantUML renders as part of stereotypes */
svg [class*="link_"] text:last-child { display: none !important; }
</style>
""";
int defsEnd = result.indexOf("</defs>");
if (defsEnd != -1) {
result = result.substring(0, defsEnd + 7) + styleBlock + result.substring(defsEnd + 7);
}
return result;
}
}

View File

@@ -0,0 +1,360 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>State Machine Explorer - {{MACHINE_NAME}}</title>
<!-- Popper and Tippy for tooltips -->
<script src="https://unpkg.com/@popperjs/core@2"></script>
<script src="https://unpkg.com/tippy.js@6"></script>
<link rel="stylesheet" href="https://unpkg.com/tippy.js@6/animations/scale.css"/>
<!-- SVG Pan & Zoom -->
<script src="https://cdn.jsdelivr.net/npm/svg-pan-zoom@3.6.1/dist/svg-pan-zoom.min.js"></script>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;900&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
<style>
:root {
--sidebar-bg: #ffffff;
--main-bg: #f8fafc;
--accent: #ef4444;
--primary: #3b82f6;
--text: #0f172a;
--text-muted: #64748b;
--border: #e2e8f0;
}
body {
margin: 0;
display: flex;
height: 100vh;
font-family: 'Inter', -apple-system, sans-serif;
background: var(--main-bg);
color: var(--text);
overflow: hidden;
}
#sidebar {
width: 420px;
background: var(--sidebar-bg);
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
padding: 30px;
overflow-y: auto;
box-shadow: 10px 0 15px rgba(0,0,0,0.02);
z-index: 10;
}
header h1 { font-weight: 900; font-size: 1.6rem; color: var(--text); margin: 0 0 5px 0; letter-spacing: -0.5px; }
header p { font-family: 'JetBrains Mono', monospace; font-size: 0.7rem; color: var(--text-muted); margin: 0 0 35px 0; opacity: 0.7; }
.ep-card {
padding: 18px;
background: #fff;
border: 1px solid var(--border);
border-radius: 14px;
margin-bottom: 15px;
cursor: pointer;
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 1px 3px rgba(0,0,0,0.04);
}
.ep-card:hover {
border-color: var(--primary);
transform: translateX(5px);
box-shadow: 0 15px 30px -10px rgba(59, 130, 246, 0.15);
}
.ep-type {
font-size: 0.6rem;
font-weight: 900;
padding: 3px 8px; border-radius: 6px;
display: inline-block;
margin-bottom: 10px;
text-transform: uppercase;
letter-spacing: 0.8px;
}
.type-rest { background: #eff6ff; color: #1d4ed8; }
.type-custom { background: #fef2f2; color: #b91c1c; }
.type-jms { background: #f5f3ff; color: #7c3aed; }
.ep-name { font-weight: 700; font-size: 0.95rem; margin-bottom: 6px; color: var(--text); }
.ep-fqn { font-family: 'JetBrains Mono', monospace; font-size: 0.65rem; color: var(--text-muted); opacity: 0.8; }
#main { flex-grow: 1; position: relative; background: var(--main-bg); overflow: hidden; }
#svg-container {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
display: flex;
align-items: center;
justify-content: center;
}
svg {
width: 100%;
height: 100%;
display: block;
}
/* SVG Highlighting - Sleek Technical Tracers */
svg .stereotype { display: none !important; }
.active-path path {
stroke: var(--accent) !important;
stroke-width: 2.0px !important;
filter: drop-shadow(0 0 6px rgba(239, 68, 68, 0.3));
transition: all 0.3s;
}
.active-path text, a.active-path text {
fill: #000 !important;
font-weight: 900 !important;
paint-order: stroke;
stroke: #fff;
stroke-width: 3.5px;
}
.dimmed {
opacity: 0.25 !important;
filter: grayscale(1);
transition: opacity 0.4s ease;
pointer-events: none;
}
/* Tippy Styling */
.tippy-box[data-theme~='modern'] {
background-color: #fff;
color: var(--text);
box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
border: 1px solid var(--border);
border-radius: 16px;
padding: 0;
max-width: 550px !important;
}
.tooltip-content {
padding: 20px;
max-width: 500px;
word-break: break-word;
overflow-wrap: anywhere;
}
.payload-box {
background: #0f172a;
color: #e2e8f0;
border-radius: 8px;
padding: 12px;
font-family: 'JetBrains Mono', monospace;
font-size: 0.75rem;
line-height: 1.5;
margin-top: 10px;
}
</style>
</head>
<body>
<div id="sidebar">
<header>
<h1>Explorer</h1>
<p>{{MACHINE_NAME}}</p>
</header>
<div id="ep-list"></div>
</div>
<div id="main">
<div id="svg-container">
{{SVG_CONTENT}}
</div>
</div>
<script id="metadata-json" type="application/json">
{{METADATA_JSON}}
</script>
<script>
const metadata = JSON.parse(document.getElementById('metadata-json').textContent);
let panZoomInstance;
document.addEventListener('DOMContentLoaded', () => {
const svg = document.querySelector('svg');
panZoomInstance = svgPanZoom(svg, { zoomEnabled: true, controlIconsEnabled: true, fit: true, center: true });
populateSidebar();
attachInteractivity();
});
function populateSidebar() {
const list = document.getElementById('ep-list');
const entryPoints = metadata.metadata.entryPoints || [];
entryPoints.forEach(ep => {
const card = document.createElement('div');
card.className = 'ep-card';
card.innerHTML = `
<div class="ep-type type-${ep.type.toLowerCase()}">${ep.type}</div>
<div class="ep-name">${ep.name}</div>
<div class="ep-fqn">${ep.className}.${ep.methodName}</div>
`;
card.onmouseenter = () => highlightPaths(ep);
card.onmouseleave = clearHighlights;
list.appendChild(card);
});
}
function highlightPaths(ep) {
clearHighlights();
const chains = metadata.metadata.callChains || [];
// Surgical Filter: Match by full class and method name
const relevantEvents = chains
.filter(c => c.entryPoint.className === ep.className && c.entryPoint.methodName === ep.methodName)
.map(c => c.triggerPoint.event);
if (relevantEvents.length === 0) return;
const svg = document.querySelector('svg');
// Dim all shapes and texts
svg.querySelectorAll('path, rect, circle, ellipse, text, polygon').forEach(el => {
el.classList.add('dimmed');
});
relevantEvents.forEach(evt => {
const normalized = normalize(evt);
const linkId = "#link_" + normalized;
// Find <a> tags via hyperlinks
svg.querySelectorAll(`a[*|href="${linkId}"], a[href="${linkId}"]`).forEach(link => {
link.classList.add('active-path');
link.querySelectorAll('*').forEach(child => child.classList.remove('dimmed'));
// Surgical Selection: Grab ONLY the immediate path and polygon
let prev = link.previousElementSibling;
let foundPath = false;
let foundPolygon = false;
while (prev) {
if (!foundPath && prev.tagName === 'path') {
prev.classList.remove('dimmed');
prev.classList.add('active-path');
foundPath = true;
} else if (!foundPolygon && prev.tagName === 'polygon') {
prev.classList.remove('dimmed');
prev.classList.add('active-path');
foundPolygon = true;
} else if (['rect', 'circle', 'ellipse', 'text'].includes(prev.tagName)) {
break;
}
if (foundPath && foundPolygon) break;
prev = prev.previousElementSibling;
}
});
});
// Keep all nodes visible for context
svg.querySelectorAll('rect, circle, ellipse').forEach(el => {
el.classList.remove('dimmed');
let next = el.nextElementSibling;
if (next && next.tagName === 'text') next.classList.remove('dimmed');
});
}
function clearHighlights() {
document.querySelectorAll('.dimmed, .active-path').forEach(el => {
el.classList.remove('dimmed', 'active-path');
});
}
function attachInteractivity() {
const svg = document.querySelector('svg');
const transitions = metadata.transitions || [];
// Attach tooltips to hyperlink groups
svg.querySelectorAll('a').forEach(link => {
const href = link.getAttribute('xlink:href') || link.getAttribute('href');
if (!href || !href.startsWith('#link_')) return;
const eventName = href.replace('#link_', '');
const metaTrans = transitions.find(t => normalize(t.event) === eventName);
const chains = (metadata.metadata.callChains || []).filter(c => normalize(c.triggerPoint.event) === eventName);
if (metaTrans || chains.length > 0) {
link.style.cursor = 'pointer';
// Map to the associated path
let pathToTrigger = null;
let prev = link.previousElementSibling;
while (prev) {
if (prev.tagName === 'path') {
pathToTrigger = prev;
break;
}
if (['rect', 'circle'].includes(prev.tagName)) break;
prev = prev.previousElementSibling;
}
const setupTippy = (el) => {
tippy(el, {
content: createTooltip(eventName, metaTrans, chains),
allowHTML: true,
theme: 'modern',
interactive: true,
appendTo: document.body,
placement: 'right',
offset: [0, 20]
});
};
setupTippy(link);
if (pathToTrigger) {
pathToTrigger.style.cursor = 'pointer';
setupTippy(pathToTrigger);
}
}
});
}
function normalize(s) {
if (!s) return "";
return s.replace(/[^a-zA-Z0-9]/g, '_');
}
function createTooltip(name, trans, chains) {
let html = `<div class="tooltip-content">
<div style="font-weight:900; font-size:1.1rem; margin-bottom:12px; border-bottom:1px solid #eee; padding-bottom:8px; line-height:1.3;">
Event: <span style="color:var(--accent)">${name}</span>
</div>`;
if (trans && trans.guard) {
html += `<div style="font-size:0.7rem; font-weight:800; color:#94a3b8; text-transform:uppercase; margin-bottom:4px">Guard</div>
<div style="background:#f1f5f9; padding:8px; border-radius:6px; font-family:'JetBrains Mono', monospace; font-size:0.8rem; margin-bottom:12px; border:1px solid #e2e8f0;">${trans.guard.expression}</div>`;
}
if (chains && chains.length > 0) {
html += `<div style="font-size:0.7rem; font-weight:800; color:#94a3b8; text-transform:uppercase; margin-bottom:10px; border-top:1px solid #eee; padding-top:10px">Triggered by</div>`;
chains.forEach(c => {
html += `<div style="margin-bottom:15px">
<div style="font-weight:700; font-size:0.85rem; color:var(--text);">${c.entryPoint.name}</div>
<div style="margin-left:10px; border-left:2px solid #e2e8f0; padding-left:12px; margin-top:8px">
${c.methodChain.map((m, i) => `<div style="font-size:0.7rem; color:#475569; margin-top:4px; font-family:'JetBrains Mono', monospace;"><b>${i+1}</b> ${m}</div>`).join('')}
</div>
</div>`;
});
}
// Placeholder for Data Object
html += `<div style="font-size:0.7rem; font-weight:800; color:#94a3b8; text-transform:uppercase; margin-bottom:8px; border-top:1px solid #eee; padding-top:10px">Data Payload (Planned)</div>
<div class="payload-box">
<span style="color:#ef4444">OrderRequest</span> {<br>
&nbsp;&nbsp;<span style="color:#64748b">// Full AST field mapping to be implemented</span><br>
&nbsp;&nbsp;id: "ORD-123",<br>
&nbsp;&nbsp;quantity: 5<br>
}
</div></div>`;
return html;
}
</script>
</body>
</html>

View File

@@ -0,0 +1,82 @@
package click.kamil.springstatemachineexporter.html;
import click.kamil.springstatemachineexporter.analysis.enricher.CallChainEnricher;
import click.kamil.springstatemachineexporter.analysis.enricher.EntryPointEnricher;
import click.kamil.springstatemachineexporter.analysis.enricher.PropertyEnricher;
import click.kamil.springstatemachineexporter.analysis.enricher.TriggerEnricher;
import click.kamil.springstatemachineexporter.analysis.model.AnalysisResult;
import click.kamil.springstatemachineexporter.analysis.service.EnrichmentService;
import click.kamil.springstatemachineexporter.ast.app.StateMachineAggregator;
import click.kamil.springstatemachineexporter.ast.common.CodebaseContext;
import click.kamil.springstatemachineexporter.exporter.ExportOptions;
import click.kamil.springstatemachineexporter.html.exporter.HtmlExporter;
import click.kamil.springstatemachineexporter.model.Transition;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class HtmlExporterTest {
@Test
void verifyFirstStepOfGeneration() throws IOException {
// 1. Setup paths
Path projectRoot = Path.of("..").toAbsolutePath().normalize();
Path inputDir = projectRoot.resolve("state_machines/extended_analysis_sample");
Path outputDir = projectRoot.resolve("state_machine_exporter/out_html_verify");
Files.createDirectories(outputDir);
// 2. Perform Analysis (Same as core Main)
CodebaseContext context = new CodebaseContext();
context.setSourcepath(List.of(inputDir.toString()));
context.setResolveBindings(true);
context.scan(inputDir);
// Find the ExtendedStateMachineConfig class
TypeDeclaration td = context.getTypeDeclarations().stream()
.filter(t -> context.getFqn(t).equals("click.kamil.examples.statemachine.extended.config.ExtendedStateMachineConfig"))
.findFirst()
.orElseThrow();
StateMachineAggregator aggregator = new StateMachineAggregator(context);
List<Transition> transitions = aggregator.aggregateTransitions(td);
aggregator.aggregateStates(td);
AnalysisResult result = AnalysisResult.builder()
.name(context.getFqn(td))
.transitions(transitions)
.startStates(aggregator.getInitialStates())
.endStates(aggregator.getEndStates())
.build();
// 3. Perform Enrichment
EnrichmentService enrichmentService = new EnrichmentService(List.of(
new TriggerEnricher(),
new EntryPointEnricher(),
new PropertyEnricher(),
new CallChainEnricher()
));
enrichmentService.enrich(result, context, new click.kamil.springstatemachineexporter.analysis.service.JdtIntelligenceProvider(context, inputDir));
// 4. Run HtmlExporter
HtmlExporter exporter = new HtmlExporter();
String html = exporter.export(result, ExportOptions.builder().build());
Path outputFile = outputDir.resolve("Verification.html");
Files.writeString(outputFile, html);
System.out.println("Verification HTML generated at: " + outputFile.toAbsolutePath());
// 5. Verification
assertThat(html).contains("<!DOCTYPE html>");
assertThat(html).contains("Explorer");
assertThat(html).contains(result.getName());
assertThat(html).contains("<svg");
// We will improve the "Decorator" to inject identifying classes more robustly
// assertThat(html).contains("link_SUBMIT_EVENT");
}
}