Quiz Node Type

Category: Custom • Detailed implementation guide with view integration notes

Schema Definition

Schema definition for the Quiz node type:

{
  quiz: {
    content: 'block+',
    group: 'block',
    attrs: {
      title: { default: '' }
    },
  }
}

Model Representation

Example model representation:

{
  type: 'quiz',
  attrs: { title: 'Quiz Title' },
  children: [
    {
      type: 'paragraph',
      children: [{ type: 'text', text: 'Question 1' }]
    }
  ]
}

HTML Serialization

Converting model to HTML:

function serializeQuiz(node) {
  return '<div data-type="quiz" data-title="' + escapeHtml(node.attrs.title) + '">' + 
         serializeChildren(node.children) + '</div>';
}

HTML Deserialization

Parsing HTML to model:

function parseQuiz(domNode) {
  return {
    type: 'quiz',
    attrs: { title: domNode.getAttribute('data-title') || '' },
    children: Array.from(domNode.childNodes)
      .map(node => parseNode(node))
      .filter(Boolean)
  };
}

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:

// Rendering quiz
const quiz = document.createElement('div');
quiz.setAttribute('data-type', 'quiz');
quiz.setAttribute('data-title', node.attrs.title);
quiz.contentEditable = 'true';
node.children.forEach(child => {
  quiz.appendChild(renderNode(child));
});

Common Issues

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

Common issues and solutions:

// Issue: Quiz answer validation
// Solution: Validate answers
function validateQuizAnswer(quiz, answer) {
  // Check answer against correct answer
  return answer === quiz.getAttribute('data-correct-answer');
}

// Issue: Quiz scoring
// Solution: Calculate score
function calculateQuizScore(quiz) {
  // Sum up correct answers
}

Implementation

Complete implementation example:

class QuizNode {
  constructor(attrs, children) {
    this.type = 'quiz';
    this.attrs = { title: attrs?.title || '' };
    this.children = children || [];
  }
  
  toDOM() {
    const quiz = document.createElement('div');
    quiz.setAttribute('data-type', 'quiz');
    quiz.setAttribute('data-title', this.attrs.title);
    this.children.forEach(child => {
      quiz.appendChild(child.toDOM());
    });
    return quiz;
  }
  
  static fromDOM(domNode) {
    return new QuizNode(
      { title: domNode.getAttribute('data-title') || '' },
      Array.from(domNode.childNodes)
        .map(node => parseNode(node))
        .filter(Boolean)
    );
  }
}