스키마 정의
볼드 마크 타입의 스키마 정의:
{
bold: {
// 마크는 콘텐츠가 없고, 텍스트 노드를 래핑함
}
}모델 표현
모델 표현 예제:
{
type: 'text',
text: '볼드 텍스트',
marks: [{ type: 'bold' }]
}HTML 직렬화
모델을 HTML로 변환:
function serializeBoldMark(text, mark) {
return '<strong>' + text + '</strong>';
}
// 여러 마크가 있을 때, 순서대로 적용
function applyMarks(text, marks) {
let html = text;
marks.forEach(mark => {
if (mark.type === 'bold') {
html = '<strong>' + html + '</strong>';
}
});
return html;
}HTML 역직렬화
HTML을 모델로 파싱:
function extractBoldMark(element) {
if (element.tagName === 'STRONG' || element.tagName === 'B') {
return { type: 'bold' };
}
return null;
}
// 부모 체인에서 모든 마크 추출
function extractMarks(textNode) {
const marks = [];
let current = textNode.parentElement;
while (current && current !== editor) {
const mark = getMarkFromElement(current);
if (mark) marks.push(mark);
current = current.parentElement;
}
return marks;
}뷰 연동
뷰 연동 노트: 이 노드 타입을 뷰 레이어에서 구현할 때 contenteditable 동작, 선택 처리, 이벤트 관리에 특히 주의하세요.
뷰 연동 코드:
// 볼드 토글
function toggleBold() {
const selection = window.getSelection();
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0);
const hasBold = hasMarkInSelection(range, 'bold');
if (hasBold) {
removeMark('bold');
} else {
addMark({ type: 'bold' });
}
}
// 선택에 볼드가 있는지 확인
function hasBoldMark(selection) {
const range = selection.getRangeAt(0);
const commonAncestor = range.commonAncestorContainer;
if (commonAncestor.nodeType === Node.TEXT_NODE) {
return commonAncestor.parentElement?.tagName === 'STRONG';
}
return range.commonAncestorContainer.querySelector('strong');
}일반적인 문제
일반적인 함정: 이 노드 타입을 구현할 때 자주 발생하는 문제들입니다. 구현 전에 주의 깊게 검토하세요.
일반적인 문제 및 해결 방법:
// 문제: <b> vs <strong> 정규화
// 해결: 항상 <b>를 <strong>으로 변환
function normalizeBold(element) {
element.querySelectorAll('b').forEach(b => {
const strong = document.createElement('strong');
strong.innerHTML = b.innerHTML;
b.parentNode.replaceChild(strong, b);
});
}
// 문제: 중첩된 볼드 태그
// 해결: 중첩된 볼드 제거
function removeNestedBold(element) {
const strongs = element.querySelectorAll('strong');
strongs.forEach(strong => {
if (strong.closest('strong') !== strong) {
// 중첩됨, 내부 언래핑
unwrapElement(strong);
}
});
}
// 문제: 다른 마크와 함께 볼드 마크
// 해결: 마크 순서 처리
function applyMarksInOrder(text, marks) {
// 볼드를 먼저 적용하고, 그 다음 다른 마크
const sortedMarks = sortMarks(marks);
let html = text;
sortedMarks.forEach(mark => {
html = wrapWithMark(html, mark);
});
return html;
}구현
완전한 구현 예제:
class BoldMark {
constructor() {
this.type = 'bold';
}
toDOM() {
return ['strong', 0];
}
static fromDOM(element) {
if (element.tagName === 'STRONG' || element.tagName === 'B') {
return new BoldMark();
}
return null;
}
}