Schema Definition
Schema definition for the Audio node type:
{
audio: {
group: 'block',
attrs: {
src: { default: '' },
controls: { default: true },
autoplay: { default: false },
loop: { default: false }
}
}
}Model Representation
Example model representation:
{
type: 'audio',
attrs: {
src: 'https://example.com/audio.mp3',
controls: true
}
}HTML Serialization
Converting model to HTML:
function serializeAudio(node) {
const attrs = {};
if (node.attrs.src) attrs.src = escapeHtml(node.attrs.src);
if (node.attrs.controls) attrs.controls = true;
if (node.attrs.autoplay) attrs.autoplay = true;
if (node.attrs.loop) attrs.loop = true;
return '<audio' + serializeAttrs(attrs) + '></audio>';
}HTML Deserialization
Parsing HTML to model:
function parseAudio(domNode) {
return {
type: 'audio',
attrs: {
src: domNode.getAttribute('src') || '',
controls: domNode.hasAttribute('controls'),
autoplay: domNode.hasAttribute('autoplay'),
loop: domNode.hasAttribute('loop')
}
};
}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 audio
const audio = document.createElement('audio');
audio.src = node.attrs.src;
audio.controls = node.attrs.controls !== false;
audio.autoplay = node.attrs.autoplay === true;
audio.loop = node.attrs.loop === true;
audio.contentEditable = 'false'; // Audio is not editableCommon Issues
Common Pitfalls: These are issues frequently encountered when implementing this node type. Review carefully before implementation.
Common issues and solutions:
// Issue: Audio format support
// Solution: Check format support
function checkAudioSupport(format) {
const audio = document.createElement('audio');
return audio.canPlayType('audio/' + format) !== '';
}
// Issue: Audio loading
// Solution: Handle loading states
audio.addEventListener('loadstart', () => {
// Show loading indicator
});
audio.addEventListener('canplay', () => {
// Hide loading indicator
}Implementation
Complete implementation example:
class AudioNode {
constructor(attrs) {
this.type = 'audio';
this.attrs = {
src: attrs?.src || '',
controls: attrs?.controls !== false,
autoplay: attrs?.autoplay === false,
loop: attrs?.loop === false
};
}
toDOM() {
const audio = document.createElement('audio');
Object.assign(audio, this.attrs);
return audio;
}
static fromDOM(domNode) {
return new AudioNode({
src: domNode.getAttribute('src') || '',
controls: domNode.hasAttribute('controls'),
autoplay: domNode.hasAttribute('autoplay'),
loop: domNode.hasAttribute('loop')
});
}
}