UIAPI

The UIAPI provides comprehensive user interface components and interaction methods for plugins. It enables plugins to create rich user experiences through notifications, dialogs, panels, progress indicators, and more.

Quick Reference

CategoryMethods
NotificationsshowInformationMessage, showWarningMessage, showErrorMessage, showNotification
DialogsshowInputBox, showPrompt, showConfirm, showDialog, showQuickPick, showOpenDialog, showSaveDialog
PanelsaddPanel, removePanel, updatePanel, registerPanel
ProgresswithProgress
Tree ViewsregisterTreeDataProvider
Status BarregisterStatusBarItem
OutputcreateOutputChannel
WebviewsregisterWebviewPanel
MenusregisterMenu
ToolbarsregisterToolbar
TerminalcreateTerminal

Notifications

showInformationMessage(message, …items)

Shows an information message to the user.

Parameters:

NameTypeDescription
messagestringMessage to display
itemsstring[]Optional action buttons

Returns: Promise\\<string | undefined\\> - Selected item or undefined if dismissed

Example:

const result = await api.ui.showInformationMessage(
  'File saved successfully',
  'Open', 'Dismiss'
);
 
if (result === 'Open') {
  // Handle open action
}

showWarningMessage(message, …items)

Shows a warning message to the user.

Parameters:

NameTypeDescription
messagestringWarning message to display
itemsstring[]Optional action buttons

Returns: Promise\\<string | undefined\\> - Selected item or undefined

Example:

await api.ui.showWarningMessage('This action cannot be undone');

showErrorMessage(message, …items)

Shows an error message to the user.

Parameters:

NameTypeDescription
messagestringError message to display
itemsstring[]Optional action buttons

Returns: Promise\\<string | undefined\\> - Selected item or undefined

Example:

await api.ui.showErrorMessage('Failed to load plugin configuration');

showNotification(message, type, actions)

Shows a notification with optional type and action buttons.

Parameters:

NameTypeDefaultDescription
messagestring-Notification message
typestring'info'Notification type: 'info', 'warning', 'error', 'success', 'loading', 'progress'
actionsArray\\<\\{id: string, label: string\\}\\>[]Action buttons

Returns: Promise\\<string | undefined\\> - Selected action ID or undefined

Example:

const actionId = await api.ui.showNotification(
  'Update available',
  'info',
  [
    { id: 'install', label: 'Install Now' },
    { id: 'later', label: 'Later' }
  ]
);
 
if (actionId === 'install') {
  // Install update
}

Dialogs

showInputBox(options)

Shows an input box to get text input from the user.

Parameters:

NameTypeDescription
optionsobjectInput box options
options.titlestringDialog title
options.promptstringPrompt message
options.placeholderstringPlaceholder text
options.valuestringDefault value
options.validateInputfunctionValidation function that returns error message or null

Returns: Promise\\<string | null\\> - User input or null if cancelled

Example:

const name = await api.ui.showInputBox({
  title: 'Enter Name',
  prompt: 'Please enter your name',
  placeholder: 'John Doe',
  validateInput: (value) => {
    if (!value || value.trim().length === 0) {
      return 'Name cannot be empty';
    }
    return null;
  }
});
 
if (name) {
  console.log('User entered:', name);
}

showPrompt(options)

Shows a prompt dialog for user input.

Parameters:

NameTypeDescription
optionsobjectPrompt options
options.titlestringDialog title
options.messagestringPrompt message
options.placeholderstringPlaceholder text
options.defaultValuestringDefault value
options.validatefunctionValidation function

Returns: Promise\\<string | null\\> - User input or null if cancelled

Example:

const apiKey = await api.ui.showPrompt({
  title: 'API Configuration',
  message: 'Enter your API key',
  placeholder: 'sk-...'
});

showConfirm(options)

Shows a confirmation dialog with OK and Cancel buttons.

Parameters:

NameTypeDefaultDescription
optionsobject-Confirm options
options.titlestring-Dialog title
options.messagestring-Confirmation message
options.confirmTextstring'OK'Confirm button text
options.cancelTextstring'Cancel'Cancel button text

Returns: Promise\\<boolean\\> - True if confirmed, false if cancelled

Example:

const confirmed = await api.ui.showConfirm({
  title: 'Delete File',
  message: 'Are you sure you want to delete this file?',
  confirmText: 'Delete',
  cancelText: 'Cancel'
});
 
if (confirmed) {
  // Delete the file
}

showDialog(options)

Shows a modal dialog with custom buttons and options.

Parameters:

NameTypeDescription
optionsobjectDialog options
options.titlestringDialog title
options.messagestringDialog message
options.typestringDialog type: 'info', 'warning', 'error'
options.buttonsArray\\<\\{id: string, label: string, primary: boolean\\}\\>Custom buttons
options.defaultButtonstringDefault button ID
options.cancelButtonstringCancel button ID
options.detailstringAdditional detail text
options.checkboxLabelstringOptional checkbox label
options.checkboxCheckedbooleanInitial checkbox state
options.modalbooleanWhether dialog is modal (default: true)

Returns: Promise\\<\\{buttonId: string, checkboxChecked: boolean\\}\\> - Dialog result

Example:

const result = await api.ui.showDialog({
  title: 'Save Changes',
  message: 'Do you want to save changes?',
  type: 'warning',
  buttons: [
    { id: 'save', label: 'Save', primary: true },
    { id: 'discard', label: 'Discard' },
    { id: 'cancel', label: 'Cancel' }
  ],
  defaultButton: 'save',
  cancelButton: 'cancel',
  checkboxLabel: 'Always save automatically',
  checkboxChecked: false
});
 
if (result.buttonId === 'save') {
  // Save changes
  if (result.checkboxChecked) {
    // Enable auto-save
  }
}

showQuickPick(items, options)

Shows a quick pick dialog for selecting from a list of items.

Parameters:

NameTypeDescription
itemsArray\\<string | \\{label: string, description?: string, detail?: string\\}\\>Items to display
optionsobjectQuick pick options
options.titlestringDialog title
options.placeholderstringPlaceholder text
options.canPickManybooleanAllow multiple selection
options.matchOnDescriptionbooleanMatch on description during search
options.matchOnDetailbooleanMatch on detail during search

Returns: Promise\\<string | string[] | undefined\\> - Selected item(s) or undefined

Example:

const selected = await api.ui.showQuickPick(
  [
    { label: 'Option 1', description: 'First option', detail: 'More details about option 1' },
    { label: 'Option 2', description: 'Second option' },
    { label: 'Option 3', description: 'Third option' }
  ],
  {
    title: 'Select an Option',
    placeholder: 'Type to search...',
    canPickMany: false
  }
);
 
if (selected) {
  console.log('Selected:', selected.label);
}

showOpenDialog(options)

Shows a native file/folder open dialog.

Parameters:

NameTypeDescription
optionsobjectOpen dialog options
options.titlestringDialog title
options.defaultUristringDefault path
options.canSelectFilesbooleanAllow file selection (default: true)
options.canSelectFoldersbooleanAllow folder selection
options.canSelectManybooleanAllow multiple selection
options.filtersobjectFile type filters: \\\{name: [extensions]\\\}

Returns: Promise\\<string[] | undefined\\> - Array of selected paths or undefined

Example:

const files = await api.ui.showOpenDialog({
  title: 'Select Files',
  canSelectMany: true,
  filters: {
    'Images': ['png', 'jpg', 'jpeg', 'gif'],
    'All Files': ['*']
  }
});
 
if (files) {
  console.log('Selected files:', files);
}

showSaveDialog(options)

Shows a native file save dialog.

Parameters:

NameTypeDescription
optionsobjectSave dialog options
options.titlestringDialog title
options.defaultUristringDefault path and filename
options.filtersobjectFile type filters: \\\{name: [extensions]\\\}

Returns: Promise\\<string | undefined\\> - Selected save path or undefined

Example:

const savePath = await api.ui.showSaveDialog({
  title: 'Save Export',
  defaultUri: '/path/to/export.json',
  filters: {
    'JSON': ['json'],
    'All Files': ['*']
  }
});
 
if (savePath) {
  // Save file to savePath
}

Panels

addPanel(options)

Adds a custom UI panel to Lokus.

Parameters:

NameTypeDescription
optionsobjectPanel options
options.idstringUnique panel ID
options.titlestringPanel title
options.positionstringPanel position: 'sidebar-left', 'sidebar-right', 'bottom', 'modal'
options.iconstringPanel icon
options.componentReact.ComponentReact component to render
options.propsobjectProps to pass to component

Returns: object - Panel object

Example:

const panel = api.ui.addPanel({
  id: 'my-panel',
  title: 'My Panel',
  position: 'sidebar-left',
  icon: 'list',
  component: MyPanelComponent,
  props: { data: initialData }
});

removePanel(id)

Removes a panel by ID.

Parameters:

NameTypeDescription
idstringPanel ID to remove

Returns: boolean - True if panel was removed

Example:

api.ui.removePanel('my-panel');

updatePanel(id, props)

Updates panel props.

Parameters:

NameTypeDescription
idstringPanel ID
propsobjectNew props to merge

Returns: object - Updated panel object

Example:

api.ui.updatePanel('my-panel', {
  data: updatedData,
  loading: false
});

registerPanel(definition)

Registers a panel using SDK-style definition (returns disposable).

Parameters:

NameTypeDescription
definitionobjectPanel definition
definition.idstringUnique panel ID
definition.titlestringPanel title
definition.locationstringPanel location: 'sidebar', 'bottom'
definition.iconstringPanel icon
definition.componentReact.ComponentReact component
definition.initialStateobjectInitial state/props

Returns: Disposable - Disposable to unregister panel

Example:

const disposable = api.ui.registerPanel({
  id: 'my-panel',
  title: 'My Panel',
  location: 'sidebar',
  icon: 'list',
  component: MyPanelComponent,
  initialState: { data: [] }
});
 
// Later, to remove:
disposable.dispose();

Progress

withProgress(options, task)

Shows a progress indicator while executing a task.

Parameters:

NameTypeDescription
optionsobjectProgress options
options.locationstringProgress location: 'notification', 'window', 'statusBar'
options.titlestringProgress title
options.cancellablebooleanWhether progress can be cancelled
taskfunctionTask function: (progress, token) => Promise\<T\>

Task Function:

  • progress.report(value) - Report progress with \\\{message: string, increment: number\\\}
  • token.isCancellationRequested - Boolean indicating cancellation
  • token.onCancellationRequested(callback) - Register cancellation handler

Returns: Promise\\<T\\> - Result of task function

Example:

const result = await api.ui.withProgress(
  {
    location: 'notification',
    title: 'Processing Files',
    cancellable: true
  },
  async (progress, token) => {
    for (let i = 0; i < 100; i++) {
      if (token.isCancellationRequested) {
        return null;
      }
 
      progress.report({
        message: `Processing file ${i + 1}/100`,
        increment: 1
      });
 
      await processFile(i);
    }
    return 'Complete';
  }
);

Tree Views

registerTreeDataProvider(viewId, provider, options)

Registers a tree data provider for displaying hierarchical data.

Parameters:

NameTypeDescription
viewIdstringUnique view ID
providerobjectTree data provider implementation
optionsobjectTree view options
options.titlestringTree view title

Provider Interface:

interface TreeDataProvider {
  getChildren(element?: TreeItem): Promise<TreeItem[]>
  getTreeItem(element: TreeItem): Promise<TreeItem>
  onDidChangeTreeData?: Event<TreeItem | undefined>
}
 
interface TreeItem {
  id: string
  label: string
  collapsibleState?: 'none' | 'collapsed' | 'expanded'
  iconPath?: string
  contextValue?: string
  command?: { command: string, arguments: any[] }
  children?: TreeItem[]
}

Returns: Disposable - Disposable to unregister provider

Example:

const provider = {
  getChildren: async (element) => {
    if (!element) {
      // Root level
      return [
        { id: 'folder1', label: 'Folder 1', collapsibleState: 'collapsed' },
        { id: 'folder2', label: 'Folder 2', collapsibleState: 'collapsed' }
      ];
    }
    // Child items
    return [
      { id: 'item1', label: 'Item 1', collapsibleState: 'none' },
      { id: 'item2', label: 'Item 2', collapsibleState: 'none' }
    ];
  },
  getTreeItem: async (element) => element
};
 
const disposable = api.ui.registerTreeDataProvider('myTreeView', provider, {
  title: 'My Tree View'
});

Status Bar

registerStatusBarItem(definition)

Registers a status bar item.

Parameters:

NameTypeDescription
definitionobjectStatus bar item definition
definition.idstringUnique item ID
definition.textstringDisplay text
definition.tooltipstringTooltip text
definition.commandstring | \\\{command: string, arguments: any[]\\\}Command to execute on click
definition.alignmentnumberAlignment: 1 (left), 2 (right)
definition.prioritynumberPriority for ordering (higher = left/top)
definition.colorstringText color
definition.backgroundColorstringBackground color

Returns: object - Status bar item with show(), hide(), dispose() methods

Example:

const statusItem = api.ui.registerStatusBarItem({
  id: 'my-status',
  text: '$(check) Ready',
  tooltip: 'Plugin is ready',
  alignment: 2, // Right
  priority: 100,
  command: 'myPlugin.showInfo'
});
 
statusItem.show();
 
// Update text
statusItem.text = '$(sync~spin) Processing...';
 
// Later
statusItem.dispose();

Output Channels

createOutputChannel(name)

Creates an output channel for displaying plugin output.

Parameters:

NameTypeDescription
namestringChannel name

Returns: object - Output channel with methods:

  • append(value) - Append text without newline
  • appendLine(value) - Append text with newline
  • replace(value) - Replace entire content
  • clear() - Clear all content
  • show(preserveFocus) - Show the output channel
  • hide() - Hide the output channel
  • dispose() - Dispose the output channel

Example:

const output = api.ui.createOutputChannel('My Plugin');
 
output.appendLine('Plugin initialized');
output.appendLine('Processing...');
output.show(true); // Show without stealing focus
 
// Later
output.appendLine('Complete!');
output.dispose();

Webviews

registerWebviewPanel(definition)

Registers a webview panel with custom HTML content.

Parameters:

NameTypeDescription
definitionobjectWebview panel definition
definition.idstringUnique panel ID
definition.titlestringPanel title
definition.htmlstringHTML content

Returns: object - Webview panel with methods:

  • postMessage(message) - Send message to webview
  • onDidReceiveMessage(handler) - Register message handler from webview
  • dispose() - Dispose the webview

Example:

const webview = api.ui.registerWebviewPanel({
  id: 'my-webview',
  title: 'My Webview',
  html: `
    <!DOCTYPE html>
    <html>
      <head>
        <style>body { font-family: sans-serif; }</style>
      </head>
      <body>
        <h1>Hello from Webview</h1>
        <button id="btn">Send Message</button>
        <script>
          const vscode = acquireVsCodeApi();
          document.getElementById('btn').addEventListener('click', () => {
            vscode.postMessage({ type: 'buttonClicked' });
          });
        </script>
      </body>
    </html>
  `
});
 
// Listen for messages from webview
webview.onDidReceiveMessage((message) => {
  if (message.type === 'buttonClicked') {
    console.log('Button clicked in webview');
  }
});
 
// Send message to webview
webview.postMessage({ type: 'update', data: 'New data' });

registerMenu(definition)

Registers a menu item contribution.

Parameters:

NameTypeDescription
definitionobjectMenu definition
definition.idstringUnique menu ID
definition.labelstringMenu label
definition.groupstringMenu group
definition.ordernumberOrder within group
definition.whenstringCondition expression
definition.submenuArraySubmenu items
definition.commandstringCommand to execute
definition.iconstringMenu icon

Returns: Disposable - Disposable to unregister menu

Example:

const disposable = api.ui.registerMenu({
  id: 'my-menu',
  label: 'My Menu Item',
  group: 'navigation',
  order: 1,
  command: 'myPlugin.action',
  icon: 'settings'
});

Toolbars

registerToolbar(definition)

Registers a toolbar contribution.

Parameters:

NameTypeDescription
definitionobjectToolbar definition
definition.idstringUnique toolbar ID
definition.titlestringToolbar title
definition.locationstringToolbar location: 'editor', 'panel', 'sidebar'
definition.groupstringToolbar group
definition.ordernumberOrder within group
definition.itemsArrayToolbar items
definition.whenstringCondition expression

Returns: Disposable - Disposable to unregister toolbar

Example:

const disposable = api.ui.registerToolbar({
  id: 'my-toolbar',
  title: 'My Toolbar',
  location: 'editor',
  items: [
    { command: 'myPlugin.action1', icon: 'play', tooltip: 'Action 1' },
    { command: 'myPlugin.action2', icon: 'stop', tooltip: 'Action 2' }
  ]
});

Terminal

createTerminal(options)

Creates a terminal instance.

Parameters:

NameTypeDescription
optionsobjectTerminal options
options.namestringTerminal name
options.shellPathstringPath to shell executable
options.shellArgsArray\\<string\\>Shell arguments
options.cwdstringWorking directory
options.envobjectEnvironment variables

Returns: object - Terminal with methods:

  • sendText(text, addNewLine) - Send text to terminal
  • show(preserveFocus) - Show terminal
  • hide() - Hide terminal
  • dispose() - Dispose terminal

Example:

const terminal = api.ui.createTerminal({
  name: 'My Plugin',
  cwd: '/path/to/project'
});
 
terminal.show();
terminal.sendText('npm install');

Events

The UIAPI emits various events that you can listen to:

// Panel events
api.ui.on('panel_added', ({ id, panel }) => {});
api.ui.on('panel_removed', ({ id }) => {});
api.ui.on('panel_updated', ({ id, props }) => {});
 
// Output channel events
api.ui.on('output-channel-created', ({ name }) => {});
api.ui.on('output-channel-update', ({ name, lines }) => {});
api.ui.on('output-channel-show', ({ name }) => {});
api.ui.on('output-channel-hide', ({ name }) => {});
 
// Progress events
api.ui.on('progress-start', ({ id, title }) => {});
api.ui.on('progress-update', ({ id, message, percentage }) => {});
api.ui.on('progress-end', ({ id }) => {});
 
// Tree provider events
api.ui.on('tree-provider-registered', ({ viewId, provider }) => {});
api.ui.on('tree-provider-unregistered', ({ viewId }) => {});
 
// Webview events
api.ui.on('webview-registered', ({ panelId, panel }) => {});
api.ui.on('webview-disposed', ({ panelId }) => {});

Best Practices

1. Use Appropriate Message Types

Choose the right notification type for your message:

  • Information: General status updates
  • Warning: Non-critical issues that need attention
  • Error: Critical failures that block functionality
  • Success: Confirmation of successful operations

2. Provide User Choices

When appropriate, offer action buttons for immediate user response:

const action = await api.ui.showInformationMessage(
  'Configuration updated',
  'Reload Now', 'Later'
);

3. Progress Feedback

Use withProgress for long-running operations:

await api.ui.withProgress(
  { title: 'Loading...', cancellable: true },
  async (progress, token) => {
    // Your task
  }
);

4. Clean Up Resources

Always dispose of UI components when your plugin deactivates:

export function deactivate() {
  statusItem.dispose();
  outputChannel.dispose();
  panelDisposable.dispose();
}

5. Responsive UI

Keep UI operations responsive and don’t block the main thread for long periods.


See Also