简体   繁体   English

如何创建树作为 Vs 代码的扩展

[英]How to create a tree as extension for Vs code

I want to create a tree in VS code, but my problem is how to manually add a node to my tree.我想在 VS 代码中创建一棵树,但我的问题是如何手动将节点添加到我的树中。 I am not sure from where to start.我不确定从哪里开始。 I tried to review all the projects that created a tree for VScode as an extension.我尝试查看所有为 VScode 创建树作为扩展的项目。

My problem is that I am not an expert in Typescript and the examples are not so clear or I am not sure how it is working.我的问题是我不是 Typescript 的专家,而且例子不是很清楚,或者我不确定它是如何工作的。

Would you mind helping me to understand how to create the tree in VS code?你介意帮助我了解如何在 VS 代码中创建树吗? My problem is with creating a node and then adding the node to tree.我的问题是创建一个节点,然后将该节点添加到树中。

I reviewed these projects:我审查了这些项目:

vscode-code-outline
vscode-extension-samples
vscode-git-tree-compare
vscode-html-languageserver-bin
vscode-mock-debug

vscode-tree-view vscode-树视图

Update1: I managed to use "vscode-extension-samples" and generate the below code examples;更新 1:我设法使用“vscode-extension-samples”并生成以下代码示例; now I don't know what I should do, or in other words, how to fill the tree.现在我不知道我应该做什么,或者换句话说,如何填充树。 I tried to use mytree class to fill the data but it didn't work.我尝试使用 mytree 类来填充数据,但没有用。 Would you mind advising me what is next?你介意告诉我下一步是什么吗?

extension.ts扩展名.ts

    'use strict';

    import * as vscode from 'vscode';

    import { DepNodeProvider } from './nodeDependencies'
    import { JsonOutlineProvider } from './jsonOutline'
    import { FtpExplorer } from './ftpExplorer.textDocumentContentProvider'
    import { FileExplorer } from './fileExplorer';
    //mycode
    import { SCCExplorer } from './sccExplorer';

    export function activate(context: vscode.ExtensionContext) {
        // Complete Tree View Sample
        new FtpExplorer(context);
        new FileExplorer(context);
        //mycode
        new SCCExplorer(context);

        // Following are just data provider samples
        const rootPath = vscode.workspace.rootPath;
        const nodeDependenciesProvider = new DepNodeProvider(rootPath);
        const jsonOutlineProvider = new JsonOutlineProvider(context);

        vscode.window.registerTreeDataProvider('nodeDependencies', nodeDependenciesProvider);
        vscode.commands.registerCommand('nodeDependencies.refreshEntry', () => nodeDependenciesProvider.refresh());
        vscode.commands.registerCommand('nodeDependencies.addEntry', node => vscode.window.showInformationMessage('Successfully called add entry'));
        vscode.commands.registerCommand('nodeDependencies.deleteEntry', node => vscode.window.showInformationMessage('Successfully called delete entry'));
        vscode.commands.registerCommand('extension.openPackageOnNpm', moduleName => vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(`https://www.npmjs.com/package/${moduleName}`)));

        vscode.window.registerTreeDataProvider('jsonOutline', jsonOutlineProvider);
        vscode.commands.registerCommand('jsonOutline.refresh', () => jsonOutlineProvider.refresh());
        vscode.commands.registerCommand('jsonOutline.refreshNode', offset => jsonOutlineProvider.refresh(offset));
        vscode.commands.registerCommand('jsonOutline.renameNode', offset => jsonOutlineProvider.rename(offset));
        vscode.commands.registerCommand('extension.openJsonSelection', range => jsonOutlineProvider.select(range));

    }

sccExplorer.ts sccExplorer.ts

import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import * as mkdirp from 'mkdirp';
import * as rimraf from 'rimraf';

//#region Utilities


interface Entry {
    uri: vscode.Uri,
    type: vscode.FileType
}

//#endregion

export class FileSystemProvider implements vscode.TreeDataProvider<Entry> {
    getTreeItem(element: Entry): vscode.TreeItem | Thenable<vscode.TreeItem> {
        throw new Error("Method not implemented.");
    }
    onDidChangeTreeData?: vscode.Event<Entry>;

    getChildren(element?: Entry): vscode.ProviderResult<Entry[]> {
        throw new Error("Method not implemented.");
    }
    getParent?(element: Entry): vscode.ProviderResult<Entry> {
        throw new Error("Method not implemented.");
    }

    private _onDidChangeFile: vscode.EventEmitter<vscode.FileChangeEvent[]>;

    constructor() {
        this._onDidChangeFile = new vscode.EventEmitter<vscode.FileChangeEvent[]>();
    }


}

export class SCCExplorer {

    private fileExplorer: vscode.TreeView<any>;

    constructor(context: vscode.ExtensionContext) {
        const treeDataProvider = new myTree().directories;
        this.fileExplorer = vscode.window.createTreeView('scc_Explorer', { treeDataProvider });
        vscode.commands.registerCommand('scc_Explorer.openFile', (resource) => this.openResource(resource));
    }

    private openResource(resource: vscode.Uri): void {
        vscode.window.showTextDocument(resource);
    }
}

export class myTree{
    directories: any;
    constructor()
    {
        this.directories = [
        {
            name: 'parent1',
            child: [{
                name: 'child1',
                child: []
            },
            {
                name: 'child2',
                child: []
            }]
        },
        {
            name: 'parent2',
            child: {
                name: 'child1',
                child: []
            }
        },
        {
            name: 'parent2',
            child: [{
                name: 'child1',
                child: []
            },
            {
                name: 'child2',
                child: []
            }]
        }];
    }
}    

I finally got it working.我终于让它工作了。 It took me very long and I had it right all the time.我花了很长时间,而且我一直都做对了。 My issue was I never did explicitly expand the items, so I would never see nested results and only the top level.我的问题是我从未明确扩展项目,所以我永远不会看到嵌套结果,只能看到顶层。

Basic working example基本工作示例

import * as vscode from "vscode";

export class OutlineProvider
  implements vscode.TreeDataProvider<any> {
  constructor(private outline: any) {
    console.log(outline);
  }

  getTreeItem(item: any): vscode.TreeItem {
    return new vscode.TreeItem(
      item.label,
      item.children.length > 0
        ? vscode.TreeItemCollapsibleState.Expanded
        : vscode.TreeItemCollapsibleState.None
    );
  }

  getChildren(element?: any): Thenable<[]> {
    if (element) {
      return Promise.resolve(element.children);
    } else {
      return Promise.resolve(this.outline);
    }
  }
}

export function activate(context: vscode.ExtensionContext) {
  let disposable = vscode.commands.registerCommand(
    "outliner.outline",
    async () => {
      vscode.window.registerTreeDataProvider(
        "documentOutline",
        new OutlineProvider([dataObject])
      );
    }
  );
  context.subscriptions.push(disposable);
}

const dataObject = {
  label: "level one",
  children: [
    {
      label: "level two a",
      children: [
        {
          label: "level three",
          children: [],
        },
      ],
    },
    {
      label: "level two b",
      children: [],
    },
  ],
}

And of course in package.json当然在 package.json 中

"contributes": {
    "commands": [
        {
            "command": "outliner.outline",
            "title": "Outline"
        }
    ],
    "views": {
    "explorer": [
        {
          "id": "documentOutline",
          "name": "Document Outline"
        }
      ]
    }
},

Types类型

note the type for treeDataProvider is not neccecarly what you return.注意 treeDataProvider 的类型并不是你返回的类型。 Only the getTree item has to return a tree item or a class that extends it.只有 getTree 项必须返回树项或扩展它的类。

interface CustomType {
    label: string
    children?: CustomType[]
}

export class TypeExample
    implements vscode.TreeDataProvider<CustomType> {

    constructor(private data: CustomType[]) { }

    getTreeItem(element: CustomType): vscode.TreeItem {
        return new vscode.TreeItem(
            element.label,
            (element.children?.length ?? 0) > 0
                ? vscode.TreeItemCollapsibleState.Expanded
                : vscode.TreeItemCollapsibleState.None
        );
    }

    getChildren(element?: CustomType): Thenable<CustomType[]> {
        return element && Promise.resolve(element.children ?? [])
            || Promise.resolve(this.data);
    }
}

I thought at first the type of the data provider should be the return type of the tree item, this doesnt make much sense of course and I was trying to wrap my head around the reasoning.起初我认为数据提供者的类型应该是树项的返回类型,这当然没有多大意义,我试图围绕推理展开我的头脑。 Now I understand that you pass your custom type in and all other methods inherit this type and expect this type as its argument.现在我知道您传入了您的自定义类型,并且所有其他方法都继承了此类型并期望将此类型作为其参数。 Only the getTreeItem method has to return a valid tree item that can be rendered.只有 getTreeItem 方法必须返回可以呈现的有效树项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM