I'm trying to add a Tree View to my VS Code extension. Data is a complex JSON object. I stuggle to get this to working as the examples aren't straight forward to me.
Lets say I have a simple object:
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] }
]
I would like to render this in the treeview as follows:
Cars
> Ford
> Fiesta
> Focus
> Mustang
> BMW
> 320
> X3
> X5
Any pointers how to achieve this, or know of an repo I can look at that does something similar?
In order to do that, open the Command Palette (using Ctrl + Shift + P), and then searching for Change Language Mode, then select JSON in the drop-down. Alternatively, you can click the file format button in the lower right corner and select JSON in the drop-down menu to achieve the same result.
Here's a straightforward implementation:
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
vscode.window.registerTreeDataProvider('exampleView', new TreeDataProvider());
}
class TreeDataProvider implements vscode.TreeDataProvider<TreeItem> {
onDidChangeTreeData?: vscode.Event<TreeItem|null|undefined>|undefined;
data: TreeItem[];
constructor() {
this.data = [new TreeItem('cars', [
new TreeItem(
'Ford', [new TreeItem('Fiesta'), new TreeItem('Focus'), new TreeItem('Mustang')]),
new TreeItem(
'BMW', [new TreeItem('320'), new TreeItem('X3'), new TreeItem('X5')])
])];
}
getTreeItem(element: TreeItem): vscode.TreeItem|Thenable<vscode.TreeItem> {
return element;
}
getChildren(element?: TreeItem|undefined): vscode.ProviderResult<TreeItem[]> {
if (element === undefined) {
return this.data;
}
return element.children;
}
}
class TreeItem extends vscode.TreeItem {
children: TreeItem[]|undefined;
constructor(label: string, children?: TreeItem[]) {
super(
label,
children === undefined ? vscode.TreeItemCollapsibleState.None :
vscode.TreeItemCollapsibleState.Expanded);
this.children = children;
}
}
And in package.json
:
{
[...]
"contributes": {
"views": {
"explorer": [
{
"id": "exampleView",
"name": "exampleView"
}
]
}
}
}
You might want to have a way of creating the data
dynamically from your JSON data, but to keep the example as simple as possible I just create it statically in the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With