Wrap Operation

노드나 콘텐츠를 다른 노드로 감쌉니다.

개요

Wrap operation은 기존 노드나 콘텐츠를 새로운 부모 노드로 감쌉니다. 텍스트를 링크로 감싸거나 단락을 목록 항목으로 감쌀 때 일반적으로 사용됩니다.

인터페이스

interface WrapOperation extends Operation {
  type: 'wrap';
  path: Path; // 감쌀 첫 번째 노드 경로
  length?: number; // 감쌀 노드 수 (기본값: 1)
  wrapper: Node; // 감쌀 노드
}

사용법

// 텍스트를 링크로 감싸기
function wrapTextWithLink(editor: Editor, textPath: Path, url: string) {
  const operation: WrapOperation = {
    type: 'wrap',
    path: textPath,
    wrapper: {
      type: 'link',
      attributes: { href: url },
      children: [editor.getNodeAtPath(textPath)]
    }
  };
  
  editor.applyOperation(operation);
}

// 선택 영역을 링크로 감싸기
function wrapSelectionWithLink(editor: Editor, selection: Selection, url: string) {
  const nodes = editor.getNodesInRange(selection);
  
  const tx = editor.beginTransaction();
  
  // 각 노드 감싸기
  for (const node of nodes) {
    tx.add({
      type: 'wrap',
      path: node.path,
      wrapper: {
        type: 'link',
        attributes: { href: url },
        children: [node]
      }
    });
  }
  
  tx.commit();
}

리버스 Operation

Wrap의 리버스 Operation은 unwrap입니다:

function getInverse(operation: WrapOperation): UnwrapOperation {
  return {
    type: 'unwrap',
    path: operation.path,
    wrapperType: operation.wrapper.type
  };
}