Skip to content

Enhance code editing with CodeEditorField integration #16

@jsirish

Description

@jsirish

Enhance Code Editing Experience with CodeEditorField Integration

Overview

Replace the current basic TextareaField used for the "Code" field in ElementEmbeddedCode with the advanced CodeEditorField provided by nathancox/codeeditorfield. This will significantly improve the developer experience when embedding HTML, CSS, JavaScript, and other code snippets.

Current State Analysis

Current Implementation

The ElementEmbeddedCode class currently uses a basic TextareaField for code input:

// src/Elements/ElementEmbeddedCode.php line 52-56
$fields->replaceField(
    'Code',
    TextareaField::create('Code')
        ->setTitle('Embed Code')
);

Current Issues

  • No syntax highlighting
  • No code validation or error indication
  • Poor readability for complex code snippets
  • No language-specific formatting
  • Limited editing capabilities for developers
  • No line numbers or code folding

Proposed Enhancement

Benefits of CodeEditorField Integration

CodeEditorField (nathancox/codeeditorfield) provides:

Ace Editor Integration: Professional code editing experience with Ace Editor
Syntax Highlighting: Support for HTML, CSS, JavaScript, JSON, and more
Multiple Themes: Light/dark theme support with customizable appearances
Line Numbers: Easy navigation and debugging
Code Folding: Collapse/expand code blocks
Auto-indentation: Proper code formatting
SilverStripe 5+ Compatible: Works with current framework requirements
Minimal Dependencies: Clean integration with existing codebase

Technical Implementation

1. Add Dependency

composer.json - Add to requirements:

{
    "require": {
        "nathancox/codeeditorfield": "^2.0"
    }
}

2. Update ElementEmbeddedCode Class

src/Elements/ElementEmbeddedCode.php:

<?php

namespace Dynamic\Elements\Embedded\Elements;

use DNADesign\Elemental\Models\BaseElement;
use SilverStripe\Forms\FieldList;
use NathanCox\CodeEditorField\CodeEditorField;  // Add import
use SilverStripe\ORM\FieldType\DBField;

class ElementEmbeddedCode extends BaseElement
{
    // ... existing code ...

    /**
     * @return FieldList
     */
    public function getCMSFields()
    {
        $fields = parent::getCMSFields();
        
        // Replace TextareaField with CodeEditorField
        $codeField = CodeEditorField::create('Code', 'Embed Code')
            ->setRows(20)                    // Taller field for better visibility
            ->setMode('html')                // Default to HTML syntax highlighting
            ->addExtraClass('stacked');      // Full width in CMS
            
        $fields->replaceField('Code', $codeField);

        return $fields;
    }

    // ... existing code ...
}

3. Configuration Options

_config/codeeditor.yml (optional global configuration):

---
Name: embedded-code-editor
---

NathanCox\CodeEditorField\CodeEditorField:
  default_mode: 'html'
  default_theme: 'github'          # Light theme default
  default_dark_theme: 'monokai'    # Dark theme fallback

Advanced Implementation Options

Multi-Language Support

For advanced use cases, consider adding language selection:

public function getCMSFields()
{
    $fields = parent::getCMSFields();
    
    // Add language selector
    $fields->addFieldToTab('Root.Main', 
        DropdownField::create('CodeLanguage', 'Code Language')
            ->setSource([
                'html' => 'HTML',
                'css' => 'CSS', 
                'javascript' => 'JavaScript',
                'json' => 'JSON',
                'xml' => 'XML',
                'php' => 'PHP'
            ])
            ->setEmptyString('Auto-detect')
    );
    
    // Dynamic code field based on selection
    $codeField = CodeEditorField::create('Code', 'Embed Code')
        ->setRows(20)
        ->setMode($this->CodeLanguage ?: 'html')
        ->addExtraClass('stacked');
        
    $fields->replaceField('Code', $codeField);
    return $fields;
}

Theme Customization

For Bethlehem brand consistency:

$codeField = CodeEditorField::create('Code', 'Embed Code')
    ->setRows(20)
    ->setMode('html')
    ->setTheme('tomorrow')  // or 'twilight', 'monokai', etc.
    ->addExtraClass('stacked');

Testing Considerations

Browser Testing

  • Test in Chrome, Firefox, Safari, Edge
  • Verify mobile/tablet responsiveness in CMS
  • Test theme switching functionality

Code Validation Testing

  • Test with various HTML snippets
  • Test with JavaScript embeds (Google Analytics, etc.)
  • Test with iframe embeds
  • Test with malformed code (should not break CMS)

Performance Testing

  • Verify no impact on CMS load times
  • Test with large code snippets
  • Ensure proper cleanup when switching between elements

Migration Path

Backward Compatibility

  • Existing Code field data remains unchanged
  • No database migrations required
  • Seamless upgrade path for existing content

Rollback Strategy

If issues arise, rollback requires only:

  1. Remove composer dependency
  2. Revert getCMSFields() method changes
  3. Clear caches with dev/build?flush

User Experience Benefits

Content Editors

  • Immediate Visual Feedback: See code structure clearly
  • Error Prevention: Syntax highlighting reveals issues
  • Professional Interface: Modern code editing experience
  • Improved Productivity: Faster code editing and validation

Developers

  • Better Debugging: Line numbers and error indication
  • Code Organization: Folding and proper indentation
  • Multiple Language Support: Syntax highlighting for various code types
  • Theme Preferences: Light/dark mode support

Implementation Timeline

Phase 1 (1-2 days):

  • Add composer dependency
  • Update ElementEmbeddedCode class
  • Basic functionality testing

Phase 2 (1 day):

  • Advanced configuration options
  • Theme customization
  • Comprehensive testing across browsers

Phase 3 (Optional - 1 day):

  • Multi-language support
  • Custom validation rules
  • Performance optimization

Acceptance Criteria

Core Functionality

  • CodeEditorField successfully replaces TextareaField
  • Syntax highlighting works for HTML, CSS, JavaScript
  • Code field data saves and loads correctly
  • CMS interface remains responsive and stable

User Experience

  • Field displays with proper height and width
  • Theme switching works (light/dark modes)
  • Code folding and line numbers function correctly
  • Copy/paste operations work smoothly

Compatibility

  • No breaking changes to existing functionality
  • Maintains compatibility with SilverStripe 5+
  • Works across all supported browsers
  • Performance remains acceptable with large code snippets

Testing Coverage

  • Unit tests pass for ElementEmbeddedCode
  • Manual testing covers common embed scenarios
  • Cross-browser compatibility verified
  • Mobile CMS experience tested

Additional Resources

  • CodeEditorField Documentation: GitHub Wiki
  • Ace Editor Documentation: ace.c9.io
  • Live Demo: Ace Editor Kitchen Sink
  • Supported Themes: Available in codeeditorfield/thirdparty/ace/src-noconflict/theme-*.js
  • Supported Languages: Available in codeeditorfield/thirdparty/ace/src-noconflict/mode-*.js

This enhancement will significantly improve the code editing experience for both content editors and developers working with the ElementEmbeddedCode module, providing professional-grade syntax highlighting and editing capabilities while maintaining full backward compatibility.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions