Highlight Node Type

Category: Formatting • Detailed implementation guide with view integration notes

Schema Definition

Schema definition for the Highlight mark type:

{
  highlight: {
    attrs: {
      color: { default: '#ffff00' }
    },
      style: 'background-color: ' + node.attrs.color 
    }, 0]
  }
}

Model Representation

Example model representation:

{
  type: 'text',
  text: 'Highlighted text',
  marks: [{
    type: 'highlight',
    attrs: { color: '#ffff00' }
  }]
}

HTML Serialization

Converting model to HTML:

function serializeHighlightMark(text, mark) {
  const color = mark.attrs?.color || '#ffff00';
  return '<mark style="background-color: ' + escapeHtml(color) + '">' + 
         text + '</mark>';
}

HTML Deserialization

Parsing HTML to model:

function extractHighlightMark(element) {
  if (element.tagName === 'MARK') {
    const color = element.style.backgroundColor || '#ffff00';
    return {
      type: 'highlight',
      attrs: { color }
    };
  }
  return null;
}

View Integration

View Integration Notes: Pay special attention to contenteditable behavior, selection handling, and event management when implementing this node type in your view layer.

View integration code:

// Applying highlight
function applyHighlight(color = '#ffff00') {
  addMark({
    type: 'highlight',
    attrs: { color }
  });
}

// Removing highlight
function removeHighlight() {
  removeMark('highlight');
}

Common Issues

Common Pitfalls: These are issues frequently encountered when implementing this node type. Review carefully before implementation.

Common issues and solutions:

// Issue: Highlight color format
// Solution: Normalize to hex
function normalizeHighlightColor(color) {
  return normalizeColor(color);
}

// Issue: Nested highlights
// Solution: Merge or flatten nested highlights
function mergeHighlights(element) {
  const marks = element.querySelectorAll('mark');
  // Handle nested marks
}

Implementation

Complete implementation example:

class HighlightMark {
  constructor(attrs) {
    this.type = 'highlight';
    this.attrs = { color: attrs?.color || '#ffff00' };
  }
  
  toDOM() {
    return ['mark', { 
      style: 'background-color: ' + this.attrs.color 
    }, 0];
  }
  
  static fromDOM(element) {
    if (element.tagName === 'MARK') {
      return new HighlightMark({ 
        color: element.style.backgroundColor || '#ffff00' 
      });
    }
    return null;
  }
}