【问题标题】:Detect light/dark theme programmatically in Visual Studio Code在 Visual Studio Code 中以编程方式检测明暗主题
【发布时间】:2016-05-16 15:45:31
【问题描述】:

我正在开发一个 Visual Studio Code extension,它可以预览 mermaid 图表:

扩展使用默认样式表,如果使用浅色主题,则可以正常工作。但是,如果用户已将 Visual Studio Code 切换为使用深色主题,则样式表有一些与默认深色样式表不兼容的规则:

是否可以以编程方式检测活动主题类型(例如浅色/深色),以便为每种情况提供不同的样式表?

我想使用美人鱼中捆绑的样式表,而不是在我的扩展程序中制作完全不同的样式表。

【问题讨论】:

    标签: visual-studio-code vscode-extensions mermaid


    【解决方案1】:

    Visual Studio Code 1.3 添加了这个功能:

    在预览html时,我们通过暴露当前主题的样式 body 元素的类名。分别是 vscode-lightvscode-dark、 和 vscode-high-contrast

    使用 JavaScript 检查这些值之一允许自定义预览样式表以匹配编辑器中的活动主题。

    【讨论】:

      【解决方案2】:

      自从回答了这个问题后,HTML 预览功能已被弃用,取而代之的是 Webview。这是文档的相关部分:Theming Webview content。 弗拉德的回答仍然有效,但我发现它不完整。

      Webview 中自定义 html 内容的样式表确实需要考虑document.body.class,但是除了在页面加载时读取属性值之外,您还需要处理事件,当用户加载 Webview 后更改主题。所以 Vald 的回答很有帮助,但我意识到我需要处理动态主题更改案例。这通常发生在我在大屏幕上进行演示时,人们要求我切换主题以确保清晰,然后我就被主题混乱且难以辨认的 Webview 卡住了。

      以下是有帮助的:

      html 代码在加载完成时需要触发onLoad() javascript 函数,并且它应该采用默认主题(因此 HTML 可以在 Webview 之外进行测试)。

      <body onload="onLoad()" class="vscode-light">
      

      那么javascriptonLoad()函数需要读取document.body.className的初始值,并使用MutationObserver订阅后续的变化。

      var theme = 'unknown';
      
      function onLoad() {
          postCommand('onload');
          applyTheme(document.body.className);
      
          var observer = new MutationObserver(function(mutations) {
              mutations.forEach(function(mutationRecord) {
                  applyTheme(mutationRecord.target.className);
              });    
          });
      
          var target = document.body;
          observer.observe(target, { attributes : true, attributeFilter : ['class'] });
      }
      
      function applyTheme(newTheme) {
          var prefix = 'vscode-';
          if (newTheme.startsWith(prefix)) {
              // strip prefix
              newTheme = newTheme.substr(prefix.length);
          }
      
          if (newTheme === 'high-contrast') {
              newTheme = 'dark'; // the high-contrast theme seems to be an extreme case of the dark theme
          }
      
          if (theme === newTheme) return;
          theme = newTheme;
      
          console.log('Applying theme: ' + newTheme);
      
          /* PUT YOUR CUSTOM CODE HERE */
      }
      
      

      【讨论】:

        【解决方案3】:

        在扩展中,您可以使用

        vscode.window.activeColorTheme: ColorTheme

        ColorTheme.kind 类型具有以下属性:

        Dark
        
        HighContrast
        
        Light
        

        vscode.window 对象上还有一个onDidChangeActiveColorTheme: Event&lt;ColorTheme&gt; eventListener。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-07
          • 2020-10-14
          • 1970-01-01
          相关资源
          最近更新 更多