Wrap Operation

Wrap nodes or content with another node.

Overview

The wrap operation wraps existing nodes or content with a new parent node. Commonly used to wrap text with a link, or wrap paragraphs with a list item.

Interface

interface WrapOperation extends Operation {
  type: 'wrap';
  path: Path; // Path to first node to wrap
  length?: number; // Number of nodes to wrap (default: 1)
  wrapper: Node; // Node to wrap with
}

Usage

// Wrap text with link
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);
}

// Wrap selection with link
function wrapSelectionWithLink(editor: Editor, selection: Selection, url: string) {
  const nodes = editor.getNodesInRange(selection);
  
  const tx = editor.beginTransaction();
  
  // Wrap each node
  for (const node of nodes) {
    tx.add({
      type: 'wrap',
      path: node.path,
      wrapper: {
        type: 'link',
        attributes: { href: url },
        children: [node]
      }
    });
  }
  
  tx.commit();
}

// Wrap paragraph with list item
function wrapParagraphWithListItem(editor: Editor, paragraphPath: Path) {
  const operation: WrapOperation = {
    type: 'wrap',
    path: paragraphPath,
    wrapper: {
      type: 'listItem',
      children: [editor.getNodeAtPath(paragraphPath)]
    }
  };
  
  editor.applyOperation(operation);
}

Inverse Operation

The inverse of wrap is unwrap:

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