【问题标题】:Conditional view contribution with vscode extension api使用 vscode 扩展 api 的条件视图贡献
【发布时间】:2020-05-02 06:50:27
【问题描述】:

我试图仅在编辑器有 HTML 文件时显示我的视图贡献。根据this issue on GitHub,我可以使用when 子句。我发现in the docs 是基于文件类型条件的示例。它用于命令而不是视图贡献。

我正在尝试使用以下配置,视图贡献被隐藏但在我打开 HTML 文件时不显示。如果我删除 when 子句,视图贡献会显示正常,但当然一直都是。

"activationEvents": [
    "onLanguage:html"
],
"contributes": {
    "views": {
    "explorer": [
        {
          "id": "documentOutline",
          "name": "Document Outline",
          "when": "editorLangId == html"
        }
      ]
    }
}

【问题讨论】:

    标签: visual-studio-code vscode-extensions


    【解决方案1】:

    根据contributes.views 文档,when 取决于 context 值。

    根据 npm 扩展,它还可以包含配置设置。

        "views": {
          "explorer": [{
            "id": "npm",
            "name": "%view.name%",
            "when": "npm:showScriptExplorer || config.npm.enableScriptExplorer"
          }]
        },
    

    npm 扩展在激活函数中设置上下文值

        if (await hasPackageJson()) {
            vscode.commands.executeCommand('setContext', 'npm:showScriptExplorer', true);
        }
    

    您可以尝试以下方法:

    在您的扩展程序中定义一个事件处理程序,以便在编辑器更改时调用 (onDidChangeActiveTextEditor)。

    在事件处理程序中,根据文档的 langugeId 设置上下文值。

    编辑

    它适用于以下代码

      const setContext = () => {
          vscode.commands.executeCommand('setContext', 'documentOutline:fileIsHTML',
              vscode.window.activeTextEditor.document.languageId == 'html'); };
      vscode.window.onDidChangeActiveTextEditor(setContext, null, context.subscriptions);
      setContext();
    

    而在package.json

    "activationEvents": [
        "onLanguage:html"
    ],
    "contributes": {
        "views": {
        "explorer": [
            {
              "id": "documentOutline",
              "name": "Document Outline",
              "when": "documentOutline:fileIsHTML"
            }
          ]
        }
    }
    

    或者看看这个问题conditional visibility for custom views 它可能更简单。请参阅 Weinands 示例:在 == 比较中添加引号。

    "activationEvents": [
        "onLanguage:html"
    ],
    "contributes": {
        "views": {
        "explorer": [
            {
              "id": "documentOutline",
              "name": "Document Outline",
              "when": "editorLangId == 'html'"
            }
          ]
        }
    }
    

    编辑

    试过了,还是不行,可能editorLangId不是上下文变量。

    【讨论】:

    • 谢谢,我完全忽略了上下文,并且已经想知道他们从哪里获得使用条件句的值。设置一些上下文布尔值并对其进行检查非常有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    相关资源
    最近更新 更多