在Visual Studio Code中以编程方式检测明/暗主题

时间:2016-05-16 15:45:31

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

我正在开发一个能够预览extension图表的Visual Studio代码mermaid

enter image description here

扩展使用默认样式表,如果使用灯光主题,则可以正常工作。但是,如果用户已将Visual Studio代码切换为使用黑暗主题,则样式表的某些规则与默认的深色样式表不兼容:

enter image description here

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

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

2 个答案:

答案 0 :(得分:8)

Visual Studio Code 1.3添加了此功能:

  

预览html时,我们会公开当前主题的样式   body元素的类名。这些是 vscode-light vscode-dark ,   和 vscode-high-contrast

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

答案 1 :(得分:0)

自从回答了这个问题以来,不推荐使用HTML预览功能,而推荐使用Webview。这是文档的相关部分:Theming Webview content。 弗拉德的答案仍然有效,但我发现它不完整。

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

这是有帮助的:

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

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

然后,javascript onLoad()函数需要读取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 */
}