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 Code Field Laravel Package

creagia/filament-code-field

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require creagia/filament-code-field
    

    Ensure your project uses Filament 3 and Laravel 11+.

  2. Publish Assets (if needed):

    php artisan vendor:publish --provider="Creagia\FilamentCodeField\FilamentCodeFieldServiceProvider"
    

    (Default assets are auto-loaded; publish only if customizing themes.)

  3. First Usage: Add the field to a Filament form/resource:

    use Creagia\FilamentCodeField\Fields\CodeField;
    
    CodeField::make('code_content')
        ->language('javascript') // Defaults to 'text/x-markdown'
        ->rows(15)
    

    Place this in a Form or TableColumn definition.


First Use Case: Editing Markdown in a Blog Post

// In a Filament Resource Form
public static function form(Form $form): Form
{
    return $form
        ->schema([
            CodeField::make('markdown_content')
                ->label('Post Content')
                ->language('markdown')
                ->rows(20)
                ->columnSpanFull(),
        ]);
}

Result: A syntax-highlighted Markdown editor with live preview (if configured).


Implementation Patterns

Core Workflows

  1. Dynamic Language Selection:

    CodeField::make('config')
        ->language(function (string $context) {
            return match ($context) {
                'settings' => 'json',
                'scripts' => 'javascript',
                default => 'php',
            };
        })
        ->languageLabel('Language')
    

    Useful for multi-purpose fields (e.g., config files with mixed syntax).

  2. Read-Only Mode for Tables:

    // In a TableColumn
    CodeField::make('snippet')
        ->language('python')
        ->readOnly()
        ->extraAttributes(['class' => 'font-mono'])
    

    Ideal for displaying code snippets in admin lists without edit access.

  3. Integration with Filament Actions:

    public static function getTableActions(): array
    {
        return [
            Tables\Actions\EditAction::make()->form([
                CodeField::make('custom_logic')
                    ->language('php')
                    ->rules(['required']),
            ]),
        ];
    }
    

Advanced Patterns

  1. Custom Themes: Extend the default CodeMirror theme via published assets:

    /* resources/css/filament-code-field.css */
    .cm-s-creagia-dark .cm-line {
        background: #1a1a1a;
    }
    

    Re-publish assets after changes.

  2. Line Numbers & Gutter:

    CodeField::make('sql_query')
        ->lineNumbers()
        ->gutter(true)
        ->height('300px')
    
  3. Autocomplete Setup:

    CodeField::make('api_endpoint')
        ->language('javascript')
        ->extraAttributes([
            'data-autocomplete' => json_encode([
                'hintOptions' => ['completeSingle' => false],
                'sources' => [
                    {
                        'list': ['getUsers', 'fetchPosts', 'deleteItem'],
                        'match': '/\\b(get|fetch|delete)\\w*/',
                    },
                ],
            ]),
        ])
    

    Requires codemirror-autocomplete (included by default).

  4. Form Validation:

    CodeField::make('validation_rules')
        ->language('yaml')
        ->rules([
            'required',
            function (string $attribute, $value, Closure $fail) {
                if (str_contains($value, 'invalid_syntax')) {
                    $fail('Code contains invalid syntax.');
                }
            },
        ])
    

Integration Tips

  • Laravel Models: Cast the field to a string in your model:
    protected $casts = [
        'code_content' => 'string',
    ];
    
  • Filament Panels: Works seamlessly in Filament Admin, Filament Nova, and Filament Spark panels.
  • Livewire Components: Use within custom Livewire components by embedding the field’s Blade view:
    <x-filament-code-field::code-field
        wire:model="code"
        language="typescript"
        rows="10"
    />
    

Gotchas and Tips

Common Pitfalls

  1. Asset Loading Issues:

    • Symptom: Code editor appears blank or broken.
    • Fix: Ensure filament-code-field is after filament/support in resources/js/app.js:
      import '@creagia/filament-code-field/dist/filament-code-field.js';
      
    • Debug: Check browser console for Uncaught ReferenceError: CodeMirror.
  2. Language Mismatch:

    • Issue: Syntax highlighting fails for custom languages.
    • Solution: Verify the language mode exists in CodeMirror’s mode list. Fallback to 'text/x-custom' and manually configure:
      ->extraAttributes([
          'data-language-config' => json_encode([
              'name' => 'custom',
              'mime' => 'text/x-custom',
          ]),
      ])
      
  3. Performance with Large Files:

    • Problem: Laggy rendering for files >10KB.
    • Mitigation:
      • Use ->debounce(300) to delay updates.
      • Implement client-side chunking (custom JS).

Debugging Tips

  1. Inspect the Field: Add ->extraAttributes(['data-test-id' => 'debug-code-field']) to target the element in DevTools.

  2. Log CodeMirror Events: Override the field’s JavaScript via a custom asset:

    document.addEventListener('DOMContentLoaded', () => {
        const editor = CodeMirror.fromTextArea(
            document.querySelector('[data-test-id="debug-code-field"]'),
            { /* ... */ }
        );
        editor.on('change', (cm) => {
            console.log('Changed:', cm.getValue());
        });
    });
    
  3. Clear Cache: After publishing assets or updating the package:

    php artisan view:clear
    php artisan filament:cache:clear
    

Extension Points

  1. Custom Modes: Extend CodeMirror modes by publishing the package’s assets and adding:

    // resources/js/filament-code-field-extensions.js
    CodeMirror.defineMode('custom-mode', function () { /* ... */ });
    

    Register in filament-code-field.js:

    window.FilamentCodeField = {
        modes: {
            'custom-mode': 'custom-mode',
        },
    };
    
  2. Plugin Integration: Add CodeMirror plugins dynamically:

    ->extraAttributes([
        'data-plugins' => json_encode([
            'foldcode',
            'comment',
        ]),
    ])
    
  3. Server-Side Processing: Use Filament’s afterStateUpdated to process code before saving:

    CodeField::make('template')
        ->afterStateUpdated(function (string $state, Closure $set) {
            $processed = preg_replace('/\s+/', ' ', $state);
            $set('template', $processed);
        })
    

Pro Tips

  • Dark Mode Support: Use ->theme('dracula') for built-in dark themes (requires theme package).
  • Collapsible Sections: Combine with Filament’s Collapsible:
    Collapsible::make('Advanced Settings')
        ->schema([
            CodeField::make('config')->language('json'),
        ])
    
  • Preserve Whitespace: Add ->extraAttributes(['data-preserve-whitespace' => 'true']) for monospace-sensitive content (e.g., YAML).
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle