nicegui: Dark mode breaks Tailwind styling in some situations since NiceGUI 2.0

Description

I’m not (currently) able to give a minimal reproducible example. In lieu of that, I’m going to write down the basic things I’m observing here, and then go spend some time debugging the NiceGUI code to see if I can figure out what’s going on. I’ll report back with any findings.

We upgraded from NiceGUI 1.4.30 to 2.1.0, and a lot of our CSS styling broke. We think it mostly has to do with tailwind classes somehow no longer being present/applied. I have narrowed it down to the 1.4.37 -> 2.0.0 upgrade by installing those versions specifically.

Systems affected are various, including multiple developer Mac laptops and our Linux-based deployment.

Screenshots, before and after the upgrade:

(expected layout, which we get in 1.4.37 and earlier) Screenshot 2024-09-19 at 12 42 57

(what we see in 2.0) Screenshot 2024-09-19 at 12 42 04

The relevant code, which was unchanged:

def _render_task_counts_display(task_counts: ty.Collection[QueueCount]) -> None:
    with ui.row(wrap=False).classes("w-full"):
        with ui.column().classes("w-1/2"):
            viz.render_task_counts_by_intent(task_counts)
            viz.render_task_counts_by_typename(task_counts)
        with ui.column().classes("w-1/2"):
            viz.render_task_counts_by_typename_and_intent(task_counts)


async def queue_stats_area():
    task_counts = await list_queue_counts("task")
    policy_counts = await list_queue_counts("policy")

    with ui.column().classes("w-full"):
        viz.render_total_task_count(task_counts)
        with ui.row(wrap=False).classes("w-full"):
            with ui.column().classes("w-1/2"):
                _render_task_counts_display(task_counts)
            with ui.column().classes("w-1/2"):
                viz.render_policy_counts(policy_counts)

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 1
  • Comments: 23 (21 by maintainers)

Commits related to this issue

Most upvoted comments

I just noticed that the bug also occurs when using ui.dark_mode to switch between True and None:

dark_mode = ui.dark_mode(value=None)
ui.button('Dark: True', on_click=lambda: dark_mode.set_value(True))  # breaks Tailwind
ui.button('Dark: None', on_click=lambda: dark_mode.set_value(None))
ui.link('This should be red').classes('text-red-500')

Apparently there have been changes to Tailwind’s dark mode configuration in 3.3 and 3.4: https://tailwindcss.com/docs/dark-mode#toggling-dark-mode-manually The documentation suggests to use the “selector” strategy instead of “class” and to add the “dark” class to document.html instead of document.documentElement. But whatever I try, something’s always broken.

To verify dark mode, we need to make sure every ui.run(dark=...) value works nicely standalone or with different values in ui.dark_mode. Tailwind styling shouldn’t break (of course) and the “dark” prefix needs to work, e.g. .classes(dark:bg-red-400).

At the moment it looks like we might need to re-implement the whole dark mode integration, maybe based on window.matchMedia('(prefers-color-scheme: dark)'). As a quick fix we could raise an exception when using ui.dark_mode while dark=None in ui.run.

Fresh news everybody!

While reviewing PRs opened by me, I tried to check out the examples shown above with UnoCSS at #4832

Conclusion being: all examples above where Tailwind fails, UnoCSS works perfectly.

from nicegui import ui

ui.dark_mode(True)
ui.label('This should be bordered').classes('border')

ui.run(dark=None, unocss_preset='mini', tailwind=False)
Image
from nicegui import ui

dark_mode = ui.dark_mode(value=None)
ui.button('Dark: True', on_click=lambda: dark_mode.set_value(True))  # breaks Tailwind
ui.button('Dark: None', on_click=lambda: dark_mode.set_value(None))
ui.link('This should be red').classes('text-red-500')

ui.run(dark=None, unocss_preset='mini', tailwind=False)
Image

Note this raises 2 questions:

  • Is there a bug in Tailwind CDN JS?
  • In the UnoCSS integration, I did matchMedia for auto dark mode. Possibly if we do something like this for Tailwind CDN JS, it’d be happy?

https://github.com/zauberzeug/nicegui/blob/c9cd70718e6d62b3be549d14bda7e7df021b2d82/nicegui/templates/index.html#L51-L57

After debugging this myself I found a minimal reproducible example. It looks to be a weird case where we set dark=None when calling ui.run, and nicegui sets the Quasar dark plugin to auto and does not add any tailwind config (see here), but in another place we use the ui.dark_mode element used in a toggle which sets the value to either True or False (never None/undefined). This plugin updates the tailwind config but for some reason this does not trigger the tailwind JIT style generation to run again. Not sure what the issue is but it’s definitely related to these to values being different. I think the fix for us is to remove dark=None in ui.run since it’s handled by another component in our app.

Note that the only case where the tailwind styling is not applied/generated is when ui.run(dark=None) and ui.dark_mode(True | False).

from nicegui import ui


def render_total_count(total: int) -> None:
    with ui.card().classes("w-full v-26 items-center").props("bordered"):
        ui.label("Total Count").classes("text-3xl")
        ui.separator()
        ui.label(str(total)).classes("text-2xl")


@ui.page("/")
def index() -> None:
    dark_mode = ui.dark_mode(True)
    with ui.column().classes("w-full"):
        render_total_count(50)


if __name__ in {"__main__", "__mp_main__"}:
    ui.run(
        dark=None,
    )

further indications that there is a bug of some sort in NiceGUI or its dependencies, though I’m beginning to believe it’s somewhat non-deterministic and possibly a race condition, is that if I run a background task with an asyncio.sleep, I get the color that I want:

        btn = ui.button(
            "Reject Selected",
            on_click=lambda: render_reject_dialog(
                render_labels=render_labels, table=_labels_table_loaded.element
            ),
            color="red-500",  # doesn't work
        )
        btn.tailwind.background_color("orange-400")  # doesn't work
        import asyncio

        await asyncio.sleep(2)
        btn.tailwind.background_color("yellow-400")  # doesn't work

        async def fixco():

            await asyncio.sleep(4)

            btn.tailwind.background_color("purple-500")  # works

        background_tasks.create(fixco())

resulting HTML (all classes present and in order): Screenshot 2024-09-19 at 23 19 42

resulting CSS (only bg-purple-500 is ever added to the Tailwind CSS): Screenshot 2024-09-19 at 23 20 16