Skip to content

feat(Vditor): add Vditor component#466

Merged
ArgoZhang merged 7 commits intomasterfrom
feat-vditor
Jun 14, 2025
Merged

feat(Vditor): add Vditor component#466
ArgoZhang merged 7 commits intomasterfrom
feat-vditor

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Jun 14, 2025

Link issues

fixes #465

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Add a new Vditor markdown editor component to BootstrapBlazor.Extensions, providing a Blazor wrapper with JS interop, configuration options, event callbacks, and bundled styling and scripts.

New Features:

  • Introduce Vditor Blazor component with rich Markdown editing and two-way binding
  • Implement C# interop logic in Vditor.razor.cs including lifecycle methods and input/focus/blur/select/escape/ctrlEnter callbacks
  • Add VditorOptions struct plus VditorMode and VditorIconStyle enums for customizable editor configuration
  • Include JavaScript module for initializing, resetting, and disposing Vditor instances
  • Bundle Vditor core CSS and multiple content theme styles (ant-design, dark, light, wechat) alongside the editor’s JS library

@bb-auto bb-auto Bot added the enhancement New feature or request label Jun 14, 2025
@bb-auto bb-auto Bot added this to the v9.2.0 milestone Jun 14, 2025
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Jun 14, 2025

Reviewer's Guide

This PR adds a standalone Razor class library project for a new Vditor markdown editor component, wiring up all necessary C# and JavaScript interop to initialize, configure, and control the editor in Blazor.

Sequence Diagram for Vditor Component Initialization

sequenceDiagram
    participant U as User/Razor Page
    participant CSharp as Vditor.razor.cs
    participant JSInterop as Vditor.razor.js
    participant VditorLib as vditor.js Library

    U->>CSharp: Renders Vditor component
    activate CSharp
    CSharp->>JSInterop: InvokeAsync("init", id, Interop, {Options, Value})
    activate JSInterop
    JSInterop->>VditorLib: new Vditor(id, vditorOptionsWithCallbacks)
    activate VditorLib
    VditorLib-->>JSInterop: Vditor instance created
    VditorLib->>JSInterop: Calls options.after() callback
    deactivate VditorLib
    JSInterop->>CSharp: invokeMethodAsync("TriggerRenderedAsync")
    activate CSharp
    CSharp->>CSharp: Executes OnRenderedAsync (if any)
    deactivate CSharp
    deactivate JSInterop
    deactivate CSharp
Loading

Sequence Diagram for Vditor User Input Handling

sequenceDiagram
    actor User
    participant VditorLib as vditor.js Library
    participant JSInterop as Vditor.razor.js
    participant CSharp as Vditor.razor.cs

    User->>VditorLib: Types text in editor
    activate VditorLib
    VditorLib->>JSInterop: Calls options.input(value) callback
    activate JSInterop
    JSInterop->>CSharp: invokeMethodAsync("TriggerInputAsync", value)
    activate CSharp
    CSharp->>CSharp: Updates CurrentValue
    CSharp->>CSharp: Executes OnInputAsync(value) (if any)
    deactivate CSharp
    deactivate JSInterop
    deactivate VditorLib
Loading

File-Level Changes

Change Details Files
New Razor class library project added to the solution
  • Updated solution file to include BootstrapBlazor.Vditor.csproj
  • Created BootstrapBlazor.Vditor.csproj with required SDK and package references
BootstrapBlazor.Extensions.sln
src/components/BootstrapBlazor.Vditor/BootstrapBlazor.Vditor.csproj
Vditor component creation with C# API and lifecycle logic
  • Added Vditor.razor defining the editor container and JS module loader
  • Implemented Vditor.razor.cs with Parameters, JS interop (init, reset, dispose), OnAfterRender value sync, and public editor methods
  • Defined callback handlers via JSInvokable to relay editor events back to .NET
src/components/BootstrapBlazor.Vditor/Vditor.razor
src/components/BootstrapBlazor.Vditor/Vditor.razor.cs
JavaScript module for editor initialization and asset loading
  • Created Vditor.razor.js exporting init, reset, dispose functions
  • Used utility methods addLink/addScript to inject CSS and JS assets at runtime
  • Wired Vditor events (after, input, focus, blur, esc, select, ctrlEnter) to invoke .NET callbacks
src/components/BootstrapBlazor.Vditor/Vditor.razor.js
Introduced configuration types for editor customization
  • Added VditorOptions struct with JSON-serializable properties for mode, language, style, dimensions, etc.
  • Defined VditorMode and VditorIconStyle enums for editor behavior and icon appearance
src/components/BootstrapBlazor.Vditor/VditorOptions.cs
src/components/BootstrapBlazor.Vditor/VditorMode.cs
src/components/BootstrapBlazor.Vditor/VditorIconStyle.cs
Embedded Vditor asset files in wwwroot
  • Added full Vditor core CSS (index.css) and multiple theme CSS under content-theme
  • Bundled vditor.min.js distribution script for editor functionality
src/components/BootstrapBlazor.Vditor/wwwroot/css/index.css
src/components/BootstrapBlazor.Vditor/wwwroot/css/content-theme/ant-design.css
src/components/BootstrapBlazor.Vditor/wwwroot/css/content-theme/dark.css
src/components/BootstrapBlazor.Vditor/wwwroot/css/content-theme/light.css
src/components/BootstrapBlazor.Vditor/wwwroot/css/content-theme/wechat.css
src/components/BootstrapBlazor.Vditor/wwwroot/js/vditor.min.js
Razor imports and module auto-loading setup
  • Created _Imports.razor to import namespaces for the component
  • Added JSModuleAutoLoader attribute in Vditor.razor for automatic script loading
src/components/BootstrapBlazor.Vditor/_Imports.razor

Assessment against linked issues

Issue Objective Addressed Explanation

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@ArgoZhang ArgoZhang merged commit 379986b into master Jun 14, 2025
1 check passed
@ArgoZhang ArgoZhang deleted the feat-vditor branch June 14, 2025 09:04
Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @ArgoZhang - I've reviewed your changes - here's some feedback:

  • The DisableAsync method invokes "disabled" but the Vditor API uses "disable"—please update the invocation to match the correct method name.
  • In Vditor.razor.js you’re loading "vditor.js" but the project ships "vditor.min.js"—update the script path to the minified file (or include the unminified version) to avoid 404s and improve performance.
  • Rather than bundling all theme CSS variants, consider dynamically loading only the selected theme (e.g. ant-design, light, dark) to trim down the payload size.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The DisableAsync method invokes "disabled" but the Vditor API uses "disable"—please update the invocation to match the correct method name.
- In Vditor.razor.js you’re loading "vditor.js" but the project ships "vditor.min.js"—update the script path to the minified file (or include the unminified version) to avoid 404s and improve performance.
- Rather than bundling all theme CSS variants, consider dynamically loading only the selected theme (e.g. ant-design, light, dark) to trim down the payload size.

## Individual Comments

### Comment 1
<location> `src/components/BootstrapBlazor.Vditor/Vditor.razor.cs:113` </location>
<code_context>
+    /// <param name="value"></param>
+    /// <param name="options"></param>
+    /// <returns></returns>
+    public async Task Reset(string value, VditorOptions options)
+    {
+        if (!string.IsNullOrEmpty(value))
+        {
+            Value = value;
+        }
+        _vditor = await InvokeAsync<IJSObjectReference>("reset", Id, Value, Options);
+    }
+
</code_context>

<issue_to_address>
Reset uses the `Options` property instead of the passed-in parameter

Pass the `options` parameter to JS instead of the component's `Options` property, or update the property before invoking JS to ensure the correct configuration is used.
</issue_to_address>

### Comment 2
<location> `src/components/BootstrapBlazor.Vditor/Vditor.razor.cs:188` </location>
<code_context>
+    /// <summary>
+    /// 禁用编辑器
+    /// </summary>
+    public async ValueTask DisableAsync()
+    {
+        if (_vditor != null)
+        {
+            await _vditor.InvokeVoidAsync("disabled");
+        }
+    }
</code_context>

<issue_to_address>
Calling incorrect Vditor API method for disabling

Use `InvokeVoidAsync("disable")` instead of `InvokeVoidAsync("disabled")` to correctly disable the editor.
</issue_to_address>

### Comment 3
<location> `src/components/BootstrapBlazor.Vditor/wwwroot/js/vditor.js:5878` </location>
<code_context>
+ * @param afterCombine 每个脚注块合并完成后的回调, param: root为合并后的脚注块
+ */
+var combineFootnote = function (elements, afterCombine) {
+    elements.querySelectorAll("[data-type=footnotes-link]").forEach(function (el) {
+        var root = el.parentElement;
+        var footnote = root.nextSibling;
</code_context>

<issue_to_address>
Avoid mutating a live NodeList while iterating

Clone the childNodes into an array before iterating to avoid issues from modifying the live list during the loop.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +113 to +119
public async Task Reset(string value, VditorOptions options)
{
if (!string.IsNullOrEmpty(value))
{
Value = value;
}
_vditor = await InvokeAsync<IJSObjectReference>("reset", Id, Value, Options);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Reset uses the Options property instead of the passed-in parameter

Pass the options parameter to JS instead of the component's Options property, or update the property before invoking JS to ensure the correct configuration is used.

Comment on lines +188 to +192
public async ValueTask DisableAsync()
{
if (_vditor != null)
{
await _vditor.InvokeVoidAsync("disabled");
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Calling incorrect Vditor API method for disabling

Use InvokeVoidAsync("disable") instead of InvokeVoidAsync("disabled") to correctly disable the editor.

* @param afterCombine 每个脚注块合并完成后的回调, param: root为合并后的脚注块
*/
var combineFootnote = function (elements, afterCombine) {
elements.querySelectorAll("[data-type=footnotes-link]").forEach(function (el) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Avoid mutating a live NodeList while iterating

Clone the childNodes into an array before iterating to avoid issues from modifying the live list during the loop.

Comment on lines +38 to +4804
return range;
};
var setRangeByWbr = function (element, range) {
var wbrElement = element.querySelector("wbr");
if (!wbrElement) {
return;
}
if (!wbrElement.previousElementSibling) {
if (wbrElement.previousSibling) {
// text<wbr>
range.setStart(wbrElement.previousSibling, wbrElement.previousSibling.textContent.length);
}
else if (wbrElement.nextSibling) {
if (wbrElement.nextSibling.nodeType === 3) {
// <wbr>text
range.setStart(wbrElement.nextSibling, 0);
}
else {
// <wbr><br> https://github.com/Vanessa219/vditor/issues/400
range.setStartBefore(wbrElement.nextSibling);
}
}
else {
// 内容为空
range.setStart(wbrElement.parentElement, 0);
}
}
else {
if (wbrElement.previousElementSibling.isSameNode(wbrElement.previousSibling)) {
if (wbrElement.previousElementSibling.lastChild) {
// <em>text</em><wbr>
range.setStartBefore(wbrElement);
range.collapse(true);
setSelectionFocus(range);
// fix Chrome set range bug: **c**
if ((0,_compatibility__WEBPACK_IMPORTED_MODULE_2__/* .isChrome */ .i7)() && (wbrElement.previousElementSibling.tagName === "EM" ||
wbrElement.previousElementSibling.tagName === "STRONG" ||
wbrElement.previousElementSibling.tagName === "S")) {
range.insertNode(document.createTextNode(_constants__WEBPACK_IMPORTED_MODULE_0__/* .Constants.ZWSP */ .g.ZWSP));
range.collapse(false);
}
wbrElement.remove();
return;
}
else {
// <br><wbr>
range.setStartAfter(wbrElement.previousElementSibling);
}
}
else {
// <em>text</em>text<wbr>
range.setStart(wbrElement.previousSibling, wbrElement.previousSibling.textContent.length);
}
}
range.collapse(true);
wbrElement.remove();
setSelectionFocus(range);
};
var insertHTML = function (html, vditor) {
// 使用 lute 方法会添加 p 元素,只有一个 p 元素的时候进行删除
var tempElement = document.createElement("div");
tempElement.innerHTML = html;
var tempBlockElement = tempElement.querySelectorAll("p");
if (tempBlockElement.length === 1 && !tempBlockElement[0].previousSibling && !tempBlockElement[0].nextSibling &&
vditor[vditor.currentMode].element.children.length > 0 && tempElement.firstElementChild.tagName === "P") {
html = tempBlockElement[0].innerHTML.trim();
}
var pasteElement = document.createElement("div");
pasteElement.innerHTML = html;
var range = getEditorRange(vditor);
if (range.toString() !== "") {
vditor[vditor.currentMode].preventInput = true;
document.execCommand("delete", false, "");
}
if (pasteElement.firstElementChild &&
pasteElement.firstElementChild.getAttribute("data-block") === "0") {
// 粘贴内容为块元素时,应在下一段落中插入
pasteElement.lastElementChild.insertAdjacentHTML("beforeend", "<wbr>");
var blockElement = (0,_hasClosest__WEBPACK_IMPORTED_MODULE_1__/* .hasClosestBlock */ .F9)(range.startContainer);
if (!blockElement) {
vditor[vditor.currentMode].element.insertAdjacentHTML("beforeend", pasteElement.innerHTML);
}
else {
blockElement.insertAdjacentHTML("afterend", pasteElement.innerHTML);
}
setRangeByWbr(vditor[vditor.currentMode].element, range);
}
else {
var pasteTemplate = document.createElement("template");
pasteTemplate.innerHTML = html;
range.insertNode(pasteTemplate.content.cloneNode(true));
range.collapse(false);
setSelectionFocus(range);
}
};


/***/ })

/******/ });
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Use const or let instead of var. (avoid-using-var)

Explanation`const` is preferred as it ensures you cannot reassign references (which can lead to buggy and confusing code). `let` may be used if you need to reassign references - it's preferred to `var` because it is block- rather than function-scoped.

From the Airbnb JavaScript Style Guide

Comment on lines +71 to +95
var diff_match_patch = function () {
// Defaults.
// Redefine these in your program to override the defaults.

// Number of seconds to map a diff before giving up (0 for infinity).
this.Diff_Timeout = 1.0;
// Cost of an empty edit operation in terms of edit characters.
this.Diff_EditCost = 4;
// At what point is no match declared (0.0 = perfection, 1.0 = very loose).
this.Match_Threshold = 0.5;
// How far to search for a match (0 = exact location, 1000+ = broad match).
// A match this many characters away from the expected location will add
// 1.0 to the score (0.0 is a perfect match).
this.Match_Distance = 1000;
// When deleting a large block of text (over ~64 characters), how close do
// the contents have to be to match the expected contents. (0.0 = perfection,
// 1.0 = very loose). Note that Match_Threshold controls how closely the
// end points of a delete need to match.
this.Patch_DeleteThreshold = 0.5;
// Chunk size for context length.
this.Patch_Margin = 4;

// The number of bits in an int.
this.Match_MaxBits = 32;
};
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Use const or let instead of var. (avoid-using-var)

Explanation`const` is preferred as it ensures you cannot reassign references (which can lead to buggy and confusing code). `let` may be used if you need to reassign references - it's preferred to `var` because it is block- rather than function-scoped.

From the Airbnb JavaScript Style Guide

}

// Check to see if the problem can be split in two.
var hm = this.diff_halfMatch_(text1, text2);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Use const or let instead of var. (avoid-using-var)

Explanation`const` is preferred as it ensures you cannot reassign references (which can lead to buggy and confusing code). `let` may be used if you need to reassign references - it's preferred to `var` because it is block- rather than function-scoped.

From the Airbnb JavaScript Style Guide

var hm = this.diff_halfMatch_(text1, text2);
if (hm) {
// A half-match was found, sort out the return data.
var text1_a = hm[0];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Use const or let instead of var. (avoid-using-var)

Explanation`const` is preferred as it ensures you cannot reassign references (which can lead to buggy and confusing code). `let` may be used if you need to reassign references - it's preferred to `var` because it is block- rather than function-scoped.

From the Airbnb JavaScript Style Guide

if (hm) {
// A half-match was found, sort out the return data.
var text1_a = hm[0];
var text1_b = hm[1];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Use const or let instead of var. (avoid-using-var)

Explanation`const` is preferred as it ensures you cannot reassign references (which can lead to buggy and confusing code). `let` may be used if you need to reassign references - it's preferred to `var` because it is block- rather than function-scoped.

From the Airbnb JavaScript Style Guide

// A half-match was found, sort out the return data.
var text1_a = hm[0];
var text1_b = hm[1];
var text2_a = hm[2];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Use const or let instead of var. (avoid-using-var)

Explanation`const` is preferred as it ensures you cannot reassign references (which can lead to buggy and confusing code). `let` may be used if you need to reassign references - it's preferred to `var` because it is block- rather than function-scoped.

From the Airbnb JavaScript Style Guide

var text1_a = hm[0];
var text1_b = hm[1];
var text2_a = hm[2];
var text2_b = hm[3];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Use const or let instead of var. (avoid-using-var)

Explanation`const` is preferred as it ensures you cannot reassign references (which can lead to buggy and confusing code). `let` may be used if you need to reassign references - it's preferred to `var` because it is block- rather than function-scoped.

From the Airbnb JavaScript Style Guide

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(Vditor): add Vditor component

1 participant