Request: LINQPad should update the media queries for light/dark modes

JeffMercado
edited October 20 in General

I have a script that injects bootstrap to control how the output results are displayed. I want it to react to the light/dark mode preference changes so injected this:

void OnStart()
{
    Util.HtmlHead.AddScript("text/javascript", """
    (function() {
        const m = window.matchMedia('(prefers-color-scheme: dark)');
        m.addEventListener('change', refreshTheme);
        refreshTheme(m);

        function refreshTheme(m) {
            const theme = m.matches ? 'dark' : 'light';
            document.documentElement.setAttribute('data-bs-theme', theme);
        }
    })();
    """);
    Util.HtmlHead.AddRawHtml("""
    <meta name="viewport" content="width=device-width, initial-scale=1">
    """);
    Util.HtmlHead.AddRawHtml("""
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous">
    """);
    Util.HtmlHead.AddRawHtml("""
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js" integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI" crossorigin="anonymous"></script>
    """);
}

This works fine and it can update depending on OS mode changes. However, toggling dark mode in LINQPad doesn't affect it. I'm thinking LINQPad should probably override this based on the current user setting and raise these events.

Just to be clear, toggling dark mode when not injecting bootstrap works as expected, I just want to be able to detect it from the results page.

(side note, unable to upload screenshot here, 403 error)

Comments

  • There's now a Util.ThemeChanged event in 9.3.5. Let me know if this addresses your issue.

  • JeffMercado
    edited October 23

    Thanks, that works. I wasn't aware of the Util.JS class, was able to execute the theme changed function with this:

    Util.HtmlHead.AddScript("text/javascript", """
    (function() {
        const m = window.matchMedia('(prefers-color-scheme: dark)');
        m.addEventListener('change', refreshTheme);
        refreshTheme(m);
    
        function refreshTheme(m) {
            const theme = m.matches ? 'dark' : 'light';
            themeChanged(theme);
        }
    })();
    function themeChanged(theme) {
        if (theme) {
            document.documentElement.setAttribute('data-bs-theme', theme);
        } else {
            document.documentElement.removeAttribute('data-bs-theme');
        }
    }
    """);
    Util.ThemeChanged += (_, _) =>
    {
        Util.JS.RunFunction("themeChanged", Util.IsDarkThemeEnabled ? "dark" : "light");
    };