Home > Software design >  VSCode API TreeView not getting children of elements
VSCode API TreeView not getting children of elements

Time:04-30

In providing a treeview to VSCode, it seems to get all the parent elements but fail to get the children of these parent elements, I've added a debug point into it and saw that it was only ever called with undefined, is there something improper with my implementation?

export class GalleryTreeItem extends vscode.TreeItem {
  constructor(
    private extensionUri: vscode.Uri,
    public collapsibleState: vscode.TreeItemCollapsibleState,
    public readonly name: string,
    public readonly project?: Project
  ) {
    super(name, collapsibleState);
    if (this.project) {
      this.contextValue = "gallery";
      this.description = `v${this.project.config.userContentVersion}`;
      this.tooltip = this.project.config.repositoryUrl;
      this.command = {
        title: "Plywood Gallery: Open a gallery webview.",
        command: "plywood-gallery.Open",
        arguments: [this.label],
      };
      this.iconPath = vscode.Uri.joinPath(
        this.extensionUri,
        "assets/photo-gallery.png"
      );
    } else {
      this.contextValue = "chapter";
    }
  }

  getChapters() {
    if (this.project) {
      return Object.keys(this.project.parameters).map(
        (name) =>
          new GalleryTreeItem(
            this.extensionUri,
            vscode.TreeItemCollapsibleState.Collapsed,
            name
          )
      );
    } else {
      return [];
    }
  }
}

export class InstalledGalleriesExplorerProvider
  implements vscode.TreeDataProvider<GalleryTreeItem>
{
  constructor(private extensionUri: vscode.Uri) {}

  private _onDidChangeTreeData: vscode.EventEmitter<
    GalleryTreeItem | undefined | void
  > = new vscode.EventEmitter<GalleryTreeItem | undefined | void>();
  readonly onDidChangeTreeData: vscode.Event<
    GalleryTreeItem | undefined | void
  > = this._onDidChangeTreeData.event;

  getTreeItem(element: GalleryTreeItem): vscode.TreeItem {
    return element;
  }

  refresh(): void {
    this._onDidChangeTreeData.fire();
  }

  async getChildren(element?: GalleryTreeItem): Promise<GalleryTreeItem[]> {
    if (element) {
      return Promise.resolve(element.getChapters());
    } else {
      return getLocalProjects(this.extensionUri).then((projects) =>
        projects.map(
          (prj) =>
            new GalleryTreeItem(
              this.extensionUri,
              vscode.TreeItemCollapsibleState.None,
              prj.config.projectName,
              prj
            )
        )
      );
    }
  }
}

CodePudding user response:

"If I am seeing it right you are creating GalleryTreeItems which are your parent nodes, but they have vscode.TreeItemCollapsibleState.None which means they act like they are leaf nodes."

Changing it to vscode.TreeItemCollapsibleState.Collapsed fixes it.

  • Related