vitaliymaz / vscode-svg-previewer

Vscode SVG Previewer
22 stars 4 forks source link

Support for prefers-color-scheme media query in SVG #80

Open fvsch opened 1 month ago

fvsch commented 1 month ago

Hello there,

I have a SVG file looking like this:

<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">
    <style>
        svg { fill: #333 }
        @media (prefers-color-scheme: light) {
            svg { fill: blue }
        }
        @media (prefers-color-scheme: dark) {
            svg { fill: lime }
        }
    </style>
    <rect x="4" y="4" width="8" height="8" rx="4"/>
</svg>

When rendered by this extension, the dot is lime green. Which means that the (prefers-color-scheme: dark) media query was matched, possibly because my OS is set to a dark theme (even though my vscode config used a light theme).

Ideally, the prefers-color-scheme media query would match depending on the background color. But switching the background color didn't change it.

It should be possible to tell the rendering engine to render the SVG with the correct color scheme context using the color-scheme CSS property:

.preview.light {
  color-scheme: light;
}
.preview.dark {
  color-scheme: dark;
}

In my tests in developer tools within vscode, this seemed to work well. It does impact the rendering context of the <img src="data:image/svg+xml;base64,…">.

Note that if a shape doesn't define a fill at all (and doesn't set fill="none"), it will be rendered with a black fill, regardless of the color-scheme. That's already the current behavior, and wouldn't change with this suggested fix.