Unwrap Operation

Remove wrapper node and promote its children to parent level.

Overview

The unwrap operation removes a wrapper node and promotes its children to the parent level. Commonly used to remove link formatting or convert list item back to paragraph.

Interface

interface UnwrapOperation extends Operation {
  type: 'unwrap';
  path: Path; // Path to wrapper node
  wrapperType?: string; // Type of wrapper to unwrap (for validation)
  preservedWrapper?: Node; // Store wrapper for undo
}

Usage

// Unwrap link
function unwrapLink(editor: Editor, linkPath: Path) {
  const linkNode = editor.getNodeAtPath(linkPath);
  
  const operation: UnwrapOperation = {
    type: 'unwrap',
    path: linkPath,
    wrapperType: 'link',
    preservedWrapper: linkNode
  };
  
  editor.applyOperation(operation);
}

// Unwrap list item
function unwrapListItem(editor: Editor, itemPath: Path) {
  const itemNode = editor.getNodeAtPath(itemPath);
  
  const operation: UnwrapOperation = {
    type: 'unwrap',
    path: itemPath,
    wrapperType: 'listItem',
    preservedWrapper: itemNode
  };
  
  editor.applyOperation(operation);
}

// Unwrap selection
function unwrapSelection(editor: Editor, selection: Selection) {
  const nodes = editor.getNodesInRange(selection);
  const tx = editor.beginTransaction();
  
  for (const node of nodes) {
    if (node.type === 'link') {
      tx.add({
        type: 'unwrap',
        path: node.path,
        wrapperType: 'link',
        preservedWrapper: node
      });
    }
  }
  
  tx.commit();
}

Inverse Operation

The inverse of unwrap is wrap:

function getInverse(operation: UnwrapOperation): WrapOperation {
  return {
    type: 'wrap',
    path: operation.path,
    wrapper: operation.preservedWrapper!
  };
}