tiptap: Allow handling invalid content errors

What problem are you facing?

As a developer building an application with TipTap at its core, I would like a way to handle invalid content errors caused by unknown nodes or mark types.

Rationale

Long lived production systems will eventually hit a point where the editor schema evolves in non-backwards-compatible ways. An application that stores documents in persistent storage will later be unable to load them, since the editor will error out and instead render an empty document. For end users, this is equivalent to full data loss.

Some possible solutions to this:

  • migrate documents through a full database migration
  • write a JSON traversal function that can migrate the document content before passing it to the editor

In my view, these strategies highlight a gap in TipTap’s API. I believe TipTap itself can help solve this in a more robust way.

What’s the solution you would like to see?

At a high-level, I like the approach taken by remirror: https://remirror.io/docs/concepts/error-handling/

  • The editor exposes an onError callback that is called when loading the content fails
  • This callback includes enough information so that the parent component can decide how it wants to handle it
  • The editor expects the callback to handle the error and return valid content

Another benefit to this approach is that the onError callback can be used to capture the error in an error monitoring system. Currently it’s not obvious how to do so because TipTap is catching the error.

That said, this is only one way, and maybe there are simpler alternatives that would be a better fit for TipTap.

What alternatives did you consider?

https://github.com/ueberdosis/tiptap/issues/2283#issuecomment-995526706 suggests storing and loading HTML instead:

If it’s an option you can use the HTML content instead because an HTML string is parsed each time and unsupported nodes are converted if necessary.

In my opinion this is not feasible for a lot of apps. Processing the HTML in a backend would involve reimplementing a lot of ProseMirror’s code and editor schema.

Anything to add? (optional)

Thanks for developing TipTap! It’s been a very positive experience so far 💞

Are you sponsoring us?

  • Yes, I’m a sponsor. 💖

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 15
  • Comments: 15 (8 by maintainers)

Most upvoted comments

We are working on a fix for this with: https://github.com/ueberdosis/tiptap/pull/5178

Cool idea! I added it to our tracking board. Since it’ll be of higher complexity we’ll have to see when we can tackle this feature.

Not yet released yet, and we are working on a big docs overhaul so I have written my documentation in a separate place.

But I’ll copy it here for you, hasn’t gone through review yet from others:


To track and respond to content errors, Tiptap supports checking that the content provided matches the schema derived from the registered extensions. To use this, set the enableContentCheck option to true, which activates checking the content and emitting contentError events. These events can be listened to with the onContentError callback. By default, this flag is set to false to maintain compatibility with previous versions.

<aside> 💡 **Note:** the content checking that Tiptap runs is 100% accurate on JSON content types. But, if you provide your content as HTML, we have done our best to try to alert on missing nodes but marks can be missed in certain situations, therefore, falling back to the default behavior of stripping that unrecognized content by default. </aside>

The contentError event

The contentError event is emitted when the initial content provided during editor setup is incompatible with the schema.

  • As part of the error context, you are provided with a disableCollaboration function. Invoking this function reinitializes the editor without the collaboration extension, ensuring that any removed content is not synchronized with other users.

This event can be handled either directly as an option through onContentError like:

new Editor({
	content: invalidContent,
	onContentError() {
		// your handler here
	}
})

Or by attaching a listener to the contentError event on the editor instance.

const editor = new Editor({ ...options })

editor.on('contentError', ()=> {
	// your handler here
})

For more implementation examples, refer to the [events] section.

Suggested Usage

How you handle schema errors may be specific to your application but here are our suggestions:

Single user edits at a time (i.e. no collaborative editing)

Depending on your use case, the default behavior of stripping unknown content keeps your content in a known valid state for future editing.

Collaborative editing (i.e. syncs with other users in realtime)

Depending on your use case, you may want to set the enableContentCheck flag and listen to contentError events. When this event is received, you may want to do things like this example:

onContentError({ editor, error, disableCollaboration }) {
  // This callback is only available on editor initialization.
  if (disableCollaboration) {
    // Removes the collaboration extension.
    disableCollaboration()
  }

  // Since the content is invalid, we don't want to emit an update
  // Preventing synchronization with other editors or to a server
  const emitUpdate = false

  // Disable the editor to prevent further user input
  editor.setEditable(false, emitUpdate)
  
  // Maybe show a notification to the user that they need to refresh the app
}

Maybe it helps someone, we have added this function before the json is loaded into tiptap:

function validateNodeType(jsonDoc, availableNodes) {
    // Check if the current node is valid
    if (!availableNodes.includes(jsonDoc.type)) {
        return null;
    }

    // If the node has content, apply validation to each child
    if (jsonDoc.content) {
        // Filter the content array, removing invalid nodes
        jsonDoc.content = jsonDoc.content
            .map(child => validateNodeType(child, availableNodes))
            .filter(child => child !== null);
    }

    return jsonDoc;
}

const nodes = [
      'doc',
      'paragraph',
      'text',
      'heading',
      'bullet_list',
      'ordered_list',
      'list_item',
      'image',
      'hard_break',
      'blockquote',
      // Add any additional custom nodes here
]

validateNodeType(this.value.json, nodes)

bump