Is there a way to correctly light/dark theme webview content that is not textual? VS Code automatically sets the style of my webview html body to reflect light/dark change, but that only applies to foreground/background colors of text or tables, etc but not to svg images used for buttons.
Note that the related question
Detect light/dark theme programatically in Visual Studio Code goes as far as deriving style of custom Webview content from the <body class="vscode-light|dark|high-contrast">
.
Consider webview, which shows an icon that acts as a clickable button:
<img src="images/light/chevron-up.svg" onclick="expandView()"/>
The problem: the /light/
directory needs to be replaced by /dark/
when the user changes the theme.
Theoretically, I could construct this src
attribute using the document.body.class
, which indicates the current theme, but I cannot, because the src
attribute must be created using the Webview.asWebviewUri(...)
API before it is assigned to the webview.html
as static html source.
Also theoretically, I could have a script running in the Webview to detect the document.body.class
change (caused by the user switching the theme later) and re-apply the new theme, when the user changes it. But that would not work, because the very same img.src
attribute is at runtime undefined
, when running inside the Webview. So I cannot just replace the theme folder in the Uri.
Update:
I only found a clunky solution: to define each icon twice, use a custom theme
xml attribute and use a script to show/hide the right icons when the theme changes:
<img src="images/light/chevron-up.svg" theme="light" onclick="expandView()" style="display: inherit"/>
<img src="images/dark/chevron-up.svg" theme="dark" onclick="expandView()" style="dispay: none"/>
The duplication is undesirable for maintainability reasons. That is where I ran out of options. Any ideas?