Skip to content

Commit

Permalink
refactor(Mermaid): refactor the rendering method
Browse files Browse the repository at this point in the history
  • Loading branch information
XUEWUQIUSHUANG committed Nov 20, 2024
1 parent e6fce05 commit c30a40d
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 81 deletions.
25 changes: 2 additions & 23 deletions src/components/BootstrapBlazor.Mermaid/Mermaid.razor
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,8 @@
@inherits BootstrapModuleComponentBase

<div @attributes="@AdditionalAttributes" class="@ClassString" style="@Style" id="@Id">
@if (Type != MermaidType.None)
@if (DiagramHTML is not null)
{
@Type.ToDescriptionString()
@if (Type == MermaidType.Flowchart)
{
@(" " + Direction + "\n")
}
else if (Type == MermaidType.StateDiagram)
{
@("\ndirection " + Direction + "\n")
}
else
{
@("\n")
}
@if (!string.IsNullOrEmpty(MermaidTitle) &&
(Type == MermaidType.Gantt
|| Type == MermaidType.Pie
|| Type == MermaidType.SequenceDiagram
))
{
@("\ntitle " + MermaidTitle + "\n")
}
@DiagramHTML
}
@ChildContent
</div>
78 changes: 58 additions & 20 deletions src/components/BootstrapBlazor.Mermaid/Mermaid.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
// Website: https://www.blazor.zone or https://argozhang.github.io/

using Microsoft.AspNetCore.Components;
using System.ComponentModel.DataAnnotations;
using System.Runtime.CompilerServices;
using System.Text;

namespace BootstrapBlazor.Components;

Expand All @@ -17,18 +20,6 @@ public partial class Mermaid
[Parameter]
public MermaidDirection? Direction { get; set; } = MermaidDirection.TB;

/// <summary>
/// 获取/设置 mermaid 图内容
/// </summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }

/// <summary>
/// 获取/设置 错误回调方法
/// </summary>
[Parameter]
public Func<string, Task>? OnError { get; set; }

/// <summary>
/// 获取/设置 自定义样式
/// </summary>
Expand All @@ -41,6 +32,13 @@ public partial class Mermaid
[Parameter]
public MermaidType Type { set; get; }

/// <summary>
/// 设置Mermaid字串
/// </summary>
[Parameter]
[Required]
public string? DiagramString { get; set; }

/// <summary>
/// 获取/设置 图标题 如果图类型是甘特图,饼图时和序列图时,可指定其 title 默认 null 未设置
/// </summary>
Expand All @@ -51,23 +49,63 @@ public partial class Mermaid
.AddClassFromAttributes(AdditionalAttributes)
.Build();

/// <summary>
/// 构造Mermaid代码
/// </summary>
/// <returns></returns>
private string BuildDiagramText()
{
StringBuilder sb = new();
if(Type != MermaidType.None)
{
sb.Append(Type.ToDescriptionString());
if(Type == MermaidType.Flowchart)
{
sb.Append(" " + Direction + "\n");
}
else if (Type == MermaidType.StateDiagram)
{
sb.Append("\ndirection " + Direction + "\n");

}
else
{
sb.Append('\n');
}
if(!string.IsNullOrEmpty(MermaidTitle) &&
(Type == MermaidType.Gantt
|| Type == MermaidType.Pie
|| Type == MermaidType.SequenceDiagram
))

{
sb.Append("\ntitle " + MermaidTitle + "\n");
}
}
sb.Append(DiagramString);
return sb.ToString();
}


/// <summary>
/// MermaidHelper.js实例
/// </summary>
private new IJSObjectReference? Module { get; set; }

/// <summary>
/// 初始化mermaid
/// svg图
/// </summary>
private MarkupString? DiagramHTML { get; set; }

/// <summary>
/// 渲染Mermaid
/// </summary>
/// <param name="firstRender"></param>
/// <returns></returns>
protected override async Task OnAfterRenderAsync(bool firstRender)
protected override async Task OnParametersSetAsync()
{
if (firstRender)
{
Module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/BootstrapBlazor.Mermaid/js/MermaidHelper.js");
await Module.InvokeVoidAsync("init", Id);
}
Module ??= await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/BootstrapBlazor.Mermaid/js/MermaidHelper.js");
string innerHTML = await Module.InvokeAsync<string>("render", Id, BuildDiagramText());
DiagramHTML = new MarkupString(innerHTML);
}

/// <summary>
Expand Down
37 changes: 13 additions & 24 deletions src/components/BootstrapBlazor.Mermaid/wwwroot/js/MermaidHelper.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,24 @@
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
mermaid.initialize({ startOnLoad: false });

export async function init(id) {
mermaid.initialize({ startOnLoad: false })
const el = document.getElementById(id);
if (el) {
const childNodes = el.childNodes;
for (let i = childNodes.length - 1; i >= 0; i--) {
const node = childNodes[i];
if (node.nodeType === Node.COMMENT_NODE) {
el.removeChild(node);
}
}
}
const graphDefinition = el.textContent;
mermaid.render(id + '-svg', graphDefinition).then((svgCode) => {
el.innerHTML = svgCode.svg;
});
export async function render(id, graphDefinition) {
var result = await mermaid.render(id + '-svg', graphDefinition);
return result.svg;
}


export function getContent(id) {
let svgDataUrl = "";
const el = document.getElementById(id);
if (el) {
const svgElement = el.childNodes[0];
const serializer = new XMLSerializer();
const svgString = serializer.serializeToString(svgElement);
const utf8Array = new TextEncoder().encode(svgString);
svgDataUrl = 'data:image/svg+xml;base64,' + btoa(String.fromCharCode(...utf8Array));
for (let e in el.childNodes) {
if (el.childNodes[e].nodeName == "svg") {

Check warning on line 14 in src/components/BootstrapBlazor.Mermaid/wwwroot/js/MermaidHelper.js

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/components/BootstrapBlazor.Mermaid/wwwroot/js/MermaidHelper.js#L14

Generic Object Injection Sink
const svgElement = el.childNodes[e];

Check warning on line 15 in src/components/BootstrapBlazor.Mermaid/wwwroot/js/MermaidHelper.js

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/components/BootstrapBlazor.Mermaid/wwwroot/js/MermaidHelper.js#L15

Variable Assigned to Object Injection Sink
const serializer = new XMLSerializer();
const svgString = serializer.serializeToString(svgElement);
const utf8Array = new TextEncoder().encode(svgString);
svgDataUrl = 'data:image/svg+xml;base64,' + btoa(String.fromCharCode(...utf8Array));
return svgDataUrl;
}
}
}
return svgDataUrl;
}

Loading

0 comments on commit c30a40d

Please sign in to comment.