Markdown

The Markdown component allows you to edit markdown strings. The Blazorise Markdown is based on the Easy MarkDown Editor JavaScript library.

Installation

NuGet

Install extension from NuGet.
Install-Package Blazorise.Markdown

Imports

In your main Imports.razor add:
@using Blazorise.Markdown

Static Files

Include CSS and JS links into your index.html or _Host.cshtml file, depending if you’re using a Blazor WebAssembly or Blazor Server side project.
<link href="https://unpkg.com/easymde/dist/easymde.min.css" rel="stylesheet" />
<script src="https://unpkg.com/easymde/dist/easymde.min.js"></script>
<script src="https://cdn.jsdelivr.net/highlight.js/latest/highlight.min.js"></script>

Example

<Markdown Value="@markdownValue" ValueChanged="@OnMarkdownValueChanged" />
@code{
    string markdownValue = "# EasyMDE \n Go ahead, play around with the editor! Be sure to check out **bold**, *italic*, [links](https://google.com) and all the other features. You can type the Markdown syntax, use the toolbar, or use shortcuts like `ctrl-b` or `cmd-b`.";

    string markdownHtml;

    protected override void OnInitialized()
    {
        markdownHtml = Markdig.Markdown.ToHtml( markdownValue ?? string.Empty );

        base.OnInitialized();
    }

    Task OnMarkdownValueChanged( string value )
    {
        markdownValue = value;

        markdownHtml = Markdig.Markdown.ToHtml( markdownValue ?? string.Empty );

        return Task.CompletedTask;
    }
}

Toolbar customization

The editor's toolbar can be edited to show more icons and even add custom icons!
<Markdown @bind-Value="@markdownValue" CustomButtonClicked="@OnCustomButtonClicked">
    <Toolbar>
        <MarkdownToolbarButton Action="MarkdownAction.Bold" Icon="fa fa-bolt" Title="Bold" />
        <MarkdownToolbarButton Separator Name="Custom button" Value="@("hello")" Icon="fa fa-star" Title="A Custom Button" />
        <MarkdownToolbarButton Separator Name="https://github.com/Ionaru/easy-markdown-editor" Icon="fa fab fa-github" Title="A Custom Link" />
    </Toolbar>
</Markdown>
@code {
    [Inject] private INotificationService NotificationService { get; set; }

    string markdownValue = "## Custom Toolbar\nCustom functions, icons and buttons can be defined for the toolbar.";

    Task OnCustomButtonClicked( MarkdownButtonEventArgs eventArgs )
    {
        NotificationService.Info( $"Name: {eventArgs.Name} Value: {eventArgs.Value}" );

        return Task.CompletedTask;
    }
}

Upload image

Uploading image has a similar API to our FileEdit component and it is fairly simple to do.
<Markdown ImageUploadChanged="@OnImageUploadChanged"
          ImageUploadStarted="@OnImageUploadStarted"
          ImageUploadProgressed="@OnImageUploadProgressed"
          ImageUploadEnded="@OnImageUploadEnded" />
@code {
    async Task OnImageUploadChanged( FileChangedEventArgs e )
    {
        try
        {
            foreach ( var file in e.Files )
            {
                using ( var stream = new System.IO.MemoryStream() )
                {
                    await file.WriteToStreamAsync( stream );

                    // do something with the stream
                }
            }
        }
        catch ( Exception exc )
        {
            Console.WriteLine( exc.Message );
        }
        finally
        {
            this.StateHasChanged();
        }
    }

    Task OnImageUploadStarted( FileStartedEventArgs e )
    {
        Console.WriteLine( $"Started Image: {e.File.Name}" );

        return Task.CompletedTask;
    }

    Task OnImageUploadProgressed( FileProgressedEventArgs e )
    {
        Console.WriteLine( $"Image: {e.File.Name} Progress: {(int)e.Percentage}" );

        return Task.CompletedTask;
    }

    Task OnImageUploadEnded( FileEndedEventArgs e )
    {
        // We need to report back to Markdown that upload is done. We do this by setting the UploadUrl.
        // NOTE: Since we're faking the upload in this demo we will just set some dummy UploadUrl.
        e.File.UploadUrl = "https://images.pexels.com/photos/4966601/pexels-photo-4966601.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=200";

        Console.WriteLine( $"Finished Image: {e.File.Name}, Success: {e.Success}" );

        return Task.CompletedTask;
    }
}

Attributes

Name Description Type Default
Value Gets or sets the markdown value. string null
ValueChanged An event that occurs after the markdown value has changed. EventCallback<string> Solid
AutoDownloadFontAwesome If set to true, force downloads Font Awesome (used for icons). If set to false, prevents downloading. bool? null
LineNumbers If set to true, enables line numbers in the editor. bool false
LineWrapping If set to false, disable line wrapping. Defaults to true. bool false
MinHeight Sets the minimum height for the composition area, before it starts auto-growing. Should be a string containing a valid CSS value like "500px". Defaults to "300px". string 300px
MaxHeight Sets fixed height for the composition area. minHeight option will be ignored. Should be a string containing a valid CSS value like "500px". Defaults to undefined. string
Placeholder If set, displays a custom placeholder message. string null
TabSize If set, customize the tab size. Defaults to 2. int 2
Theme Override the theme. Defaults to easymde. string easymde
Direction rtl or ltr. Changes text direction to support right-to-left languages. Defaults to ltr. string ltr
HideIcons An array of icon names to hide. Can be used to hide specific icons shown by default without completely customizing the toolbar. string[] 'side-by-side', 'fullscreen'
ShowIcons An array of icon names to show. Can be used to show specific icons hidden by default without completely customizing the toolbar. string[] 'code', 'table'
Toolbar [Optional] Gets or sets the content of the toolbar. RenderFragment
ToolbarTips If set to false, disable toolbar button tips. Defaults to true. bool true
CustomButtonClicked Occurs after the custom toolbar button is clicked. EventCallback<MarkdownButtonEventArgs>
UploadImage If set to true, enables the image upload functionality, which can be triggered by drag-drop, copy-paste and through the browse-file window (opened when the user click on the upload-image icon). Defaults to false. bool false
MaxUploadImageMessageSize Gets or sets the max message size when uploading the file. long 20 * 1024
SegmentFetchTimeout Gets or sets the Segment Fetch Timeout when uploading the file. TimeSpan 1 min
ImageMaxSize Maximum image size in bytes, checked before upload (note: never trust client, always check image size at server-side). Defaults to 1024*1024*2 (2Mb). long 1024*1024*2 (2Mb)
ImageAccept A comma-separated list of mime-types used to check image type before upload (note: never trust client, always check file types at server-side). Defaults to image/png, image/jpeg. string image/png, image/jpeg
ImageUploadEndpoint The endpoint where the images data will be sent, via an asynchronous POST request. The server is supposed to save this image, and return a json response. string
ImagePathAbsolute If set to true, will treat imageUrl from imageUploadFunction and filePath returned from imageUploadEndpoint as an absolute rather than relative path, i.e. not prepend window.location.origin to it. string
ImageCSRFToken CSRF token to include with AJAX call to upload image. For instance used with Django backend. string
ImageTexts Texts displayed to the user (mainly on the status bar) for the import image feature, where #image_name#, #image_size# and #image_max_size# will replaced by their respective values, that can be used for customization or internationalization. MarkdownImageTexts null
ImageUploadChanged Occurs every time the selected image has changed. Func<FileChangedEventArgs, Task>
ImageUploadStarted Occurs when an individual image upload has started. Func<FileStartedEventArgs, Task>
ImageUploadEnded Occurs when an individual image upload has ended. Func<FileEndedEventArgs, Task>
ImageUploadWritten Occurs every time the part of image has being written to the destination stream. Func<FileWrittenEventArgs, Task>
ImageUploadProgressed Notifies the progress of image being written to the destination stream. Func<FileProgressedEventArgs, Task>
ErrorMessages Errors displayed to the user, using the errorCallback option, where #image_name#, #image_size# and #image_max_size# will replaced by their respective values, that can be used for customization or internationalization. MarkdownErrorMessages
ErrorCallback A callback function used to define how to display an error message. Defaults to (errorMessage) => alert(errorMessage). Func<string, Task>