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

Livewire Jodit Text Editor Laravel Package

xslain/livewire-jodit-text-editor

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require xslain/livewire-jodit-text-editor
    
  2. Include Jodit assets in your layout or view (as shown in README):

    <link rel="stylesheet" href="//unpkg.com/jodit@4.1.16/es2021/jodit.min.css">
    <script src="//unpkg.com/jodit@4.1.16/es2021/jodit.min.js"></script>
    
  3. Use the component in a Livewire blade view:

    <livewire:jodit-editor wire:model="content" />
    
    • wire:model binds the editor content to a Livewire property (e.g., $content).
  4. Define the property in your Livewire component:

    public $content = '';
    

First Use Case: Basic Blog Post Editor

  • Create a Livewire component (BlogPostEditor) with a $content property.
  • Use <livewire:jodit-editor wire:model="content" /> in the blade view.
  • Save the content via a form submission:
    public function savePost()
    {
        $this->validate(['content' => 'required']);
        // Save to database (e.g., $this->post->content = $this->content)
    }
    

Implementation Patterns

Common Workflows

  1. Dynamic Configuration: Customize editor options via the config prop:

    <livewire:jodit-editor
        wire:model="content"
        config='{"buttons": ["bold", "italic", "underline", "image"]}'
    />
    
    • Pass a JSON string or use PHP arrays (via @json):
      config='@json($editorConfig)'
      
  2. Integration with Forms:

    • Use wire:model for two-way binding.
    • Add validation rules in Livewire:
      protected $rules = ['content' => 'required|min:10'];
      
  3. Handling Images/Uploads:

    • Use Jodit’s uploadImage callback (via config):
      config='{
          "uploadImage": {
              "url": "/api/upload",
              "params": {"token": "{{ auth()->token() }}"}
          }
      }'
      
    • Implement the upload endpoint in Laravel (e.g., using StoreImageAction).
  4. Reusable Components:

    • Extend the base component for domain-specific logic:
      class RichPostEditor extends JoditEditor
      {
          public function mount()
          {
              $this->config = [
                  'buttons' => ['bold', 'strike', 'quote', 'code'],
                  'enter' => 'p',
              ];
          }
      }
      
    • Use in views:
      <livewire:rich-post-editor wire:model="postContent" />
      
  5. Livewire Events:

    • Trigger actions on editor events (e.g., contentChanged):
      <livewire:jodit-editor
          wire:model="content"
          @content-changed="handleContentChange"
      />
      
    • Handle in Livewire:
      public function handleContentChange()
      {
          $this->emit('editor:content-changed', $this->content);
      }
      

Gotchas and Tips

Pitfalls

  1. Asset Loading Order:

    • Ensure Jodit CSS/JS are loaded before the Livewire component.
    • Use @stack('scripts') in layouts to avoid race conditions:
      @stack('scripts')
      @push('scripts')
          <script src="//unpkg.com/jodit@4.1.16/es2021/jodit.min.js"></script>
      @endpush
      
  2. Livewire 3 Compatibility:

    • The package requires Livewire 3. Test with:
      composer require livewire/livewire:^3.0
      
    • If using Alpine.js, ensure no conflicts with Jodit’s event system.
  3. Configuration Overrides:

    • Default config may not match Jodit’s latest version. Override explicitly:
      config='@json(array_merge([
          "buttons" => ["bold", "italic"],
          "toolbarButtonSize" => "small",
      ], $this->defaultConfig))'
      
  4. Image Uploads:

    • CORS issues may arise if using external upload URLs. Test with:
      php artisan serve --host=0.0.0.0
      
    • For local uploads, use Laravel’s Storage facade:
      public function uploadImage(Request $request)
      {
          $path = $request->file('file')->store('uploads');
          return response()->json(['location' => $path]);
      }
      
  5. Performance:

    • Heavy configurations (e.g., many plugins) can slow down the editor.
    • Lazy-load plugins:
      config='{
          "plugins": {
              "table": { "lazy": true },
              "file": { "lazy": true }
          }
      }'
      

Debugging Tips

  1. Console Errors:

    • Check browser console for Jodit initialization errors (e.g., missing dependencies).
    • Verify wire:model bindings with:
      console.log(Livewire.find('component-id').data);
      
  2. Livewire Logs:

    • Enable Livewire logging in config/livewire.php:
      'log' => env('APP_DEBUG'),
      
    • Check storage/logs/livewire.log for binding issues.
  3. Configuration Validation:

Extension Points

  1. Custom Plugins:

    • Extend Jodit’s functionality by adding plugins via config:
      config='{
          "plugins": {
              "customPlugin": {
                  "path": "/path/to/plugin.js",
                  "init": function(editor) { /* logic */ }
              }
          }
      }'
      
  2. Theming:

    • Override Jodit’s CSS by targeting .jodit classes in your global CSS:
      .jodit .jodit-toolbar {
          background: #f0f0f0;
      }
      
  3. Server-Side Processing:

    • Sanitize HTML content before saving:
      use Illuminate\Support\Str;
      $this->content = Str::of($this->content)->replaceMatches('/<script.*?>/i', '');
      
    • Use packages like laravel-html-sanitizer for stricter rules.
  4. Fallback for Non-JS Users:

    • Provide a textarea fallback:
      @if(config('app.debug') && !request()->wantsJson())
          <textarea wire:model="content">{{ $content }}</textarea>
      @endif
      

```markdown
## Additional Notes
- **Testing**: Use Laravel’s `Livewire\Livewire::test()` to simulate editor interactions:
  ```php
  Livewire::test(JoditEditor::class)
      ->set('content', '<p>Test</p>')
      ->assertSet('content', '<p>Test</p>');
  • Local Development: For offline use, download Jodit assets and serve locally:
    <link rel="stylesheet" href="{{ asset('vendor/jodit/jodit.min.css') }}">
    <script src="{{ asset('vendor/jodit/jodit.min.js') }}"></script>
    
  • Production: Minify Jodit assets for deployment:
    npm run prod  # If using Laravel Mix
    
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle