Code Monkey home page Code Monkey logo

blazormonaco's Introduction

BlazorMonaco

Blazor component for Microsoft's Monaco Editor which powers Visual Studio Code.

Some less-frequently used Monaco Editor features are currently missing, but a good amount of the basic feature set is supported. The package is updated regularly to cover more features and use cases. Any contributions, comments or suggestions are greatly welcome. Please feel free to contact me at twitter/serdarciplak or via GitHub.

Current version of BlazorMonaco :

  • Uses Monaco Editor v0.46.0
  • Supports netstandard2.0, net5.0, net6.0, net7.0 and net8.0

Demo

You can see a working sample WebAssembly app here.

Get Started

  • Add the NuGet package to your Blazor project.
dotnet add package BlazorMonaco
// or
Install-Package BlazorMonaco
  • Add the below script tags to your index.html file. Please note that these script tags must be placed before the script tag for the blazor.webassembly.js file.
<script src="_content/BlazorMonaco/jsInterop.js"></script>
<script src="_content/BlazorMonaco/lib/monaco-editor/min/vs/loader.js"></script>
<script src="_content/BlazorMonaco/lib/monaco-editor/min/vs/editor/editor.main.js"></script>
  • Everything resides in three namespaces. You can add the following using directives to your root _Imports.razor file, or any other place you may need them.
@using BlazorMonaco
@using BlazorMonaco.Editor
@using BlazorMonaco.Languages

Code Editor

Adding an editor instance

  • To add a new editor instance, you just need to add a StandaloneCodeEditor component in your razor file.
<StandaloneCodeEditor Id="my-editor-instance-id" />

Providing custom options

  • To customize your editor instance's initial options, set the ConstructionOptions parameter of the instance, and provide a method that returns a StandaloneEditorConstructionOptions instance.
<StandaloneCodeEditor Id="my-editor-instance-id" ConstructionOptions="EditorConstructionOptions" />
  • Then, add that method to your razor file's @code block and return a StandaloneEditorConstructionOptions instance with the values you need.
private StandaloneEditorConstructionOptions EditorConstructionOptions(StandaloneCodeEditor editor)
{
	return new StandaloneEditorConstructionOptions
	{
		AutomaticLayout = true,
		Language = "javascript",
		Value = "function xyz() {\n" +
				"   console.log(\"Hello world!\");\n" +
				"}"
	};
}

Editor events

  • You can subscribe to editor events (e.g. OnDidKeyUp or OnDidPaste) using the editor's event parameters.
<StandaloneCodeEditor Id="my-editor-instance-id" OnDidChangeCursorPosition="EditorDidChangeCursorPosition" />
  • Then, add your event listener method to your razor file's @code block.
private void EditorDidChangeCursorPosition(CursorPositionChangedEvent eventArgs)
{
	Console.WriteLine("EditorDidChangeCursorPosition");
}

Diff Editor

Adding a diff editor instance

  • To add a new diff editor instance, you just need to add a StandaloneDiffEditor component in your razor file.
<StandaloneDiffEditor Id="my-editor-instance-id" />

Access to inner editor instances and events

  • StandaloneDiffEditor class provides two properties named OriginalEditor and ModifiedEditor for accessing the inner editor instances. You can use them like any other StandaloneCodeEditor instances.

  • You can register to inner editors' events using the helper event parameters of the main StandaloneDiffEditor instance.

<StandaloneDiffEditor Id="my-editor-instance-id" OnKeyUpOriginal="OnKeyUpOriginal" OnKeyUpModified="OnKeyUpModified" />

Notes

Css styling

  • There are 3 css selectors you can use to add/edit css styles for your editors.
    • The main html element of all editor instances contains the monaco-editor-container css class.
    • The Id value you set for your razor component is also set as the id of its html element.
    • You can provide a string in the CssClass property of an editor instance. That value will be added to the class attribute of its html element.
<StandaloneCodeEditor Id="my-editor-id" CssClass="my-editor-class" />
.monaco-editor-container { /* for all editor instances */
	height: 100px;
}

/* or */

#my-editor-id { /* for a specific editor instance */
	height: 100px;
}

/* or */

.my-editor-class { /* for a specific editor instance */
	height: 100px;
}

⚠️ Note : As an html element cannot set its height disregarding where it's placed in, BlazorMonaco cannot manage editor instance heights. So, if you don't do that yourself, editor instances may have a height of 0px and be invisible. Please don't forget to set your editor instance heights as you need.

Global Methods

Monaco Editor JavaScript library defines some methods in the global scope. As C# does not allow global methods, BlazorMonaco groups those methods in two static classes named BlazorMonaco.Editor.Global and BlazorMonaco.Language.Global. If you need to use a Monaco Editor method in the global scope, check where in the JavaScript library that method is, and search for it in the corresponding Global class. They're defined as static methods.

For example, you can use the SetTheme method as below.

await BlazorMonaco.Editor.Global.SetTheme(jsRuntime, "my-custom-theme");

Using a custom Monaco Editor setup

  • If you've made changes to Monaco Editor, and need to use this edited version instead of the unmodified version packed with BlazorMonaco, just change the paths to monaco editor resources in your index.html file.
<script src="_content/BlazorMonaco/jsInterop.js"></script>
<script>var require = { paths: { vs: 'my-path/monaco-editor/min/vs' } };</script>
<script src="my-path/monaco-editor/min/vs/loader.js"></script>
<script src="my-path/monaco-editor/min/vs/editor/editor.main.js"></script>

Documentation

As BlazorMonaco is just a bridge between JavaScript and Blazor, you can use Monaco Editor's documentation.

Migration Guide

After a major version update (like from v2.x.x to v3.x.x), you may need to make some changes in your integration. Please see the MIGRATE.md for details.

Change Log

You can view the history and the changes in the CHANGELOG.md

License

MIT, see the LICENSE file for detail.

blazormonaco's People

Contributors

alperenbelgic avatar marijnpessers avatar sciplak-zng avatar serdarciplak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

blazormonaco's Issues

Rare unhandled exception 'monaco not defined'

With a minimal implementation of the editor it is possible to create an unhandled exception by refreshing without caching (CTRL+F5 in Chrome).

For this, I created an empty Blazor webassembly project, and just inserted an empty editor in the index. I then press CTRL+F5 a few times and every once in a while, you can see the following stack trace in the console:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: monaco is not defined
      ReferenceError: monaco is not defined
          at Object.create (https://localhost:44373/_content/BlazorMonaco/jsInterop.js:39:22)
          at https://localhost:44373/_framework/blazor.webassembly.js:1:9805
          at new Promise (<anonymous>)
          at Object.beginInvokeJSFromDotNet (https://localhost:44373/_framework/blazor.webassembly.js:1:9773)
          at _mono_wasm_invoke_js_marshalled (https://localhost:44373/_framework/wasm/dotnet.3.2.0.js:1:171294)
          at do_icall (<anonymous>:wasm-function[6049]:0x10f8b1)
          at do_icall_wrapper (<anonymous>:wasm-function[1896]:0x50b6a)
          at interp_exec_method (<anonymous>:wasm-function[1120]:0x2588e)
          at interp_runtime_invoke (<anonymous>:wasm-function[5655]:0xf7391)
          at mono_jit_runtime_invoke (<anonymous>:wasm-function[5109]:0xddb3d)
Microsoft.JSInterop.JSException: monaco is not defined
ReferenceError: monaco is not defined
    at Object.create (https://localhost:44373/_content/BlazorMonaco/jsInterop.js:39:22)
    at https://localhost:44373/_framework/blazor.webassembly.js:1:9805
    at new Promise (<anonymous>)
    at Object.beginInvokeJSFromDotNet (https://localhost:44373/_framework/blazor.webassembly.js:1:9773)
    at _mono_wasm_invoke_js_marshalled (https://localhost:44373/_framework/wasm/dotnet.3.2.0.js:1:171294)
    at do_icall (<anonymous>:wasm-function[6049]:0x10f8b1)
    at do_icall_wrapper (<anonymous>:wasm-function[1896]:0x50b6a)
    at interp_exec_method (<anonymous>:wasm-function[1120]:0x2588e)
    at interp_runtime_invoke (<anonymous>:wasm-function[5655]:0xf7391)
    at mono_jit_runtime_invoke (<anonymous>:wasm-function[5109]:0xddb3d)
  at System.Threading.Tasks.ValueTask`1[TResult].get_Result () <0x2e21640 + 0x00034> in <filename unknown>:0 
  at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync (Microsoft.JSInterop.IJSRuntime jsRuntime, System.String identifier, System.Object[] args) <0x2dd4600 + 0x000e4> in <filename unknown>:0 
  at BlazorMonaco.MonacoEditorBase.Create (System.String id, BlazorMonaco.Bridge.StandaloneEditorConstructionOptions options) <0x2d135b0 + 0x0016c> in <filename unknown>:0 
  at BlazorMonaco.MonacoEditor.OnAfterRenderAsync (System.Boolean firstRender) <0x2d12a00 + 0x000fe> in <filename unknown>:0 
  at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x2de2038 + 0x000b6> in <filename unknown>:0 

Registering custom languages

Hello @serdarciplak ,
I'm curious if you're still supporting this library, seems like no new contributions since December.
I'm actually quite interested, in using this one in a big project, and it is important to me, if there's activity/support, otherwise I will probably have to respectfully clone it if issues come up.

Blazor server side

Been trying to use it on a Blazor Server app and it seems to load fine but the component has no height, it shows as a very thin line. Is this something I'm missing or an incompatibility with Blazor Server?.
blazormonaco_issue

ITextModel.GetAllDecorations() should return an array

Hi, adding the ITextModel bindings is a huge help.

I thing there is a small error in the GetAllDecorations(). you have it returning a single ModelDecoration object, but the documentation says the returned object should be an array - ModelDecorations[], which is also implied by the function name.

Thanks again!

OnChange event

I believe the Monaco editor has an event for detecting a text change (onDidChangeContent on the model), but this hasn't been ported to BlazorMonaco (yet).

Is this going to be implemented (and if yes, when)?

All Events are triggered twice

Hi, first off, awsome project.

When using the editor and registering any eventListener, for some reason the event is triggered twice, this can be reproduced on the demo app, just open the console and right click on the editor, you should see that "OnContextMenu" was "printed/triggered" twice.

Console Print:
image

Theming for DiffEditor

Hey,

I was just curious to find out if there´s a "SetTheme" method for the diff editor.
The DiffEditorConstructionOptions doesn´t have a "Theme" property as well.

Extended Lauguage Support - JSON Schemas

I'm using this editor to support JSON file authoring. Out of the box this is supported and works fine.

I'm also looking to validate and ensure that the authored JSON conforms to a given schema that I will provide. This is similar to the "Configure Json Defaults" example on the playground.

Example: https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-configure-json-defaults

I see all of this documented on Monaco's Language API but don't see an obvious mechanism to set these values in this implementation.

API: https://microsoft.github.io/monaco-editor/api/modules/monaco.languages.json.html

Is this possible?

Thanks,
~Derek

Editor is only created the first time the component is initialized

It seems that the bridge will only create the Monaco Editor one time. Once the component is disposed, it appears that the Monaco Editor will no longer be created. After that, only the container html element is created.
Is there currently a way to generate the Editor more than once? Perhaps I missed something, but I suspect this would require a change to the interop.

Error when running in Electron

Can't have it to run in Electron.

To reproduce:
Create a new Blazor Server project.
Add ElectronNet.Api
Add Blazor Monaco and add an MonacoEditor according to instructions.

electronize start

It's working fine when running in IIS with dotnet run, but not when running as Electron with electronize start..

More API type bindings

More API type bindings

Hello, thanks for this awesome project.

Monaco has plenty of APIs and types, it'll be a non-trivial work if writing those C# type bindings by hand.

To make development of monaco-related C# projects eaiser, I've generated monaco 0.22.3 C# type bindings using TypedocConverter and saved it to https://gist.github.com/hez2010/3d3e493f8e434f1dc758438c4a2c9dab.

If you need to write C# type bindings for monaco, I think you can make use of the auto-generated type bindings so that you don't need to write most of them manually.

LineNumber property

Hi, i'm trying to "bind" two editors together, this just means that the last "line number" of the first editor will become the first linenumber of the second editor, just to allow me to have a "read only" area on the "editor"

image
should this work? knowing that most of this will run as "interop"

image
a code very "similiar" will run on the "playground" without issues.

looking at the "create" function used in the JsInterop File, maybe that the function is being set as a "string".

am i doing something wrong?

Feature: Language Server Support

With the exception of Javascript, many of the languages supported in Monaco, and thus BlazorMonaco, do not have their own inbuilt language servers, just syntax highlighting. It would be amazing to have the ability to easily add language servers, like with what https://www.npmjs.com/package/monaco-languageclient does, but reimplemented in C#.

One of the most common reasons I can see for this is, if you're using BlazorMonaco, you may want to use C# in the editor, and thus you'd probably want a language server for intelisense like the following adds support for->
https://github.com/OmniSharp/csharp-language-server-protocol

If not, an example of the implementation of such would be rather useful aswell.

Dependencies

Hi @serdarciplak I love your application but now I am trying to include it in a Razor Class Library and I get the error that is depends on Microsoft.AspNetCore.Components v 5.0.0.-preview 3
Is there a functionality in this dependency that is not covered in 3.1.6?

I have the privilege to use this in an innovative environment, but I can imagine that a lot of people don't want libraries that require their project to update to a non-release version. Now that WASM is officially released, could you change the dependencies to non-prerelease libraries?

Cheers,
Marijn

how to execute editor actions?

I am trying to pragramatically execute actions
specifically indenting the document, which is Shift+Alt+F
looking at the documenation for the key codes i cam up with this method

monacoEditor.ActionCallback("4;6;36");

however, i am getting the exception that this key code does not exist (within an internal dictionary)

getValueInRange

Is there a problem with the implementation of ITextModel.getValueInRange() ?

When I include the following code in a OnMouseUp event

        Selection sel = await _editorSource.GetSelection();
        TextModel m = await _editorSource.GetModel();
        BlazorMonaco.Bridge.Range range = new BlazorMonaco.Bridge.Range(sel.StartLineNumber, sel.StartColumn, sel.EndLineNumber, sel.EndColumn);
        string s =  m.getValueInRange(range);

I get the following compilation error:
'TextModel' does not contain a definition for 'getValueInRange' and no accessible extension method 'getValueInRange' accepting a first argument of type 'TextModel' could be found

Or am I doing something wrong?

Or, is it possibly related to the open Pull request?

Changing the suggestions box content

Hello, I am looking to compile c# , by using Roslyn.
So I need to be able to change the suggestions box content.
Can I do that with this package or not yet ?

AMD Loader Incompatible with ESM loading

I am not an expert on this but I think that the AMD loader used for loading the Monaco module is incompatible with the ESM loader used as part of a components ability to lazy load js modules. When I add the loader.js required by this project to load the monaco module then all the js inside my other components appears to stop working.

I think the fix is to change Monaco to use the ESM compiled module and ideally lazy load the js inside this component.

I am not certain though, what I know is that if I use code like:

private Task<IJSObjectReference> vjsModule => _vjsModule ??= JavaScript.InvokeAsync<IJSObjectReference>("import", "./js/vjs/vjs-module.js").AsTask();

inside my component it no longer functions when I add the loader.js script reference in my index.html.

Does this work with Blazor Server?

Does this work with Blazor Server? I tried and no matter where I put the script tags I either get an error or if I get rid of the error, then page navigation stops working.

Defining custom languages

Hi,

I'm trying to register a custom language for the editor and I can't seem to figure it out.

I have tried adding a script that I have created using the Monaco playground at the end of the index.html file that adds the language, to no avail (it doesn't seem to recognize monaco).
The console in the browser shows that the monaco object has a languages property that is undefined. The tutorials/docs I found for creating a new language seems to be accessing this property so I'm at a loss.

Is it possible to define a (simple) language in BlazorMonaco somewhere? If so, how should I approach this?

Yours sincerely,
Sven

Uncaught Error: Can only have one anonymous define call per script file with Blazor Server

Finally I can use Monaco Editor using your library in my project.
but I am having this issue .

I would like to know how to solve this issue.

Uncaught Error: Can only have one anonymous define call per script file
at r.enqueueDefineAnonymousModule (loader.js:7:5413)
at _ (loader.js:8:1734)
at Chart.min.js:7:179
at Chart.min.js:7:302
blazor.server.js:1 [2022-02-18T13:50:56.874Z] Information: Normalizing '_blazor' to 'https://localhost:5001/_blazor'.
loader.js:1344 Duplicate definition of module 'vs/editor/editor.main.nls'

I found this link but honestly I don't know how to fix it with Blazor Server
microsoft/monaco-editor#2283

thank you

Sample app is not working

Hello! the sample app in this repo is not working.
also I would like to know if BlazorMonaco project will support NET 6.
Thank you!

Editor gets buggy when Radzen.Blazor is added with supporting css libraries.

I added Radzen.Blazor and now the editor is not working correctly.
Issues experienced:
SetValue not always working
Cursor doesn't move on the editor UI
Right side preview goes past extents of actual editor.
Unable to scroll to top one you scroll down.
Intellisense menu glitching (No better description

Scrolling:

Scroll

Cursor and Intellisense:

CursorAndIntellisense

Preview overflow:

Overflow
)

Error when ConstructionOptions isn't set

Hello,

when the function reference property "ConstructionOptions" isn't set, one get's an error:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
at BlazorMonaco.MonacoEditor.OnAfterRenderAsync(Boolean firstRender)

Maybe this works as designed but a component should not cause a page exception when properties aren't said - right?

AutomaticLayout? Does it work?

AutomaticLayout = true

Should It work on width and height?
I am trying to get it work with https://split.js.org/
However, it doesn't work :(

image
image

On start is working, otherwise when I drag gutter horizontal to resize width is cutting editor. ;/

image

Monaco Editor displays

When displaying the BlazorMonaco editor in a Radzen Blazor application the control displays only about 2 pixels high making it unusable. All other controls appear normally. Can you suggest a remedy? I have checked the location of all the content links and scripts and everything appears to be correct. The Razor script is taken directly from your sample (which works fine). Screenshot attached below:
MonacoBlazor

How do you read the lines of code in the editor?

I am trying to read the lines of code in the editor, and the GetValue().ToString() does not work. I have seen many people online having this issue with Monaco in general, and was wondering if you knew how to get to the lines of code in BlazorMonaco. I really don't care how I get to them or what they come in as, but I need to see the lines of code.

Proposal: remove hardcoded style

Hi there,
I propose that you remove the hardcoded style="min-height:100px;border:1px solid gray; in MonacoEditor.razor.
It's very easy to wrap the editor with a div containing that style, but impossible to remove the border when you hardcode it like it is.
I have no beef with min-height, but assume some people might want to have a one-liner Monaco here and there.

Custom language Providers

I'm looking forward to trying this out in my project. 👍

In my setup I need to be able to switch languages between the built in providers, and also custom language providers.

How can we do this?

How to CreateDiffNavigator?

Hello,

is there a way to navigate from difference to difference like in the playground from microsoft here.

Are you working on DiffNavigatorOptions?

Best regards

Waldemar

Sample Code yields to a tiny container

See screenshot. Something is wrong with the CSS
Screenshot 2021-05-24 213426

This is the _index.html of the Blazor WebAssembly project (.NET 5.0, VS 2019)
I attached the index.html (renamed to index.txt).
index.txt
I did follow your instructions - but something seems to be broken.

Json & registerCompletionItemProvider

Hello ,

Thanks for maintaining this repo . For guys like me who are not strong with Javascript such help is always appreciated. .

I am able to change language to Json but I don’t know how to implement registerCompletionItemProvider In blazor project. I want to provide customise suggestions.

How can I use this with a base href?

In my _Host, I have an unusual tag:

<base href="~/Blazor/" />

There are reasons for this that it doesn't make sense to elaborate on right now, but it results in the base path for all relative urls to begin at mysite/Blazor... That throws off all the links. Normally I would change them like this:

<script src="~/_content/BlazorMonaco/lib/monaco-editor/min/vs/loader.js"></script>

But that isn't working in this case. I think the loader doesn't know what do with the ~/, because in the console I'm getting errors like:

Error: Could not find ~/_content/BlazorMonaco/lib/monaco-editor/min/vs/editor/editor.main.css or it was empty
at Object.t [as ensureError] (loader.js:242)

I would love use this... I have a phenomenal use case. Any ideas?

Adding languages

Hi,
Im not an expert, but i want to add different languages. Right now im trying to add kusto and looks that its not working. Do you have any small tutorial on how to do it. I know its nut an issue, but will be much appreciated.

Passing editor content as child content?

Is it possible to build a component so I can pass the content of the editor as child content? Something like this:

<MonacoEditor2>
// Hello World! program
namespace HelloWorld
{
    class Hello {
        static void Main(string[] args)
        {
            System.Console.WriteLine("Hello World!");
        }
    }
}
</MonacoEditor2>

Unable to bind value to c# object.

Is there a way to data-bind the value to a string or a string property of an object? I have not seen any documentation on data binding at all.

DeltaDecoration

Hi,
I have extended the projects with 2 methods that will Set and Reset DeltaDecorations. I would like to make a pull request. Could you open the project so I can send a pull requests to the project?

Editor is rendering squashed

image

Is there any reason it would render like this out of the box? I don't have any css applied, but it seems to be rendering at 5px in height

Add overload for Trigger() replacing JsonElement as parameter

I've created a custom c# code completion provider and created an action to trigger it manually. This requires using Monaco's editor.trigger function. However, the interop method makes this sort of awkward since JsonElement isn't really designed to be used outside of a JsonDocument.
I've made this work by directly invoking your blazorMonaco.editor.trigger javascript function.

private async Task Suggest() => await Js.InvokeVoidAsync("blazorMonaco.editor.trigger", _editor.Id, "whatever...", "editor.action.triggerSuggest", "whatever...");

While this isn't particularly burdensome, I think it would be good to offer an overload of the Trigger method that takes a string or object instead of a JsonElement for the payload, particularly since the payload doesn't require a meaningful value for many of Monaco's triggered functions.

If you agree, I'd be happy to submit a pull-request to this effect.

Update for dotnet 5.0

All the examples use RC versions of dot net currently. Will you be updating the target and sample project to dotnet core 5.0?

Diff editor System.NullReferenceException

Hey,

I´ve recreated your diffeditor implementation in my environment using the startup guide you´ve provided.
Unfortunately, when loading the page which contains the diff editor, it throws a System.NullReferenceException.

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request. System.NullReferenceException: Object reference not set to an instance of an object. at BlazorMonaco.MonacoDiffEditor.Dispose() at Microsoft.AspNetCore.Components.Rendering.ComponentState.Dispose() at Microsoft.AspNetCore.Components.RenderTree.Renderer.Dispose(Boolean disposing)

This is basically the implementation copied from your example which I tested.
`
<MonacoDiffEditor @ref="_diffEditor" Id="sample-diff-editor-123" ConstructionOptions="DiffEditorConstructionOptions" OnDidInit="EditorOnDidInit" OnKeyUpOriginal="EditorOnKeyUpOriginal" OnKeyUpModified="EditorOnKeyUpModified" />

@code {
private MonacoDiffEditor _diffEditor { get; set; }
private string ValueToSetOriginal { get; set; }
private string ValueToSetModified { get; set; }

private DiffEditorConstructionOptions DiffEditorConstructionOptions(MonacoDiffEditor editor)
{
    return new DiffEditorConstructionOptions
    {
        OriginalEditable = true
    };
}

private async Task EditorOnDidInit(MonacoEditorBase editor)
{
    // Get or create the original model
    TextModel original_model = await MonacoEditorBase.GetModel("sample-diff-editor-originalModel");
    if (original_model == null)
    {
        var original_value = "\"use strict\";\n" +
                        "function Person(age) {\n" +
                        "	if (age) {\n" +
                        "		this.age = age;\n" +
                        "	}\n" +
                        "}\n" +
                        "Person.prototype.getAge = function () {\n" +
                        "	return this.age;\n" +
                        "};\n";
        original_model = await MonacoEditorBase.CreateModel(original_value, "javascript", "sample-diff-editor-originalModel");
    }

    // Get or create the modified model
    TextModel modified_model = await MonacoEditorBase.GetModel("sample-diff-editor-modifiedModel");
    if (modified_model == null)
    {
        var modified_value = "\"don't use strict\";\n" +
                        "furction Person(age_is_just_a_number) {\n" +
                        "	if (age_is_just_a_number) {\n" +
                        "		this.age_is_just_a_number = age_is_just_a_number;\n" +
                        "	}\n" +
                        "}\n" +
                        "Person.prototype.getAge = function () {\n" +
                        "	return this.age_is_just_a_number;\n" +
                        "};\n" +
                        "//Really, it is just a number people!";
        modified_model = await MonacoEditorBase.CreateModel(modified_value, "javascript", "sample-diff-editor-modifiedModel");
    }

    // Set the editor model
    await _diffEditor.SetModel(new DiffEditorModel
    {
        Original = original_model,
        Modified = modified_model
    });
}

private void EditorOnKeyUpOriginal(KeyboardEvent keyboardEvent)
{
    Console.WriteLine("OnKeyUpOriginal : " + keyboardEvent.Code);
}

private void EditorOnKeyUpModified(KeyboardEvent keyboardEvent)
{
    Console.WriteLine("OnKeyUpModified : " + keyboardEvent.Code);
}

private async Task SetValueOriginal()
{
    Console.WriteLine($"setting original value to: {ValueToSetOriginal}");
    await _diffEditor.OriginalEditor.SetValue(ValueToSetOriginal);
}

private async Task SetValueModified()
{
    Console.WriteLine($"setting modified value to: {ValueToSetModified}");
    await _diffEditor.ModifiedEditor.SetValue(ValueToSetModified);
}

private async Task GetValueOriginal()
{
    var val = await _diffEditor.OriginalEditor.GetValue();
    Console.WriteLine($"original value is: {val}");
}

private async Task GetValueModified()
{
    var val = await _diffEditor.ModifiedEditor.GetValue();
    Console.WriteLine($"modified value is: {val}");
}

private async Task AddCommand()
{
    await _diffEditor.ModifiedEditor.AddCommand((int)KeyMode.CtrlCmd | (int)KeyCode.Enter, (editor, keyCode) =>
    {
        Console.WriteLine($"Ctrl+Enter : Original Editor command is triggered. ({editor.Id})");
    });
}

private async Task AddAction()
{
    await _diffEditor.ModifiedEditor.AddAction("testAction", "Test Action", new int[] { (int)KeyMode.CtrlCmd | (int)KeyCode.KEY_D, (int)KeyMode.CtrlCmd | (int)KeyCode.KEY_B }, null, null, "navigation", 1.5, (editor, keyCodes) =>
    {
        Console.WriteLine($"Ctrl+D : Modified Editor action is triggered. ({editor.Id})");
    });
}

}`

I´m targeting .Net 5.0 and use Blazor.ServerSide

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.