-
Notifications
You must be signed in to change notification settings - Fork 521
/
Copy pathEditorComponent.razor
73 lines (61 loc) · 2.26 KB
/
EditorComponent.razor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
@using System.Text.RegularExpressions;
@using System.Text;
@implements IAsyncDisposable
@inject IStringLocalizer<Resource> _localizer
@inject IJSRuntime _jsRuntime
@inject HttpClient _httpClient
<div class="easymde-wrapper">
<textarea @ref="_textareaReference" tabindex="2" class="visually-hidden" placeholder="@_localizer["type-here"]"></textarea>
</div>
<InputFile @ref="_inputFileReference" OnChange="@LoadImageFiles" style="display:none;" accept="image/*" />
@code {
[Parameter] public string Toolbar { get; set; } = default!;
private ValueTask<IJSObjectReference> _taskModule;
private ElementReference? _textareaReference;
private InputFile? _inputFileReference;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
_taskModule = _jsRuntime.InvokeAsync<IJSObjectReference>("import", "./admin/js/editor.js");
var module = await _taskModule;
var element = _inputFileReference?.Element;
await module.InvokeVoidAsync("loadEditor", Toolbar, _textareaReference, element);
}
}
protected async Task LoadImageFiles(InputFileChangeEventArgs args)
{
var module = await _taskModule;
var element = _inputFileReference?.Element;
await module.InvokeVoidAsync("writeFrontFile", element);
}
public async ValueTask SetValueAsync(string value)
{
var module = await _taskModule;
await module.InvokeVoidAsync("setEditorValue", value);
}
public async ValueTask<string?> GetValueAsync()
{
var module = await _taskModule;
var content = await module.InvokeAsync<string>("getEditorValue");
var imgsMatches = StringHelper.MatchesMarkdownImgBlob(content);
if (imgsMatches.Count > 0)
{
var contentStringBuilder = new StringBuilder(content);
foreach (Match match in imgsMatches)
{
var imageUrl = match.Groups[1].Value;
var imageBytes = await _httpClient.GetByteArrayAsync(imageUrl);
var base64String = Convert.ToBase64String(imageBytes);
contentStringBuilder.Replace(imageUrl, "data:image/png;base64," + base64String);
}
content = contentStringBuilder.ToString();
}
return content;
}
async ValueTask IAsyncDisposable.DisposeAsync()
{
var module = await _taskModule;
await module.DisposeAsync();
}
}