Stéphane Laurent
Stéphane Laurent

Reputation: 84559

How to add an action opening a dropdown menu in Monaco Editor?

I know how to add an entry in the context menu of the Monaco editor, with editor.addAction. How to add an action which opens a dropdown list, as the "Command Palette" action?

enter image description here

Upvotes: 4

Views: 1677

Answers (1)

voorjaar
voorjaar

Reputation: 171

As mentioned in this issue, the quick-open api is not yet implemented in monaco-editor. But after a series of in-depth research, I found a somewhat hacker solution.

First, you need to import IQuickInputService like below.

import * as monaco from 'monaco-editor/esm/vs/editor/editor.main.js';
import { IQuickInputService } from 'monaco-editor/esm/vs/platform/quickinput/common/quickInput';

Then, create our editor.

// Create your editor instance...
let editor = monaco.editor.create(
  // ...
);

// Add a new command, for getting an accessor.
let quickInputCommand = editor.addCommand(0, (accessor, func) => {
  // a hacker way to get the input service
  let quickInputService = accessor.get(IQuickInputService)
  func(quickInputService)
});

Finally, as an example, we can add an action.

editor.addAction({
    id: "myQuickInput",
    label: "Test Quick Input",
    run: (editor) => {
         // create quick input
         editor.trigger("", quickInputCommand, (quickInput) => {
             quickInput.pick([
                {
                    type: 'item',
                    id: "my_quick_item",
                    label: "MyQuickItem",
                },
                {
                    type: 'item',
                    id: "my_quick_item2",
                    label: "MyQuickItem2",
                },
                {
                    type: 'item',
                    id: "my_quick_item3",
                    label: "MyQuickItem3",
                },
             ]).then((selected) => {
                console.log(selected)
             })
         })
    }
})

For the interface of IQuickInputService, please refer to here here

If you do it right, when you run the action, you should get the same result as I did.

enter image description here

Upvotes: 1

Related Questions