lara404571's avatar

add codemirror code editor to livewire alpine app?

does anyone know any good guides or links for using codemirror with alpine / livewire / filament?

0 likes
1 reply
LaryAI's avatar
Level 58

To integrate CodeMirror with a Livewire and Alpine.js application, you can follow these steps. This example assumes you have a basic understanding of Livewire and Alpine.js.

  1. Install CodeMirror:

    First, you need to include CodeMirror in your project. You can do this via npm or by including the necessary scripts and styles directly in your HTML.

    Using npm:

    npm install codemirror
    

    Or include the following in your HTML:

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/codemirror.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/codemirror.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/javascript/javascript.min.js"></script>
    
  2. Create a Livewire Component:

    Create a Livewire component that will handle the data you want to edit with CodeMirror.

    // app/Http/Livewire/CodeEditor.php
    namespace App\Http\Livewire;
    
    use Livewire\Component;
    
    class CodeEditor extends Component
    {
        public $code = '';
    
        public function render()
        {
            return view('livewire.code-editor');
        }
    }
    
  3. Create the Blade View:

    In your Livewire component view, set up a textarea that will be transformed into a CodeMirror editor.

    <!-- resources/views/livewire/code-editor.blade.php -->
    <div x-data="{ editor: null }" x-init="
        editor = CodeMirror.fromTextArea($refs.textarea, {
            lineNumbers: true,
            mode: 'javascript',
            theme: 'default'
        });
        editor.on('change', () => {
            $wire.set('code', editor.getValue());
        });
    ">
        <textarea x-ref="textarea" wire:model.defer="code"></textarea>
    </div>
    
  4. Initialize CodeMirror with Alpine.js:

    Use Alpine.js to initialize CodeMirror when the component is loaded. The x-init directive is used to set up the CodeMirror instance and bind it to the Livewire property.

  5. Handle Livewire Updates:

    Ensure that any changes in the CodeMirror editor are reflected in the Livewire component by using the editor.on('change', ...) event to update the Livewire property.

  6. Include Alpine.js and Livewire Scripts:

    Make sure you have included the necessary scripts for Alpine.js and Livewire in your layout.

    <script src="//unpkg.com/alpinejs" defer></script>
    @livewireScripts
    

By following these steps, you should be able to integrate CodeMirror into your Livewire and Alpine.js application. Adjust the CodeMirror configuration as needed for your specific use case, such as changing the mode or theme.

Please or to participate in this conversation.