Skip to content

Application Becomes Unresponsive When Implementing Global Dark Mode with Custom CSS/JS #1706

@SK-143381

Description

@SK-143381

When attempting to implement a global dark mode using custom CSS and JavaScript in PyShiny, the app becomes unresponsive:

  • UI elements stop responding.
  • Plots do not render.
  • The theme selector has no effect.

Steps to Reproduce:

  1. Run the code snippet below.
  2. Notice that the app loads but does not function as expected.

Expected Behavior:

  • The theme selector should toggle between light and dark modes.
  • All UI elements and plots should remain functional.

Actual Behavior:

  • The app loads but is unresponsive.
  • The theme selector does not change the page appearance.
  • Plots do not render.

Reproducible Example:

import numpy as np
import matplotlib.pyplot as plt
from shiny import App, ui, render, reactive

np.random.seed(1000)

color_palettes = {"Default": "#007bc2", "Red": "#FF0000", "Green": "#00FF00"}

app_ui = ui.page_fluid(
    ui.head_content(
        ui.tags.style("""
            body.dark-theme { background-color: #2E2E2E; color: white; }
            body.light-theme { background-color: white; color: black; }
        """),
        ui.tags.script("""
            Shiny.addCustomMessageHandler("update_theme", function(theme) {
                document.body.classList.toggle("dark-theme", theme === "Dark");
                document.body.classList.toggle("light-theme", theme === "Light");
            });
        """)
    ),
    ui.navset_tab(
        ui.nav_menu(
            "Settings",
            ui.nav_control(
                ui.input_select("theme", "Theme:", choices=["Light", "Dark"], selected="Light")
            )
        ),
        ui.nav_panel(
            "Example Plot",
            ui.output_ui("example_plot"),
        )
    )
)

def server(input, output, session):

    @reactive.Effect
    @reactive.event(input.theme)
    def update_theme():
        session.sendCustomMessage("update_theme", input.theme())

    @output
    @render.plot
    def example_plot():
        data = np.random.normal(size=100)
        fig, ax = plt.subplots()
        ax.hist(data, color=color_palettes["Default"])
        ax.set_title("Example Histogram")
        return fig

app = App(app_ui, server)

if __name__ == "__main__":
    app.run()

** Demo **
theme_render

Request:

Please help identify why using custom CSS/JS for global theme switching causes the app to stop responding, and suggest how to properly implement this feature.

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions