스키마 정의
섹션 노드 타입의 스키마 정의:
{
section: {
content: 'block+',
group: 'block',
attrs: {
level: { default: 1 }
},
}
}모델 표현
모델 표현 예제:
{
type: 'section',
attrs: { level: 1 },
children: [
{
type: 'heading',
level: 2,
children: [{ type: 'text', text: '섹션 제목' }]
},
{
type: 'paragraph',
children: [{ type: 'text', text: '섹션 콘텐츠' }]
}
]
}HTML 직렬화
모델을 HTML로 변환:
function serializeSection(node) {
return '<section data-level="' + node.attrs.level + '">' +
serializeChildren(node.children) + '</section>';
}HTML 역직렬화
HTML을 모델로 파싱:
function parseSection(domNode) {
return {
type: 'section',
attrs: { level: parseInt(domNode.getAttribute('data-level')) || 1 },
children: Array.from(domNode.childNodes)
.map(node => parseNode(node))
.filter(Boolean)
};
}뷰 연동
뷰 연동 노트: 이 노드 타입을 뷰 레이어에서 구현할 때 contenteditable 동작, 선택 처리, 이벤트 관리에 특히 주의하세요.
뷰 연동 코드:
// 섹션 렌더링
const section = document.createElement('section');
section.setAttribute('data-level', node.attrs.level);
section.contentEditable = 'true';
node.children.forEach(child => {
section.appendChild(renderNode(child));
});일반적인 문제
일반적인 함정: 이 노드 타입을 구현할 때 자주 발생하는 문제들입니다. 구현 전에 주의 깊게 검토하세요.
일반적인 문제 및 해결 방법:
// 문제: 섹션 중첩
// 해결: 중첩된 섹션 처리
function validateSectionNesting(section, parent) {
const level = parseInt(section.getAttribute('data-level'));
const parentLevel = parent ? parseInt(parent.getAttribute('data-level')) : 0;
return level > parentLevel;
}
// 문제: 섹션 구조
// 해결: 올바른 섹션 구조 보장
function validateSectionStructure(section) {
// 섹션에 최소 하나의 제목이 있는지 확인
return section.querySelector('h1, h2, h3, h4, h5, h6') !== null;
}구현
완전한 구현 예제:
class SectionNode {
constructor(attrs, children) {
this.type = 'section';
this.attrs = { level: attrs?.level || 1 };
this.children = children || [];
}
toDOM() {
const section = document.createElement('section');
section.setAttribute('data-level', this.attrs.level);
this.children.forEach(child => {
section.appendChild(child.toDOM());
});
return section;
}
static fromDOM(domNode) {
return new SectionNode(
{ level: parseInt(domNode.getAttribute('data-level')) || 1 },
Array.from(domNode.childNodes)
.map(node => parseNode(node))
.filter(Boolean)
);
}
}