Search code examples
visual-studio-codevscode-extensions

how to make conditional on file presence on activity bar views?


Hello I am trying to make new extension that has a view that does not show till an html file exists. Otherwise, show a welcome view. I have the following snippet:

    "contributes": {
        "viewsContainers": {
            "activitybar": [
              {
                "id": "mainview",
                "title": "View",
                "icon": "resources/icon.png"
              }
            ]
          },
 "viewsWelcome": [
            {
              "view": "view-welcome",
              "contents": "To learn more about the best workflow read the docs",
              "when": "!workspaceContains:**/*.html"
            }
          ],
"views": {
            "myextensionView": [
               {
                "id": "html-dir",
                "name": "Models",
                "when": "workspaceContains:*.html"
            },
             {
                "id": "view-welcome",
                "name": "Project Starter"
              }

}

``

However, "workspaceContains:*html" is always false and I am always getting the welcome view.

Any guidance on that?

Solution

  • You are going to the right direction using a When Clause Context, but workspaceContains is not a when clause, it is an Activation Event.

    If you look closer at When Clause Context, you won't see any when clause similar to what you need, so you have to Add a custom when clause context yourself.

    You should create something like this in your package.json:

        "viewsWelcome": [
            {
                "view": "view-welcome",
                "contents": "To learn more about the best workflow read the docs",
                "when": "!myExtension.myWorkspaceContainsSomeHtmlFile"
            }
       ],
    

    And, in your extension source, you are responsible for detecting Html files in the workspace, and call setContext to activate/deactivate the when clause:

        vscode.commands.executeCommand('setContext', 'myExtension.myWorkspaceContainsSomeHtmlFile', hasHtmlFilesInsideTheWorkspace());
    

    Be aware that the same setContext command can/should be called as many times as necessary. For instance, you could create a FileWatcher on your workspace to detect creation/deletion of .html files to update the visibility of your Side Bar. It depends entirely of your needs

    Hope this helps