Code Editors
This application includes CodeMirror integration for enhanced code editing in textarea fields. The feature provides syntax highlighting, line numbers, linting, and auto-resizing for better code editing experience.
Features
- Syntax Highlighting: Supports JavaScript, JSON, CSS, and HTML
- Line Numbers: Shows line numbers in the gutter
- Linting: Real-time error checking for JavaScript and JSON
- Auto-resizing: Editor height adjusts based on content
- Theme: Uses the zenburn theme for better readability
- Tab Support: Tab key inserts 2 spaces instead of moving focus
Usage
Simple Data Attributes (Recommended)
Add the data-code-editor attribute to any textarea:
<%= f.text_area :javascript_code, data: { code_editor: 'javascript' } %>
<%= f.text_area :json_data, data: { code_editor: 'json' } %>
<%= f.text_area :css_styles, data: { code_editor: 'css' } %>
<%= f.text_area :html_content, data: { code_editor: 'html' } %>
Custom Height
You can specify a custom height:
<%= f.text_area :code, data: { code_editor: 'javascript', editor_height: '500px' } %>
JavaScript API
For more control, you can use the JavaScript API:
// Initialize a single editor
const editor = window.initCodeEditor('textarea-id', 'javascript', {
height: '400px'
});
// Initialize all editors with data attributes
window.initCodeEditors('[data-code-editor]');
Supported Code Types
javascript- JavaScript code with lintingjson- JSON data with validationcss- CSS styleshtml- HTML mixed content
Configuration
The editors use the following default configuration:
- Theme: zenburn (dark theme)
- Indentation: 2 spaces
- Line Wrapping: Enabled
- Line Numbers: Enabled
- Linting: Enabled for JavaScript and JSON
- Auto-resize: 200px minimum, 600px maximum
Form Integration
The editors automatically sync with their underlying textarea fields when the form is submitted, so no additional JavaScript is needed for form handling.
Examples
Schema Markup (JSON)
<%= f.text_area :schema_markup,
rows: 20,
data: { code_editor: 'json', editor_height: '400px' } %>
Inline JavaScript
<%= f.text_area :inline_js,
rows: 10,
data: { code_editor: 'javascript', editor_height: '300px' } %>
Custom CSS
<%= f.text_area :custom_css,
data: { code_editor: 'css' } %>
Browser Compatibility
- Modern browsers with ES6 support
- Requires CodeMirror 5.x (already included in the application)
Troubleshooting
- Editor not appearing: Make sure the
data-code-editorattribute is set correctly - Syntax highlighting not working: Check that the mode is one of the supported types
- Linting errors: Ensure the code is valid for the selected mode
- Form submission issues: The editor automatically saves content to the textarea on form submit
Dependencies
- CodeMirror 5.59.2
- JavaScript mode (includes JSON support)
- Lint addons for validation