FilamentF
Filament9mo ago
JanV

Listen to Theme Switcher Event or Read the Current Theme Mode State

Hey, I would like to know how a widget (a ChartWidget) is aware of the current theme mode.

The goal is, I want the chart border color changes depending on the current theme mode.

If it is dark, I want to use lighter colors for better contrast.

If the theme is system (light), the changes to another color.

While researching, I found out that the theme swticher in filament has the following component structure.
<div
    x-data="{ theme: null }"
    x-init="
        $watch('theme', () => {
            $dispatch('theme-changed', theme)
        })

        theme = localStorage.getItem('theme') || @js(filament()->getDefaultThemeMode()->value)
    "
    class="fi-theme-switcher grid grid-flow-col gap-x-1"
>
    <x-filament-panels::theme-switcher.button
        icon="heroicon-m-sun"
        theme="light"
    />

    <x-filament-panels::theme-switcher.button
        icon="heroicon-m-moon"
        theme="dark"
    />

    <x-filament-panels::theme-switcher.button
        icon="heroicon-m-computer-desktop"
        theme="system"
    />
</div>
`
From this piece I see that an event is dispatched.
I guess this is a livewire event, isn't it?
When I try to listen in with the On attribute

    #[On('theme-changed')]
    public function handleThemeChange($theme): void
    {
        $this->theme = $theme;
        $this->updateChartData();
    }

I receive the following error.

Only arrays and Traversables can be unpacked


Is there another way or approach to acccess the current theme mode?

Thanks in advance for any hint/help.
Was this page helpful?