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

Preset Color Picker Laravel Package

awcodes/preset-color-picker

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require awcodes/preset-color-picker
    npm run build  # After updating tailwind.config.js
    
  2. First Use Case: Add the field to a Filament form (e.g., CreatePost or EditPost):

    use Awcodes\PresetColorPicker\PresetColorPicker;
    
    PresetColorPicker::make('color')
        ->colors([
            Color::Red,
            Color::Blue,
            Color::Green,
        ])
        ->default(Color::Blue),
    
  3. Where to Look First:

    • Package README for basic usage.
    • Filament Docs for field customization patterns.
    • resources/views in the package for template overrides.

Implementation Patterns

Common Workflows

  1. Dynamic Color Palettes: Fetch colors from a database or API and pass them as an array:

    $colors = Color::query()->pluck('hex')->toArray();
    PresetColorPicker::make('theme_color')->colors($colors),
    
  2. Theming Across Forms: Reuse a predefined palette in multiple forms via a helper:

    function getBrandColors(): array {
        return [Color::Blue500, Color::Green500, Color::Purple500];
    }
    
  3. Conditional Palettes: Use closures to dynamically adjust colors based on context (e.g., user role):

    PresetColorPicker::make('accent_color')
        ->colors(fn () => auth()->user()->isAdmin()
            ? [Color::Red, Color::Black]
            : [Color::Gray, Color::White]),
    
  4. Integration with Filament Tables: Use the field in table actions or bulk operations:

    use Filament\Tables\Actions\Action;
    
    Action::make('updateColor')
        ->form([
            PresetColorPicker::make('new_color')
                ->colors([Color::Yellow, Color::Orange]),
        ]),
    
  5. Localization: Translate color labels (e.g., for multilingual apps):

    PresetColorPicker::make('primary_color')
        ->colors([
            Color::Red->label(__('Primary.Red')),
            Color::Blue->label(__('Primary.Blue')),
        ]),
    

Integration Tips

  • Custom CSS: Override styles via tailwind.config.js or a custom CSS file:

    // tailwind.config.js
    module.exports = {
        theme: {
            extend: {
                colors: {
                    custom: {
                        'brand-1': '#1a365d',
                        'brand-2': '#2d3748',
                    },
                },
            },
        },
    };
    

    Then use:

    PresetColorPicker::make('brand_color')
        ->colors([
            Color::Custom('brand-1'),
            Color::Custom('brand-2'),
        ]),
    
  • Validation: Combine with Filament’s validation rules:

    PresetColorPicker::make('background_color')
        ->required()
        ->colors([Color::White, Color::Black])
        ->rules(['required', 'in:'.implode(',', [Color::White->value, Color::Black->value])]),
    
  • Livewire/Alpine.js: Trigger events on color selection:

    PresetColorPicker::make('notification_color')
        ->colors([Color::Green, Color::Red])
        ->extraAttributes(['x-data' => '{ selectedColor: null }'])
        ->extraAttributes(['x-on:selected-color.window' => 'selectedColor = $event.detail']),
    

Gotchas and Tips

Pitfalls

  1. Theme Compatibility:

    • Issue: Colors may not render correctly if the Filament theme isn’t properly configured.
    • Fix: Ensure tailwind.config.js includes the package’s views and run npm run build after updates.
    • Debug: Check browser console for missing CSS errors (e.g., Unrecognized color: #hex).
  2. Color Object Mismatch:

    • Issue: Using raw strings instead of Color objects (e.g., '#ff0000' vs Color::Red).
    • Fix: Always use Color::* constants or Color::make() for consistency.
    • Workaround: Cast strings to Color objects:
      PresetColorPicker::make('color')
          ->colors(array_map(fn ($hex) => Color::make($hex), ['#ff0000', '#00ff00'])),
      
  3. Performance with Large Palettes:

    • Issue: Rendering >50 colors may slow down the form.
    • Fix: Limit palette size or use lazy-loading (e.g., paginated color grids).
  4. Default Value Conflicts:

    • Issue: default() may not work if the color isn’t in the palette.
    • Fix: Validate the default color exists in the palette array.
  5. Tailwind Conflicts:

    • Issue: Custom colors may clash with Tailwind’s default palette.
    • Fix: Use Color::Custom() with unique names (e.g., Color::Custom('app-brand-blue')).

Debugging Tips

  1. Inspect Rendered HTML: Use browser dev tools to verify the color palette structure:

    <!-- Expected structure -->
    <div class="preset-color-picker">
        <button data-color="#ff0000" style="background-color: #ff0000;"></button>
        <!-- ... -->
    </div>
    
  2. Log Color Data: Debug the palette array before passing it to the field:

    $colors = [Color::Red, Color::Blue];
    \Log::debug('Color palette:', $colors);
    
  3. Clear Cache: After updating the package or theme:

    php artisan filament:cache-reset
    php artisan view:clear
    npm run build
    

Extension Points

  1. Custom Templates: Override the default Blade template:

    cp vendor/awcodes/preset-color-picker/resources/views/fields/preset-color-picker.blade.php resources/views/vendor/filament/fields/preset-color-picker.blade.php
    

    Modify the template to add features like:

    • Color swatches with labels.
    • Alpha/opacity sliders.
  2. Dynamic Color Generation: Extend the package to generate palettes programmatically:

    use Awcodes\PresetColorPicker\Color;
    
    class PaletteGenerator {
        public static function generateMonochrome(int $shades = 5): array {
            $base = Color::Gray;
            return collect(range(100, 900, (900 - 100) / ($shades - 1)))
                ->map(fn ($shade) => Color::Gray->shade($shade))
                ->toArray();
        }
    }
    
  3. Color History: Track selected colors across sessions using middleware or Filament’s getSession():

    PresetColorPicker::make('color')
        ->default(session('last_color_selection', Color::Blue)),
    
  4. Accessibility: Ensure color contrast meets WCAG standards by validating palettes:

    use Awcodes\PresetColorPicker\Color;
    
    function isAccessible(array $colors, string $backgroundColor = '#ffffff'): bool {
        foreach ($colors as $color) {
            $contrast = calculateContrast($color->hex, $backgroundColor);
            if ($contrast < 4.5) return false;
        }
        return true;
    }
    
  5. Server-Side Validation: Validate color selections in the save() method of your resource:

    public function save(): void {
        $this->validateColorPalette();
        parent::save();
    }
    
    protected function validateColorPalette(): void {
        $allowedColors = [Color::Red->value, Color::Blue->value];
        if (!in_array($this->color, $allowedColors)) {
            throw ValidationException::withMessages([
                'color' => 'Invalid color selected.',
            ]);
        }
    }
    
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