Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Filament Themes Laravel Package

yepsua/filament-themes

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run:

    composer require yepsua/filament-themes
    php artisan vendor:publish --tag="yepsua-filament-themes-config"
    

    This publishes the config file (config/filament-themes.php) to customize theme settings.

  2. Publish Assets For CSS/JS assets (if using custom themes):

    php artisan vendor:publish --tag="yepsua-filament-themes-assets"
    

    Place your theme CSS (e.g., resources/css/app.css) in the published directory.

  3. Configure Tailwind Update tailwind.config.js to use CSS variables for dynamic theming:

    module.exports = {
        theme: {
            extend: {
                colors: {
                    primary: withOpacityValue('(--color-primary)'),
                    // Add other theme colors
                }
            }
        }
    }
    
  4. Define Themes in Config Edit config/filament-themes.php to define themes (e.g., light, dark, custom):

    'themes' => [
        'light' => [
            'primary' => '#3b82f6', // Tailwind blue-500
            'secondary' => '#10b981',
        ],
        'dark' => [
            'primary' => '#60a5fa', // Tailwind blue-400
        ],
    ],
    
  5. Set Default Theme In .env or config/filament.php, set:

    FILAMENT_THEME=light
    
  6. Test Run npm run dev (or vite) to compile assets, then refresh your Filament admin panel.


First Use Case

Quickly switch between light/dark themes without rebuilding assets:

  1. Add a theme toggle button to your Filament panel (e.g., using a Filament widget).
  2. Dynamically update the theme via JavaScript:
    // Example: Toggle theme via a button click
    document.getElementById('theme-toggle').addEventListener('click', () => {
        const theme = document.body.classList.contains('dark') ? 'light' : 'dark';
        fetch(`/filament-themes/set-theme?theme=${theme}`, { method: 'POST' });
    });
    
  3. Use the package’s setTheme() helper in a Filament action or middleware.

Implementation Patterns

Core Workflows

1. Theme Configuration

  • Centralized Management: Define all themes in config/filament-themes.php under the themes key. Use hex, rgb, or Tailwind color names (e.g., blue-500).
    'themes' => [
        'brand' => [
            'primary' => '#7c3aed', // Indigo-600
            'danger' => '#ef4444',
            'success' => '#10b981',
        ],
    ],
    
  • Environment-Specific Themes: Override themes per environment using .env:
    FILAMENT_THEMES_CUSTOM_PRIMARY=#ec4899  // Overrides 'primary' for 'custom' theme
    

2. Dynamic Theme Switching

  • Frontend Integration:

    • Use the package’s filament-themes.js (published via assets) to listen for theme changes:
      window.addEventListener('filament-themes:updated', (e) => {
          document.documentElement.style.setProperty('--color-primary', e.detail.primary);
      });
      
    • Trigger theme updates via:
      • Filament actions (e.g., a "Change Theme" button in a widget).
      • API endpoints (e.g., /filament-themes/set-theme).
      • Session-based switching (store theme in session()->put('filament_theme', 'dark')).
  • Backend Logic:

    • Use the FilamentThemes facade to manage themes programmatically:
      use Yepsua\FilamentThemes\Facades\FilamentThemes;
      
      // Set theme for current user
      FilamentThemes::setTheme('dark');
      
      // Get current theme
      $currentTheme = FilamentThemes::getTheme();
      

3. Asset Bundling

  • Vite/Tailwind Setup:

    • Ensure your app.css includes CSS variables for dynamic theming:
      @layer base {
          :root {
              --color-primary: rgb(var(--primary));
              --color-secondary: rgb(var(--secondary));
          }
      }
      
    • Rebuild assets after changing tailwind.config.js:
      npm run dev
      
    • For production, use npm run build.
  • Mix Support: If using Laravel Mix, replace withOpacityValue in tailwind.config.js with PostCSS variables or use the package’s default setup.

4. Theme-Preserving Actions

  • Middleware: Restore user-specific themes on login:
    public function handle(Request $request, Closure $next) {
        if ($userTheme = session()->get('filament_theme')) {
            FilamentThemes::setTheme($userTheme);
        }
        return $next($request);
    }
    
  • Widgets: Create a theme selector widget:
    use Yepsua\FilamentThemes\Facades\FilamentThemes;
    
    public function getThemeOptions(): array {
        return collect(config('filament-themes.themes'))
            ->keys()
            ->mapWithKeys(fn ($theme) => [$theme => __($theme)])
            ->toArray();
    }
    
    public function updateTheme(string $theme) {
        FilamentThemes::setTheme($theme);
        session()->put('filament_theme', $theme);
    }
    

5. Custom Themes

  • Extend Existing Themes: Merge custom themes with defaults:
    'themes' => [
        'custom' => [
            'extends' => 'light', // Inherit from 'light' theme
            'primary' => '#8b5cf6', // Override primary
        ],
    ],
    
  • Theme-Specific Assets: Use Filament’s resource folders to load theme-specific CSS/JS:
    Filament::serving(function () {
        if (FilamentThemes::getTheme() === 'dark') {
            Filament::registerAsset('css', asset('css/filament-dark.css'));
        }
    });
    

Integration Tips

  1. Filament Panels:

    • Set a default theme per panel in config/filament.php:
      'panels' => [
          'admin' => [
              'theme' => env('FILAMENT_PANEL_THEME', 'light'),
          ],
      ],
      
    • Override dynamically in middleware or actions.
  2. Dark Mode Detection:

    • Auto-switch themes based on prefers-color-scheme:
      if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
          fetch('/filament-themes/set-theme?theme=dark', { method: 'POST' });
      }
      
  3. Localization:

    • Translate theme names in lang/en/json:
      {
          "themes": {
              "light": "Light Mode",
              "dark": "Dark Mode"
          }
      }
      
  4. Testing:

    • Mock themes in tests:
      FilamentThemes::shouldReceive('getTheme')->andReturn('dark');
      

Gotchas and Tips

Pitfalls

  1. CSS Variable Conflicts:

    • Issue: Tailwind’s default colors may override your CSS variables if not scoped properly.
    • Fix: Use @apply sparingly and ensure variables are declared in :root or a higher-specificity layer:
      @layer base {
          :root {
              --color-primary: rgb(var(--primary));
          }
      }
      
  2. Asset Caching:

    • Issue: Changes to tailwind.config.js or theme colors may not reflect until assets are rebuilt.
    • Fix: Clear Laravel’s cache and rebuild assets:
      php artisan cache:clear
      npm run dev
      
  3. Theme Inheritance:

    • Issue: extends in themes may not work as expected if the parent theme’s variables are not properly inherited.
    • Fix: Explicitly define all variables in child themes or use CSS @apply for inherited styles.
  4. Middleware Order:

    • Issue: Theme middleware may not run if placed after Filament’s auth middleware.
    • Fix: Register theme middleware in app/Providers/AppServiceProvider.php:
      public function boot() {
          $this->app->booted(fn () => $this->app->make(\Yepsua\FilamentThemes\Http\Middleware\Set
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours