Skip to main content

Basic Usage

This page will explain about the basic usage of the constrain editor plugin.

Creating an Instance#

The instance of the constrain editor has to be created only after the monaco editor is loaded. And monaco editor has to be sent into constructor as a first argument.

require(['vs/editor/editor.main'], function () {  // ...  const constrainedInstance = constrainedEditor(monaco);  // ...}

Here, monaco instance will be used for checking the incoming editor instances and generating ranges from the array.

Initializing#

Once the constrained editor instance is created, it can be used to add the necessary APIs into the editor instance via initializeIn API.

require(['vs/editor/editor.main'], function () {  const constrainedInstance = constrainedEditor(monaco);  const editorInstance = monaco.editor.create(document.getElementById('container'), {    value: [      'const utils = {};',      'function addKeysToUtils(){',      '',      '}',      'addKeysToUtils();'    ].join('\n'),    language: 'javascript'  });  constrainedInstance.initializeIn(editorInstance);}

Adding Restrictions To Model#

After initializing the constrained editor in the editor instance of the monaco editor, Restrictions in the model has to be added to the model via addRestrictionsTo API.

const model = editorInstance.getModel();constrainedInstance.addRestrictionsTo(model, [  {    range: [1, 7, 1, 12], // Range of Util Variable name    label: "utilName",  },  {    range: [3, 1, 3, 1], // Range of Function definition    allowMultiline: true,    label: "funcDefinition",  },]);

Now, try typing in the editor, Only places defined in the addRestrictionsTo will be editable.All other places will become read-only.

tip

Label key is optional, yet it will be very useful while fetching the values.

Add Change Listener#

A Content Change Listener exclusively for the changes happening in the editable ranges is present in Constrained Editor Plugin.

caution

This function won't be called if the validate function of any one of the range restriction has returned false

model.onDidChangeContentInEditableRange(function (  currentlyChangedContent,  allValuesInEditableRanges,  currentEditableRangeObject) {  // Function to execute on content change inside editable ranges});

For more information on this API, click here