스키마 정의
테이블 셀 노드 타입의 스키마 정의:
{
tableCell: {
content: 'block+',
tableRole: 'cell',
isolating: true,
attrs: {
colspan: { default: 1 },
rowspan: { default: 1 }
},
node.attrs.rowspan > 1 ? { rowspan: node.attrs.rowspan } : {}, 0]
}
}모델 표현
모델 표현 예제:
{
type: 'tableCell',
attrs: { colspan: 1, rowspan: 1 },
children: [
{
type: 'paragraph',
children: [{ type: 'text', text: '셀 콘텐츠' }]
}
]
}HTML 직렬화
모델을 HTML로 변환:
function serializeTableCell(node) {
const attrs = {};
if (node.attrs.colspan > 1) attrs.colspan = node.attrs.colspan;
if (node.attrs.rowspan > 1) attrs.rowspan = node.attrs.rowspan;
return '<td' + serializeAttrs(attrs) + '>' +
serializeChildren(node.children) + '</td>';
}HTML 역직렬화
HTML을 모델로 파싱:
function parseTableCell(domNode) {
return {
type: 'tableCell',
attrs: {
colspan: parseInt(domNode.getAttribute('colspan')) || 1,
rowspan: parseInt(domNode.getAttribute('rowspan')) || 1
},
children: Array.from(domNode.childNodes)
.map(node => parseNode(node))
.filter(Boolean)
};
}뷰 연동
뷰 연동 노트: 이 노드 타입을 뷰 레이어에서 구현할 때 contenteditable 동작, 선택 처리, 이벤트 관리에 특히 주의하세요.
뷰 연동 코드:
// 테이블 셀 렌더링
const td = document.createElement('td');
td.contentEditable = 'true';
if (node.attrs.colspan > 1) td.colSpan = node.attrs.colspan;
if (node.attrs.rowspan > 1) td.rowSpan = node.attrs.rowspan;
node.children.forEach(child => {
td.appendChild(renderNode(child));
});
// 테이블 셀에서 Enter 처리
function handleEnterInTableCell(e) {
e.preventDefault();
// 셀에 새 단락 생성
const p = document.createElement('p');
insertNode({ type: 'paragraph', children: [] });
}일반적인 문제
일반적인 함정: 이 노드 타입을 구현할 때 자주 발생하는 문제들입니다. 구현 전에 주의 깊게 검토하세요.
일반적인 문제 및 해결 방법:
// 문제: 빈 셀
// 해결: 최소 하나의 블록 보장
function validateTableCell(cell) {
if (!cell.querySelector('p, ul, ol, h1, h2, h3, h4, h5, h6')) {
const p = document.createElement('p');
cell.appendChild(p);
}
}
// 문제: 셀 선택
// 해결: 셀 선택 처리
function selectCell(td) {
const range = document.createRange();
range.selectNodeContents(td);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
// 문제: Colspan/rowspan 검증
// 해결: span 속성 검증
function validateCellSpan(cell, table) {
// colspan/rowspan이 테이블 크기를 초과하지 않도록 보장
}구현
완전한 구현 예제:
class TableCellNode {
constructor(attrs, children) {
this.type = 'tableCell';
this.attrs = {
colspan: attrs?.colspan || 1,
rowspan: attrs?.rowspan || 1
};
this.children = children || [];
}
toDOM() {
const td = document.createElement('td');
if (this.attrs.colspan > 1) td.colSpan = this.attrs.colspan;
if (this.attrs.rowspan > 1) td.rowSpan = this.attrs.rowspan;
this.children.forEach(child => {
td.appendChild(child.toDOM());
});
return td;
}
static fromDOM(domNode) {
return new TableCellNode(
{
colspan: parseInt(domNode.getAttribute('colspan')) || 1,
rowspan: parseInt(domNode.getAttribute('rowspan')) || 1
},
Array.from(domNode.childNodes)
.map(node => parseNode(node))
.filter(Boolean)
);
}
}