Skip to content

Commit e2073ef

Browse files
committed
refactor: ShikiRenderCodeService formatting and logic
1 parent d34617c commit e2073ef

1 file changed

Lines changed: 32 additions & 30 deletions

File tree

src/main/java/top/howiehz/halo/plugin/extra/api/service/js/post/render/shiki/ShikiRenderCodeService.java

Lines changed: 32 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import java.util.concurrent.CompletableFuture;
88
import java.util.concurrent.ConcurrentHashMap;
99
import java.util.stream.Collectors;
10+
1011
import lombok.RequiredArgsConstructor;
1112
import lombok.extern.slf4j.Slf4j;
1213
import org.jsoup.Jsoup;
@@ -53,8 +54,9 @@ public String renderCode(String content, ShikiConfig shikiConfig) {
5354
Document doc = Jsoup.parse(content);
5455
Elements codeElements = doc.select("pre > code");
5556

57+
// 如果没有代码块,直接返回原内容
5658
if (codeElements.isEmpty()) {
57-
return doc.body().html();
59+
return content;
5860
}
5961

6062
// 收集所有需要高亮的请求,同时进行去重
@@ -124,8 +126,9 @@ public String renderCode(String content, ShikiConfig shikiConfig) {
124126
}
125127
}
126128

129+
// 如果没有高亮请求,直接返回原内容
127130
if (allRequests.isEmpty()) {
128-
return doc.body().html();
131+
return content;
129132
}
130133

131134
// 统计去重效果
@@ -135,8 +138,8 @@ public String renderCode(String content, ShikiConfig shikiConfig) {
135138
- uniqueRequests;
136139
if (duplicates > 0) {
137140
metrics.recordDeduplication(duplicates);
138-
log.debug("代码块去重: 总块数={}, 唯一请求={}, 去重节省={}",
139-
totalBlocks, uniqueRequests, duplicates);
141+
log.debug("代码块去重: 总块数={}, 唯一请求={}, 去重节省={}", totalBlocks,
142+
uniqueRequests, duplicates);
140143
}
141144

142145
// 智能分组并并行处理
@@ -150,8 +153,7 @@ public String renderCode(String content, ShikiConfig shikiConfig) {
150153
log.debug("Shiki 渲染统计: 缓存命中率={}%, 去重节省={}, 平均耗时={}ms, 缓存大小={}",
151154
String.format("%.1f", snapshot.getHitRatePercent()),
152155
snapshot.getDeduplicatedRequests(),
153-
String.format("%.1f", snapshot.getAvgRenderTimeMs()),
154-
renderCache.size());
156+
String.format("%.1f", snapshot.getAvgRenderTimeMs()), renderCache.size());
155157
}
156158

157159
// 批量应用高亮结果 - 使用两阶段 DOM 操作减少性能开销
@@ -196,13 +198,13 @@ public String renderCode(String content, ShikiConfig shikiConfig) {
196198
String lightHtml = results.get(lightKey);
197199
String darkHtml = results.get(darkKey);
198200

199-
if (lightHtml != null && !lightHtml.startsWith("Error:")
200-
&& darkHtml != null && !darkHtml.startsWith("Error:")) {
201+
if (lightHtml != null && !lightHtml.startsWith("Error:") && darkHtml != null
202+
&& !darkHtml.startsWith("Error:")) {
201203

202-
Element lightDiv = doc.createElement("div")
203-
.attr("class", shikiConfig.getLightCodeClass());
204-
Element darkDiv = doc.createElement("div")
205-
.attr("class", shikiConfig.getDarkCodeClass());
204+
Element lightDiv =
205+
doc.createElement("div").attr("class", shikiConfig.getLightCodeClass());
206+
Element darkDiv =
207+
doc.createElement("div").attr("class", shikiConfig.getDarkCodeClass());
206208

207209
lightDiv.html(lightHtml);
208210
darkDiv.html(darkHtml);
@@ -213,8 +215,8 @@ public String renderCode(String content, ShikiConfig shikiConfig) {
213215
}
214216
}
215217
} catch (Exception e) {
216-
log.warn("Failed to prepare replacement for block {}: {}",
217-
blockInfo.index, e.getMessage());
218+
log.warn("Failed to prepare replacement for block {}: {}", blockInfo.index,
219+
e.getMessage());
218220
}
219221
}
220222

@@ -236,6 +238,9 @@ public String renderCode(String content, ShikiConfig shikiConfig) {
236238

237239
log.debug("DOM 批量操作完成: 替换了 {} 个代码块", toRemove.size());
238240

241+
// 返回最终 HTML 内容,避免 Jsoup 自动格式化破坏原始结构(如多行 mermaid 代码无分号结尾时)
242+
doc.outputSettings(new Document.OutputSettings().prettyPrint(false));
243+
239244
return doc.body().html();
240245
}
241246

@@ -274,8 +279,8 @@ private Map<String, String> processRequestsIntelligently(List<HighlightRequest>
274279
}
275280
}
276281

277-
log.debug("缓存检查: 总请求={}, 缓存命中={}, 需要渲染={}, 命中率={}%",
278-
totalRequests, cacheHits, requestsToRender.size(),
282+
log.debug("缓存检查: 总请求={}, 缓存命中={}, 需要渲染={}, 命中率={}%", totalRequests,
283+
cacheHits, requestsToRender.size(),
279284
totalRequests > 0 ? String.format("%.1f", (cacheHits * 100.0 / totalRequests)) : "0.0");
280285

281286
// 如果全部命中缓存,直接返回
@@ -288,8 +293,8 @@ private Map<String, String> processRequestsIntelligently(List<HighlightRequest>
288293
// 计算最优分组数:如果请求少于引擎数,就按请求数分组;否则充分利用引擎池
289294
int numGroups = Math.min(requestsToRender.size(), v8EnginePoolService.getPoolMaxSize());
290295

291-
log.debug("智能分组: {} 个请求分配到 {} 个引擎(池大小: {})",
292-
requestsToRender.size(), numGroups, v8EnginePoolService.getPoolMaxSize());
296+
log.debug("智能分组: {} 个请求分配到 {} 个引擎(池大小: {})", requestsToRender.size(),
297+
numGroups, v8EnginePoolService.getPoolMaxSize());
293298

294299
// 将需要渲染的请求分组
295300
List<List<HighlightRequest>> groups = partitionRequests(requestsToRender, numGroups);
@@ -306,13 +311,13 @@ private Map<String, String> processRequestsIntelligently(List<HighlightRequest>
306311
log.debug("组 {} 开始处理 {} 个请求", groupIndex, group.size());
307312

308313
// 转换为批量请求格式
309-
Map<String, ShikiHighlightService.CodeHighlightRequest> batchRequests
310-
= new java.util.LinkedHashMap<>();
314+
Map<String, ShikiHighlightService.CodeHighlightRequest> batchRequests =
315+
new java.util.LinkedHashMap<>();
311316

312317
for (HighlightRequest req : group) {
313318
batchRequests.put(req.id,
314-
new ShikiHighlightService.CodeHighlightRequest(
315-
req.code, req.language, req.theme));
319+
new ShikiHighlightService.CodeHighlightRequest(req.code, req.language,
320+
req.theme));
316321
}
317322

318323
// 在单个引擎中批量处理
@@ -338,16 +343,13 @@ private Map<String, String> processRequestsIntelligently(List<HighlightRequest>
338343
// 等待所有组完成并合并渲染结果
339344
Map<String, String> renderResults = new ConcurrentHashMap<>();
340345
try {
341-
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
342-
.thenApply(v -> futures.stream()
343-
.map(CompletableFuture::join)
344-
.collect(Collectors.toList()))
346+
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenApply(
347+
v -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList()))
345348
.thenAccept(resultsList -> {
346349
for (Map<String, String> results : resultsList) {
347350
renderResults.putAll(results);
348351
}
349-
})
350-
.join();
352+
}).join();
351353
} catch (Exception e) {
352354
log.error("智能批量处理失败: {}", e.getMessage());
353355
}
@@ -377,8 +379,8 @@ private Map<String, String> processRequestsIntelligently(List<HighlightRequest>
377379
* @param numGroups number of groups / 分组数
378380
* @return list of request groups / 请求分组列表
379381
*/
380-
private List<List<HighlightRequest>> partitionRequests(
381-
List<HighlightRequest> requests, int numGroups) {
382+
private List<List<HighlightRequest>> partitionRequests(List<HighlightRequest> requests,
383+
int numGroups) {
382384

383385
List<List<HighlightRequest>> groups = new ArrayList<>();
384386
int groupSize = (int) Math.ceil((double) requests.size() / numGroups);

0 commit comments

Comments
 (0)