Skip to content

Save Editor State API (api/editor/saveState.ts)

Endpoint Overview

Handles saving and versioning of editor state for documents, including content, themes, and selection state. Supports concurrent editing and version control.

Request Handlers

POST

  • Body:
    {
      documentId: string;     // ID of the document
      state: {
        content: object;      // Lexical editor content
        themes?: Theme[];     // Theme annotations
        selection?: object;   // Cursor selection state
        timestamp: string;    // State timestamp
      };
      version: number;        // Current version number
      createNewVersion?: boolean; // Whether to create new version
    }
    
  • Response:
    {
      success: boolean;
      version: number;      // Updated version number
      timestamp: string;    // Save timestamp
      status: string;      // Save status
    }
    
  • Status: 200 OK, 400 Bad Request, 401 Unauthorized, 409 Conflict

Error Handling

try {
  // Validate document and state
  if (!isValidState(state)) {
    throw new Error('INVALID_STATE');
  }

  // Check version conflicts
  if (hasVersionConflict(documentId, version)) {
    throw new Error('VERSION_CONFLICT');
  }

  // Save state
  await saveEditorState(documentId, state, version);
} catch (error) {
  return {
    error: error.message,
    code: error.code
  };
}

Common errors: - DOCUMENT_NOT_FOUND: Document does not exist - UNAUTHORIZED: User not authorized - INVALID_STATE: State format is invalid - VERSION_CONFLICT: Version conflict detected - SAVE_FAILED: Failed to save state

Usage Example

const response = await fetch('/api/editor/saveState', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    documentId: 'doc_123',
    state: {
      content: {
        root: {
          children: [{
            type: 'paragraph',
            children: [{ type: 'text', text: 'Updated content...' }]
          }]
        }
      },
      themes: [{
        id: 'theme_1',
        name: 'Theme 1',
        color: '#FF0000',
        ranges: [[0, 10], [20, 30]]
      }],
      selection: {
        anchor: { path: [0, 0], offset: 0 },
        focus: { path: [0, 0], offset: 10 }
      },
      timestamp: new Date().toISOString()
    },
    version: 2,
    createNewVersion: false
  })
});

const result = await response.json();

Implementation Details

  • Implements version control
  • Handles concurrent edits
  • Validates state format
  • Maintains edit history
  • Supports collaborative editing
  • Auto-merges non-conflicting changes
  • Tracks cursor positions
  • Manages theme annotations
  • Atomic state updates

Pages/Components Referenced By

Notes

  • Requires authentication
  • Version control enabled
  • Concurrent editing support
  • State validation
  • History tracking
  • Theme persistence
  • Selection state handling
  • Atomic operations
  • Collaborative features