Tree View API

The Tree View API allows extensions to show content in the sidebar in Visual Studio Code. This content is structured as a tree and conforms to the style of the built-in views of VS Code.

For example, the built-in References Search View extension shows reference search results as a separate view.

References Search View

The Find All References results are displayed in a References: Results Tree View, which is in the References View Container.

This guide teaches you how to write an extension that contributes Tree Views and View Containers to Visual Studio Code.

Tree View API Basics

To explain the Tree View API, we are going to build a sample extension called Node Dependencies. This extension will use a treeview to display all Node.js dependencies in the current folder. The steps for adding a treeview are to contribute the treeview in your package.json, create a TreeDataProvider, and register the TreeDataProvider. You can find the complete source code of this sample extension in the tree-view-sample in the vscode-extension-samples GitHub repository.

package.json Contribution

First you have to let VS Code know that you are contributing a view, using the contributes.views Contribution Point in package.json.

Here’s the package.json for the first version of our extension:

  1. {
  2. "name": "custom-view-samples",
  3. "displayName": "Custom view Samples",
  4. "description": "Samples for VS Code's view API",
  5. "version": "0.0.1",
  6. "publisher": "alexr00",
  7. "engines": {
  8. "vscode": "^1.42.0"
  9. },
  10. "activationEvents": ["onView:nodeDependencies"],
  11. "main": "./out/extension.js",
  12. "contributes": {
  13. "views": {
  14. "explorer": [
  15. {
  16. "id": "nodeDependencies",
  17. "name": "Node Dependencies"
  18. }
  19. ]
  20. }
  21. },
  22. "scripts": {
  23. "vscode:prepublish": "npm run compile",
  24. "compile": "tsc -p ./",
  25. "watch": "tsc -watch -p ./"
  26. },
  27. "devDependencies": {
  28. "@types/node": "^10.12.21",
  29. "@types/vscode": "^1.42.0",
  30. "typescript": "^3.5.1",
  31. "tslint": "^5.12.1"
  32. }
  33. }

You must specify an identifier and name for the view, and you can contribute to following locations:

  • explorer: Explorer view in the Side Bar
  • debug: Run and Debug view in the Side Bar
  • scm: Source Control view in the Side Bar
  • test: Test explorer view in the Side Bar
  • Custom View Containers

Tree Data Provider

The second step is to provide data to the view you registered so that VS Code can display the data in the view. To do so, you should first implement the TreeDataProvider. Our TreeDataProvider will provide node dependencies data, but you can have a data provider that provides other types of data.

There are two necessary methods in this API that you need to implement:

  • getChildren(element?: T): ProviderResult<T[]> - Implement this to return the children for the given element or root (if no element is passed).
  • getTreeItem(element: T): TreeItem | Thenable<TreeItem> - Implement this to return the UI representation (TreeItem) of the element that gets displayed in the view.

When the user opens the Tree View, the getChildren method will be called without an element. From there, your TreeDataProvider should return your top-level tree items. getChildren is then called for each of your top-level tree items, so that you can provide the children of those items.

Here is an example of a TreeDataProvider implementation that provides node dependencies data:

  1. import * as vscode from 'vscode';
  2. import * as fs from 'fs';
  3. import * as path from 'path';
  4. export class NodeDependenciesProvider implements vscode.TreeDataProvider<Dependency> {
  5. constructor(private workspaceRoot: string) {}
  6. getTreeItem(element: Dependency): vscode.TreeItem {
  7. return element;
  8. }
  9. getChildren(element?: Dependency): Thenable<Dependency[]> {
  10. if (!this.workspaceRoot) {
  11. vscode.window.showInformationMessage('No dependency in empty workspace');
  12. return Promise.resolve([]);
  13. }
  14. if (element) {
  15. return Promise.resolve(
  16. this.getDepsInPackageJson(
  17. path.join(this.workspaceRoot, 'node_modules', element.label, 'package.json')
  18. )
  19. );
  20. } else {
  21. const packageJsonPath = path.join(this.workspaceRoot, 'package.json');
  22. if (this.pathExists(packageJsonPath)) {
  23. return Promise.resolve(this.getDepsInPackageJson(packageJsonPath));
  24. } else {
  25. vscode.window.showInformationMessage('Workspace has no package.json');
  26. return Promise.resolve([]);
  27. }
  28. }
  29. }
  30. /**
  31. * Given the path to package.json, read all its dependencies and devDependencies.
  32. */
  33. private getDepsInPackageJson(packageJsonPath: string): Dependency[] {
  34. if (this.pathExists(packageJsonPath)) {
  35. const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
  36. const toDep = (moduleName: string, version: string): Dependency => {
  37. if (this.pathExists(path.join(this.workspaceRoot, 'node_modules', moduleName))) {
  38. return new Dependency(
  39. moduleName,
  40. version,
  41. vscode.TreeItemCollapsibleState.Collapsed
  42. );
  43. } else {
  44. return new Dependency(moduleName, version, vscode.TreeItemCollapsibleState.None);
  45. }
  46. };
  47. const deps = packageJson.dependencies
  48. ? Object.keys(packageJson.dependencies).map(dep =>
  49. toDep(dep, packageJson.dependencies[dep])
  50. )
  51. : [];
  52. const devDeps = packageJson.devDependencies
  53. ? Object.keys(packageJson.devDependencies).map(dep =>
  54. toDep(dep, packageJson.devDependencies[dep])
  55. )
  56. : [];
  57. return deps.concat(devDeps);
  58. } else {
  59. return [];
  60. }
  61. }
  62. private pathExists(p: string): boolean {
  63. try {
  64. fs.accessSync(p);
  65. } catch (err) {
  66. return false;
  67. }
  68. return true;
  69. }
  70. }
  71. class Dependency extends vscode.TreeItem {
  72. constructor(
  73. public readonly label: string,
  74. private version: string,
  75. public readonly collapsibleState: vscode.TreeItemCollapsibleState
  76. ) {
  77. super(label, collapsibleState);
  78. this.tooltip = `${this.label}-${this.version}`;
  79. this.description = this.version;
  80. }
  81. iconPath = {
  82. light: path.join(__filename, '..', '..', 'resources', 'light', 'dependency.svg'),
  83. dark: path.join(__filename, '..', '..', 'resources', 'dark', 'dependency.svg')
  84. };
  85. }

Registering the TreeDataProvider

The third step is to register the above data provider to your view.

This can be done in the following two ways:

  • vscode.window.registerTreeDataProvider - Register the tree data provider by providing the registered view id and above data provider.

    1. vscode.window.registerTreeDataProvider(
    2. 'nodeDependencies',
    3. new NodeDependenciesProvider(vscode.workspace.rootPath)
    4. );
  • vscode.window.createTreeView - Create the Tree View by providing the registered view id and above data provider. This will give access to the TreeView, which you can use for performing other view operations. Use createTreeView, if you need the TreeView API.

    1. vscode.window.createTreeView('nodeDependencies', {
    2. treeDataProvider: new NodeDependenciesProvider(vscode.workspace.rootPath)
    3. });

Here’s the extension in action:

View

Updating Tree View content

Our node dependencies view is simple, and once the data is shown, it isn’t updated. However, it would be useful to have a refresh button in the view and update the node dependencies view with the current contents of the package.json. To do this, we can use the onDidChangeTreeData event.

  • onDidChangeTreeData?: Event<T | undefined | null | void> - Implement this if your tree data can change and you want to update the treeview.

Add the following to your NodeDependenciesProvider.

  1. private _onDidChangeTreeData: vscode.EventEmitter<Dependency | undefined | null | void> = new vscode.EventEmitter<Dependency | undefined | null | void>();
  2. readonly onDidChangeTreeData: vscode.Event<Dependency | undefined | null | void> = this._onDidChangeTreeData.event;
  3. refresh(): void {
  4. this._onDidChangeTreeData.fire();
  5. }

Now we have a refresh method, but no one is calling it. We can add a command to call refresh.

In the contributes section of your package.json, add:

  1. "commands": [
  2. {
  3. "command": "nodeDependencies.refreshEntry",
  4. "title": "Refresh",
  5. "icon": {
  6. "light": "resources/light/refresh.svg",
  7. "dark": "resources/dark/refresh.svg"
  8. }
  9. },
  10. ]

And register the command in your extension activation:

  1. import * as vscode from 'vscode';
  2. import { NodeDependenciesProvider } from './nodeDependencies';
  3. export function activate(context: vscode.ExtensionContext) {
  4. const nodeDependenciesProvider = new NodeDependenciesProvider(vscode.workspace.rootPath);
  5. vscode.window.registerTreeDataProvider('nodeDependencies', nodeDependenciesProvider);
  6. vscode.commands.registerCommand('nodeDependencies.refreshEntry', () =>
  7. nodeDependenciesProvider.refresh()
  8. );
  9. }

Now we have a command that will refresh the node dependencies view, but a button on the view would be even better. We already added an icon to the command, so it will show up with that icon when we add it to the view.

In the contributes section of your package.json, add:

  1. "menus": {
  2. "view/title": [
  3. {
  4. "command": "nodeDependencies.refreshEntry",
  5. "when": "view == nodeDependencies",
  6. "group": "navigation"
  7. },
  8. ]
  9. }

Activation

It is important that your extension is activated only when user needs the functionality that your extension provides. In this case, you should consider activating your extension when the user starts using the view. VS Code emits an activationEvent onView:${viewId} (onView:nodeDependencies for the example above) when the user opens the view.

You can register to this activation event in package.json and VS Code will activate your extension on this event:

  1. "activationEvents": [
  2. "onView:nodeDependencies",
  3. ],

View Container

A View Container contains a list of views that are displayed in the Activity Bar or Panel along with the built-in View Containers. Examples of built-in View Containers are Source Control and Explorer.

View Container

To contribute a View Container, you should first register it using contributes.viewsContainers Contribution Point in package.json.

You have to specify the following required fields:

  • id - The name of the new view container you’re creating.
  • title - The name that will show up at the top of the view container.
  • icon - An image that will be displayed for the view container when in the Activity Bar.
  1. "contributes": {
  2. "viewsContainers": {
  3. "activitybar": [
  4. {
  5. "id": "package-explorer",
  6. "title": "Package Explorer",
  7. "icon": "media/dep.svg"
  8. }
  9. ]
  10. }
  11. }

Alternatively, you could contribute this view to the panel by placing it under the panel node.

  1. "contributes": {
  2. "viewsContainers": {
  3. "panel": [
  4. {
  5. "id": "package-explorer",
  6. "title": "Package Explorer",
  7. "icon": "media/dep.svg"
  8. }
  9. ]
  10. }
  11. }

Contributing views to View Containers

Once you’ve created a View Container, you can use the contributes.views Contribution Point in package.json.

  1. "contributes": {
  2. "views": {
  3. "package-explorer": [
  4. {
  5. "id": "nodeDependencies",
  6. "name": "Node Dependencies",
  7. "icon": "media/dep.svg",
  8. "contextualTitle": "Package Explorer"
  9. }
  10. ]
  11. }
  12. }

A view can also have an optional visibility property which can be set to visible, collapsed, or hidden. This property is only respected by VS Code the first time a workspace is opened with this view. After that, the visibility is set to whatever the user has chosen. If you have a view container with many views, or if your view will not be useful to every user of your extension, consider setting the view the collapsed or hidden. A hidden view will appear in the the view containers “Views” menu:

Views Menu

View Actions

Actions are available as inline icons on your individual tree items, in tree item context menus, and at the top of your view in the view title. Actions are commands that you set to show up in these locations by adding contributions to your package.json.

To contribute to these three places, you can use the following menu contribution points in your package.json:

  • view/title - Location to show actions in the view title. Primary or inline actions use "group": "navigation" and rest are secondary actions, which are in ... menu.
  • view/item/context - Location to show actions for the tree item. Inline actions use "group": "inline" and rest are secondary actions, which are in ... menu.

You can control the visibility of these actions using the when property.

View Actions

Examples:

  1. "contributes": {
  2. "commands": [
  3. {
  4. "command": "nodeDependencies.refreshEntry",
  5. "title": "Refresh",
  6. "icon": {
  7. "light": "resources/light/refresh.svg",
  8. "dark": "resources/dark/refresh.svg"
  9. }
  10. },
  11. {
  12. "command": "nodeDependencies.addEntry",
  13. "title": "Add"
  14. },
  15. {
  16. "command": "nodeDependencies.editEntry",
  17. "title": "Edit",
  18. "icon": {
  19. "light": "resources/light/edit.svg",
  20. "dark": "resources/dark/edit.svg"
  21. }
  22. },
  23. {
  24. "command": "nodeDependencies.deleteEntry",
  25. "title": "Delete"
  26. }
  27. ],
  28. "menus": {
  29. "view/title": [
  30. {
  31. "command": "nodeDependencies.refreshEntry",
  32. "when": "view == nodeDependencies",
  33. "group": "navigation"
  34. },
  35. {
  36. "command": "nodeDependencies.addEntry",
  37. "when": "view == nodeDependencies"
  38. }
  39. ],
  40. "view/item/context": [
  41. {
  42. "command": "nodeDependencies.editEntry",
  43. "when": "view == nodeDependencies && viewItem == dependency",
  44. "group": "inline"
  45. },
  46. {
  47. "command": "nodeDependencies.deleteEntry",
  48. "when": "view == nodeDependencies && viewItem == dependency"
  49. }
  50. ]
  51. }
  52. }

Note: If you want to show an action for specific tree items, you can do so by defining the context of a tree item using TreeItem.contextValue and you can specify the context value for key viewItem in when expression.

Examples:

  1. "contributes": {
  2. "menus": {
  3. "view/item/context": [
  4. {
  5. "command": "nodeDependencies.deleteEntry",
  6. "when": "view == nodeDependencies && viewItem == dependency"
  7. }
  8. ]
  9. }
  10. }

Welcome content

If your view can be empty, or if you want to add Welcome content to another extension’s empty view, you can contribute viewsWelcome content. An empty view is a view that has no message and an empty tree.

  1. "contributes": {
  2. "viewsWelcome": [
  3. {
  4. "view": "nodeDependencies",
  5. "contents": "No node dependencies found [learn more](https://www.npmjs.com/).\n[Add Dependency](command:nodeDependencies.addEntry)",
  6. }
  7. ]
  8. }

Welcome Content

Links are supported in Welcome content. By convention, a link on a line by itself is a button. Each Welcome content can also contain a when clause. For more examples, see the built-in Git extension.

TreeDataProvider

Extension writers should register a TreeDataProvider programmatically to populate data in the view.

  1. vscode.window.registerTreeDataProvider('nodeDependencies', new DepNodeProvider());

See nodeDependencies.ts in the tree-view-sample for the implementation.

TreeView

If you would like to perform some UI operations on the view programmatically, you can use window.createTreeView instead of window.registerTreeDataProvider. This will give access to the view, which you can use for performing view operations.

  1. vscode.window.createTreeView('ftpExplorer', {
  2. treeDataProvider: new FtpTreeDataProvider()
  3. });

See ftpExplorer.ts in the tree-view-sample for the implementation.